diff --git a/src/main/java/appeng/block/AEBaseBlock.java b/src/main/java/appeng/block/AEBaseBlock.java index e7fb5b15c..15f9f22d9 100644 --- a/src/main/java/appeng/block/AEBaseBlock.java +++ b/src/main/java/appeng/block/AEBaseBlock.java @@ -19,11 +19,12 @@ package appeng.block; -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Nullable; - +import appeng.api.util.IOrientable; +import appeng.api.util.IOrientableBlock; +import appeng.helpers.AEGlassMaterial; +import appeng.helpers.ICustomCollision; +import appeng.util.LookDirection; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; @@ -46,464 +47,378 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.util.IOrientable; -import appeng.api.util.IOrientableBlock; -import appeng.helpers.AEGlassMaterial; -import appeng.helpers.ICustomCollision; -import appeng.util.LookDirection; -import appeng.util.Platform; - - -public abstract class AEBaseBlock extends Block -{ - - private boolean isOpaque = true; - private boolean isFullSize = true; - private boolean hasSubtypes = false; - private boolean isInventory = false; - - protected AxisAlignedBB boundingBox = FULL_BLOCK_AABB; - - protected AEBaseBlock( final Material mat ) - { - super( mat ); - - if( mat == AEGlassMaterial.INSTANCE || mat == Material.GLASS ) - { - this.setSoundType( SoundType.GLASS ); - } - else if( mat == Material.ROCK ) - { - this.setSoundType( SoundType.STONE ); - } - else if( mat == Material.WOOD ) - { - this.setSoundType( SoundType.WOOD ); - } - else - { - this.setSoundType( SoundType.METAL ); - } - - this.setLightOpacity( 255 ); - this.setLightLevel( 0 ); - this.setHardness( 2.2F ); - this.setHarvestLevel( "pickaxe", 0 ); - - // Workaround as vanilla sets it way too early. - this.fullBlock = this.isFullSize(); - } - - @Override - protected BlockStateContainer createBlockState() - { - return new BlockStateContainer( this, this.getAEStates() ); - } - - @Override - public final boolean isNormalCube( IBlockState state ) - { - return this.isFullSize() && this.isOpaque(); - } - - @Override - public AxisAlignedBB getBoundingBox( IBlockState state, IBlockAccess source, BlockPos pos ) - { - return this.boundingBox; - } - - @SuppressWarnings( "deprecation" ) - @Override - public void addCollisionBoxToList( final IBlockState state, final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, @Nullable final Entity e, boolean p_185477_7_ ) - { - final ICustomCollision collisionHandler = this.getCustomCollision( w, pos ); - - if( collisionHandler != null && bb != null ) - { - final List tmp = new ArrayList<>(); - collisionHandler.addCollidingBlockToList( w, pos, bb, tmp, e ); - for( final AxisAlignedBB b : tmp ) - { - final AxisAlignedBB offset = b.offset( pos.getX(), pos.getY(), pos.getZ() ); - if( bb.intersects( offset ) ) - { - out.add( offset ); - } - } - } - else - { - super.addCollisionBoxToList( state, w, pos, bb, out, e, p_185477_7_ ); - } - } - - @SuppressWarnings( "deprecation" ) - @Override - @SideOnly( Side.CLIENT ) - public AxisAlignedBB getSelectedBoundingBox( IBlockState state, final World w, final BlockPos pos ) - { - final ICustomCollision collisionHandler = this.getCustomCollision( w, pos ); - - if( collisionHandler != null ) - { - if( Platform.isClient() ) - { - final EntityPlayer player = Minecraft.getMinecraft().player; - final LookDirection ld = Platform.getPlayerRay( player, Platform.getEyeOffset( player ) ); - - final Iterable bbs = collisionHandler.getSelectedBoundingBoxesFromPool( w, pos, Minecraft.getMinecraft().player, true ); - AxisAlignedBB br = null; - - double lastDist = 0; - - for( final AxisAlignedBB bb : bbs ) - { - this.boundingBox = bb; - - final RayTraceResult r = super.collisionRayTrace( state, w, pos, ld.getA(), ld.getB() ); - - this.boundingBox = FULL_BLOCK_AABB; - - if( r != null ) - { - final double xLen = ( ld.getA().x - r.hitVec.x ); - final double yLen = ( ld.getA().y - r.hitVec.y ); - final double zLen = ( ld.getA().z - r.hitVec.z ); - - final double thisDist = xLen * xLen + yLen * yLen + zLen * zLen; - - if( br == null || lastDist > thisDist ) - { - lastDist = thisDist; - br = bb; - } - } - } - - if( br != null ) - { - br = new AxisAlignedBB( br.minX + pos.getX(), br.minY + pos.getY(), br.minZ + pos.getZ(), br.maxX + pos.getX(), br.maxY + pos - .getY(), br.maxZ + pos.getZ() ); - return br; - } - } - - AxisAlignedBB b = null; // new AxisAlignedBB( 16d, 16d, 16d, 0d, 0d, 0d ); - - for( final AxisAlignedBB bx : collisionHandler.getSelectedBoundingBoxesFromPool( w, pos, null, false ) ) - { - if( b == null ) - { - b = bx; - continue; - } - - final double minX = Math.min( b.minX, bx.minX ); - final double minY = Math.min( b.minY, bx.minY ); - final double minZ = Math.min( b.minZ, bx.minZ ); - final double maxX = Math.max( b.maxX, bx.maxX ); - final double maxY = Math.max( b.maxY, bx.maxY ); - final double maxZ = Math.max( b.maxZ, bx.maxZ ); - - b = new AxisAlignedBB( minX, minY, minZ, maxX, maxY, maxZ ); - } - - if( b == null ) - { - b = new AxisAlignedBB( 16d, 16d, 16d, 0d, 0d, 0d ); - } - else - { - b = new AxisAlignedBB( b.minX + pos.getX(), b.minY + pos.getY(), b.minZ + pos.getZ(), b.maxX + pos.getX(), b.maxY + pos.getY(), b.maxZ + pos - .getZ() ); - } - - return b; - } - - return super.getSelectedBoundingBox( state, w, pos ); - } - - @Override - public final boolean isOpaqueCube( IBlockState state ) - { - return this.isOpaque(); - } - - @SuppressWarnings( "deprecation" ) - @Override - public RayTraceResult collisionRayTrace( final IBlockState state, final World w, final BlockPos pos, final Vec3d a, final Vec3d b ) - { - final ICustomCollision collisionHandler = this.getCustomCollision( w, pos ); - - if( collisionHandler != null ) - { - final Iterable bbs = collisionHandler.getSelectedBoundingBoxesFromPool( w, pos, null, true ); - RayTraceResult br = null; - - double lastDist = 0; - - for( final AxisAlignedBB bb : bbs ) - { - this.boundingBox = bb; - - final RayTraceResult r = super.collisionRayTrace( state, w, pos, a, b ); - - this.boundingBox = FULL_BLOCK_AABB; - - if( r != null ) - { - final double xLen = ( a.x - r.hitVec.x ); - final double yLen = ( a.y - r.hitVec.y ); - final double zLen = ( a.z - r.hitVec.z ); - - final double thisDist = xLen * xLen + yLen * yLen + zLen * zLen; - if( br == null || lastDist > thisDist ) - { - lastDist = thisDist; - br = r; - } - } - } - - if( br != null ) - { - return br; - } - - return null; - } - - this.boundingBox = FULL_BLOCK_AABB; - return super.collisionRayTrace( state, w, pos, a, b ); - } - - @Override - public boolean hasComparatorInputOverride( IBlockState state ) - { - return this.isInventory(); - } - - @Override - public int getComparatorInputOverride( IBlockState state, final World worldIn, final BlockPos pos ) - { - return 0; - } - - @Override - public final boolean isNormalCube( IBlockState state, final IBlockAccess world, final BlockPos pos ) - { - return this.isFullSize(); - } - - @Override - public boolean rotateBlock( final World w, final BlockPos pos, final EnumFacing axis ) - { - final IOrientable rotatable = this.getOrientable( w, pos ); - - if( rotatable != null && rotatable.canBeRotated() ) - { - if( this.hasCustomRotation() ) - { - this.customRotateBlock( rotatable, axis ); - return true; - } - else - { - EnumFacing forward = rotatable.getForward(); - EnumFacing up = rotatable.getUp(); - - for( int rs = 0; rs < 4; rs++ ) - { - forward = Platform.rotateAround( forward, axis ); - up = Platform.rotateAround( up, axis ); - - if( this.isValidOrientation( w, pos, forward, up ) ) - { - rotatable.setOrientation( forward, up ); - return true; - } - } - } - } - - return super.rotateBlock( w, pos, axis ); - } - - @Override - public EnumFacing[] getValidRotations( final World w, final BlockPos pos ) - { - return new EnumFacing[0]; - } - - @SideOnly( Side.CLIENT ) - @Override - public void addInformation( final ItemStack is, final World world, final List lines, final ITooltipFlag advancedItemTooltips ) - { - - } - - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - return false; - } - - public final EnumFacing mapRotation( final IOrientable ori, final EnumFacing dir ) - { - // case DOWN: return bottomIcon; - // case UP: return blockIcon; - // case NORTH: return northIcon; - // case SOUTH: return southIcon; - // case WEST: return sideIcon; - // case EAST: return sideIcon; - - final EnumFacing forward = ori.getForward(); - final EnumFacing up = ori.getUp(); - - if( forward == null || up == null ) - { - return dir; - } - - final int west_x = forward.getFrontOffsetY() * up.getFrontOffsetZ() - forward.getFrontOffsetZ() * up.getFrontOffsetY(); - final int west_y = forward.getFrontOffsetZ() * up.getFrontOffsetX() - forward.getFrontOffsetX() * up.getFrontOffsetZ(); - final int west_z = forward.getFrontOffsetX() * up.getFrontOffsetY() - forward.getFrontOffsetY() * up.getFrontOffsetX(); - - EnumFacing west = null; - for( final EnumFacing dx : EnumFacing.VALUES ) - { - if( dx.getFrontOffsetX() == west_x && dx.getFrontOffsetY() == west_y && dx.getFrontOffsetZ() == west_z ) - { - west = dx; - } - } - - if( west == null ) - { - return dir; - } - - if( dir == forward ) - { - return EnumFacing.SOUTH; - } - if( dir == forward.getOpposite() ) - { - return EnumFacing.NORTH; - } - - if( dir == up ) - { - return EnumFacing.UP; - } - if( dir == up.getOpposite() ) - { - return EnumFacing.DOWN; - } - - if( dir == west ) - { - return EnumFacing.WEST; - } - if( dir == west.getOpposite() ) - { - return EnumFacing.EAST; - } - - return null; - } - - @Override - public String toString() - { - String regName = this.getRegistryName() != null ? this.getRegistryName().getResourcePath() : "unregistered"; - return this.getClass().getSimpleName() + "[" + regName + "]"; - } - - protected String getUnlocalizedName( final ItemStack is ) - { - return this.getUnlocalizedName(); - } - - protected boolean hasCustomRotation() - { - return false; - } - - protected void customRotateBlock( final IOrientable rotatable, final EnumFacing axis ) - { - - } - - protected IOrientable getOrientable( final IBlockAccess w, final BlockPos pos ) - { - if( this instanceof IOrientableBlock ) - { - IOrientableBlock orientable = (IOrientableBlock) this; - return orientable.getOrientable( w, pos ); - } - return null; - } - - protected boolean isValidOrientation( final World w, final BlockPos pos, final EnumFacing forward, final EnumFacing up ) - { - return true; - } - - protected ICustomCollision getCustomCollision( final World w, final BlockPos pos ) - { - if( this instanceof ICustomCollision ) - { - return (ICustomCollision) this; - } - return null; - } - - protected IProperty[] getAEStates() - { - return new IProperty[0]; - } - - protected boolean isOpaque() - { - return this.isOpaque; - } - - protected boolean setOpaque( final boolean isOpaque ) - { - this.isOpaque = isOpaque; - return isOpaque; - } - - protected boolean hasSubtypes() - { - return this.hasSubtypes; - } - - protected void setHasSubtypes( final boolean hasSubtypes ) - { - this.hasSubtypes = hasSubtypes; - } - - protected boolean isFullSize() - { - return this.isFullSize; - } - - protected boolean setFullSize( final boolean isFullSize ) - { - this.isFullSize = isFullSize; - return isFullSize; - } - - protected boolean isInventory() - { - return this.isInventory; - } - - protected void setInventory( final boolean isInventory ) - { - this.isInventory = isInventory; - } +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; + + +public abstract class AEBaseBlock extends Block { + + private boolean isOpaque = true; + private boolean isFullSize = true; + private boolean hasSubtypes = false; + private boolean isInventory = false; + + protected AxisAlignedBB boundingBox = FULL_BLOCK_AABB; + + protected AEBaseBlock(final Material mat) { + super(mat); + + if (mat == AEGlassMaterial.INSTANCE || mat == Material.GLASS) { + this.setSoundType(SoundType.GLASS); + } else if (mat == Material.ROCK) { + this.setSoundType(SoundType.STONE); + } else if (mat == Material.WOOD) { + this.setSoundType(SoundType.WOOD); + } else { + this.setSoundType(SoundType.METAL); + } + + this.setLightOpacity(255); + this.setLightLevel(0); + this.setHardness(2.2F); + this.setHarvestLevel("pickaxe", 0); + + // Workaround as vanilla sets it way too early. + this.fullBlock = this.isFullSize(); + } + + @Override + protected BlockStateContainer createBlockState() { + return new BlockStateContainer(this, this.getAEStates()); + } + + @Override + public final boolean isNormalCube(IBlockState state) { + return this.isFullSize() && this.isOpaque(); + } + + @Override + public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { + return this.boundingBox; + } + + @SuppressWarnings("deprecation") + @Override + public void addCollisionBoxToList(final IBlockState state, final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, @Nullable final Entity e, boolean p_185477_7_) { + final ICustomCollision collisionHandler = this.getCustomCollision(w, pos); + + if (collisionHandler != null && bb != null) { + final List tmp = new ArrayList<>(); + collisionHandler.addCollidingBlockToList(w, pos, bb, tmp, e); + for (final AxisAlignedBB b : tmp) { + final AxisAlignedBB offset = b.offset(pos.getX(), pos.getY(), pos.getZ()); + if (bb.intersects(offset)) { + out.add(offset); + } + } + } else { + super.addCollisionBoxToList(state, w, pos, bb, out, e, p_185477_7_); + } + } + + @SuppressWarnings("deprecation") + @Override + @SideOnly(Side.CLIENT) + public AxisAlignedBB getSelectedBoundingBox(IBlockState state, final World w, final BlockPos pos) { + final ICustomCollision collisionHandler = this.getCustomCollision(w, pos); + + if (collisionHandler != null) { + if (Platform.isClient()) { + final EntityPlayer player = Minecraft.getMinecraft().player; + final LookDirection ld = Platform.getPlayerRay(player, Platform.getEyeOffset(player)); + + final Iterable bbs = collisionHandler.getSelectedBoundingBoxesFromPool(w, pos, Minecraft.getMinecraft().player, true); + AxisAlignedBB br = null; + + double lastDist = 0; + + for (final AxisAlignedBB bb : bbs) { + this.boundingBox = bb; + + final RayTraceResult r = super.collisionRayTrace(state, w, pos, ld.getA(), ld.getB()); + + this.boundingBox = FULL_BLOCK_AABB; + + if (r != null) { + final double xLen = (ld.getA().x - r.hitVec.x); + final double yLen = (ld.getA().y - r.hitVec.y); + final double zLen = (ld.getA().z - r.hitVec.z); + + final double thisDist = xLen * xLen + yLen * yLen + zLen * zLen; + + if (br == null || lastDist > thisDist) { + lastDist = thisDist; + br = bb; + } + } + } + + if (br != null) { + br = new AxisAlignedBB(br.minX + pos.getX(), br.minY + pos.getY(), br.minZ + pos.getZ(), br.maxX + pos.getX(), br.maxY + pos + .getY(), br.maxZ + pos.getZ()); + return br; + } + } + + AxisAlignedBB b = null; // new AxisAlignedBB( 16d, 16d, 16d, 0d, 0d, 0d ); + + for (final AxisAlignedBB bx : collisionHandler.getSelectedBoundingBoxesFromPool(w, pos, null, false)) { + if (b == null) { + b = bx; + continue; + } + + final double minX = Math.min(b.minX, bx.minX); + final double minY = Math.min(b.minY, bx.minY); + final double minZ = Math.min(b.minZ, bx.minZ); + final double maxX = Math.max(b.maxX, bx.maxX); + final double maxY = Math.max(b.maxY, bx.maxY); + final double maxZ = Math.max(b.maxZ, bx.maxZ); + + b = new AxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ); + } + + if (b == null) { + b = new AxisAlignedBB(16d, 16d, 16d, 0d, 0d, 0d); + } else { + b = new AxisAlignedBB(b.minX + pos.getX(), b.minY + pos.getY(), b.minZ + pos.getZ(), b.maxX + pos.getX(), b.maxY + pos.getY(), b.maxZ + pos + .getZ()); + } + + return b; + } + + return super.getSelectedBoundingBox(state, w, pos); + } + + @Override + public final boolean isOpaqueCube(IBlockState state) { + return this.isOpaque(); + } + + @SuppressWarnings("deprecation") + @Override + public RayTraceResult collisionRayTrace(final IBlockState state, final World w, final BlockPos pos, final Vec3d a, final Vec3d b) { + final ICustomCollision collisionHandler = this.getCustomCollision(w, pos); + + if (collisionHandler != null) { + final Iterable bbs = collisionHandler.getSelectedBoundingBoxesFromPool(w, pos, null, true); + RayTraceResult br = null; + + double lastDist = 0; + + for (final AxisAlignedBB bb : bbs) { + this.boundingBox = bb; + + final RayTraceResult r = super.collisionRayTrace(state, w, pos, a, b); + + this.boundingBox = FULL_BLOCK_AABB; + + if (r != null) { + final double xLen = (a.x - r.hitVec.x); + final double yLen = (a.y - r.hitVec.y); + final double zLen = (a.z - r.hitVec.z); + + final double thisDist = xLen * xLen + yLen * yLen + zLen * zLen; + if (br == null || lastDist > thisDist) { + lastDist = thisDist; + br = r; + } + } + } + + return br; + } + + this.boundingBox = FULL_BLOCK_AABB; + return super.collisionRayTrace(state, w, pos, a, b); + } + + @Override + public boolean hasComparatorInputOverride(IBlockState state) { + return this.isInventory(); + } + + @Override + public int getComparatorInputOverride(IBlockState state, final World worldIn, final BlockPos pos) { + return 0; + } + + @Override + public final boolean isNormalCube(IBlockState state, final IBlockAccess world, final BlockPos pos) { + return this.isFullSize(); + } + + @Override + public boolean rotateBlock(final World w, final BlockPos pos, final EnumFacing axis) { + final IOrientable rotatable = this.getOrientable(w, pos); + + if (rotatable != null && rotatable.canBeRotated()) { + if (this.hasCustomRotation()) { + this.customRotateBlock(rotatable, axis); + return true; + } else { + EnumFacing forward = rotatable.getForward(); + EnumFacing up = rotatable.getUp(); + + for (int rs = 0; rs < 4; rs++) { + forward = Platform.rotateAround(forward, axis); + up = Platform.rotateAround(up, axis); + + if (this.isValidOrientation(w, pos, forward, up)) { + rotatable.setOrientation(forward, up); + return true; + } + } + } + } + + return super.rotateBlock(w, pos, axis); + } + + @Override + public EnumFacing[] getValidRotations(final World w, final BlockPos pos) { + return new EnumFacing[0]; + } + + @SideOnly(Side.CLIENT) + @Override + public void addInformation(final ItemStack is, final World world, final List lines, final ITooltipFlag advancedItemTooltips) { + + } + + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + return false; + } + + public final EnumFacing mapRotation(final IOrientable ori, final EnumFacing dir) { + // case DOWN: return bottomIcon; + // case UP: return blockIcon; + // case NORTH: return northIcon; + // case SOUTH: return southIcon; + // case WEST: return sideIcon; + // case EAST: return sideIcon; + + final EnumFacing forward = ori.getForward(); + final EnumFacing up = ori.getUp(); + + if (forward == null || up == null) { + return dir; + } + + final int west_x = forward.getFrontOffsetY() * up.getFrontOffsetZ() - forward.getFrontOffsetZ() * up.getFrontOffsetY(); + final int west_y = forward.getFrontOffsetZ() * up.getFrontOffsetX() - forward.getFrontOffsetX() * up.getFrontOffsetZ(); + final int west_z = forward.getFrontOffsetX() * up.getFrontOffsetY() - forward.getFrontOffsetY() * up.getFrontOffsetX(); + + EnumFacing west = null; + for (final EnumFacing dx : EnumFacing.VALUES) { + if (dx.getFrontOffsetX() == west_x && dx.getFrontOffsetY() == west_y && dx.getFrontOffsetZ() == west_z) { + west = dx; + } + } + + if (west == null) { + return dir; + } + + if (dir == forward) { + return EnumFacing.SOUTH; + } + if (dir == forward.getOpposite()) { + return EnumFacing.NORTH; + } + + if (dir == up) { + return EnumFacing.UP; + } + if (dir == up.getOpposite()) { + return EnumFacing.DOWN; + } + + if (dir == west) { + return EnumFacing.WEST; + } + if (dir == west.getOpposite()) { + return EnumFacing.EAST; + } + + return null; + } + + @Override + public String toString() { + String regName = this.getRegistryName() != null ? this.getRegistryName().getResourcePath() : "unregistered"; + return this.getClass().getSimpleName() + "[" + regName + "]"; + } + + protected String getUnlocalizedName(final ItemStack is) { + return this.getUnlocalizedName(); + } + + protected boolean hasCustomRotation() { + return false; + } + + protected void customRotateBlock(final IOrientable rotatable, final EnumFacing axis) { + + } + + protected IOrientable getOrientable(final IBlockAccess w, final BlockPos pos) { + if (this instanceof IOrientableBlock) { + IOrientableBlock orientable = (IOrientableBlock) this; + return orientable.getOrientable(w, pos); + } + return null; + } + + protected boolean isValidOrientation(final World w, final BlockPos pos, final EnumFacing forward, final EnumFacing up) { + return true; + } + + protected ICustomCollision getCustomCollision(final World w, final BlockPos pos) { + if (this instanceof ICustomCollision) { + return (ICustomCollision) this; + } + return null; + } + + protected IProperty[] getAEStates() { + return new IProperty[0]; + } + + protected boolean isOpaque() { + return this.isOpaque; + } + + protected boolean setOpaque(final boolean isOpaque) { + this.isOpaque = isOpaque; + return isOpaque; + } + + protected boolean hasSubtypes() { + return this.hasSubtypes; + } + + protected void setHasSubtypes(final boolean hasSubtypes) { + this.hasSubtypes = hasSubtypes; + } + + protected boolean isFullSize() { + return this.isFullSize; + } + + protected boolean setFullSize(final boolean isFullSize) { + this.isFullSize = isFullSize; + return isFullSize; + } + + protected boolean isInventory() { + return this.isInventory; + } + + protected void setInventory(final boolean isInventory) { + this.isInventory = isInventory; + } } diff --git a/src/main/java/appeng/block/AEBaseItemBlock.java b/src/main/java/appeng/block/AEBaseItemBlock.java index 8062cd01d..65161a79c 100644 --- a/src/main/java/appeng/block/AEBaseItemBlock.java +++ b/src/main/java/appeng/block/AEBaseItemBlock.java @@ -19,8 +19,13 @@ package appeng.block; -import java.util.List; - +import appeng.api.util.IOrientable; +import appeng.api.util.IOrientableBlock; +import appeng.block.misc.BlockLightDetector; +import appeng.block.misc.BlockSkyCompass; +import appeng.block.networking.BlockWireless; +import appeng.me.helpers.IGridProxyable; +import appeng.tile.AEBaseTile; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.util.ITooltipFlag; @@ -34,178 +39,137 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.util.IOrientable; -import appeng.api.util.IOrientableBlock; -import appeng.block.misc.BlockLightDetector; -import appeng.block.misc.BlockSkyCompass; -import appeng.block.networking.BlockWireless; -import appeng.me.helpers.IGridProxyable; -import appeng.tile.AEBaseTile; +import java.util.List; -public class AEBaseItemBlock extends ItemBlock -{ +public class AEBaseItemBlock extends ItemBlock { - private final AEBaseBlock blockType; + private final AEBaseBlock blockType; - public AEBaseItemBlock( final Block id ) - { - super( id ); - this.blockType = (AEBaseBlock) id; - this.hasSubtypes = this.blockType.hasSubtypes(); - } + public AEBaseItemBlock(final Block id) { + super(id); + this.blockType = (AEBaseBlock) id; + this.hasSubtypes = this.blockType.hasSubtypes(); + } - @Override - public int getMetadata( final int dmg ) - { - if( this.hasSubtypes ) - { - return dmg; - } - return 0; - } + @Override + public int getMetadata(final int dmg) { + if (this.hasSubtypes) { + return dmg; + } + return 0; + } - @Override - @SideOnly( Side.CLIENT ) - public final void addInformation( final ItemStack itemStack, final World world, final List toolTip, final ITooltipFlag advancedTooltips ) - { - this.addCheckedInformation( itemStack, world, toolTip, advancedTooltips ); - } + @Override + @SideOnly(Side.CLIENT) + public final void addInformation(final ItemStack itemStack, final World world, final List toolTip, final ITooltipFlag advancedTooltips) { + this.addCheckedInformation(itemStack, world, toolTip, advancedTooltips); + } - @SideOnly( Side.CLIENT ) - public void addCheckedInformation( final ItemStack itemStack, final World world, final List toolTip, final ITooltipFlag advancedTooltips ) - { - this.blockType.addInformation( itemStack, world, toolTip, advancedTooltips ); - } + @SideOnly(Side.CLIENT) + public void addCheckedInformation(final ItemStack itemStack, final World world, final List toolTip, final ITooltipFlag advancedTooltips) { + this.blockType.addInformation(itemStack, world, toolTip, advancedTooltips); + } - @Override - public boolean isBookEnchantable( final ItemStack itemstack1, final ItemStack itemstack2 ) - { - return false; - } + @Override + public boolean isBookEnchantable(final ItemStack itemstack1, final ItemStack itemstack2) { + return false; + } - @Override - public String getUnlocalizedName( final ItemStack is ) - { - return this.blockType.getUnlocalizedName( is ); - } + @Override + public String getUnlocalizedName(final ItemStack is) { + return this.blockType.getUnlocalizedName(is); + } - @Override - public boolean placeBlockAt( final ItemStack stack, final EntityPlayer player, final World w, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final IBlockState newState ) - { - EnumFacing up = null; - EnumFacing forward = null; + @Override + public boolean placeBlockAt(final ItemStack stack, final EntityPlayer player, final World w, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final IBlockState newState) { + EnumFacing up = null; + EnumFacing forward = null; - if( this.blockType instanceof AEBaseTileBlock ) - { - if( this.blockType instanceof BlockLightDetector ) - { - up = side; - if( up == EnumFacing.UP || up == EnumFacing.DOWN ) - { - forward = EnumFacing.SOUTH; - } - else - { - forward = EnumFacing.UP; - } - } - else if( this.blockType instanceof BlockWireless || this.blockType instanceof BlockSkyCompass ) - { - forward = side; - if( forward == EnumFacing.UP || forward == EnumFacing.DOWN ) - { - up = EnumFacing.SOUTH; - } - else - { - up = EnumFacing.UP; - } - } - else - { - up = EnumFacing.UP; + if (this.blockType instanceof AEBaseTileBlock) { + if (this.blockType instanceof BlockLightDetector) { + up = side; + if (up == EnumFacing.UP || up == EnumFacing.DOWN) { + forward = EnumFacing.SOUTH; + } else { + forward = EnumFacing.UP; + } + } else if (this.blockType instanceof BlockWireless || this.blockType instanceof BlockSkyCompass) { + forward = side; + if (forward == EnumFacing.UP || forward == EnumFacing.DOWN) { + up = EnumFacing.SOUTH; + } else { + up = EnumFacing.UP; + } + } else { + up = EnumFacing.UP; - final byte rotation = (byte) ( MathHelper.floor( ( player.rotationYaw * 4F ) / 360F + 2.5D ) & 3 ); + final byte rotation = (byte) (MathHelper.floor((player.rotationYaw * 4F) / 360F + 2.5D) & 3); - switch( rotation ) - { - default: - case 0: - forward = EnumFacing.SOUTH; - break; - case 1: - forward = EnumFacing.WEST; - break; - case 2: - forward = EnumFacing.NORTH; - break; - case 3: - forward = EnumFacing.EAST; - break; - } + switch (rotation) { + default: + case 0: + forward = EnumFacing.SOUTH; + break; + case 1: + forward = EnumFacing.WEST; + break; + case 2: + forward = EnumFacing.NORTH; + break; + case 3: + forward = EnumFacing.EAST; + break; + } - if( player.rotationPitch > 65 ) - { - up = forward.getOpposite(); - forward = EnumFacing.UP; - } - else if( player.rotationPitch < -65 ) - { - up = forward.getOpposite(); - forward = EnumFacing.DOWN; - } - } - } + if (player.rotationPitch > 65) { + up = forward.getOpposite(); + forward = EnumFacing.UP; + } else if (player.rotationPitch < -65) { + up = forward.getOpposite(); + forward = EnumFacing.DOWN; + } + } + } - IOrientable ori = null; - if( this.blockType instanceof IOrientableBlock ) - { - ori = ( (IOrientableBlock) this.blockType ).getOrientable( w, pos ); - up = side; - forward = EnumFacing.SOUTH; - if( up.getFrontOffsetY() == 0 ) - { - forward = EnumFacing.UP; - } - } + IOrientable ori = null; + if (this.blockType instanceof IOrientableBlock) { + ori = ((IOrientableBlock) this.blockType).getOrientable(w, pos); + up = side; + forward = EnumFacing.SOUTH; + if (up.getFrontOffsetY() == 0) { + forward = EnumFacing.UP; + } + } - if( !this.blockType.isValidOrientation( w, pos, forward, up ) ) - { - return false; - } + if (!this.blockType.isValidOrientation(w, pos, forward, up)) { + return false; + } - if( super.placeBlockAt( stack, player, w, pos, side, hitX, hitY, hitZ, newState ) ) - { - if( this.blockType instanceof AEBaseTileBlock && !( this.blockType instanceof BlockLightDetector ) ) - { - final AEBaseTile tile = ( (AEBaseTileBlock) this.blockType ).getTileEntity( w, pos ); - ori = tile; + if (super.placeBlockAt(stack, player, w, pos, side, hitX, hitY, hitZ, newState)) { + if (this.blockType instanceof AEBaseTileBlock && !(this.blockType instanceof BlockLightDetector)) { + final AEBaseTile tile = ((AEBaseTileBlock) this.blockType).getTileEntity(w, pos); + ori = tile; - if( tile == null ) - { - return true; - } + if (tile == null) { + return true; + } - if( ori.canBeRotated() && !this.blockType.hasCustomRotation() ) - { - ori.setOrientation( forward, up ); - } + if (ori.canBeRotated() && !this.blockType.hasCustomRotation()) { + ori.setOrientation(forward, up); + } - if( tile instanceof IGridProxyable ) - { - ( (IGridProxyable) tile ).getProxy().setOwner( player ); - } + if (tile instanceof IGridProxyable) { + ((IGridProxyable) tile).getProxy().setOwner(player); + } - tile.onPlacement( stack, player, side ); - } - else if( this.blockType instanceof IOrientableBlock ) - { - ori.setOrientation( forward, up ); - } + tile.onPlacement(stack, player, side); + } else if (this.blockType instanceof IOrientableBlock) { + ori.setOrientation(forward, up); + } - return true; - } - return false; - } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/AEBaseItemBlockChargeable.java b/src/main/java/appeng/block/AEBaseItemBlockChargeable.java index 2b9a16797..918f4db29 100644 --- a/src/main/java/appeng/block/AEBaseItemBlockChargeable.java +++ b/src/main/java/appeng/block/AEBaseItemBlockChargeable.java @@ -19,17 +19,6 @@ package appeng.block; -import java.text.MessageFormat; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.PowerUnits; @@ -38,118 +27,110 @@ import appeng.api.implementations.items.IAEItemPowerStorage; import appeng.core.Api; import appeng.core.localization.GuiText; import appeng.util.Platform; +import net.minecraft.block.Block; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import java.text.MessageFormat; +import java.util.List; -public class AEBaseItemBlockChargeable extends AEBaseItemBlock implements IAEItemPowerStorage -{ +public class AEBaseItemBlockChargeable extends AEBaseItemBlock implements IAEItemPowerStorage { - public AEBaseItemBlockChargeable( final Block id ) - { - super( id ); - } + public AEBaseItemBlockChargeable(final Block id) { + super(id); + } - @Override - @SideOnly( Side.CLIENT ) - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - final NBTTagCompound tag = stack.getTagCompound(); - double internalCurrentPower = 0; - final double internalMaxPower = this.getMaxEnergyCapacity(); + @Override + @SideOnly(Side.CLIENT) + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + final NBTTagCompound tag = stack.getTagCompound(); + double internalCurrentPower = 0; + final double internalMaxPower = this.getMaxEnergyCapacity(); - if( internalMaxPower > 0 ) - { - if( tag != null ) - { - internalCurrentPower = tag.getDouble( "internalCurrentPower" ); - } + if (internalMaxPower > 0) { + if (tag != null) { + internalCurrentPower = tag.getDouble("internalCurrentPower"); + } - final double percent = internalCurrentPower / internalMaxPower; + final double percent = internalCurrentPower / internalMaxPower; - lines.add( GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format( " {0,number,#} ", internalCurrentPower ) + Platform - .gui_localize( PowerUnits.AE.unlocalizedName ) + " - " + MessageFormat.format( " {0,number,#.##%} ", percent ) ); - } - } + lines.add(GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format(" {0,number,#} ", internalCurrentPower) + Platform + .gui_localize(PowerUnits.AE.unlocalizedName) + " - " + MessageFormat.format(" {0,number,#.##%} ", percent)); + } + } - @Override - public double injectAEPower( final ItemStack is, double amount, Actionable mode ) - { - final double internalCurrentPower = this.getInternal( is ); - final double internalMaxPower = this.getAEMaxPower( is ); - final double required = internalMaxPower - internalCurrentPower; - final double overflow = Math.max( 0, amount - required ); + @Override + public double injectAEPower(final ItemStack is, double amount, Actionable mode) { + final double internalCurrentPower = this.getInternal(is); + final double internalMaxPower = this.getAEMaxPower(is); + final double required = internalMaxPower - internalCurrentPower; + final double overflow = Math.max(0, amount - required); - if( mode == Actionable.MODULATE ) - { - final double toAdd = Math.min( required, amount ); - final double newPowerStored = internalCurrentPower + toAdd; + if (mode == Actionable.MODULATE) { + final double toAdd = Math.min(required, amount); + final double newPowerStored = internalCurrentPower + toAdd; - this.setInternal( is, newPowerStored ); - } + this.setInternal(is, newPowerStored); + } - return overflow; - } + return overflow; + } - @Override - public double extractAEPower( final ItemStack is, double amount, Actionable mode ) - { - final double internalCurrentPower = this.getInternal( is ); - final double fulfillable = Math.min( amount, internalCurrentPower ); + @Override + public double extractAEPower(final ItemStack is, double amount, Actionable mode) { + final double internalCurrentPower = this.getInternal(is); + final double fulfillable = Math.min(amount, internalCurrentPower); - if( mode == Actionable.MODULATE ) - { - final double newPowerStored = internalCurrentPower - fulfillable; + if (mode == Actionable.MODULATE) { + final double newPowerStored = internalCurrentPower - fulfillable; - this.setInternal( is, newPowerStored ); - } + this.setInternal(is, newPowerStored); + } - return fulfillable; - } + return fulfillable; + } - @Override - public double getAEMaxPower( final ItemStack is ) - { - return this.getMaxEnergyCapacity(); - } + @Override + public double getAEMaxPower(final ItemStack is) { + return this.getMaxEnergyCapacity(); + } - @Override - public double getAECurrentPower( final ItemStack is ) - { - return this.getInternal( is ); - } + @Override + public double getAECurrentPower(final ItemStack is) { + return this.getInternal(is); + } - @Override - public AccessRestriction getPowerFlow( final ItemStack is ) - { - return AccessRestriction.WRITE; - } + @Override + public AccessRestriction getPowerFlow(final ItemStack is) { + return AccessRestriction.WRITE; + } - private double getMaxEnergyCapacity() - { - final Block blockID = Block.getBlockFromItem( this ); - final IBlockDefinition energyCell = Api.INSTANCE.definitions().blocks().energyCell(); + private double getMaxEnergyCapacity() { + final Block blockID = Block.getBlockFromItem(this); + final IBlockDefinition energyCell = Api.INSTANCE.definitions().blocks().energyCell(); - return energyCell.maybeBlock().map( block -> - { - if( blockID == block ) - { - return 200000; - } - else - { - return 8 * 200000; - } - } ).orElse( 0 ); - } + return energyCell.maybeBlock().map(block -> + { + if (blockID == block) { + return 200000; + } else { + return 8 * 200000; + } + }).orElse(0); + } - private double getInternal( final ItemStack is ) - { - final NBTTagCompound nbt = Platform.openNbtData( is ); - return nbt.getDouble( "internalCurrentPower" ); - } + private double getInternal(final ItemStack is) { + final NBTTagCompound nbt = Platform.openNbtData(is); + return nbt.getDouble("internalCurrentPower"); + } - private void setInternal( final ItemStack is, final double amt ) - { - final NBTTagCompound nbt = Platform.openNbtData( is ); - nbt.setDouble( "internalCurrentPower", amt ); - } + private void setInternal(final ItemStack is, final double amt) { + final NBTTagCompound nbt = Platform.openNbtData(is); + nbt.setDouble("internalCurrentPower", amt); + } } diff --git a/src/main/java/appeng/block/AEBaseStairBlock.java b/src/main/java/appeng/block/AEBaseStairBlock.java index b426dd23b..36ddfb142 100644 --- a/src/main/java/appeng/block/AEBaseStairBlock.java +++ b/src/main/java/appeng/block/AEBaseStairBlock.java @@ -20,31 +20,27 @@ package appeng.block; import com.google.common.base.Preconditions; - import net.minecraft.block.Block; import net.minecraft.block.BlockStairs; -public abstract class AEBaseStairBlock extends BlockStairs -{ +public abstract class AEBaseStairBlock extends BlockStairs { - protected AEBaseStairBlock( final Block block, final String type ) - { - super( block.getDefaultState() ); + protected AEBaseStairBlock(final Block block, final String type) { + super(block.getDefaultState()); - Preconditions.checkNotNull( block ); - Preconditions.checkNotNull( block.getUnlocalizedName() ); - Preconditions.checkArgument( block.getUnlocalizedName().length() > 0 ); + Preconditions.checkNotNull(block); + Preconditions.checkNotNull(block.getUnlocalizedName()); + Preconditions.checkArgument(block.getUnlocalizedName().length() > 0); - this.setUnlocalizedName( "stair." + type ); - this.setLightOpacity( 0 ); - } + this.setUnlocalizedName("stair." + type); + this.setLightOpacity(0); + } - @Override - public String toString() - { - String regName = this.getRegistryName() != null ? this.getRegistryName().getResourcePath() : "unregistered"; - return this.getClass().getSimpleName() + "[" + regName + "]"; - } + @Override + public String toString() { + String regName = this.getRegistryName() != null ? this.getRegistryName().getResourcePath() : "unregistered"; + return this.getClass().getSimpleName() + "[" + regName + "]"; + } } diff --git a/src/main/java/appeng/block/AEBaseTileBlock.java b/src/main/java/appeng/block/AEBaseTileBlock.java index f5a6c0e61..89b7bd768 100644 --- a/src/main/java/appeng/block/AEBaseTileBlock.java +++ b/src/main/java/appeng/block/AEBaseTileBlock.java @@ -19,17 +19,23 @@ package appeng.block; -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - +import appeng.api.implementations.items.IMemoryCard; +import appeng.api.implementations.items.MemoryCardMessages; +import appeng.api.implementations.tiles.IColorableTile; +import appeng.api.util.AEColor; import appeng.api.util.AEPartLocation; +import appeng.api.util.IOrientable; +import appeng.block.networking.BlockCableBus; import appeng.core.sync.GuiBridge; +import appeng.helpers.ICustomCollision; import appeng.items.tools.quartz.ToolQuartzCuttingKnife; +import appeng.tile.AEBaseInvTile; +import appeng.tile.AEBaseTile; +import appeng.tile.networking.TileCableBus; +import appeng.tile.storage.TileSkyChest; +import appeng.util.Platform; +import appeng.util.SettingsFrom; import com.google.common.collect.Lists; - import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.Material; @@ -52,354 +58,284 @@ import net.minecraftforge.common.property.IUnlistedProperty; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.items.ItemHandlerHelper; -import appeng.api.implementations.items.IMemoryCard; -import appeng.api.implementations.items.MemoryCardMessages; -import appeng.api.implementations.tiles.IColorableTile; -import appeng.api.util.AEColor; -import appeng.api.util.IOrientable; -import appeng.block.networking.BlockCableBus; -import appeng.helpers.ICustomCollision; -import appeng.tile.AEBaseInvTile; -import appeng.tile.AEBaseTile; -import appeng.tile.networking.TileCableBus; -import appeng.tile.storage.TileSkyChest; -import appeng.util.Platform; -import appeng.util.SettingsFrom; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; -public abstract class AEBaseTileBlock extends AEBaseBlock implements ITileEntityProvider -{ +public abstract class AEBaseTileBlock extends AEBaseBlock implements ITileEntityProvider { - @Nonnull - private Class tileEntityType; + @Nonnull + private Class tileEntityType; - public AEBaseTileBlock( final Material mat ) - { - super( mat ); - } + public AEBaseTileBlock(final Material mat) { + super(mat); + } - public static final UnlistedDirection FORWARD = new UnlistedDirection( "forward" ); - public static final UnlistedDirection UP = new UnlistedDirection( "up" ); + public static final UnlistedDirection FORWARD = new UnlistedDirection("forward"); + public static final UnlistedDirection UP = new UnlistedDirection("up"); - @Override - public IBlockState getExtendedState( IBlockState state, IBlockAccess world, BlockPos pos ) - { - // A subclass may decide it doesn't want extended block state for whatever reason - if( !( state instanceof IExtendedBlockState ) ) - { - return state; - } + @Override + public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { + // A subclass may decide it doesn't want extended block state for whatever reason + if (!(state instanceof IExtendedBlockState)) { + return state; + } - AEBaseTile tile = this.getTileEntity( world, pos ); - if( tile == null ) - { - return state; // No info available - } + AEBaseTile tile = this.getTileEntity(world, pos); + if (tile == null) { + return state; // No info available + } - IExtendedBlockState extState = (IExtendedBlockState) state; - return extState.withProperty( FORWARD, tile.getForward() ).withProperty( UP, tile.getUp() ); - } + IExtendedBlockState extState = (IExtendedBlockState) state; + return extState.withProperty(FORWARD, tile.getForward()).withProperty(UP, tile.getUp()); + } - @Override - protected BlockStateContainer createBlockState() - { - return new ExtendedBlockState( this, this.getAEStates(), new IUnlistedProperty[] { - FORWARD, - UP - } ); - } + @Override + protected BlockStateContainer createBlockState() { + return new ExtendedBlockState(this, this.getAEStates(), new IUnlistedProperty[]{ + FORWARD, + UP + }); + } - @Override - public int getMetaFromState( IBlockState state ) - { - return 0; - } + @Override + public int getMetaFromState(IBlockState state) { + return 0; + } - // TODO : Was this change needed? - public void setTileEntity( final Class c ) - { - this.tileEntityType = c; - this.setInventory( AEBaseInvTile.class.isAssignableFrom( c ) ); - } + // TODO : Was this change needed? + public void setTileEntity(final Class c) { + this.tileEntityType = c; + this.setInventory(AEBaseInvTile.class.isAssignableFrom(c)); + } - @Override - public boolean hasTileEntity( IBlockState state ) - { - return this.hasBlockTileEntity(); - } + @Override + public boolean hasTileEntity(IBlockState state) { + return this.hasBlockTileEntity(); + } - private boolean hasBlockTileEntity() - { - return this.tileEntityType != null; - } + private boolean hasBlockTileEntity() { + return this.tileEntityType != null; + } - public Class getTileEntityClass() - { - return this.tileEntityType; - } + public Class getTileEntityClass() { + return this.tileEntityType; + } - @Nullable - public T getTileEntity( final IBlockAccess w, final int x, final int y, final int z ) - { - return this.getTileEntity( w, new BlockPos( x, y, z ) ); - } + @Nullable + public T getTileEntity(final IBlockAccess w, final int x, final int y, final int z) { + return this.getTileEntity(w, new BlockPos(x, y, z)); + } - @Nullable - public T getTileEntity( final IBlockAccess w, final BlockPos pos ) - { - if( !this.hasBlockTileEntity() ) - { - return null; - } + @Nullable + public T getTileEntity(final IBlockAccess w, final BlockPos pos) { + if (!this.hasBlockTileEntity()) { + return null; + } - final TileEntity te = w.getTileEntity( pos ); - if( this.tileEntityType.isInstance( te ) ) - { - return (T) te; - } + final TileEntity te = w.getTileEntity(pos); + if (this.tileEntityType.isInstance(te)) { + return (T) te; + } - return null; - } + return null; + } - @Override - public final TileEntity createNewTileEntity( final World var1, final int var2 ) - { - if( this.hasBlockTileEntity() ) - { - try - { - return this.tileEntityType.newInstance(); - } - catch( final InstantiationException e ) - { - throw new IllegalStateException( "Failed to create a new instance of an illegal class " + this.tileEntityType, e ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( "Failed to create a new instance of " + this.tileEntityType + ", because lack of permissions", e ); - } - } + @Override + public final TileEntity createNewTileEntity(final World var1, final int var2) { + if (this.hasBlockTileEntity()) { + try { + return this.tileEntityType.newInstance(); + } catch (final InstantiationException e) { + throw new IllegalStateException("Failed to create a new instance of an illegal class " + this.tileEntityType, e); + } catch (final IllegalAccessException e) { + throw new IllegalStateException("Failed to create a new instance of " + this.tileEntityType + ", because lack of permissions", e); + } + } - return null; - } + return null; + } - @Override - public void breakBlock( final World w, final BlockPos pos, final IBlockState state ) - { - final AEBaseTile te = this.getTileEntity( w, pos ); - if( te != null ) - { - final ArrayList drops = new ArrayList<>(); - if( te.dropItems() ) - { - te.getDrops( w, pos, drops ); - } - else - { - te.getNoDrops( w, pos, drops ); - } + @Override + public void breakBlock(final World w, final BlockPos pos, final IBlockState state) { + final AEBaseTile te = this.getTileEntity(w, pos); + if (te != null) { + final ArrayList drops = new ArrayList<>(); + if (te.dropItems()) { + te.getDrops(w, pos, drops); + } else { + te.getNoDrops(w, pos, drops); + } - // Cry ;_; ... - Platform.spawnDrops( w, pos, drops ); - } + // Cry ;_; ... + Platform.spawnDrops(w, pos, drops); + } - // super will remove the TE, as it is not an instance of BlockContainer - super.breakBlock( w, pos, state ); - } + // super will remove the TE, as it is not an instance of BlockContainer + super.breakBlock(w, pos, state); + } - @Override - public final EnumFacing[] getValidRotations( final World w, final BlockPos pos ) - { - final AEBaseTile obj = this.getTileEntity( w, pos ); - if( obj != null && obj.canBeRotated() ) - { - return EnumFacing.VALUES; - } + @Override + public final EnumFacing[] getValidRotations(final World w, final BlockPos pos) { + final AEBaseTile obj = this.getTileEntity(w, pos); + if (obj != null && obj.canBeRotated()) { + return EnumFacing.VALUES; + } - return super.getValidRotations( w, pos ); - } + return super.getValidRotations(w, pos); + } - @Override - public boolean recolorBlock( final World world, final BlockPos pos, final EnumFacing side, final EnumDyeColor color ) - { - final TileEntity te = this.getTileEntity( world, pos ); + @Override + public boolean recolorBlock(final World world, final BlockPos pos, final EnumFacing side, final EnumDyeColor color) { + final TileEntity te = this.getTileEntity(world, pos); - if( te instanceof IColorableTile ) - { - final IColorableTile ct = (IColorableTile) te; - final AEColor c = ct.getColor(); - final AEColor newColor = AEColor.values()[color.getMetadata()]; + if (te instanceof IColorableTile) { + final IColorableTile ct = (IColorableTile) te; + final AEColor c = ct.getColor(); + final AEColor newColor = AEColor.values()[color.getMetadata()]; - if( c != newColor ) - { - ct.recolourBlock( side, newColor, null ); - return true; - } - return false; - } + if (c != newColor) { + ct.recolourBlock(side, newColor, null); + return true; + } + return false; + } - return super.recolorBlock( world, pos, side, color ); - } + return super.recolorBlock(world, pos, side, color); + } - @Override - public int getComparatorInputOverride( IBlockState state, final World w, final BlockPos pos ) - { - final TileEntity te = this.getTileEntity( w, pos ); - if( te instanceof AEBaseInvTile ) - { - AEBaseInvTile invTile = (AEBaseInvTile) te; - if( invTile.getInternalInventory().getSlots() > 0 ) - { - return ItemHandlerHelper.calcRedstoneFromInventory( invTile.getInternalInventory() ); - } - } - return 0; - } + @Override + public int getComparatorInputOverride(IBlockState state, final World w, final BlockPos pos) { + final TileEntity te = this.getTileEntity(w, pos); + if (te instanceof AEBaseInvTile) { + AEBaseInvTile invTile = (AEBaseInvTile) te; + if (invTile.getInternalInventory().getSlots() > 0) { + return ItemHandlerHelper.calcRedstoneFromInventory(invTile.getInternalInventory()); + } + } + return 0; + } - @Override - public boolean eventReceived( final IBlockState state, final World worldIn, final BlockPos pos, final int eventID, final int eventParam ) - { - super.eventReceived( state, worldIn, pos, eventID, eventParam ); - final TileEntity tileentity = worldIn.getTileEntity( pos ); - return tileentity != null ? tileentity.receiveClientEvent( eventID, eventParam ) : false; - } + @Override + public boolean eventReceived(final IBlockState state, final World worldIn, final BlockPos pos, final int eventID, final int eventParam) { + super.eventReceived(state, worldIn, pos, eventID, eventParam); + final TileEntity tileentity = worldIn.getTileEntity(pos); + return tileentity != null && tileentity.receiveClientEvent(eventID, eventParam); + } - @Override - public void onBlockPlacedBy( final World w, final BlockPos pos, final IBlockState state, final EntityLivingBase placer, final ItemStack is ) - { - if( is.hasDisplayName() ) - { - final TileEntity te = this.getTileEntity( w, pos ); - if( te instanceof AEBaseTile ) - { - ( (AEBaseTile) w.getTileEntity( pos ) ).setName( is.getDisplayName() ); - } - } - } + @Override + public void onBlockPlacedBy(final World w, final BlockPos pos, final IBlockState state, final EntityLivingBase placer, final ItemStack is) { + if (is.hasDisplayName()) { + final TileEntity te = this.getTileEntity(w, pos); + if (te instanceof AEBaseTile) { + ((AEBaseTile) w.getTileEntity(pos)).setName(is.getDisplayName()); + } + } + } - @Override - public boolean onBlockActivated( World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ ) - { - ItemStack heldItem; - if( player != null && !player.getHeldItem( hand ).isEmpty() ) - { - heldItem = player.getHeldItem( hand ); + @Override + public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { + ItemStack heldItem; + if (player != null && !player.getHeldItem(hand).isEmpty()) { + heldItem = player.getHeldItem(hand); - if( Platform.isWrench( player, heldItem, pos ) && player.isSneaking() ) - { - final IBlockState blockState = world.getBlockState( pos ); - final Block block = blockState.getBlock(); + if (Platform.isWrench(player, heldItem, pos) && player.isSneaking()) { + final IBlockState blockState = world.getBlockState(pos); + final Block block = blockState.getBlock(); - if( block == null ) - { - return false; - } + if (block == null) { + return false; + } - final AEBaseTile tile = this.getTileEntity( world, pos ); + final AEBaseTile tile = this.getTileEntity(world, pos); - if( tile == null ) - { - return false; - } + if (tile == null) { + return false; + } - if( tile instanceof TileCableBus || tile instanceof TileSkyChest ) - { - return false; - } + if (tile instanceof TileCableBus || tile instanceof TileSkyChest) { + return false; + } - final ItemStack[] itemDropCandidates = Platform.getBlockDrops( world, pos ); - final ItemStack op = new ItemStack( this ); + final ItemStack[] itemDropCandidates = Platform.getBlockDrops(world, pos); + final ItemStack op = new ItemStack(this); - for( final ItemStack ol : itemDropCandidates ) - { - if( Platform.itemComparisons().isEqualItemType( ol, op ) ) - { - final NBTTagCompound tag = tile.downloadSettings( SettingsFrom.DISMANTLE_ITEM ); - if( tag != null ) - { - ol.setTagCompound( tag ); - } - } - } + for (final ItemStack ol : itemDropCandidates) { + if (Platform.itemComparisons().isEqualItemType(ol, op)) { + final NBTTagCompound tag = tile.downloadSettings(SettingsFrom.DISMANTLE_ITEM); + if (tag != null) { + ol.setTagCompound(tag); + } + } + } - if( block.removedByPlayer( blockState, world, pos, player, false ) ) - { - final List itemsToDrop = Lists.newArrayList( itemDropCandidates ); - Platform.spawnDrops( world, pos, itemsToDrop ); - world.setBlockToAir( pos ); - } + if (block.removedByPlayer(blockState, world, pos, player, false)) { + final List itemsToDrop = Lists.newArrayList(itemDropCandidates); + Platform.spawnDrops(world, pos, itemsToDrop); + world.setBlockToAir(pos); + } - return false; - } + return false; + } - if( heldItem.getItem() instanceof IMemoryCard && !( this instanceof BlockCableBus ) ) - { - final IMemoryCard memoryCard = (IMemoryCard) heldItem.getItem(); - final AEBaseTile tileEntity = this.getTileEntity( world, pos ); + if (heldItem.getItem() instanceof IMemoryCard && !(this instanceof BlockCableBus)) { + final IMemoryCard memoryCard = (IMemoryCard) heldItem.getItem(); + final AEBaseTile tileEntity = this.getTileEntity(world, pos); - if( tileEntity == null ) - { - return false; - } + if (tileEntity == null) { + return false; + } - final String name = this.getUnlocalizedName(); + final String name = this.getUnlocalizedName(); - if( player.isSneaking() ) - { - final NBTTagCompound data = tileEntity.downloadSettings( SettingsFrom.MEMORY_CARD ); - if( data != null ) - { - memoryCard.setMemoryCardContents( heldItem, name, data ); - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_SAVED ); - } - } - else - { - final String savedName = memoryCard.getSettingsName( heldItem ); - final NBTTagCompound data = memoryCard.getData( heldItem ); + if (player.isSneaking()) { + final NBTTagCompound data = tileEntity.downloadSettings(SettingsFrom.MEMORY_CARD); + if (data != null) { + memoryCard.setMemoryCardContents(heldItem, name, data); + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_SAVED); + } + } else { + final String savedName = memoryCard.getSettingsName(heldItem); + final NBTTagCompound data = memoryCard.getData(heldItem); - if( this.getUnlocalizedName().equals( savedName ) ) - { - tileEntity.uploadSettings( SettingsFrom.MEMORY_CARD, data ); - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_LOADED ); - } - else - { - memoryCard.notifyUser( player, MemoryCardMessages.INVALID_MACHINE ); - } - } + if (this.getUnlocalizedName().equals(savedName)) { + tileEntity.uploadSettings(SettingsFrom.MEMORY_CARD, data); + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_LOADED); + } else { + memoryCard.notifyUser(player, MemoryCardMessages.INVALID_MACHINE); + } + } - return true; - } + return true; + } - if (heldItem.getItem() instanceof ToolQuartzCuttingKnife && !(this instanceof BlockCableBus)) { - if (ForgeEventFactory.onItemUseStart(player, heldItem, 1) <= 0) return false; - final AEBaseTile tile = this.getTileEntity(world, pos); - if (tile == null) return false; - Platform.openGUI(player, tile, AEPartLocation.fromFacing(facing), GuiBridge.GUI_RENAMER); - return true; - } - } + if (heldItem.getItem() instanceof ToolQuartzCuttingKnife && !(this instanceof BlockCableBus)) { + if (ForgeEventFactory.onItemUseStart(player, heldItem, 1) <= 0) return false; + final AEBaseTile tile = this.getTileEntity(world, pos); + if (tile == null) return false; + Platform.openGUI(player, tile, AEPartLocation.fromFacing(facing), GuiBridge.GUI_RENAMER); + return true; + } + } - return this.onActivated( world, pos, player, hand, player.getHeldItem( hand ), facing, hitX, hitY, hitZ ); - } + return this.onActivated(world, pos, player, hand, player.getHeldItem(hand), facing, hitX, hitY, hitZ); + } - @Override - public IOrientable getOrientable( final IBlockAccess w, final BlockPos pos ) - { - return this.getTileEntity( w, pos ); - } + @Override + public IOrientable getOrientable(final IBlockAccess w, final BlockPos pos) { + return this.getTileEntity(w, pos); + } - @Override - public ICustomCollision getCustomCollision( final World w, final BlockPos pos ) - { - final AEBaseTile te = this.getTileEntity( w, pos ); - if( te instanceof ICustomCollision ) - { - return (ICustomCollision) te; - } + @Override + public ICustomCollision getCustomCollision(final World w, final BlockPos pos) { + final AEBaseTile te = this.getTileEntity(w, pos); + if (te instanceof ICustomCollision) { + return (ICustomCollision) te; + } - return super.getCustomCollision( w, pos ); - } + return super.getCustomCollision(w, pos); + } } diff --git a/src/main/java/appeng/block/AEDecorativeBlock.java b/src/main/java/appeng/block/AEDecorativeBlock.java index 3a554d71d..4e9c52861 100644 --- a/src/main/java/appeng/block/AEDecorativeBlock.java +++ b/src/main/java/appeng/block/AEDecorativeBlock.java @@ -22,10 +22,8 @@ package appeng.block; import net.minecraft.block.material.Material; -public abstract class AEDecorativeBlock extends AEBaseBlock -{ - public AEDecorativeBlock( final Material mat ) - { - super( mat ); - } +public abstract class AEDecorativeBlock extends AEBaseBlock { + public AEDecorativeBlock(final Material mat) { + super(mat); + } } diff --git a/src/main/java/appeng/block/UnlistedBlockAccess.java b/src/main/java/appeng/block/UnlistedBlockAccess.java index 80eee4c7f..0ad762eda 100644 --- a/src/main/java/appeng/block/UnlistedBlockAccess.java +++ b/src/main/java/appeng/block/UnlistedBlockAccess.java @@ -23,29 +23,24 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.property.IUnlistedProperty; -public final class UnlistedBlockAccess implements IUnlistedProperty -{ - @Override - public String getName() - { - return "ba"; - } +public final class UnlistedBlockAccess implements IUnlistedProperty { + @Override + public String getName() { + return "ba"; + } - @Override - public boolean isValid( final IBlockAccess value ) - { - return true; - } + @Override + public boolean isValid(final IBlockAccess value) { + return true; + } - @Override - public Class getType() - { - return IBlockAccess.class; - } + @Override + public Class getType() { + return IBlockAccess.class; + } - @Override - public String valueToString( final IBlockAccess value ) - { - return null; - } + @Override + public String valueToString(final IBlockAccess value) { + return null; + } } \ No newline at end of file diff --git a/src/main/java/appeng/block/UnlistedBlockPos.java b/src/main/java/appeng/block/UnlistedBlockPos.java index 1cdd4793c..4eda8a37c 100644 --- a/src/main/java/appeng/block/UnlistedBlockPos.java +++ b/src/main/java/appeng/block/UnlistedBlockPos.java @@ -23,29 +23,24 @@ import net.minecraft.util.math.BlockPos; import net.minecraftforge.common.property.IUnlistedProperty; -public final class UnlistedBlockPos implements IUnlistedProperty -{ - @Override - public String getName() - { - return "pos"; - } +public final class UnlistedBlockPos implements IUnlistedProperty { + @Override + public String getName() { + return "pos"; + } - @Override - public boolean isValid( final BlockPos value ) - { - return true; - } + @Override + public boolean isValid(final BlockPos value) { + return true; + } - @Override - public Class getType() - { - return BlockPos.class; - } + @Override + public Class getType() { + return BlockPos.class; + } - @Override - public String valueToString( final BlockPos value ) - { - return null; - } + @Override + public String valueToString(final BlockPos value) { + return null; + } } \ No newline at end of file diff --git a/src/main/java/appeng/block/UnlistedDirection.java b/src/main/java/appeng/block/UnlistedDirection.java index 3e4639d80..66e41df2f 100644 --- a/src/main/java/appeng/block/UnlistedDirection.java +++ b/src/main/java/appeng/block/UnlistedDirection.java @@ -23,38 +23,32 @@ import net.minecraft.util.EnumFacing; import net.minecraftforge.common.property.IUnlistedProperty; -public class UnlistedDirection implements IUnlistedProperty -{ +public class UnlistedDirection implements IUnlistedProperty { - private final String name; + private final String name; - public UnlistedDirection( String name ) - { - this.name = name; - } + public UnlistedDirection(String name) { + this.name = name; + } - @Override - public String getName() - { - return this.name; - } + @Override + public String getName() { + return this.name; + } - @Override - public boolean isValid( EnumFacing value ) - { - return value != null; - } + @Override + public boolean isValid(EnumFacing value) { + return value != null; + } - @Override - public Class getType() - { - return EnumFacing.class; - } + @Override + public Class getType() { + return EnumFacing.class; + } - @Override - public String valueToString( EnumFacing value ) - { - return value.getName(); - } + @Override + public String valueToString(EnumFacing value) { + return value.getName(); + } } diff --git a/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java b/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java index a237a0af6..345eff732 100644 --- a/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java +++ b/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java @@ -19,6 +19,9 @@ package appeng.block.crafting; +import appeng.api.util.AEColor; +import appeng.client.UnlistedProperty; +import appeng.tile.crafting.TileCraftingMonitorTile; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; @@ -33,57 +36,47 @@ import net.minecraftforge.common.property.IUnlistedProperty; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.util.AEColor; -import appeng.client.UnlistedProperty; -import appeng.tile.crafting.TileCraftingMonitorTile; +public class BlockCraftingMonitor extends BlockCraftingUnit { -public class BlockCraftingMonitor extends BlockCraftingUnit -{ + public static final UnlistedProperty COLOR = new UnlistedProperty<>("color", AEColor.class); - public static final UnlistedProperty COLOR = new UnlistedProperty<>( "color", AEColor.class ); + public BlockCraftingMonitor() { + super(CraftingUnitType.MONITOR); + } - public BlockCraftingMonitor() - { - super( CraftingUnitType.MONITOR ); - } + @Override + protected BlockStateContainer createBlockState() { + return new ExtendedBlockState(this, this.getAEStates(), new IUnlistedProperty[]{ + STATE, + COLOR, + FORWARD, + UP + }); + } - @Override - protected BlockStateContainer createBlockState() - { - return new ExtendedBlockState( this, this.getAEStates(), new IUnlistedProperty[] { - STATE, - COLOR, - FORWARD, - UP - } ); - } + @Override + public IExtendedBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { + AEColor color = AEColor.TRANSPARENT; + EnumFacing forward = EnumFacing.NORTH; + EnumFacing up = EnumFacing.UP; - @Override - public IExtendedBlockState getExtendedState( IBlockState state, IBlockAccess world, BlockPos pos ) - { - AEColor color = AEColor.TRANSPARENT; - EnumFacing forward = EnumFacing.NORTH; - EnumFacing up = EnumFacing.UP; + TileCraftingMonitorTile te = this.getTileEntity(world, pos); + if (te != null) { + color = te.getColor(); + forward = te.getForward(); + up = te.getUp(); + } - TileCraftingMonitorTile te = this.getTileEntity( world, pos ); - if( te != null ) - { - color = te.getColor(); - forward = te.getForward(); - up = te.getUp(); - } + return super.getExtendedState(state, world, pos) + .withProperty(COLOR, color) + .withProperty(FORWARD, forward) + .withProperty(UP, up); + } - return super.getExtendedState( state, world, pos ) - .withProperty( COLOR, color ) - .withProperty( FORWARD, forward ) - .withProperty( UP, up ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void getSubBlocks( final CreativeTabs tabs, final NonNullList itemStacks ) - { - itemStacks.add( new ItemStack( this, 1, 0 ) ); - } + @Override + @SideOnly(Side.CLIENT) + public void getSubBlocks(final CreativeTabs tabs, final NonNullList itemStacks) { + itemStacks.add(new ItemStack(this, 1, 0)); + } } diff --git a/src/main/java/appeng/block/crafting/BlockCraftingStorage.java b/src/main/java/appeng/block/crafting/BlockCraftingStorage.java index 103387560..8d99a3387 100644 --- a/src/main/java/appeng/block/crafting/BlockCraftingStorage.java +++ b/src/main/java/appeng/block/crafting/BlockCraftingStorage.java @@ -19,12 +19,10 @@ package appeng.block.crafting; -public class BlockCraftingStorage extends BlockCraftingUnit -{ +public class BlockCraftingStorage extends BlockCraftingUnit { - public BlockCraftingStorage( final CraftingUnitType type ) - { - super( type ); - } + public BlockCraftingStorage(final CraftingUnitType type) { + super(type); + } } diff --git a/src/main/java/appeng/block/crafting/BlockCraftingUnit.java b/src/main/java/appeng/block/crafting/BlockCraftingUnit.java index 0cb8ce7f7..78648f39e 100644 --- a/src/main/java/appeng/block/crafting/BlockCraftingUnit.java +++ b/src/main/java/appeng/block/crafting/BlockCraftingUnit.java @@ -19,8 +19,13 @@ package appeng.block.crafting; -import java.util.EnumSet; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.client.UnlistedProperty; +import appeng.client.render.crafting.CraftingCubeState; +import appeng.core.sync.GuiBridge; +import appeng.tile.crafting.TileCraftingTile; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -38,130 +43,105 @@ import net.minecraftforge.common.property.ExtendedBlockState; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.common.property.IUnlistedProperty; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.client.UnlistedProperty; -import appeng.client.render.crafting.CraftingCubeState; -import appeng.core.sync.GuiBridge; -import appeng.tile.crafting.TileCraftingTile; -import appeng.util.Platform; +import java.util.EnumSet; -public class BlockCraftingUnit extends AEBaseTileBlock -{ - public static final PropertyBool FORMED = PropertyBool.create( "formed" ); - public static final PropertyBool POWERED = PropertyBool.create( "powered" ); - public static final UnlistedProperty STATE = new UnlistedProperty<>( "state", CraftingCubeState.class ); +public class BlockCraftingUnit extends AEBaseTileBlock { + public static final PropertyBool FORMED = PropertyBool.create("formed"); + public static final PropertyBool POWERED = PropertyBool.create("powered"); + public static final UnlistedProperty STATE = new UnlistedProperty<>("state", CraftingCubeState.class); - public final CraftingUnitType type; + public final CraftingUnitType type; - public BlockCraftingUnit( final CraftingUnitType type ) - { - super( Material.IRON ); + public BlockCraftingUnit(final CraftingUnitType type) { + super(Material.IRON); - this.type = type; - } + this.type = type; + } - @Override - protected IProperty[] getAEStates() - { - return new IProperty[] { POWERED, FORMED }; - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{POWERED, FORMED}; + } - @Override - public IExtendedBlockState getExtendedState( IBlockState state, IBlockAccess world, BlockPos pos ) - { + @Override + public IExtendedBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { - EnumSet connections = EnumSet.noneOf( EnumFacing.class ); + EnumSet connections = EnumSet.noneOf(EnumFacing.class); - for( EnumFacing facing : EnumFacing.values() ) - { - if( this.isConnected( world, pos, facing ) ) - { - connections.add( facing ); - } - } + for (EnumFacing facing : EnumFacing.values()) { + if (this.isConnected(world, pos, facing)) { + connections.add(facing); + } + } - IExtendedBlockState extState = (IExtendedBlockState) state; + IExtendedBlockState extState = (IExtendedBlockState) state; - return extState.withProperty( STATE, new CraftingCubeState( connections ) ); - } + return extState.withProperty(STATE, new CraftingCubeState(connections)); + } - private boolean isConnected( IBlockAccess world, BlockPos pos, EnumFacing side ) - { - BlockPos adjacentPos = pos.offset( side ); - return world.getBlockState( adjacentPos ).getBlock() instanceof BlockCraftingUnit; - } + private boolean isConnected(IBlockAccess world, BlockPos pos, EnumFacing side) { + BlockPos adjacentPos = pos.offset(side); + return world.getBlockState(adjacentPos).getBlock() instanceof BlockCraftingUnit; + } - @Override - protected BlockStateContainer createBlockState() - { - return new ExtendedBlockState( this, this.getAEStates(), new IUnlistedProperty[] { STATE } ); - } + @Override + protected BlockStateContainer createBlockState() { + return new ExtendedBlockState(this, this.getAEStates(), new IUnlistedProperty[]{STATE}); + } - @Override - public IBlockState getStateFromMeta( final int meta ) - { - return this.getDefaultState().withProperty( POWERED, ( meta & 1 ) == 1 ).withProperty( FORMED, ( meta & 2 ) == 2 ); - } + @Override + public IBlockState getStateFromMeta(final int meta) { + return this.getDefaultState().withProperty(POWERED, (meta & 1) == 1).withProperty(FORMED, (meta & 2) == 2); + } - @Override - public int getMetaFromState( final IBlockState state ) - { - boolean p = state.getValue( POWERED ); - boolean f = state.getValue( FORMED ); - return ( p ? 1 : 0 ) | ( f ? 2 : 0 ); - } + @Override + public int getMetaFromState(final IBlockState state) { + boolean p = state.getValue(POWERED); + boolean f = state.getValue(FORMED); + return (p ? 1 : 0) | (f ? 2 : 0); + } - @Override - public void neighborChanged( final IBlockState state, final World worldIn, final BlockPos pos, final Block blockIn, final BlockPos fromPos ) - { - final TileCraftingTile cp = this.getTileEntity( worldIn, pos ); - if( cp != null ) - { - cp.updateMultiBlock(); - } - } + @Override + public void neighborChanged(final IBlockState state, final World worldIn, final BlockPos pos, final Block blockIn, final BlockPos fromPos) { + final TileCraftingTile cp = this.getTileEntity(worldIn, pos); + if (cp != null) { + cp.updateMultiBlock(); + } + } - @Override - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } + @Override + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } - @Override - public void breakBlock( final World w, final BlockPos pos, final IBlockState state ) - { - final TileCraftingTile cp = this.getTileEntity( w, pos ); - if( cp != null ) - { - cp.breakCluster(); - } + @Override + public void breakBlock(final World w, final BlockPos pos, final IBlockState state) { + final TileCraftingTile cp = this.getTileEntity(w, pos); + if (cp != null) { + cp.breakCluster(); + } - super.breakBlock( w, pos, state ); - } + super.breakBlock(w, pos, state); + } - @Override - public boolean onBlockActivated( final World w, final BlockPos pos, final IBlockState state, final EntityPlayer p, final EnumHand hand, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - final TileCraftingTile tg = this.getTileEntity( w, pos ); + @Override + public boolean onBlockActivated(final World w, final BlockPos pos, final IBlockState state, final EntityPlayer p, final EnumHand hand, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + final TileCraftingTile tg = this.getTileEntity(w, pos); - if( tg != null && !p.isSneaking() && tg.isFormed() && tg.isActive() ) - { - if( Platform.isClient() ) - { - return true; - } + if (tg != null && !p.isSneaking() && tg.isFormed() && tg.isActive()) { + if (Platform.isClient()) { + return true; + } - Platform.openGUI( p, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_CRAFTING_CPU ); - return true; - } + Platform.openGUI(p, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_CRAFTING_CPU); + return true; + } - return super.onBlockActivated( w, pos, state, p, hand, side, hitX, hitY, hitZ ); - } + return super.onBlockActivated(w, pos, state, p, hand, side, hitX, hitY, hitZ); + } - public enum CraftingUnitType - { - UNIT, ACCELERATOR, STORAGE_1K, STORAGE_4K, STORAGE_16K, STORAGE_64K, MONITOR - } + public enum CraftingUnitType { + UNIT, ACCELERATOR, STORAGE_1K, STORAGE_4K, STORAGE_16K, STORAGE_64K, MONITOR + } } diff --git a/src/main/java/appeng/block/crafting/BlockMolecularAssembler.java b/src/main/java/appeng/block/crafting/BlockMolecularAssembler.java index 60f3dbdb8..95a00f028 100644 --- a/src/main/java/appeng/block/crafting/BlockMolecularAssembler.java +++ b/src/main/java/appeng/block/crafting/BlockMolecularAssembler.java @@ -19,6 +19,11 @@ package appeng.block.crafting; +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.core.sync.GuiBridge; +import appeng.tile.crafting.TileMolecularAssembler; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -33,89 +38,71 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.core.sync.GuiBridge; -import appeng.tile.crafting.TileMolecularAssembler; -import appeng.util.Platform; +public class BlockMolecularAssembler extends AEBaseTileBlock { -public class BlockMolecularAssembler extends AEBaseTileBlock -{ + public static final PropertyBool POWERED = PropertyBool.create("powered"); - public static final PropertyBool POWERED = PropertyBool.create( "powered" ); + public BlockMolecularAssembler() { + super(Material.IRON); - public BlockMolecularAssembler() - { - super( Material.IRON ); + this.setOpaque(false); + this.lightOpacity = 1; + } - this.setOpaque( false ); - this.lightOpacity = 1; - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{POWERED}; + } - @Override - protected IProperty[] getAEStates() - { - return new IProperty[]{POWERED}; - } + @Override + public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { + boolean powered = false; + TileMolecularAssembler te = this.getTileEntity(worldIn, pos); + if (te != null) { + powered = te.isPowered(); + } - @Override - public IBlockState getActualState( IBlockState state, IBlockAccess worldIn, BlockPos pos ) - { - boolean powered = false; - TileMolecularAssembler te = this.getTileEntity( worldIn, pos ); - if( te != null ) - { - powered = te.isPowered(); - } + return super.getActualState(state, worldIn, pos).withProperty(POWERED, powered); + } - return super.getActualState( state, worldIn, pos ).withProperty( POWERED, powered ); - } + /** + * NOTE: This is only used to determine how to render an item being held in hand. + * For determining block rendering, the method below is used (canRenderInLayer). + */ + @SideOnly(Side.CLIENT) + @Override + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } - /** - * NOTE: This is only used to determine how to render an item being held in hand. - * For determining block rendering, the method below is used (canRenderInLayer). - */ - @SideOnly( Side.CLIENT ) - @Override - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } + @SideOnly(Side.CLIENT) + @Override + public boolean canRenderInLayer(IBlockState state, BlockRenderLayer layer) { + return layer == BlockRenderLayer.CUTOUT || layer == BlockRenderLayer.TRANSLUCENT; + } - @SideOnly( Side.CLIENT ) - @Override - public boolean canRenderInLayer( IBlockState state, BlockRenderLayer layer ) - { - return layer == BlockRenderLayer.CUTOUT || layer == BlockRenderLayer.TRANSLUCENT; - } + @Override + public boolean isFullCube(IBlockState state) { + return false; + } - @Override - public boolean isFullCube( IBlockState state ) - { - return false; - } + @Override + public boolean onBlockActivated(final World w, final BlockPos pos, final IBlockState state, final EntityPlayer p, final EnumHand hand, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + final TileMolecularAssembler tg = this.getTileEntity(w, pos); + if (tg != null && !p.isSneaking()) { + Platform.openGUI(p, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_MAC); + return true; + } - @Override - public boolean onBlockActivated( final World w, final BlockPos pos, final IBlockState state, final EntityPlayer p, final EnumHand hand, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - final TileMolecularAssembler tg = this.getTileEntity( w, pos ); - if( tg != null && !p.isSneaking() ) - { - Platform.openGUI( p, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_MAC ); - return true; - } + return super.onBlockActivated(w, pos, state, p, hand, side, hitX, hitY, hitZ); + } - return super.onBlockActivated( w, pos, state, p, hand, side, hitX, hitY, hitZ ); - } - - @Override - public void onNeighborChange( IBlockAccess world, BlockPos pos, BlockPos neighbor ) - { - final TileMolecularAssembler tg = this.getTileEntity( world, pos ); - if( tg != null ) - { - tg.updateNeighbors( world, pos, neighbor ); - } - } + @Override + public void onNeighborChange(IBlockAccess world, BlockPos pos, BlockPos neighbor) { + final TileMolecularAssembler tg = this.getTileEntity(world, pos); + if (tg != null) { + tg.updateNeighbors(world, pos, neighbor); + } + } } diff --git a/src/main/java/appeng/block/crafting/ItemCraftingStorage.java b/src/main/java/appeng/block/crafting/ItemCraftingStorage.java index b242147b5..85839167e 100644 --- a/src/main/java/appeng/block/crafting/ItemCraftingStorage.java +++ b/src/main/java/appeng/block/crafting/ItemCraftingStorage.java @@ -19,32 +19,27 @@ package appeng.block.crafting; -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.block.AEBaseItemBlock; import appeng.core.AEConfig; import appeng.core.features.AEFeature; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; -public class ItemCraftingStorage extends AEBaseItemBlock -{ +public class ItemCraftingStorage extends AEBaseItemBlock { - public ItemCraftingStorage( final Block id ) - { - super( id ); - } + public ItemCraftingStorage(final Block id) { + super(id); + } - @Override - public ItemStack getContainerItem( final ItemStack itemStack ) - { - return AEApi.instance().definitions().blocks().craftingUnit().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - } + @Override + public ItemStack getContainerItem(final ItemStack itemStack) { + return AEApi.instance().definitions().blocks().craftingUnit().maybeStack(1).orElse(ItemStack.EMPTY); + } - @Override - public boolean hasContainerItem( final ItemStack stack ) - { - return AEConfig.instance().isFeatureEnabled( AEFeature.ENABLE_DISASSEMBLY_CRAFTING ); - } + @Override + public boolean hasContainerItem(final ItemStack stack) { + return AEConfig.instance().isFeatureEnabled(AEFeature.ENABLE_DISASSEMBLY_CRAFTING); + } } diff --git a/src/main/java/appeng/block/grindstone/BlockCrank.java b/src/main/java/appeng/block/grindstone/BlockCrank.java index 000134704..f66486aed 100644 --- a/src/main/java/appeng/block/grindstone/BlockCrank.java +++ b/src/main/java/appeng/block/grindstone/BlockCrank.java @@ -19,8 +19,11 @@ package appeng.block.grindstone; -import javax.annotation.Nullable; - +import appeng.api.implementations.tiles.ICrankable; +import appeng.block.AEBaseTileBlock; +import appeng.core.stats.Stats; +import appeng.tile.AEBaseTile; +import appeng.tile.grindstone.TileCrank; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.BlockFaceShape; @@ -37,145 +40,114 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.FakePlayer; -import appeng.api.implementations.tiles.ICrankable; -import appeng.block.AEBaseTileBlock; -import appeng.core.stats.Stats; -import appeng.tile.AEBaseTile; -import appeng.tile.grindstone.TileCrank; +import javax.annotation.Nullable; -public class BlockCrank extends AEBaseTileBlock -{ +public class BlockCrank extends AEBaseTileBlock { - public BlockCrank() - { - super( Material.WOOD ); + public BlockCrank() { + super(Material.WOOD); - this.setLightOpacity( 0 ); - this.setHarvestLevel( "axe", 0 ); - this.setFullSize( this.setOpaque( false ) ); - } + this.setLightOpacity(0); + this.setHarvestLevel("axe", 0); + this.setFullSize(this.setOpaque(false)); + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( player instanceof FakePlayer || player == null ) - { - this.dropCrank( w, pos ); - return true; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (player instanceof FakePlayer || player == null) { + this.dropCrank(w, pos); + return true; + } - final AEBaseTile tile = this.getTileEntity( w, pos ); - if( tile instanceof TileCrank ) - { - if( ( (TileCrank) tile ).power() ) - { - Stats.TurnedCranks.addToPlayer( player, 1 ); - } - } + final AEBaseTile tile = this.getTileEntity(w, pos); + if (tile instanceof TileCrank) { + if (((TileCrank) tile).power()) { + Stats.TurnedCranks.addToPlayer(player, 1); + } + } - return true; - } + return true; + } - private void dropCrank( final World world, final BlockPos pos ) - { - world.destroyBlock( pos, true ); // w.destroyBlock( x, y, z, true ); - world.notifyBlockUpdate( pos, this.getDefaultState(), world.getBlockState( pos ), 3 ); - } + private void dropCrank(final World world, final BlockPos pos) { + world.destroyBlock(pos, true); // w.destroyBlock( x, y, z, true ); + world.notifyBlockUpdate(pos, this.getDefaultState(), world.getBlockState(pos), 3); + } - @Override - public void onBlockPlacedBy( final World world, final BlockPos pos, final IBlockState state, final EntityLivingBase placer, final ItemStack stack ) - { - final AEBaseTile tile = this.getTileEntity( world, pos ); - if( tile != null ) - { - final EnumFacing mnt = this.findCrankable( world, pos ); - EnumFacing forward = EnumFacing.UP; - if( mnt == EnumFacing.UP || mnt == EnumFacing.DOWN ) - { - forward = EnumFacing.SOUTH; - } - tile.setOrientation( forward, mnt.getOpposite() ); - } - else - { - this.dropCrank( world, pos ); - } - } + @Override + public void onBlockPlacedBy(final World world, final BlockPos pos, final IBlockState state, final EntityLivingBase placer, final ItemStack stack) { + final AEBaseTile tile = this.getTileEntity(world, pos); + if (tile != null) { + final EnumFacing mnt = this.findCrankable(world, pos); + EnumFacing forward = EnumFacing.UP; + if (mnt == EnumFacing.UP || mnt == EnumFacing.DOWN) { + forward = EnumFacing.SOUTH; + } + tile.setOrientation(forward, mnt.getOpposite()); + } else { + this.dropCrank(world, pos); + } + } - @Override - public boolean isValidOrientation( final World w, final BlockPos pos, final EnumFacing forward, final EnumFacing up ) - { - final TileEntity te = w.getTileEntity( pos ); - return !( te instanceof TileCrank ) || this.isCrankable( w, pos, up.getOpposite() ); - } + @Override + public boolean isValidOrientation(final World w, final BlockPos pos, final EnumFacing forward, final EnumFacing up) { + final TileEntity te = w.getTileEntity(pos); + return !(te instanceof TileCrank) || this.isCrankable(w, pos, up.getOpposite()); + } - private EnumFacing findCrankable( final World world, final BlockPos pos ) - { - for( final EnumFacing dir : EnumFacing.VALUES ) - { - if( this.isCrankable( world, pos, dir ) ) - { - return dir; - } - } - return null; - } + private EnumFacing findCrankable(final World world, final BlockPos pos) { + for (final EnumFacing dir : EnumFacing.VALUES) { + if (this.isCrankable(world, pos, dir)) { + return dir; + } + } + return null; + } - private boolean isCrankable( final World world, final BlockPos pos, final EnumFacing offset ) - { - final BlockPos o = pos.offset( offset ); - final TileEntity te = world.getTileEntity( o ); + private boolean isCrankable(final World world, final BlockPos pos, final EnumFacing offset) { + final BlockPos o = pos.offset(offset); + final TileEntity te = world.getTileEntity(o); - return te instanceof ICrankable && ( (ICrankable) te ).canCrankAttach( offset.getOpposite() ); - } + return te instanceof ICrankable && ((ICrankable) te).canCrankAttach(offset.getOpposite()); + } - @Override - public EnumBlockRenderType getRenderType( IBlockState state ) - { - return EnumBlockRenderType.ENTITYBLOCK_ANIMATED; - } + @Override + public EnumBlockRenderType getRenderType(IBlockState state) { + return EnumBlockRenderType.ENTITYBLOCK_ANIMATED; + } - @Override - public void neighborChanged( IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos ) - { + @Override + public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { - final AEBaseTile tile = this.getTileEntity( world, pos ); - if( tile != null ) - { - if( !this.isCrankable( world, pos, tile.getUp().getOpposite() ) ) - { - this.dropCrank( world, pos ); - } - } - else - { - this.dropCrank( world, pos ); - } - } + final AEBaseTile tile = this.getTileEntity(world, pos); + if (tile != null) { + if (!this.isCrankable(world, pos, tile.getUp().getOpposite())) { + this.dropCrank(world, pos); + } + } else { + this.dropCrank(world, pos); + } + } - @Override - public boolean canPlaceBlockAt( final World world, final BlockPos pos ) - { - return this.findCrankable( world, pos ) != null; - } + @Override + public boolean canPlaceBlockAt(final World world, final BlockPos pos) { + return this.findCrankable(world, pos) != null; + } - @Override - public boolean isFullCube( IBlockState state ) - { - return false; - } + @Override + public boolean isFullCube(IBlockState state) { + return false; + } - @Override - public boolean canPlaceTorchOnTop( IBlockState state, IBlockAccess world, BlockPos pos ) - { - return false; - } + @Override + public boolean canPlaceTorchOnTop(IBlockState state, IBlockAccess world, BlockPos pos) { + return false; + } - @Override - public BlockFaceShape getBlockFaceShape( IBlockAccess worldIn, IBlockState state, BlockPos pos, EnumFacing face ) - { - return BlockFaceShape.UNDEFINED; - } + @Override + public BlockFaceShape getBlockFaceShape(IBlockAccess worldIn, IBlockState state, BlockPos pos, EnumFacing face) { + return BlockFaceShape.UNDEFINED; + } } diff --git a/src/main/java/appeng/block/grindstone/BlockGrinder.java b/src/main/java/appeng/block/grindstone/BlockGrinder.java index f494ac9db..44c99155b 100644 --- a/src/main/java/appeng/block/grindstone/BlockGrinder.java +++ b/src/main/java/appeng/block/grindstone/BlockGrinder.java @@ -19,8 +19,11 @@ package appeng.block.grindstone; -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.core.sync.GuiBridge; +import appeng.tile.grindstone.TileGrinder; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -29,32 +32,24 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.core.sync.GuiBridge; -import appeng.tile.grindstone.TileGrinder; -import appeng.util.Platform; +import javax.annotation.Nullable; -public class BlockGrinder extends AEBaseTileBlock -{ +public class BlockGrinder extends AEBaseTileBlock { - public BlockGrinder() - { - super( Material.ROCK ); + public BlockGrinder() { + super(Material.ROCK); - this.setHardness( 3.2F ); - } + this.setHardness(3.2F); + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - final TileGrinder tg = this.getTileEntity( w, pos ); - if( tg != null && !p.isSneaking() ) - { - Platform.openGUI( p, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_GRINDER ); - return true; - } - return false; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + final TileGrinder tg = this.getTileEntity(w, pos); + if (tg != null && !p.isSneaking()) { + Platform.openGUI(p, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_GRINDER); + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/grindstone/CrankRendering.java b/src/main/java/appeng/block/grindstone/CrankRendering.java index 569b6fa7c..9a0793a32 100644 --- a/src/main/java/appeng/block/grindstone/CrankRendering.java +++ b/src/main/java/appeng/block/grindstone/CrankRendering.java @@ -19,22 +19,19 @@ package appeng.block.grindstone; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.bootstrap.BlockRenderingCustomizer; import appeng.bootstrap.IBlockRendering; import appeng.bootstrap.IItemRendering; import appeng.client.render.tesr.CrankTESR; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class CrankRendering extends BlockRenderingCustomizer -{ +public class CrankRendering extends BlockRenderingCustomizer { - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - rendering.tesr( new CrankTESR() ); - } + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + rendering.tesr(new CrankTESR()); + } } diff --git a/src/main/java/appeng/block/misc/BlockCellWorkbench.java b/src/main/java/appeng/block/misc/BlockCellWorkbench.java index 8e2046631..cb05e9eb2 100644 --- a/src/main/java/appeng/block/misc/BlockCellWorkbench.java +++ b/src/main/java/appeng/block/misc/BlockCellWorkbench.java @@ -19,8 +19,11 @@ package appeng.block.misc; -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.core.sync.GuiBridge; +import appeng.tile.misc.TileCellWorkbench; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -29,38 +32,28 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.core.sync.GuiBridge; -import appeng.tile.misc.TileCellWorkbench; -import appeng.util.Platform; +import javax.annotation.Nullable; -public class BlockCellWorkbench extends AEBaseTileBlock -{ +public class BlockCellWorkbench extends AEBaseTileBlock { - public BlockCellWorkbench() - { - super( Material.IRON ); - } + public BlockCellWorkbench() { + super(Material.IRON); + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileCellWorkbench tg = this.getTileEntity( w, pos ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_CELL_WORKBENCH ); - } - return true; - } - return false; - } + final TileCellWorkbench tg = this.getTileEntity(w, pos); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_CELL_WORKBENCH); + } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/misc/BlockCharger.java b/src/main/java/appeng/block/misc/BlockCharger.java index 82755d98a..79cad240a 100644 --- a/src/main/java/appeng/block/misc/BlockCharger.java +++ b/src/main/java/appeng/block/misc/BlockCharger.java @@ -19,17 +19,18 @@ package appeng.block.misc; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -import javax.annotation.Nullable; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.lwjgl.util.vector.Matrix4f; -import org.lwjgl.util.vector.Vector3f; - +import appeng.api.AEApi; +import appeng.api.util.AEAxisAlignedBB; +import appeng.block.AEBaseTileBlock; +import appeng.client.render.effects.LightningFX; +import appeng.client.render.renderable.ItemRenderable; +import appeng.client.render.tesr.ModularTESR; +import appeng.core.AEConfig; +import appeng.core.AppEng; +import appeng.helpers.ICustomCollision; +import appeng.tile.AEBaseTile; +import appeng.tile.misc.TileCharger; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -44,164 +45,138 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.lwjgl.util.vector.Matrix4f; +import org.lwjgl.util.vector.Vector3f; -import appeng.api.AEApi; -import appeng.api.util.AEAxisAlignedBB; -import appeng.block.AEBaseTileBlock; -import appeng.client.render.effects.LightningFX; -import appeng.client.render.renderable.ItemRenderable; -import appeng.client.render.tesr.ModularTESR; -import appeng.core.AEConfig; -import appeng.core.AppEng; -import appeng.helpers.ICustomCollision; -import appeng.tile.AEBaseTile; -import appeng.tile.misc.TileCharger; -import appeng.util.Platform; +import javax.annotation.Nullable; +import java.util.Collections; +import java.util.List; +import java.util.Random; -public class BlockCharger extends AEBaseTileBlock implements ICustomCollision -{ +public class BlockCharger extends AEBaseTileBlock implements ICustomCollision { - public BlockCharger() - { - super( Material.IRON ); + public BlockCharger() { + super(Material.IRON); - this.setLightOpacity( 2 ); - this.setFullSize( this.setOpaque( false ) ); - } + this.setLightOpacity(2); + this.setFullSize(this.setOpaque(false)); + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( player.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (player.isSneaking()) { + return false; + } - if( Platform.isServer() ) - { - final TileCharger tc = this.getTileEntity( w, pos ); - if( tc != null ) - { - tc.activate( player ); - } - } + if (Platform.isServer()) { + final TileCharger tc = this.getTileEntity(w, pos); + if (tc != null) { + tc.activate(player); + } + } - return true; - } + return true; + } - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final IBlockState state, final World w, final BlockPos pos, final Random r ) - { - if( !AEConfig.instance().isEnableEffects() ) - { - return; - } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final IBlockState state, final World w, final BlockPos pos, final Random r) { + if (!AEConfig.instance().isEnableEffects()) { + return; + } - if( r.nextFloat() < 0.98 ) - { - return; - } + if (r.nextFloat() < 0.98) { + return; + } - final AEBaseTile tile = this.getTileEntity( w, pos ); - if( tile instanceof TileCharger ) - { - final TileCharger tc = (TileCharger) tile; + final AEBaseTile tile = this.getTileEntity(w, pos); + if (tile instanceof TileCharger) { + final TileCharger tc = (TileCharger) tile; - if( AEApi.instance().definitions().materials().certusQuartzCrystalCharged().isSameAs( tc.getInternalInventory().getStackInSlot( 0 ) ) ) - { - final double xOff = 0.0; - final double yOff = 0.0; - final double zOff = 0.0; + if (AEApi.instance().definitions().materials().certusQuartzCrystalCharged().isSameAs(tc.getInternalInventory().getStackInSlot(0))) { + final double xOff = 0.0; + final double yOff = 0.0; + final double zOff = 0.0; - for( int bolts = 0; bolts < 3; bolts++ ) - { - if( AppEng.proxy.shouldAddParticles( r ) ) - { - final LightningFX fx = new LightningFX( w, xOff + 0.5 + pos.getX(), yOff + 0.5 + pos.getY(), zOff + 0.5 + pos - .getZ(), 0.0D, 0.0D, 0.0D ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - } - } - } + for (int bolts = 0; bolts < 3; bolts++) { + if (AppEng.proxy.shouldAddParticles(r)) { + final LightningFX fx = new LightningFX(w, xOff + 0.5 + pos.getX(), yOff + 0.5 + pos.getY(), zOff + 0.5 + pos + .getZ(), 0.0D, 0.0D, 0.0D); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } + } + } + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final BlockPos pos, final Entity thePlayer, final boolean b ) - { - final TileCharger tile = this.getTileEntity( w, pos ); - if( tile != null ) - { - final double twoPixels = 2.0 / 16.0; - final EnumFacing up = tile.getUp(); - final EnumFacing forward = tile.getForward(); - final AEAxisAlignedBB bb = new AEAxisAlignedBB( twoPixels, twoPixels, twoPixels, 1.0 - twoPixels, 1.0 - twoPixels, 1.0 - twoPixels ); + @Override + public Iterable getSelectedBoundingBoxesFromPool(final World w, final BlockPos pos, final Entity thePlayer, final boolean b) { + final TileCharger tile = this.getTileEntity(w, pos); + if (tile != null) { + final double twoPixels = 2.0 / 16.0; + final EnumFacing up = tile.getUp(); + final EnumFacing forward = tile.getForward(); + final AEAxisAlignedBB bb = new AEAxisAlignedBB(twoPixels, twoPixels, twoPixels, 1.0 - twoPixels, 1.0 - twoPixels, 1.0 - twoPixels); - if( up.getFrontOffsetX() != 0 ) - { - bb.minX = 0; - bb.maxX = 1; - } - if( up.getFrontOffsetY() != 0 ) - { - bb.minY = 0; - bb.maxY = 1; - } - if( up.getFrontOffsetZ() != 0 ) - { - bb.minZ = 0; - bb.maxZ = 1; - } + if (up.getFrontOffsetX() != 0) { + bb.minX = 0; + bb.maxX = 1; + } + if (up.getFrontOffsetY() != 0) { + bb.minY = 0; + bb.maxY = 1; + } + if (up.getFrontOffsetZ() != 0) { + bb.minZ = 0; + bb.maxZ = 1; + } - switch( forward ) - { - case DOWN: - bb.maxY = 1; - break; - case UP: - bb.minY = 0; - break; - case NORTH: - bb.maxZ = 1; - break; - case SOUTH: - bb.minZ = 0; - break; - case EAST: - bb.minX = 0; - break; - case WEST: - bb.maxX = 1; - break; - default: - break; - } + switch (forward) { + case DOWN: + bb.maxY = 1; + break; + case UP: + bb.minY = 0; + break; + case NORTH: + bb.maxZ = 1; + break; + case SOUTH: + bb.minZ = 0; + break; + case EAST: + bb.minX = 0; + break; + case WEST: + bb.maxX = 1; + break; + default: + break; + } - return Collections.singletonList( bb.getBoundingBox() ); - } - return Collections.singletonList( new AxisAlignedBB( 0.0, 0, 0.0, 1.0, 1.0, 1.0 ) ); - } + return Collections.singletonList(bb.getBoundingBox()); + } + return Collections.singletonList(new AxisAlignedBB(0.0, 0, 0.0, 1.0, 1.0, 1.0)); + } - @Override - public void addCollidingBlockToList( final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e ) - { - out.add( new AxisAlignedBB( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ) ); - } + @Override + public void addCollidingBlockToList(final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e) { + out.add(new AxisAlignedBB(0.0, 0.0, 0.0, 1.0, 1.0, 1.0)); + } - @SideOnly( Side.CLIENT ) - public static TileEntitySpecialRenderer createTesr() - { - return new ModularTESR<>( new ItemRenderable<>( BlockCharger::getRenderedItem ) ); - } + @SideOnly(Side.CLIENT) + public static TileEntitySpecialRenderer createTesr() { + return new ModularTESR<>(new ItemRenderable<>(BlockCharger::getRenderedItem)); + } - @SideOnly( Side.CLIENT ) - private static Pair getRenderedItem( TileCharger tile ) - { - Matrix4f transform = new Matrix4f(); - transform.translate( new Vector3f( 0.5f, 0.4f, 0.5f ) ); - return new ImmutablePair<>( tile.getInternalInventory().getStackInSlot( 0 ), transform ); - } + @SideOnly(Side.CLIENT) + private static Pair getRenderedItem(TileCharger tile) { + Matrix4f transform = new Matrix4f(); + transform.translate(new Vector3f(0.5f, 0.4f, 0.5f)); + return new ImmutablePair<>(tile.getInternalInventory().getStackInSlot(0), transform); + } } diff --git a/src/main/java/appeng/block/misc/BlockCondenser.java b/src/main/java/appeng/block/misc/BlockCondenser.java index d4b094a06..ec34bbea9 100644 --- a/src/main/java/appeng/block/misc/BlockCondenser.java +++ b/src/main/java/appeng/block/misc/BlockCondenser.java @@ -19,8 +19,11 @@ package appeng.block.misc; -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.core.sync.GuiBridge; +import appeng.tile.misc.TileCondenser; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -29,39 +32,29 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.core.sync.GuiBridge; -import appeng.tile.misc.TileCondenser; -import appeng.util.Platform; +import javax.annotation.Nullable; -public class BlockCondenser extends AEBaseTileBlock -{ +public class BlockCondenser extends AEBaseTileBlock { - public BlockCondenser() - { - super( Material.IRON ); - } + public BlockCondenser() { + super(Material.IRON); + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( player.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (player.isSneaking()) { + return false; + } - if( Platform.isServer() ) - { - final TileCondenser tc = this.getTileEntity( w, pos ); - if( tc != null && !player.isSneaking() ) - { - Platform.openGUI( player, tc, AEPartLocation.fromFacing( side ), GuiBridge.GUI_CONDENSER ); - return true; - } - } + if (Platform.isServer()) { + final TileCondenser tc = this.getTileEntity(w, pos); + if (tc != null && !player.isSneaking()) { + Platform.openGUI(player, tc, AEPartLocation.fromFacing(side), GuiBridge.GUI_CONDENSER); + return true; + } + } - return true; - } + return true; + } } diff --git a/src/main/java/appeng/block/misc/BlockInscriber.java b/src/main/java/appeng/block/misc/BlockInscriber.java index f5f950c20..5b702df33 100644 --- a/src/main/java/appeng/block/misc/BlockInscriber.java +++ b/src/main/java/appeng/block/misc/BlockInscriber.java @@ -19,8 +19,11 @@ package appeng.block.misc; -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.core.sync.GuiBridge; +import appeng.tile.misc.TileInscriber; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; @@ -31,53 +34,41 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.core.sync.GuiBridge; -import appeng.tile.misc.TileInscriber; -import appeng.util.Platform; +import javax.annotation.Nullable; -public class BlockInscriber extends AEBaseTileBlock -{ +public class BlockInscriber extends AEBaseTileBlock { - public BlockInscriber() - { - super( Material.IRON ); + public BlockInscriber() { + super(Material.IRON); - this.setLightOpacity( 2 ); - this.setFullSize( this.setOpaque( false ) ); - } + this.setLightOpacity(2); + this.setFullSize(this.setOpaque(false)); + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileInscriber tg = this.getTileEntity( w, pos ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_INSCRIBER ); - } - return true; - } - return false; - } + final TileInscriber tg = this.getTileEntity(w, pos); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_INSCRIBER); + } + return true; + } + return false; + } - @Override - public EnumBlockRenderType getRenderType( IBlockState state ) - { - return EnumBlockRenderType.MODEL; - } + @Override + public EnumBlockRenderType getRenderType(IBlockState state) { + return EnumBlockRenderType.MODEL; + } - @Override - public String getUnlocalizedName( final ItemStack is ) - { - return super.getUnlocalizedName( is ); - } + @Override + public String getUnlocalizedName(final ItemStack is) { + return super.getUnlocalizedName(is); + } } diff --git a/src/main/java/appeng/block/misc/BlockInterface.java b/src/main/java/appeng/block/misc/BlockInterface.java index 879e3586a..8bab2e728 100644 --- a/src/main/java/appeng/block/misc/BlockInterface.java +++ b/src/main/java/appeng/block/misc/BlockInterface.java @@ -19,8 +19,12 @@ package appeng.block.misc; -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.api.util.IOrientable; +import appeng.block.AEBaseTileBlock; +import appeng.core.sync.GuiBridge; +import appeng.tile.misc.TileInterface; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -33,77 +37,60 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.api.util.IOrientable; -import appeng.block.AEBaseTileBlock; -import appeng.core.sync.GuiBridge; -import appeng.tile.misc.TileInterface; -import appeng.util.Platform; +import javax.annotation.Nullable; -public class BlockInterface extends AEBaseTileBlock -{ +public class BlockInterface extends AEBaseTileBlock { - private static final PropertyBool OMNIDIRECTIONAL = PropertyBool.create( "omnidirectional" ); + private static final PropertyBool OMNIDIRECTIONAL = PropertyBool.create("omnidirectional"); - public BlockInterface() - { - super( Material.IRON ); - } + public BlockInterface() { + super(Material.IRON); + } - @Override - protected IProperty[] getAEStates() - { - return new IProperty[] { OMNIDIRECTIONAL }; - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{OMNIDIRECTIONAL}; + } - @Override - public IBlockState getActualState( IBlockState state, IBlockAccess world, BlockPos pos ) - { - // Determine whether the interface is omni-directional or not - TileInterface te = this.getTileEntity( world, pos ); - boolean omniDirectional = true; // The default - if( te != null ) - { - omniDirectional = te.isOmniDirectional(); - } + @Override + public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) { + // Determine whether the interface is omni-directional or not + TileInterface te = this.getTileEntity(world, pos); + boolean omniDirectional = true; // The default + if (te != null) { + omniDirectional = te.isOmniDirectional(); + } - return super.getActualState( state, world, pos ) - .withProperty( OMNIDIRECTIONAL, omniDirectional ); - } + return super.getActualState(state, world, pos) + .withProperty(OMNIDIRECTIONAL, omniDirectional); + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileInterface tg = this.getTileEntity( w, pos ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_INTERFACE ); - } - return true; - } - return false; - } + final TileInterface tg = this.getTileEntity(w, pos); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_INTERFACE); + } + return true; + } + return false; + } - @Override - protected boolean hasCustomRotation() - { - return true; - } + @Override + protected boolean hasCustomRotation() { + return true; + } - @Override - protected void customRotateBlock( final IOrientable rotatable, final EnumFacing axis ) - { - if( rotatable instanceof TileInterface ) - { - ( (TileInterface) rotatable ).setSide( axis ); - } - } + @Override + protected void customRotateBlock(final IOrientable rotatable, final EnumFacing axis) { + if (rotatable instanceof TileInterface) { + ((TileInterface) rotatable).setSide(axis); + } + } } diff --git a/src/main/java/appeng/block/misc/BlockLightDetector.java b/src/main/java/appeng/block/misc/BlockLightDetector.java index d4fcf6c2f..a82e6aca1 100644 --- a/src/main/java/appeng/block/misc/BlockLightDetector.java +++ b/src/main/java/appeng/block/misc/BlockLightDetector.java @@ -19,10 +19,12 @@ package appeng.block.misc; -import java.util.Collections; -import java.util.List; -import java.util.Random; - +import appeng.api.util.IOrientable; +import appeng.api.util.IOrientableBlock; +import appeng.block.AEBaseTileBlock; +import appeng.helpers.ICustomCollision; +import appeng.helpers.MetaRotation; +import appeng.tile.misc.TileLightDetector; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -39,166 +41,139 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.util.IOrientable; -import appeng.api.util.IOrientableBlock; -import appeng.block.AEBaseTileBlock; -import appeng.helpers.ICustomCollision; -import appeng.helpers.MetaRotation; -import appeng.tile.misc.TileLightDetector; +import java.util.Collections; +import java.util.List; +import java.util.Random; -public class BlockLightDetector extends AEBaseTileBlock implements IOrientableBlock, ICustomCollision -{ +public class BlockLightDetector extends AEBaseTileBlock implements IOrientableBlock, ICustomCollision { - // Cannot use the vanilla FACING property here because it excludes facing DOWN - public static final PropertyDirection FACING = PropertyDirection.create( "facing" ); + // Cannot use the vanilla FACING property here because it excludes facing DOWN + public static final PropertyDirection FACING = PropertyDirection.create("facing"); - // Used to alternate between two variants of the fixture on adjacent blocks - public static final PropertyBool ODD = PropertyBool.create( "odd" ); + // Used to alternate between two variants of the fixture on adjacent blocks + public static final PropertyBool ODD = PropertyBool.create("odd"); - public BlockLightDetector() - { - super( Material.CIRCUITS ); + public BlockLightDetector() { + super(Material.CIRCUITS); - this.setDefaultState( this.blockState.getBaseState().withProperty( FACING, EnumFacing.UP ).withProperty( ODD, false ) ); - this.setLightOpacity( 0 ); - this.setFullSize( false ); - this.setOpaque( false ); - } + this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.UP).withProperty(ODD, false)); + this.setLightOpacity(0); + this.setFullSize(false); + this.setOpaque(false); + } - @Override - public int getMetaFromState( final IBlockState state ) - { - return state.getValue( FACING ).ordinal(); - } + @Override + public int getMetaFromState(final IBlockState state) { + return state.getValue(FACING).ordinal(); + } - @Override - public IBlockState getStateFromMeta( final int meta ) - { - EnumFacing facing = EnumFacing.values()[meta]; - return this.getDefaultState().withProperty( FACING, facing ); - } + @Override + public IBlockState getStateFromMeta(final int meta) { + EnumFacing facing = EnumFacing.values()[meta]; + return this.getDefaultState().withProperty(FACING, facing); + } - @Override - protected IProperty[] getAEStates() - { - return new IProperty[] { FACING, ODD }; - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{FACING, ODD}; + } - @Override - public int getWeakPower( final IBlockState state, final IBlockAccess w, final BlockPos pos, final EnumFacing side ) - { - if( w instanceof World && ( (TileLightDetector) this.getTileEntity( w, pos ) ).isReady() ) - { - return ( (World) w ).getLightFromNeighbors( pos ) - 6; - } + @Override + public int getWeakPower(final IBlockState state, final IBlockAccess w, final BlockPos pos, final EnumFacing side) { + if (w instanceof World && ((TileLightDetector) this.getTileEntity(w, pos)).isReady()) { + return ((World) w).getLightFromNeighbors(pos) - 6; + } - return 0; - } + return 0; + } - @Override - public void onNeighborChange( final IBlockAccess world, final BlockPos pos, final BlockPos neighbor ) - { - super.onNeighborChange( world, pos, neighbor ); + @Override + public void onNeighborChange(final IBlockAccess world, final BlockPos pos, final BlockPos neighbor) { + super.onNeighborChange(world, pos, neighbor); - final TileLightDetector tld = this.getTileEntity( world, pos ); - if( tld != null ) - { - tld.updateLight(); - } - } + final TileLightDetector tld = this.getTileEntity(world, pos); + if (tld != null) { + tld.updateLight(); + } + } - @Override - public void randomDisplayTick( final IBlockState state, final World worldIn, final BlockPos pos, final Random rand ) - { - // cancel out lightning - } + @Override + public void randomDisplayTick(final IBlockState state, final World worldIn, final BlockPos pos, final Random rand) { + // cancel out lightning + } - @Override - public boolean isValidOrientation( final World w, final BlockPos pos, final EnumFacing forward, final EnumFacing up ) - { - return this.canPlaceAt( w, pos, up.getOpposite() ); - } + @Override + public boolean isValidOrientation(final World w, final BlockPos pos, final EnumFacing forward, final EnumFacing up) { + return this.canPlaceAt(w, pos, up.getOpposite()); + } - private boolean canPlaceAt( final World w, final BlockPos pos, final EnumFacing dir ) - { - return w.isSideSolid( pos.offset( dir ), dir.getOpposite(), false ); - } + private boolean canPlaceAt(final World w, final BlockPos pos, final EnumFacing dir) { + return w.isSideSolid(pos.offset(dir), dir.getOpposite(), false); + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final BlockPos pos, final Entity thePlayer, final boolean b ) - { - final EnumFacing up = this.getOrientable( w, pos ).getUp(); - final double xOff = -0.3 * up.getFrontOffsetX(); - final double yOff = -0.3 * up.getFrontOffsetY(); - final double zOff = -0.3 * up.getFrontOffsetZ(); - return Collections.singletonList( new AxisAlignedBB( xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7 ) ); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool(final World w, final BlockPos pos, final Entity thePlayer, final boolean b) { + final EnumFacing up = this.getOrientable(w, pos).getUp(); + final double xOff = -0.3 * up.getFrontOffsetX(); + final double yOff = -0.3 * up.getFrontOffsetY(); + final double zOff = -0.3 * up.getFrontOffsetZ(); + return Collections.singletonList(new AxisAlignedBB(xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7)); + } - @Override - public void addCollidingBlockToList( final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e ) - {/* - * double xOff = -0.15 * getUp().offsetX; double yOff = -0.15 * - * getUp().offsetY; double zOff = -0.15 * getUp().offsetZ; out.add( - * AxisAlignedBB.getBoundingBox( xOff + (double) x + 0.15, yOff + - * (double) y + 0.15, zOff + (double) z + 0.15,// ahh xOff + (double) x - * + 0.85, yOff + (double) y + 0.85, zOff + (double) z + 0.85 ) ); - */ - } + @Override + public void addCollidingBlockToList(final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e) {/* + * double xOff = -0.15 * getUp().offsetX; double yOff = -0.15 * + * getUp().offsetY; double zOff = -0.15 * getUp().offsetZ; out.add( + * AxisAlignedBB.getBoundingBox( xOff + (double) x + 0.15, yOff + + * (double) y + 0.15, zOff + (double) z + 0.15,// ahh xOff + (double) x + * + 0.85, yOff + (double) y + 0.85, zOff + (double) z + 0.85 ) ); + */ + } - @Override - public void neighborChanged( IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos ) - { - final EnumFacing up = this.getOrientable( world, pos ).getUp(); - if( !this.canPlaceAt( world, pos, up.getOpposite() ) ) - { - this.dropTorch( world, pos ); - } - } + @Override + public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { + final EnumFacing up = this.getOrientable(world, pos).getUp(); + if (!this.canPlaceAt(world, pos, up.getOpposite())) { + this.dropTorch(world, pos); + } + } - private void dropTorch( final World w, final BlockPos pos ) - { - final IBlockState prev = w.getBlockState( pos ); - w.destroyBlock( pos, true ); - w.notifyBlockUpdate( pos, prev, w.getBlockState( pos ), 3 ); - } + private void dropTorch(final World w, final BlockPos pos) { + final IBlockState prev = w.getBlockState(pos); + w.destroyBlock(pos, true); + w.notifyBlockUpdate(pos, prev, w.getBlockState(pos), 3); + } - @Override - public boolean canPlaceBlockAt( final World w, final BlockPos pos ) - { - for( final EnumFacing dir : EnumFacing.VALUES ) - { - if( this.canPlaceAt( w, pos, dir ) ) - { - return true; - } - } - return false; - } + @Override + public boolean canPlaceBlockAt(final World w, final BlockPos pos) { + for (final EnumFacing dir : EnumFacing.VALUES) { + if (this.canPlaceAt(w, pos, dir)) { + return true; + } + } + return false; + } - @Override - public boolean usesMetadata() - { - return false; - } + @Override + public boolean usesMetadata() { + return false; + } - @Override - public boolean isFullCube( IBlockState state ) - { - return false; - } + @Override + public boolean isFullCube(IBlockState state) { + return false; + } - @Override - @SideOnly( Side.CLIENT ) - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } + @Override + @SideOnly(Side.CLIENT) + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } - @Override - public IOrientable getOrientable( final IBlockAccess w, final BlockPos pos ) - { - return new MetaRotation( w, pos, FACING ); - } + @Override + public IOrientable getOrientable(final IBlockAccess w, final BlockPos pos) { + return new MetaRotation(w, pos, FACING); + } } diff --git a/src/main/java/appeng/block/misc/BlockQuartzFixture.java b/src/main/java/appeng/block/misc/BlockQuartzFixture.java index 0ea0d171b..39b968a25 100644 --- a/src/main/java/appeng/block/misc/BlockQuartzFixture.java +++ b/src/main/java/appeng/block/misc/BlockQuartzFixture.java @@ -19,10 +19,14 @@ package appeng.block.misc; -import java.util.Collections; -import java.util.List; -import java.util.Random; - +import appeng.api.util.IOrientable; +import appeng.api.util.IOrientableBlock; +import appeng.block.AEBaseBlock; +import appeng.client.render.effects.LightningFX; +import appeng.core.AEConfig; +import appeng.core.AppEng; +import appeng.helpers.ICustomCollision; +import appeng.helpers.MetaRotation; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -40,187 +44,156 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.util.IOrientable; -import appeng.api.util.IOrientableBlock; -import appeng.block.AEBaseBlock; -import appeng.client.render.effects.LightningFX; -import appeng.core.AEConfig; -import appeng.core.AppEng; -import appeng.helpers.ICustomCollision; -import appeng.helpers.MetaRotation; +import java.util.Collections; +import java.util.List; +import java.util.Random; -public class BlockQuartzFixture extends AEBaseBlock implements IOrientableBlock, ICustomCollision -{ +public class BlockQuartzFixture extends AEBaseBlock implements IOrientableBlock, ICustomCollision { - // Cannot use the vanilla FACING property here because it excludes facing DOWN - public static final PropertyDirection FACING = PropertyDirection.create( "facing" ); + // Cannot use the vanilla FACING property here because it excludes facing DOWN + public static final PropertyDirection FACING = PropertyDirection.create("facing"); - // Used to alternate between two variants of the fixture on adjacent blocks - public static final PropertyBool ODD = PropertyBool.create( "odd" ); + // Used to alternate between two variants of the fixture on adjacent blocks + public static final PropertyBool ODD = PropertyBool.create("odd"); - public BlockQuartzFixture() - { - super( Material.CIRCUITS ); + public BlockQuartzFixture() { + super(Material.CIRCUITS); - this.setDefaultState( this.blockState.getBaseState().withProperty( FACING, EnumFacing.UP ).withProperty( ODD, false ) ); - this.setLightLevel( 0.9375F ); - this.setLightOpacity( 0 ); - this.setFullSize( false ); - this.setOpaque( false ); - } + this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.UP).withProperty(ODD, false)); + this.setLightLevel(0.9375F); + this.setLightOpacity(0); + this.setFullSize(false); + this.setOpaque(false); + } - /** - * Sets the "ODD" property of the block state according to the placement of the block. - */ - @Override - public IBlockState getActualState( IBlockState state, IBlockAccess worldIn, BlockPos pos ) - { - boolean oddPlacement = ( ( pos.getX() + pos.getY() + pos.getZ() ) % 2 ) != 0; + /** + * Sets the "ODD" property of the block state according to the placement of the block. + */ + @Override + public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { + boolean oddPlacement = ((pos.getX() + pos.getY() + pos.getZ()) % 2) != 0; - return super.getActualState( state, worldIn, pos ) - .withProperty( ODD, oddPlacement ); - } + return super.getActualState(state, worldIn, pos) + .withProperty(ODD, oddPlacement); + } - @Override - public int getMetaFromState( final IBlockState state ) - { - return state.getValue( FACING ).ordinal(); - } + @Override + public int getMetaFromState(final IBlockState state) { + return state.getValue(FACING).ordinal(); + } - @Override - public IBlockState getStateFromMeta( final int meta ) - { - EnumFacing facing = EnumFacing.values()[meta]; - return this.getDefaultState().withProperty( FACING, facing ); - } + @Override + public IBlockState getStateFromMeta(final int meta) { + EnumFacing facing = EnumFacing.values()[meta]; + return this.getDefaultState().withProperty(FACING, facing); + } - @Override - protected IProperty[] getAEStates() - { - return new IProperty[] { FACING, ODD }; - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{FACING, ODD}; + } - @Override - public boolean isValidOrientation( final World w, final BlockPos pos, final EnumFacing forward, final EnumFacing up ) - { - return this.canPlaceAt( w, pos, up.getOpposite() ); - } + @Override + public boolean isValidOrientation(final World w, final BlockPos pos, final EnumFacing forward, final EnumFacing up) { + return this.canPlaceAt(w, pos, up.getOpposite()); + } - private boolean canPlaceAt( final World w, final BlockPos pos, final EnumFacing dir ) - { - final BlockPos test = pos.offset( dir ); - return w.isSideSolid( test, dir.getOpposite(), false ); - } + private boolean canPlaceAt(final World w, final BlockPos pos, final EnumFacing dir) { + final BlockPos test = pos.offset(dir); + return w.isSideSolid(test, dir.getOpposite(), false); + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final BlockPos pos, final Entity e, final boolean isVisual ) - { - final EnumFacing up = this.getOrientable( w, pos ).getUp(); - final double xOff = -0.3 * up.getFrontOffsetX(); - final double yOff = -0.3 * up.getFrontOffsetY(); - final double zOff = -0.3 * up.getFrontOffsetZ(); - return Collections.singletonList( new AxisAlignedBB( xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7 ) ); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool(final World w, final BlockPos pos, final Entity e, final boolean isVisual) { + final EnumFacing up = this.getOrientable(w, pos).getUp(); + final double xOff = -0.3 * up.getFrontOffsetX(); + final double yOff = -0.3 * up.getFrontOffsetY(); + final double zOff = -0.3 * up.getFrontOffsetZ(); + return Collections.singletonList(new AxisAlignedBB(xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7)); + } - @Override - public void addCollidingBlockToList( final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e ) - {/* - * double xOff = -0.15 * getUp().offsetX; double yOff = -0.15 * getUp().offsetY; double zOff = -0.15 * - * getUp().offsetZ; out.add( AxisAlignedBB.getBoundingBox( xOff + (double) x + 0.15, yOff + (double) y + 0.15, - * zOff - * + (double) z + 0.15,// ahh xOff + (double) x + 0.85, yOff + (double) y + 0.85, zOff + (double) z + 0.85 ) ); - */ - } + @Override + public void addCollidingBlockToList(final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e) {/* + * double xOff = -0.15 * getUp().offsetX; double yOff = -0.15 * getUp().offsetY; double zOff = -0.15 * + * getUp().offsetZ; out.add( AxisAlignedBB.getBoundingBox( xOff + (double) x + 0.15, yOff + (double) y + 0.15, + * zOff + * + (double) z + 0.15,// ahh xOff + (double) x + 0.85, yOff + (double) y + 0.85, zOff + (double) z + 0.85 ) ); + */ + } - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final IBlockState state, final World w, final BlockPos pos, final Random r ) - { - if( !AEConfig.instance().isEnableEffects() ) - { - return; - } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final IBlockState state, final World w, final BlockPos pos, final Random r) { + if (!AEConfig.instance().isEnableEffects()) { + return; + } - if( r.nextFloat() < 0.98 ) - { - return; - } + if (r.nextFloat() < 0.98) { + return; + } - final EnumFacing up = this.getOrientable( w, pos ).getUp(); - final double xOff = -0.3 * up.getFrontOffsetX(); - final double yOff = -0.3 * up.getFrontOffsetY(); - final double zOff = -0.3 * up.getFrontOffsetZ(); - for( int bolts = 0; bolts < 3; bolts++ ) - { - if( AppEng.proxy.shouldAddParticles( r ) ) - { - final LightningFX fx = new LightningFX( w, xOff + 0.5 + pos.getX(), yOff + 0.5 + pos.getY(), zOff + 0.5 + pos.getZ(), 0.0D, 0.0D, 0.0D ); + final EnumFacing up = this.getOrientable(w, pos).getUp(); + final double xOff = -0.3 * up.getFrontOffsetX(); + final double yOff = -0.3 * up.getFrontOffsetY(); + final double zOff = -0.3 * up.getFrontOffsetZ(); + for (int bolts = 0; bolts < 3; bolts++) { + if (AppEng.proxy.shouldAddParticles(r)) { + final LightningFX fx = new LightningFX(w, xOff + 0.5 + pos.getX(), yOff + 0.5 + pos.getY(), zOff + 0.5 + pos.getZ(), 0.0D, 0.0D, 0.0D); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - } + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } + } - @Override - public void neighborChanged( IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos ) - { - final EnumFacing up = this.getOrientable( world, pos ).getUp(); - if( !this.canPlaceAt( world, pos, up.getOpposite() ) ) - { - this.dropTorch( world, pos ); - } - } + @Override + public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { + final EnumFacing up = this.getOrientable(world, pos).getUp(); + if (!this.canPlaceAt(world, pos, up.getOpposite())) { + this.dropTorch(world, pos); + } + } - private void dropTorch( final World w, final BlockPos pos ) - { - final IBlockState prev = w.getBlockState( pos ); - w.destroyBlock( pos, true ); - w.notifyBlockUpdate( pos, prev, w.getBlockState( pos ), 3 ); - } + private void dropTorch(final World w, final BlockPos pos) { + final IBlockState prev = w.getBlockState(pos); + w.destroyBlock(pos, true); + w.notifyBlockUpdate(pos, prev, w.getBlockState(pos), 3); + } - @Override - public boolean canPlaceBlockAt( final World w, final BlockPos pos ) - { - for( final EnumFacing dir : EnumFacing.VALUES ) - { - if( this.canPlaceAt( w, pos, dir ) ) - { - return true; - } - } - return false; - } + @Override + public boolean canPlaceBlockAt(final World w, final BlockPos pos) { + for (final EnumFacing dir : EnumFacing.VALUES) { + if (this.canPlaceAt(w, pos, dir)) { + return true; + } + } + return false; + } - @Override - public boolean usesMetadata() - { - return true; - } + @Override + public boolean usesMetadata() { + return true; + } - @Override - public IOrientable getOrientable( final IBlockAccess w, final BlockPos pos ) - { - return new MetaRotation( w, pos, FACING ); - } + @Override + public IOrientable getOrientable(final IBlockAccess w, final BlockPos pos) { + return new MetaRotation(w, pos, FACING); + } - @Override - public boolean isOpaque() - { - return false; - } + @Override + public boolean isOpaque() { + return false; + } - @Override - public boolean isFullCube( IBlockState state ) - { - return false; - } + @Override + public boolean isFullCube(IBlockState state) { + return false; + } - @Override - @SideOnly( Side.CLIENT ) - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } + @Override + @SideOnly(Side.CLIENT) + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } } diff --git a/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java b/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java index c732a3ed0..83a63d2d6 100644 --- a/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java +++ b/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java @@ -19,8 +19,13 @@ package appeng.block.misc; -import java.util.Random; - +import appeng.api.util.IOrientableBlock; +import appeng.block.AEBaseTileBlock; +import appeng.client.render.effects.LightningFX; +import appeng.core.AEConfig; +import appeng.core.AppEng; +import appeng.tile.misc.TileQuartzGrowthAccelerator; +import appeng.util.Platform; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -34,129 +39,113 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.util.IOrientableBlock; -import appeng.block.AEBaseTileBlock; -import appeng.client.render.effects.LightningFX; -import appeng.core.AEConfig; -import appeng.core.AppEng; -import appeng.tile.misc.TileQuartzGrowthAccelerator; -import appeng.util.Platform; +import java.util.Random; -public class BlockQuartzGrowthAccelerator extends AEBaseTileBlock implements IOrientableBlock -{ +public class BlockQuartzGrowthAccelerator extends AEBaseTileBlock implements IOrientableBlock { - private static final PropertyBool POWERED = PropertyBool.create( "powered" ); + private static final PropertyBool POWERED = PropertyBool.create("powered"); - public BlockQuartzGrowthAccelerator() - { - super( Material.ROCK ); - this.setSoundType( SoundType.METAL ); - this.setDefaultState( this.getDefaultState().withProperty( POWERED, false ) ); - } + public BlockQuartzGrowthAccelerator() { + super(Material.ROCK); + this.setSoundType(SoundType.METAL); + this.setDefaultState(this.getDefaultState().withProperty(POWERED, false)); + } - @Override - public IBlockState getActualState( IBlockState state, IBlockAccess world, BlockPos pos ) - { - TileQuartzGrowthAccelerator te = this.getTileEntity( world, pos ); - boolean powered = te != null && te.isPowered(); + @Override + public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) { + TileQuartzGrowthAccelerator te = this.getTileEntity(world, pos); + boolean powered = te != null && te.isPowered(); - return super.getActualState( state, world, pos ) - .withProperty( POWERED, powered ); - } + return super.getActualState(state, world, pos) + .withProperty(POWERED, powered); + } - @Override - protected IProperty[] getAEStates() - { - return new IProperty[] { POWERED }; - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{POWERED}; + } - @SideOnly( Side.CLIENT ) - @Override - public void randomDisplayTick( final IBlockState state, final World w, final BlockPos pos, final Random r ) - { - if( !AEConfig.instance().isEnableEffects() ) - { - return; - } + @SideOnly(Side.CLIENT) + @Override + public void randomDisplayTick(final IBlockState state, final World w, final BlockPos pos, final Random r) { + if (!AEConfig.instance().isEnableEffects()) { + return; + } - final TileQuartzGrowthAccelerator cga = this.getTileEntity( w, pos ); + final TileQuartzGrowthAccelerator cga = this.getTileEntity(w, pos); - if( cga != null && cga.isPowered() && AppEng.proxy.shouldAddParticles( r ) ) - { - final double d0 = r.nextFloat() - 0.5F; - final double d1 = r.nextFloat() - 0.5F; + if (cga != null && cga.isPowered() && AppEng.proxy.shouldAddParticles(r)) { + final double d0 = r.nextFloat() - 0.5F; + final double d1 = r.nextFloat() - 0.5F; - final EnumFacing up = cga.getUp(); - final EnumFacing forward = cga.getForward(); - final EnumFacing west = Platform.crossProduct( forward, up ); + final EnumFacing up = cga.getUp(); + final EnumFacing forward = cga.getForward(); + final EnumFacing west = Platform.crossProduct(forward, up); - double rx = 0.5 + pos.getX(); - double ry = 0.5 + pos.getY(); - double rz = 0.5 + pos.getZ(); + double rx = 0.5 + pos.getX(); + double ry = 0.5 + pos.getY(); + double rz = 0.5 + pos.getZ(); - rx += up.getFrontOffsetX() * d0; - ry += up.getFrontOffsetY() * d0; - rz += up.getFrontOffsetZ() * d0; + rx += up.getFrontOffsetX() * d0; + ry += up.getFrontOffsetY() * d0; + rz += up.getFrontOffsetZ() * d0; - final int x = pos.getX(); - final int y = pos.getY(); - final int z = pos.getZ(); + final int x = pos.getX(); + final int y = pos.getY(); + final int z = pos.getZ(); - double dz = 0; - double dx = 0; - BlockPos pt = null; + double dz = 0; + double dx = 0; + BlockPos pt = null; - switch( r.nextInt( 4 ) ) - { - case 0: - dx = 0.6; - dz = d1; - pt = new BlockPos( x + west.getFrontOffsetX(), y + west.getFrontOffsetY(), z + west.getFrontOffsetZ() ); + switch (r.nextInt(4)) { + case 0: + dx = 0.6; + dz = d1; + pt = new BlockPos(x + west.getFrontOffsetX(), y + west.getFrontOffsetY(), z + west.getFrontOffsetZ()); - break; - case 1: - dx = d1; - dz += 0.6; - pt = new BlockPos( x + forward.getFrontOffsetX(), y + forward.getFrontOffsetY(), z + forward.getFrontOffsetZ() ); + break; + case 1: + dx = d1; + dz += 0.6; + pt = new BlockPos(x + forward.getFrontOffsetX(), y + forward.getFrontOffsetY(), z + forward.getFrontOffsetZ()); - break; - case 2: - dx = d1; - dz = -0.6; - pt = new BlockPos( x - forward.getFrontOffsetX(), y - forward.getFrontOffsetY(), z - forward.getFrontOffsetZ() ); + break; + case 2: + dx = d1; + dz = -0.6; + pt = new BlockPos(x - forward.getFrontOffsetX(), y - forward.getFrontOffsetY(), z - forward.getFrontOffsetZ()); - break; - case 3: - dx = -0.6; - dz = d1; - pt = new BlockPos( x - west.getFrontOffsetX(), y - west.getFrontOffsetY(), z - west.getFrontOffsetZ() ); + break; + case 3: + dx = -0.6; + dz = d1; + pt = new BlockPos(x - west.getFrontOffsetX(), y - west.getFrontOffsetY(), z - west.getFrontOffsetZ()); - break; - } + break; + } - if( !w.getBlockState( pt ).getBlock().isAir( w.getBlockState( pt ), w, pt ) ) - { - return; - } + if (!w.getBlockState(pt).getBlock().isAir(w.getBlockState(pt), w, pt)) { + return; + } - rx += dx * west.getFrontOffsetX(); - ry += dx * west.getFrontOffsetY(); - rz += dx * west.getFrontOffsetZ(); + rx += dx * west.getFrontOffsetX(); + ry += dx * west.getFrontOffsetY(); + rz += dx * west.getFrontOffsetZ(); - rx += dz * forward.getFrontOffsetX(); - ry += dz * forward.getFrontOffsetY(); - rz += dz * forward.getFrontOffsetZ(); + rx += dz * forward.getFrontOffsetX(); + ry += dz * forward.getFrontOffsetY(); + rz += dz * forward.getFrontOffsetZ(); - final LightningFX fx = new LightningFX( w, rx, ry, rz, 0.0D, 0.0D, 0.0D ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } + final LightningFX fx = new LightningFX(w, rx, ry, rz, 0.0D, 0.0D, 0.0D); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } - @Override - public boolean usesMetadata() - { - return false; - } + @Override + public boolean usesMetadata() { + return false; + } } diff --git a/src/main/java/appeng/block/misc/BlockSecurityStation.java b/src/main/java/appeng/block/misc/BlockSecurityStation.java index 4b26e2648..1d6845906 100644 --- a/src/main/java/appeng/block/misc/BlockSecurityStation.java +++ b/src/main/java/appeng/block/misc/BlockSecurityStation.java @@ -19,8 +19,11 @@ package appeng.block.misc; -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.core.sync.GuiBridge; +import appeng.tile.misc.TileSecurityStation; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -34,70 +37,56 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.core.sync.GuiBridge; -import appeng.tile.misc.TileSecurityStation; -import appeng.util.Platform; +import javax.annotation.Nullable; -public class BlockSecurityStation extends AEBaseTileBlock -{ +public class BlockSecurityStation extends AEBaseTileBlock { - private static final PropertyBool POWERED = PropertyBool.create( "powered" ); + private static final PropertyBool POWERED = PropertyBool.create("powered"); - public BlockSecurityStation() - { - super( Material.IRON ); + public BlockSecurityStation() { + super(Material.IRON); - this.setDefaultState( this.getDefaultState().withProperty( POWERED, false ) ); - } + this.setDefaultState(this.getDefaultState().withProperty(POWERED, false)); + } - @Override - protected IProperty[] getAEStates() - { - return new IProperty[] { POWERED }; - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{POWERED}; + } - @Override - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } + @Override + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } - @Override - public IBlockState getActualState( IBlockState state, IBlockAccess world, BlockPos pos ) - { - boolean powered = false; - TileSecurityStation te = this.getTileEntity( world, pos ); - if( te != null ) - { - powered = te.isActive(); - } + @Override + public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) { + boolean powered = false; + TileSecurityStation te = this.getTileEntity(world, pos); + if (te != null) { + powered = te.isActive(); + } - return super.getActualState( state, world, pos ) - .withProperty( POWERED, powered ); - } + return super.getActualState(state, world, pos) + .withProperty(POWERED, powered); + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileSecurityStation tg = this.getTileEntity( w, pos ); - if( tg != null ) - { - if( Platform.isClient() ) - { - return true; - } + final TileSecurityStation tg = this.getTileEntity(w, pos); + if (tg != null) { + if (Platform.isClient()) { + return true; + } - Platform.openGUI( p, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_SECURITY ); - return true; - } - return false; - } + Platform.openGUI(p, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_SECURITY); + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/misc/BlockSkyCompass.java b/src/main/java/appeng/block/misc/BlockSkyCompass.java index 9c941b4bc..033805f90 100644 --- a/src/main/java/appeng/block/misc/BlockSkyCompass.java +++ b/src/main/java/appeng/block/misc/BlockSkyCompass.java @@ -19,9 +19,9 @@ package appeng.block.misc; -import java.util.Collections; -import java.util.List; - +import appeng.block.AEBaseTileBlock; +import appeng.helpers.ICustomCollision; +import appeng.tile.misc.TileSkyCompass; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.BlockStateContainer; @@ -36,156 +36,137 @@ import net.minecraftforge.common.property.ExtendedBlockState; import net.minecraftforge.common.property.IUnlistedProperty; import net.minecraftforge.common.property.PropertyFloat; -import appeng.block.AEBaseTileBlock; -import appeng.helpers.ICustomCollision; -import appeng.tile.misc.TileSkyCompass; +import java.util.Collections; +import java.util.List; -public class BlockSkyCompass extends AEBaseTileBlock implements ICustomCollision -{ +public class BlockSkyCompass extends AEBaseTileBlock implements ICustomCollision { - // Rotation is expressed as radians - public static final PropertyFloat ROTATION = new PropertyFloat( "rotation" ); + // Rotation is expressed as radians + public static final PropertyFloat ROTATION = new PropertyFloat("rotation"); - public BlockSkyCompass() - { - super( Material.CIRCUITS ); - this.setLightOpacity( 0 ); - this.setFullSize( false ); - this.setOpaque( false ); - } + public BlockSkyCompass() { + super(Material.CIRCUITS); + this.setLightOpacity(0); + this.setFullSize(false); + this.setOpaque(false); + } - @Override - protected BlockStateContainer createBlockState() - { - return new ExtendedBlockState( this, this.getAEStates(), new IUnlistedProperty[] { FORWARD, UP, ROTATION } ); - } + @Override + protected BlockStateContainer createBlockState() { + return new ExtendedBlockState(this, this.getAEStates(), new IUnlistedProperty[]{FORWARD, UP, ROTATION}); + } - @Override - public boolean isValidOrientation( final World w, final BlockPos pos, final EnumFacing forward, final EnumFacing up ) - { - final TileSkyCompass sc = this.getTileEntity( w, pos ); - if( sc != null ) - { - return false; - } - return this.canPlaceAt( w, pos, forward.getOpposite() ); - } + @Override + public boolean isValidOrientation(final World w, final BlockPos pos, final EnumFacing forward, final EnumFacing up) { + final TileSkyCompass sc = this.getTileEntity(w, pos); + if (sc != null) { + return false; + } + return this.canPlaceAt(w, pos, forward.getOpposite()); + } - private boolean canPlaceAt( final World w, final BlockPos pos, final EnumFacing dir ) - { - return w.isSideSolid( pos.offset( dir ), dir.getOpposite(), false ); - } + private boolean canPlaceAt(final World w, final BlockPos pos, final EnumFacing dir) { + return w.isSideSolid(pos.offset(dir), dir.getOpposite(), false); + } - @Override - public void neighborChanged( IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos ) - { - final TileSkyCompass sc = this.getTileEntity( world, pos ); - final EnumFacing forward = sc.getForward(); - if( !this.canPlaceAt( world, pos, forward.getOpposite() ) ) - { - this.dropTorch( world, pos ); - } - } + @Override + public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { + final TileSkyCompass sc = this.getTileEntity(world, pos); + final EnumFacing forward = sc.getForward(); + if (!this.canPlaceAt(world, pos, forward.getOpposite())) { + this.dropTorch(world, pos); + } + } - private void dropTorch( final World w, final BlockPos pos ) - { - final IBlockState prev = w.getBlockState( pos ); - w.destroyBlock( pos, true ); - w.notifyBlockUpdate( pos, prev, w.getBlockState( pos ), 3 ); - } + private void dropTorch(final World w, final BlockPos pos) { + final IBlockState prev = w.getBlockState(pos); + w.destroyBlock(pos, true); + w.notifyBlockUpdate(pos, prev, w.getBlockState(pos), 3); + } - @Override - public boolean canPlaceBlockAt( final World w, final BlockPos pos ) - { - for( final EnumFacing dir : EnumFacing.VALUES ) - { - if( this.canPlaceAt( w, pos, dir ) ) - { - return true; - } - } - return false; - } + @Override + public boolean canPlaceBlockAt(final World w, final BlockPos pos) { + for (final EnumFacing dir : EnumFacing.VALUES) { + if (this.canPlaceAt(w, pos, dir)) { + return true; + } + } + return false; + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final BlockPos pos, final Entity thePlayer, final boolean b ) - { - final TileSkyCompass tile = this.getTileEntity( w, pos ); - if( tile != null ) - { - final EnumFacing forward = tile.getForward(); + @Override + public Iterable getSelectedBoundingBoxesFromPool(final World w, final BlockPos pos, final Entity thePlayer, final boolean b) { + final TileSkyCompass tile = this.getTileEntity(w, pos); + if (tile != null) { + final EnumFacing forward = tile.getForward(); - double minX = 0; - double minY = 0; - double minZ = 0; - double maxX = 1; - double maxY = 1; - double maxZ = 1; + double minX = 0; + double minY = 0; + double minZ = 0; + double maxX = 1; + double maxY = 1; + double maxZ = 1; - switch( forward ) - { - case DOWN: - minZ = minX = 5.0 / 16.0; - maxZ = maxX = 11.0 / 16.0; - maxY = 1.0; - minY = 14.0 / 16.0; - break; - case EAST: - minZ = minY = 5.0 / 16.0; - maxZ = maxY = 11.0 / 16.0; - maxX = 2.0 / 16.0; - minX = 0.0; - break; - case NORTH: - minY = minX = 5.0 / 16.0; - maxY = maxX = 11.0 / 16.0; - maxZ = 1.0; - minZ = 14.0 / 16.0; - break; - case SOUTH: - minY = minX = 5.0 / 16.0; - maxY = maxX = 11.0 / 16.0; - maxZ = 2.0 / 16.0; - minZ = 0.0; - break; - case UP: - minZ = minX = 5.0 / 16.0; - maxZ = maxX = 11.0 / 16.0; - maxY = 2.0 / 16.0; - minY = 0.0; - break; - case WEST: - minZ = minY = 5.0 / 16.0; - maxZ = maxY = 11.0 / 16.0; - maxX = 1.0; - minX = 14.0 / 16.0; - break; - default: - break; - } + switch (forward) { + case DOWN: + minZ = minX = 5.0 / 16.0; + maxZ = maxX = 11.0 / 16.0; + maxY = 1.0; + minY = 14.0 / 16.0; + break; + case EAST: + minZ = minY = 5.0 / 16.0; + maxZ = maxY = 11.0 / 16.0; + maxX = 2.0 / 16.0; + minX = 0.0; + break; + case NORTH: + minY = minX = 5.0 / 16.0; + maxY = maxX = 11.0 / 16.0; + maxZ = 1.0; + minZ = 14.0 / 16.0; + break; + case SOUTH: + minY = minX = 5.0 / 16.0; + maxY = maxX = 11.0 / 16.0; + maxZ = 2.0 / 16.0; + minZ = 0.0; + break; + case UP: + minZ = minX = 5.0 / 16.0; + maxZ = maxX = 11.0 / 16.0; + maxY = 2.0 / 16.0; + minY = 0.0; + break; + case WEST: + minZ = minY = 5.0 / 16.0; + maxZ = maxY = 11.0 / 16.0; + maxX = 1.0; + minX = 14.0 / 16.0; + break; + default: + break; + } - return Collections.singletonList( new AxisAlignedBB( minX, minY, minZ, maxX, maxY, maxZ ) ); - } - return Collections.singletonList( new AxisAlignedBB( 0.0, 0, 0.0, 1.0, 1.0, 1.0 ) ); - } + return Collections.singletonList(new AxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ)); + } + return Collections.singletonList(new AxisAlignedBB(0.0, 0, 0.0, 1.0, 1.0, 1.0)); + } - @Override - public void addCollidingBlockToList( final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e ) - { + @Override + public void addCollidingBlockToList(final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e) { - } + } - @Override - public EnumBlockRenderType getRenderType( IBlockState state ) - { - return EnumBlockRenderType.ENTITYBLOCK_ANIMATED; - } + @Override + public EnumBlockRenderType getRenderType(IBlockState state) { + return EnumBlockRenderType.ENTITYBLOCK_ANIMATED; + } - @Override - public boolean isFullBlock( IBlockState state ) - { - return false; - } + @Override + public boolean isFullBlock(IBlockState state) { + return false; + } } diff --git a/src/main/java/appeng/block/misc/BlockTinyTNT.java b/src/main/java/appeng/block/misc/BlockTinyTNT.java index c7cfa272a..d6011a152 100644 --- a/src/main/java/appeng/block/misc/BlockTinyTNT.java +++ b/src/main/java/appeng/block/misc/BlockTinyTNT.java @@ -19,11 +19,9 @@ package appeng.block.misc; -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nullable; - +import appeng.block.AEBaseBlock; +import appeng.entity.EntityTinyTNTPrimed; +import appeng.helpers.ICustomCollision; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; @@ -43,126 +41,105 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.Explosion; import net.minecraft.world.World; -import appeng.block.AEBaseBlock; -import appeng.entity.EntityTinyTNTPrimed; -import appeng.helpers.ICustomCollision; +import javax.annotation.Nullable; +import java.util.Collections; +import java.util.List; -public class BlockTinyTNT extends AEBaseBlock implements ICustomCollision -{ +public class BlockTinyTNT extends AEBaseBlock implements ICustomCollision { - public BlockTinyTNT() - { - super( Material.TNT ); + public BlockTinyTNT() { + super(Material.TNT); - this.boundingBox = new AxisAlignedBB( 0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f ); + this.boundingBox = new AxisAlignedBB(0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f); - this.setLightOpacity( 2 ); - this.setFullSize( false ); - this.setOpaque( false ); + this.setLightOpacity(2); + this.setFullSize(false); + this.setOpaque(false); - this.setSoundType( SoundType.GROUND ); - this.setHardness( 0F ); - } + this.setSoundType(SoundType.GROUND); + this.setHardness(0F); + } - @Override - public boolean isFullCube( IBlockState state ) - { - return false; - } + @Override + public boolean isFullCube(IBlockState state) { + return false; + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( heldItem != null && heldItem.getItem() == Items.FLINT_AND_STEEL ) - { - this.startFuse( w, pos, player ); - w.setBlockToAir( pos ); - heldItem.damageItem( 1, player ); - return true; - } - else - { - return super.onActivated( w, pos, player, hand, heldItem, side, hitX, hitY, hitZ ); - } - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (heldItem != null && heldItem.getItem() == Items.FLINT_AND_STEEL) { + this.startFuse(w, pos, player); + w.setBlockToAir(pos); + heldItem.damageItem(1, player); + return true; + } else { + return super.onActivated(w, pos, player, hand, heldItem, side, hitX, hitY, hitZ); + } + } - public void startFuse( final World w, final BlockPos pos, final EntityLivingBase igniter ) - { - if( !w.isRemote ) - { - final EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed( w, pos.getX() + 0.5F, pos.getY() + 0.5F, pos.getZ() + 0.5F, igniter ); - w.spawnEntity( primedTinyTNTEntity ); - w.playSound( null, primedTinyTNTEntity.posX, primedTinyTNTEntity.posY, primedTinyTNTEntity.posZ, SoundEvents.ENTITY_TNT_PRIMED, - SoundCategory.BLOCKS, 1, 1 ); - } - } + public void startFuse(final World w, final BlockPos pos, final EntityLivingBase igniter) { + if (!w.isRemote) { + final EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed(w, pos.getX() + 0.5F, pos.getY() + 0.5F, pos.getZ() + 0.5F, igniter); + w.spawnEntity(primedTinyTNTEntity); + w.playSound(null, primedTinyTNTEntity.posX, primedTinyTNTEntity.posY, primedTinyTNTEntity.posZ, SoundEvents.ENTITY_TNT_PRIMED, + SoundCategory.BLOCKS, 1, 1); + } + } - @Override - public void neighborChanged( IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos ) - { - if( world.isBlockIndirectlyGettingPowered( pos ) > 0 ) - { - this.startFuse( world, pos, null ); - world.setBlockToAir( pos ); - } - } + @Override + public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { + if (world.isBlockIndirectlyGettingPowered(pos) > 0) { + this.startFuse(world, pos, null); + world.setBlockToAir(pos); + } + } - @Override - public void onBlockAdded( final World w, final BlockPos pos, final IBlockState state ) - { - super.onBlockAdded( w, pos, state ); + @Override + public void onBlockAdded(final World w, final BlockPos pos, final IBlockState state) { + super.onBlockAdded(w, pos, state); - if( w.isBlockIndirectlyGettingPowered( pos ) > 0 ) - { - this.startFuse( w, pos, null ); - w.setBlockToAir( pos ); - } - } + if (w.isBlockIndirectlyGettingPowered(pos) > 0) { + this.startFuse(w, pos, null); + w.setBlockToAir(pos); + } + } - @Override - public void onEntityWalk( final World w, final BlockPos pos, final Entity entity ) - { - if( entity instanceof EntityArrow && !w.isRemote ) - { - final EntityArrow entityarrow = (EntityArrow) entity; + @Override + public void onEntityWalk(final World w, final BlockPos pos, final Entity entity) { + if (entity instanceof EntityArrow && !w.isRemote) { + final EntityArrow entityarrow = (EntityArrow) entity; - if( entityarrow.isBurning() ) - { - this.startFuse( w, pos, entityarrow.shootingEntity instanceof EntityLivingBase ? (EntityLivingBase) entityarrow.shootingEntity : null ); - w.setBlockToAir( pos ); - } - } - } + if (entityarrow.isBurning()) { + this.startFuse(w, pos, entityarrow.shootingEntity instanceof EntityLivingBase ? (EntityLivingBase) entityarrow.shootingEntity : null); + w.setBlockToAir(pos); + } + } + } - @Override - public boolean canDropFromExplosion( final Explosion exp ) - { - return false; - } + @Override + public boolean canDropFromExplosion(final Explosion exp) { + return false; + } - @Override - public void onBlockExploded( final World w, final BlockPos pos, final Explosion exp ) - { - super.onBlockExploded( w, pos, exp ); - if( !w.isRemote ) - { - final EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed( w, pos.getX() + 0.5F, pos.getY() + 0.5F, pos.getZ() + 0.5F, exp - .getExplosivePlacedBy() ); - primedTinyTNTEntity.setFuse( w.rand.nextInt( primedTinyTNTEntity.getFuse() / 4 ) + primedTinyTNTEntity.getFuse() / 8 ); - w.spawnEntity( primedTinyTNTEntity ); - } - } + @Override + public void onBlockExploded(final World w, final BlockPos pos, final Explosion exp) { + super.onBlockExploded(w, pos, exp); + if (!w.isRemote) { + final EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed(w, pos.getX() + 0.5F, pos.getY() + 0.5F, pos.getZ() + 0.5F, exp + .getExplosivePlacedBy()); + primedTinyTNTEntity.setFuse(w.rand.nextInt(primedTinyTNTEntity.getFuse() / 4) + primedTinyTNTEntity.getFuse() / 8); + w.spawnEntity(primedTinyTNTEntity); + } + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final BlockPos pos, final Entity thePlayer, final boolean b ) - { - return Collections.singletonList( new AxisAlignedBB( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) ); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool(final World w, final BlockPos pos, final Entity thePlayer, final boolean b) { + return Collections.singletonList(new AxisAlignedBB(0.25, 0, 0.25, 0.75, 0.5, 0.75)); + } - @Override - public void addCollidingBlockToList( final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e ) - { - out.add( new AxisAlignedBB( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) ); - } + @Override + public void addCollidingBlockToList(final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e) { + out.add(new AxisAlignedBB(0.25, 0, 0.25, 0.75, 0.5, 0.75)); + } } diff --git a/src/main/java/appeng/block/misc/BlockVibrationChamber.java b/src/main/java/appeng/block/misc/BlockVibrationChamber.java index 94c80c84d..f4706b091 100644 --- a/src/main/java/appeng/block/misc/BlockVibrationChamber.java +++ b/src/main/java/appeng/block/misc/BlockVibrationChamber.java @@ -19,10 +19,13 @@ package appeng.block.misc; -import java.util.Random; - -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.core.AEConfig; +import appeng.core.sync.GuiBridge; +import appeng.tile.AEBaseTile; +import appeng.tile.misc.TileVibrationChamber; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -36,108 +39,91 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.core.AEConfig; -import appeng.core.sync.GuiBridge; -import appeng.tile.AEBaseTile; -import appeng.tile.misc.TileVibrationChamber; -import appeng.util.Platform; +import javax.annotation.Nullable; +import java.util.Random; -public final class BlockVibrationChamber extends AEBaseTileBlock -{ +public final class BlockVibrationChamber extends AEBaseTileBlock { - // Indicates that the vibration chamber is currently working - private static final PropertyBool ACTIVE = PropertyBool.create( "active" ); + // Indicates that the vibration chamber is currently working + private static final PropertyBool ACTIVE = PropertyBool.create("active"); - public BlockVibrationChamber() - { - super( Material.IRON ); - this.setHardness( 4.2F ); - this.setDefaultState( this.getDefaultState().withProperty( ACTIVE, false ) ); - } + public BlockVibrationChamber() { + super(Material.IRON); + this.setHardness(4.2F); + this.setDefaultState(this.getDefaultState().withProperty(ACTIVE, false)); + } - @Override - public IBlockState getActualState( IBlockState state, IBlockAccess world, BlockPos pos ) - { - TileVibrationChamber te = this.getTileEntity( world, pos ); - boolean active = te != null && te.isOn; + @Override + public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) { + TileVibrationChamber te = this.getTileEntity(world, pos); + boolean active = te != null && te.isOn; - return super.getActualState( state, world, pos ) - .withProperty( ACTIVE, active ); - } + return super.getActualState(state, world, pos) + .withProperty(ACTIVE, active); + } - @Override - protected IProperty[] getAEStates() - { - return new IProperty[] { ACTIVE }; - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{ACTIVE}; + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( player.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (player.isSneaking()) { + return false; + } - if( Platform.isServer() ) - { - final TileVibrationChamber tc = this.getTileEntity( w, pos ); - if( tc != null && !player.isSneaking() ) - { - Platform.openGUI( player, tc, AEPartLocation.fromFacing( side ), GuiBridge.GUI_VIBRATION_CHAMBER ); - return true; - } - } + if (Platform.isServer()) { + final TileVibrationChamber tc = this.getTileEntity(w, pos); + if (tc != null && !player.isSneaking()) { + Platform.openGUI(player, tc, AEPartLocation.fromFacing(side), GuiBridge.GUI_VIBRATION_CHAMBER); + return true; + } + } - return true; - } + return true; + } - @Override - public void randomDisplayTick( final IBlockState state, final World w, final BlockPos pos, final Random r ) - { - if( !AEConfig.instance().isEnableEffects() ) - { - return; - } + @Override + public void randomDisplayTick(final IBlockState state, final World w, final BlockPos pos, final Random r) { + if (!AEConfig.instance().isEnableEffects()) { + return; + } - final AEBaseTile tile = this.getTileEntity( w, pos ); - if( tile instanceof TileVibrationChamber ) - { - final TileVibrationChamber tc = (TileVibrationChamber) tile; - if( tc.isOn ) - { - float f1 = pos.getX() + 0.5F; - float f2 = pos.getY() + 0.5F; - float f3 = pos.getZ() + 0.5F; + final AEBaseTile tile = this.getTileEntity(w, pos); + if (tile instanceof TileVibrationChamber) { + final TileVibrationChamber tc = (TileVibrationChamber) tile; + if (tc.isOn) { + float f1 = pos.getX() + 0.5F; + float f2 = pos.getY() + 0.5F; + float f3 = pos.getZ() + 0.5F; - final EnumFacing forward = tc.getForward(); - final EnumFacing up = tc.getUp(); + final EnumFacing forward = tc.getForward(); + final EnumFacing up = tc.getUp(); - final int west_x = forward.getFrontOffsetY() * up.getFrontOffsetZ() - forward.getFrontOffsetZ() * up.getFrontOffsetY(); - final int west_y = forward.getFrontOffsetZ() * up.getFrontOffsetX() - forward.getFrontOffsetX() * up.getFrontOffsetZ(); - final int west_z = forward.getFrontOffsetX() * up.getFrontOffsetY() - forward.getFrontOffsetY() * up.getFrontOffsetX(); + final int west_x = forward.getFrontOffsetY() * up.getFrontOffsetZ() - forward.getFrontOffsetZ() * up.getFrontOffsetY(); + final int west_y = forward.getFrontOffsetZ() * up.getFrontOffsetX() - forward.getFrontOffsetX() * up.getFrontOffsetZ(); + final int west_z = forward.getFrontOffsetX() * up.getFrontOffsetY() - forward.getFrontOffsetY() * up.getFrontOffsetX(); - f1 += forward.getFrontOffsetX() * 0.6; - f2 += forward.getFrontOffsetY() * 0.6; - f3 += forward.getFrontOffsetZ() * 0.6; + f1 += forward.getFrontOffsetX() * 0.6; + f2 += forward.getFrontOffsetY() * 0.6; + f3 += forward.getFrontOffsetZ() * 0.6; - final float ox = r.nextFloat(); - final float oy = r.nextFloat() * 0.2f; + final float ox = r.nextFloat(); + final float oy = r.nextFloat() * 0.2f; - f1 += up.getFrontOffsetX() * ( -0.3 + oy ); - f2 += up.getFrontOffsetY() * ( -0.3 + oy ); - f3 += up.getFrontOffsetZ() * ( -0.3 + oy ); + f1 += up.getFrontOffsetX() * (-0.3 + oy); + f2 += up.getFrontOffsetY() * (-0.3 + oy); + f3 += up.getFrontOffsetZ() * (-0.3 + oy); - f1 += west_x * ( 0.3 * ox - 0.15 ); - f2 += west_y * ( 0.3 * ox - 0.15 ); - f3 += west_z * ( 0.3 * ox - 0.15 ); + f1 += west_x * (0.3 * ox - 0.15); + f2 += west_y * (0.3 * ox - 0.15); + f3 += west_z * (0.3 * ox - 0.15); - w.spawnParticle( EnumParticleTypes.SMOKE_NORMAL, f1, f2, f3, 0.0D, 0.0D, 0.0D, new int[0] ); - w.spawnParticle( EnumParticleTypes.FLAME, f1, f2, f3, 0.0D, 0.0D, 0.0D, new int[0] ); - } - } - } + w.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, f1, f2, f3, 0.0D, 0.0D, 0.0D); + w.spawnParticle(EnumParticleTypes.FLAME, f1, f2, f3, 0.0D, 0.0D, 0.0D); + } + } + } } diff --git a/src/main/java/appeng/block/misc/InscriberRendering.java b/src/main/java/appeng/block/misc/InscriberRendering.java index 4f5702b35..4541c30cb 100644 --- a/src/main/java/appeng/block/misc/InscriberRendering.java +++ b/src/main/java/appeng/block/misc/InscriberRendering.java @@ -1,24 +1,20 @@ - package appeng.block.misc; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.bootstrap.BlockRenderingCustomizer; import appeng.bootstrap.IBlockRendering; import appeng.bootstrap.IItemRendering; import appeng.client.render.tesr.InscriberTESR; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class InscriberRendering extends BlockRenderingCustomizer -{ +public class InscriberRendering extends BlockRenderingCustomizer { - @SideOnly( Side.CLIENT ) - @Override - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - rendering.tesr( new InscriberTESR() ); - } + @SideOnly(Side.CLIENT) + @Override + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + rendering.tesr(new InscriberTESR()); + } } diff --git a/src/main/java/appeng/block/misc/SecurityStationRendering.java b/src/main/java/appeng/block/misc/SecurityStationRendering.java index da41210b0..bb090d212 100644 --- a/src/main/java/appeng/block/misc/SecurityStationRendering.java +++ b/src/main/java/appeng/block/misc/SecurityStationRendering.java @@ -19,25 +19,22 @@ package appeng.block.misc; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.util.AEColor; import appeng.bootstrap.BlockRenderingCustomizer; import appeng.bootstrap.IBlockRendering; import appeng.bootstrap.IItemRendering; import appeng.client.render.ColorableTileBlockColor; import appeng.client.render.StaticItemColor; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class SecurityStationRendering extends BlockRenderingCustomizer -{ +public class SecurityStationRendering extends BlockRenderingCustomizer { - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - rendering.blockColor( ColorableTileBlockColor.INSTANCE ); - itemRendering.color( new StaticItemColor( AEColor.TRANSPARENT ) ); - } + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + rendering.blockColor(ColorableTileBlockColor.INSTANCE); + itemRendering.color(new StaticItemColor(AEColor.TRANSPARENT)); + } } diff --git a/src/main/java/appeng/block/misc/SkyCompassRendering.java b/src/main/java/appeng/block/misc/SkyCompassRendering.java index 2bbe1905f..a650f512b 100644 --- a/src/main/java/appeng/block/misc/SkyCompassRendering.java +++ b/src/main/java/appeng/block/misc/SkyCompassRendering.java @@ -19,29 +19,26 @@ package appeng.block.misc; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.bootstrap.BlockRenderingCustomizer; import appeng.bootstrap.IBlockRendering; import appeng.bootstrap.IItemRendering; import appeng.client.render.model.SkyCompassModel; import appeng.client.render.tesr.SkyCompassTESR; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class SkyCompassRendering extends BlockRenderingCustomizer -{ +public class SkyCompassRendering extends BlockRenderingCustomizer { - private static final ModelResourceLocation ITEM_MODEL = new ModelResourceLocation( "appliedenergistics2:sky_compass", "normal" ); + private static final ModelResourceLocation ITEM_MODEL = new ModelResourceLocation("appliedenergistics2:sky_compass", "normal"); - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - rendering.tesr( new SkyCompassTESR() ); - itemRendering.model( ITEM_MODEL ); - itemRendering.builtInModel( "models/block/builtin/sky_compass", new SkyCompassModel() ); - } + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + rendering.tesr(new SkyCompassTESR()); + itemRendering.model(ITEM_MODEL); + itemRendering.builtInModel("models/block/builtin/sky_compass", new SkyCompassModel()); + } } diff --git a/src/main/java/appeng/block/networking/BlockCableBus.java b/src/main/java/appeng/block/networking/BlockCableBus.java index ccb53d72c..9dfb76a8e 100644 --- a/src/main/java/appeng/block/networking/BlockCableBus.java +++ b/src/main/java/appeng/block/networking/BlockCableBus.java @@ -19,12 +19,29 @@ package appeng.block.networking; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; - -import javax.annotation.Nullable; - +import appeng.api.parts.IFacadeContainer; +import appeng.api.parts.IFacadePart; +import appeng.api.parts.PartItemStack; +import appeng.api.parts.SelectedPart; +import appeng.api.util.AEColor; +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.client.UnlistedProperty; +import appeng.client.render.cablebus.CableBusBakedModel; +import appeng.client.render.cablebus.CableBusRenderState; +import appeng.core.Api; +import appeng.core.AppEng; +import appeng.core.sync.network.NetworkHandler; +import appeng.core.sync.packets.PacketClick; +import appeng.helpers.AEGlassMaterial; +import appeng.integration.abstraction.IAEFacade; +import appeng.parts.ICableBusContainer; +import appeng.parts.NullCableBusContainer; +import appeng.tile.AEBaseTile; +import appeng.tile.networking.CableBusTESR; +import appeng.tile.networking.TileCableBus; +import appeng.tile.networking.TileCableBusTESR; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.BlockStateContainer; @@ -61,439 +78,354 @@ import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.parts.IFacadeContainer; -import appeng.api.parts.IFacadePart; -import appeng.api.parts.PartItemStack; -import appeng.api.parts.SelectedPart; -import appeng.api.util.AEColor; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.client.UnlistedProperty; -import appeng.client.render.cablebus.CableBusBakedModel; -import appeng.client.render.cablebus.CableBusRenderState; -import appeng.core.Api; -import appeng.core.AppEng; -import appeng.core.sync.network.NetworkHandler; -import appeng.core.sync.packets.PacketClick; -import appeng.helpers.AEGlassMaterial; -import appeng.integration.abstraction.IAEFacade; -import appeng.parts.ICableBusContainer; -import appeng.parts.NullCableBusContainer; -import appeng.tile.AEBaseTile; -import appeng.tile.networking.CableBusTESR; -import appeng.tile.networking.TileCableBus; -import appeng.tile.networking.TileCableBusTESR; -import appeng.util.Platform; - - -public class BlockCableBus extends AEBaseTileBlock implements IAEFacade -{ - - public static final UnlistedProperty RENDER_STATE_PROPERTY = new UnlistedProperty<>( "cable_bus_render_state", CableBusRenderState.class ); - - private static final ICableBusContainer NULL_CABLE_BUS = new NullCableBusContainer(); - - private static Class noTesrTile; - - private static Class tesrTile; - - public BlockCableBus() - { - super( AEGlassMaterial.INSTANCE ); - this.setLightOpacity( 0 ); - this.setFullSize( false ); - this.setOpaque( false ); - - // this will actually be overwritten later through setupTile and the - // combined layers - this.setTileEntity( TileCableBus.class ); - } - - @Override - public boolean isFullCube( IBlockState state ) - { - return false; - } - - @Override - protected BlockStateContainer createBlockState() - { - return new ExtendedBlockState( this, new IProperty[0], new IUnlistedProperty[] { RENDER_STATE_PROPERTY } ); - } - - @Override - public IBlockState getExtendedState( IBlockState state, IBlockAccess world, BlockPos pos ) - { - CableBusRenderState renderState = this.cb( world, pos ).getRenderState(); - renderState.setWorld( world ); - renderState.setPos( pos ); - return ( (IExtendedBlockState) state ).withProperty( RENDER_STATE_PROPERTY, renderState ); - } - - @Override - public void randomDisplayTick( final IBlockState state, final World worldIn, final BlockPos pos, final Random rand ) - { - this.cb( worldIn, pos ).randomDisplayTick( worldIn, pos, rand ); - } - - @Override - public void onNeighborChange( final IBlockAccess w, final BlockPos pos, final BlockPos neighbor ) - { - this.cb( w, pos ).onNeighborChanged( w, pos, neighbor ); - } - - @Override - public Item getItemDropped( final IBlockState state, final Random rand, final int fortune ) - { - return null; - } - - @Override - public int getWeakPower( final IBlockState state, final IBlockAccess w, final BlockPos pos, final EnumFacing side ) - { - return this.cb( w, pos ).isProvidingWeakPower( side.getOpposite() ); // TODO: - // IS - // OPPOSITE!? - } - - @Override - public boolean canProvidePower( final IBlockState state ) - { - return true; - } - - @Override - public void onEntityCollidedWithBlock( final World w, final BlockPos pos, final IBlockState state, final Entity entityIn ) - { - this.cb( w, pos ).onEntityCollision( entityIn ); - } - - @Override - public int getStrongPower( final IBlockState state, final IBlockAccess w, final BlockPos pos, final EnumFacing side ) - { - return this.cb( w, pos ).isProvidingStrongPower( side.getOpposite() ); // TODO: - // IS - // OPPOSITE!? - } - - @Override - public int getLightValue( final IBlockState state, final IBlockAccess world, final BlockPos pos ) - { - if( state.getBlock() != this ) - { - return state.getBlock().getLightValue( state, world, pos ); - } - return this.cb( world, pos ).getLightValue(); - } - - @Override - public boolean isLadder( final IBlockState state, final IBlockAccess world, final BlockPos pos, final EntityLivingBase entity ) - { - return this.cb( world, pos ).isLadder( entity ); - } - - @Override - public boolean isSideSolid( final IBlockState state, final IBlockAccess w, final BlockPos pos, final EnumFacing side ) - { - return this.cb( w, pos ).isSolidOnSide( side ); - } - - @Override - public boolean isReplaceable( final IBlockAccess w, final BlockPos pos ) - { - return this.cb( w, pos ).isEmpty(); - } - - @Override - public boolean removedByPlayer( final IBlockState state, final World world, final BlockPos pos, final EntityPlayer player, final boolean willHarvest ) - { - if( player.capabilities.isCreativeMode ) - { - final AEBaseTile tile = this.getTileEntity( world, pos ); - if( tile != null ) - { - tile.disableDrops(); - } - // maybe ray trace? - } - return super.removedByPlayer( state, world, pos, player, willHarvest ); - } - - @Override - public boolean canConnectRedstone( final IBlockState state, final IBlockAccess w, final BlockPos pos, EnumFacing side ) - { - if( side == null ) - { - side = EnumFacing.UP; - } - - return this.cb( w, pos ).canConnectRedstone( EnumSet.of( side ) ); - } - - @Override - public ItemStack getPickBlock( final IBlockState state, final RayTraceResult target, final World world, final BlockPos pos, final EntityPlayer player ) - { - final Vec3d v3 = target.hitVec.subtract( pos.getX(), pos.getY(), pos.getZ() ); - final SelectedPart sp = this.cb( world, pos ).selectPart( v3 ); - - if( sp.part != null ) - { - return sp.part.getItemStack( PartItemStack.PICK ); - } - else if( sp.facade != null ) - { - return sp.facade.getItemStack(); - } - - return ItemStack.EMPTY; - } - - @Override - @SideOnly( Side.CLIENT ) - public boolean addHitEffects( final IBlockState state, final World world, final RayTraceResult target, final ParticleManager effectRenderer ) - { - - // Half the particle rate. Since we're spawning concentrated on a specific spot, - // our particle effect otherwise looks too strong - if( Platform.getRandom().nextBoolean() ) - { - return true; - } - - ICableBusContainer cb = this.cb( world, target.getBlockPos() ); - - // Our built-in model has the actual baked sprites we need - IBakedModel model = Minecraft.getMinecraft().getBlockRendererDispatcher().getModelForState( this.getDefaultState() ); - - // We cannot add the effect if we don't have the model - if( !( model instanceof CableBusBakedModel ) ) - { - return true; - } - - CableBusBakedModel cableBusModel = (CableBusBakedModel) model; - - CableBusRenderState renderState = cb.getRenderState(); - - // Spawn a particle for one of the particle textures - TextureAtlasSprite texture = Platform.pickRandom( cableBusModel.getParticleTextures( renderState ) ); - if( texture != null ) - { - double x = target.hitVec.x; - double y = target.hitVec.y; - double z = target.hitVec.z; - - Particle fx = new DestroyFX( world, x, y, z, 0.0D, 0.0D, 0.0D, state ).setBlockPos( target.getBlockPos() ).multipleParticleScaleBy( 0.8F ); - fx.setParticleTexture( texture ); - effectRenderer.addEffect( fx ); - } - - return true; - } - - @Override - @SideOnly( Side.CLIENT ) - public boolean addDestroyEffects( final World world, final BlockPos pos, final ParticleManager effectRenderer ) - { - ICableBusContainer cb = this.cb( world, pos ); - - // Our built-in model has the actual baked sprites we need - IBakedModel model = Minecraft.getMinecraft().getBlockRendererDispatcher().getModelForState( this.getDefaultState() ); - - // We cannot add the effect if we dont have the model - if( !( model instanceof CableBusBakedModel ) ) - { - return true; - } - - CableBusBakedModel cableBusModel = (CableBusBakedModel) model; - - CableBusRenderState renderState = cb.getRenderState(); - - List textures = cableBusModel.getParticleTextures( renderState ); - - if( !textures.isEmpty() ) - { - // Shamelessly inspired by ParticleManager.addBlockDestroyEffects - for( int j = 0; j < 4; ++j ) - { - for( int k = 0; k < 4; ++k ) - { - for( int l = 0; l < 4; ++l ) - { - // Randomly select one of the textures if the cable bus has more than just one possibility here - final TextureAtlasSprite texture = Platform.pickRandom( textures ); - - final double d0 = pos.getX() + ( j + 0.5D ) / 4.0D; - final double d1 = pos.getY() + ( k + 0.5D ) / 4.0D; - final double d2 = pos.getZ() + ( l + 0.5D ) / 4.0D; - final ParticleDigging particle = new DestroyFX( world, d0, d1, d2, d0 - pos.getX() - 0.5D, d1 - pos - .getY() - 0.5D, d2 - pos.getZ() - 0.5D, this.getDefaultState() ).setBlockPos( pos ); - - particle.setParticleTexture( texture ); - effectRenderer.addEffect( particle ); - } - } - } - } - - return true; - } - - @Override - public void neighborChanged( IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos ) - { - if( Platform.isServer() ) - { - this.cb( world, pos ).onNeighborChanged( world, pos, fromPos ); - } - } - - private ICableBusContainer cb( final IBlockAccess w, final BlockPos pos ) - { - final TileEntity te = w.getTileEntity( pos ); - ICableBusContainer out = null; - - if( te instanceof TileCableBus ) - { - out = ( (TileCableBus) te ).getCableBus(); - } - - return out == null ? NULL_CABLE_BUS : out; - } - - @Nullable - private IFacadeContainer fc( final IBlockAccess w, final BlockPos pos ) - { - final TileEntity te = w.getTileEntity( pos ); - IFacadeContainer out = null; - - if( te instanceof TileCableBus ) - { - out = ( (TileCableBus) te ).getCableBus().getFacadeContainer(); - } - - return out; - } - - @Override - public void onBlockClicked( World worldIn, BlockPos pos, EntityPlayer playerIn ) - { - if( Platform.isClient() ) - { - final RayTraceResult rtr = Minecraft.getMinecraft().objectMouseOver; - if( rtr != null && rtr.typeOfHit == Type.BLOCK && pos.equals( rtr.getBlockPos() ) ) - { - final Vec3d hitVec = rtr.hitVec.subtract( new Vec3d( pos ) ); - - if( this.cb( worldIn, pos ).clicked( playerIn, EnumHand.MAIN_HAND, hitVec ) ) - { - NetworkHandler.instance() - .sendToServer( - new PacketClick( pos, rtr.sideHit, (float) hitVec.x, (float) hitVec.y, (float) hitVec.z, EnumHand.MAIN_HAND, true ) ); - } - } - } - } - - public void onBlockClickPacket( World worldIn, BlockPos pos, EntityPlayer playerIn, EnumHand hand, Vec3d hitVec ) - { - this.cb( worldIn, pos ).clicked( playerIn, hand, hitVec ); - } - - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - return this.cb( w, pos ).activate( player, hand, new Vec3d( hitX, hitY, hitZ ) ); - } - - @Override - public boolean recolorBlock( final World world, final BlockPos pos, final EnumFacing side, final EnumDyeColor color ) - { - return this.recolorBlock( world, pos, side, color, null ); - } - - public boolean recolorBlock( final World world, final BlockPos pos, final EnumFacing side, final EnumDyeColor color, final EntityPlayer who ) - { - try - { - return this.cb( world, pos ).recolourBlock( side, AEColor.values()[color.ordinal()], who ); - } - catch( final Throwable ignored ) - { - } - return false; - } - - @Override - @SideOnly( Side.CLIENT ) - public void getSubBlocks( final CreativeTabs tabs, final NonNullList itemStacks ) - { - // do nothing - } - - public void setupTile() - { - noTesrTile = Api.INSTANCE.partHelper().getCombinedInstance( TileCableBus.class ); - this.setTileEntity( noTesrTile ); - - GameRegistry.registerTileEntity( noTesrTile, AppEng.MOD_ID.toLowerCase() + ":" + "BlockCableBus" ); - - if( Platform.isClient() ) - { - setupTesr(); - } - } - - @SideOnly( Side.CLIENT ) - private static void setupTesr() - { - tesrTile = Api.INSTANCE.partHelper().getCombinedInstance( TileCableBusTESR.class ); - GameRegistry.registerTileEntity( tesrTile, AppEng.MOD_ID.toLowerCase() + ":" + "ClientOnly_TESR_CableBus" ); - ClientRegistry.bindTileEntitySpecialRenderer( BlockCableBus.getTesrTile(), new CableBusTESR() ); - } - - @Override - public boolean canRenderInLayer( IBlockState state, BlockRenderLayer layer ) - { - return true; - } - - @Override - public IBlockState getFacadeState( IBlockAccess world, BlockPos pos, EnumFacing side ) - { - if( side != null ) - { - IFacadeContainer container = this.fc( world, pos ); - if( container != null ) - { - IFacadePart facade = container.getFacade( AEPartLocation.fromFacing( side ) ); - if( facade != null ) - { - return facade.getBlockState(); - } - } - } - return world.getBlockState( pos ); - } - - public static Class getNoTesrTile() - { - return noTesrTile; - } - - public static Class getTesrTile() - { - return tesrTile; - } - - // Helper to get access to the protected constructor - @SideOnly( Side.CLIENT ) - private static class DestroyFX extends ParticleDigging - { - DestroyFX( World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, IBlockState state ) - { - super( worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn, state ); - } - } +import javax.annotation.Nullable; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; + + +public class BlockCableBus extends AEBaseTileBlock implements IAEFacade { + + public static final UnlistedProperty RENDER_STATE_PROPERTY = new UnlistedProperty<>("cable_bus_render_state", CableBusRenderState.class); + + private static final ICableBusContainer NULL_CABLE_BUS = new NullCableBusContainer(); + + private static Class noTesrTile; + + private static Class tesrTile; + + public BlockCableBus() { + super(AEGlassMaterial.INSTANCE); + this.setLightOpacity(0); + this.setFullSize(false); + this.setOpaque(false); + + // this will actually be overwritten later through setupTile and the + // combined layers + this.setTileEntity(TileCableBus.class); + } + + @Override + public boolean isFullCube(IBlockState state) { + return false; + } + + @Override + protected BlockStateContainer createBlockState() { + return new ExtendedBlockState(this, new IProperty[0], new IUnlistedProperty[]{RENDER_STATE_PROPERTY}); + } + + @Override + public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { + CableBusRenderState renderState = this.cb(world, pos).getRenderState(); + renderState.setWorld(world); + renderState.setPos(pos); + return ((IExtendedBlockState) state).withProperty(RENDER_STATE_PROPERTY, renderState); + } + + @Override + public void randomDisplayTick(final IBlockState state, final World worldIn, final BlockPos pos, final Random rand) { + this.cb(worldIn, pos).randomDisplayTick(worldIn, pos, rand); + } + + @Override + public void onNeighborChange(final IBlockAccess w, final BlockPos pos, final BlockPos neighbor) { + this.cb(w, pos).onNeighborChanged(w, pos, neighbor); + } + + @Override + public Item getItemDropped(final IBlockState state, final Random rand, final int fortune) { + return null; + } + + @Override + public int getWeakPower(final IBlockState state, final IBlockAccess w, final BlockPos pos, final EnumFacing side) { + return this.cb(w, pos).isProvidingWeakPower(side.getOpposite()); // TODO: + // IS + // OPPOSITE!? + } + + @Override + public boolean canProvidePower(final IBlockState state) { + return true; + } + + @Override + public void onEntityCollidedWithBlock(final World w, final BlockPos pos, final IBlockState state, final Entity entityIn) { + this.cb(w, pos).onEntityCollision(entityIn); + } + + @Override + public int getStrongPower(final IBlockState state, final IBlockAccess w, final BlockPos pos, final EnumFacing side) { + return this.cb(w, pos).isProvidingStrongPower(side.getOpposite()); // TODO: + // IS + // OPPOSITE!? + } + + @Override + public int getLightValue(final IBlockState state, final IBlockAccess world, final BlockPos pos) { + if (state.getBlock() != this) { + return state.getBlock().getLightValue(state, world, pos); + } + return this.cb(world, pos).getLightValue(); + } + + @Override + public boolean isLadder(final IBlockState state, final IBlockAccess world, final BlockPos pos, final EntityLivingBase entity) { + return this.cb(world, pos).isLadder(entity); + } + + @Override + public boolean isSideSolid(final IBlockState state, final IBlockAccess w, final BlockPos pos, final EnumFacing side) { + return this.cb(w, pos).isSolidOnSide(side); + } + + @Override + public boolean isReplaceable(final IBlockAccess w, final BlockPos pos) { + return this.cb(w, pos).isEmpty(); + } + + @Override + public boolean removedByPlayer(final IBlockState state, final World world, final BlockPos pos, final EntityPlayer player, final boolean willHarvest) { + if (player.capabilities.isCreativeMode) { + final AEBaseTile tile = this.getTileEntity(world, pos); + if (tile != null) { + tile.disableDrops(); + } + // maybe ray trace? + } + return super.removedByPlayer(state, world, pos, player, willHarvest); + } + + @Override + public boolean canConnectRedstone(final IBlockState state, final IBlockAccess w, final BlockPos pos, EnumFacing side) { + if (side == null) { + side = EnumFacing.UP; + } + + return this.cb(w, pos).canConnectRedstone(EnumSet.of(side)); + } + + @Override + public ItemStack getPickBlock(final IBlockState state, final RayTraceResult target, final World world, final BlockPos pos, final EntityPlayer player) { + final Vec3d v3 = target.hitVec.subtract(pos.getX(), pos.getY(), pos.getZ()); + final SelectedPart sp = this.cb(world, pos).selectPart(v3); + + if (sp.part != null) { + return sp.part.getItemStack(PartItemStack.PICK); + } else if (sp.facade != null) { + return sp.facade.getItemStack(); + } + + return ItemStack.EMPTY; + } + + @Override + @SideOnly(Side.CLIENT) + public boolean addHitEffects(final IBlockState state, final World world, final RayTraceResult target, final ParticleManager effectRenderer) { + + // Half the particle rate. Since we're spawning concentrated on a specific spot, + // our particle effect otherwise looks too strong + if (Platform.getRandom().nextBoolean()) { + return true; + } + + ICableBusContainer cb = this.cb(world, target.getBlockPos()); + + // Our built-in model has the actual baked sprites we need + IBakedModel model = Minecraft.getMinecraft().getBlockRendererDispatcher().getModelForState(this.getDefaultState()); + + // We cannot add the effect if we don't have the model + if (!(model instanceof CableBusBakedModel)) { + return true; + } + + CableBusBakedModel cableBusModel = (CableBusBakedModel) model; + + CableBusRenderState renderState = cb.getRenderState(); + + // Spawn a particle for one of the particle textures + TextureAtlasSprite texture = Platform.pickRandom(cableBusModel.getParticleTextures(renderState)); + if (texture != null) { + double x = target.hitVec.x; + double y = target.hitVec.y; + double z = target.hitVec.z; + + Particle fx = new DestroyFX(world, x, y, z, 0.0D, 0.0D, 0.0D, state).setBlockPos(target.getBlockPos()).multipleParticleScaleBy(0.8F); + fx.setParticleTexture(texture); + effectRenderer.addEffect(fx); + } + + return true; + } + + @Override + @SideOnly(Side.CLIENT) + public boolean addDestroyEffects(final World world, final BlockPos pos, final ParticleManager effectRenderer) { + ICableBusContainer cb = this.cb(world, pos); + + // Our built-in model has the actual baked sprites we need + IBakedModel model = Minecraft.getMinecraft().getBlockRendererDispatcher().getModelForState(this.getDefaultState()); + + // We cannot add the effect if we dont have the model + if (!(model instanceof CableBusBakedModel)) { + return true; + } + + CableBusBakedModel cableBusModel = (CableBusBakedModel) model; + + CableBusRenderState renderState = cb.getRenderState(); + + List textures = cableBusModel.getParticleTextures(renderState); + + if (!textures.isEmpty()) { + // Shamelessly inspired by ParticleManager.addBlockDestroyEffects + for (int j = 0; j < 4; ++j) { + for (int k = 0; k < 4; ++k) { + for (int l = 0; l < 4; ++l) { + // Randomly select one of the textures if the cable bus has more than just one possibility here + final TextureAtlasSprite texture = Platform.pickRandom(textures); + + final double d0 = pos.getX() + (j + 0.5D) / 4.0D; + final double d1 = pos.getY() + (k + 0.5D) / 4.0D; + final double d2 = pos.getZ() + (l + 0.5D) / 4.0D; + final ParticleDigging particle = new DestroyFX(world, d0, d1, d2, d0 - pos.getX() - 0.5D, d1 - pos + .getY() - 0.5D, d2 - pos.getZ() - 0.5D, this.getDefaultState()).setBlockPos(pos); + + particle.setParticleTexture(texture); + effectRenderer.addEffect(particle); + } + } + } + } + + return true; + } + + @Override + public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { + if (Platform.isServer()) { + this.cb(world, pos).onNeighborChanged(world, pos, fromPos); + } + } + + private ICableBusContainer cb(final IBlockAccess w, final BlockPos pos) { + final TileEntity te = w.getTileEntity(pos); + ICableBusContainer out = null; + + if (te instanceof TileCableBus) { + out = ((TileCableBus) te).getCableBus(); + } + + return out == null ? NULL_CABLE_BUS : out; + } + + @Nullable + private IFacadeContainer fc(final IBlockAccess w, final BlockPos pos) { + final TileEntity te = w.getTileEntity(pos); + IFacadeContainer out = null; + + if (te instanceof TileCableBus) { + out = ((TileCableBus) te).getCableBus().getFacadeContainer(); + } + + return out; + } + + @Override + public void onBlockClicked(World worldIn, BlockPos pos, EntityPlayer playerIn) { + if (Platform.isClient()) { + final RayTraceResult rtr = Minecraft.getMinecraft().objectMouseOver; + if (rtr != null && rtr.typeOfHit == Type.BLOCK && pos.equals(rtr.getBlockPos())) { + final Vec3d hitVec = rtr.hitVec.subtract(new Vec3d(pos)); + + if (this.cb(worldIn, pos).clicked(playerIn, EnumHand.MAIN_HAND, hitVec)) { + NetworkHandler.instance() + .sendToServer( + new PacketClick(pos, rtr.sideHit, (float) hitVec.x, (float) hitVec.y, (float) hitVec.z, EnumHand.MAIN_HAND, true)); + } + } + } + } + + public void onBlockClickPacket(World worldIn, BlockPos pos, EntityPlayer playerIn, EnumHand hand, Vec3d hitVec) { + this.cb(worldIn, pos).clicked(playerIn, hand, hitVec); + } + + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + return this.cb(w, pos).activate(player, hand, new Vec3d(hitX, hitY, hitZ)); + } + + @Override + public boolean recolorBlock(final World world, final BlockPos pos, final EnumFacing side, final EnumDyeColor color) { + return this.recolorBlock(world, pos, side, color, null); + } + + public boolean recolorBlock(final World world, final BlockPos pos, final EnumFacing side, final EnumDyeColor color, final EntityPlayer who) { + try { + return this.cb(world, pos).recolourBlock(side, AEColor.values()[color.ordinal()], who); + } catch (final Throwable ignored) { + } + return false; + } + + @Override + @SideOnly(Side.CLIENT) + public void getSubBlocks(final CreativeTabs tabs, final NonNullList itemStacks) { + // do nothing + } + + public void setupTile() { + noTesrTile = Api.INSTANCE.partHelper().getCombinedInstance(TileCableBus.class); + this.setTileEntity(noTesrTile); + + GameRegistry.registerTileEntity(noTesrTile, AppEng.MOD_ID.toLowerCase() + ":" + "BlockCableBus"); + + if (Platform.isClient()) { + setupTesr(); + } + } + + @SideOnly(Side.CLIENT) + private static void setupTesr() { + tesrTile = Api.INSTANCE.partHelper().getCombinedInstance(TileCableBusTESR.class); + GameRegistry.registerTileEntity(tesrTile, AppEng.MOD_ID.toLowerCase() + ":" + "ClientOnly_TESR_CableBus"); + ClientRegistry.bindTileEntitySpecialRenderer(BlockCableBus.getTesrTile(), new CableBusTESR()); + } + + @Override + public boolean canRenderInLayer(IBlockState state, BlockRenderLayer layer) { + return true; + } + + @Override + public IBlockState getFacadeState(IBlockAccess world, BlockPos pos, EnumFacing side) { + if (side != null) { + IFacadeContainer container = this.fc(world, pos); + if (container != null) { + IFacadePart facade = container.getFacade(AEPartLocation.fromFacing(side)); + if (facade != null) { + return facade.getBlockState(); + } + } + } + return world.getBlockState(pos); + } + + public static Class getNoTesrTile() { + return noTesrTile; + } + + public static Class getTesrTile() { + return tesrTile; + } + + // Helper to get access to the protected constructor + @SideOnly(Side.CLIENT) + private static class DestroyFX extends ParticleDigging { + DestroyFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, IBlockState state) { + super(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn, state); + } + } } diff --git a/src/main/java/appeng/block/networking/BlockController.java b/src/main/java/appeng/block/networking/BlockController.java index d13515d3a..be5015236 100644 --- a/src/main/java/appeng/block/networking/BlockController.java +++ b/src/main/java/appeng/block/networking/BlockController.java @@ -19,6 +19,8 @@ package appeng.block.networking; +import appeng.block.AEBaseTileBlock; +import appeng.tile.networking.TileController; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -31,154 +33,126 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import appeng.block.AEBaseTileBlock; -import appeng.tile.networking.TileController; +public class BlockController extends AEBaseTileBlock { -public class BlockController extends AEBaseTileBlock -{ + public enum ControllerBlockState implements IStringSerializable { + offline, online, conflicted; - public enum ControllerBlockState implements IStringSerializable - { - offline, online, conflicted; + @Override + public String getName() { + return this.name(); + } - @Override - public String getName() - { - return this.name(); - } + } - } + /** + * Controls the rendering of the controller block (connected texture style). + * inside_a and inside_b are alternating patterns for a controller that is enclosed by other controllers, + * and since they are always offline, they do not have the usual sub-states. + */ + public enum ControllerRenderType implements IStringSerializable { + block, column_x, column_y, column_z, inside_a, inside_b; - /** - * Controls the rendering of the controller block (connected texture style). - * inside_a and inside_b are alternating patterns for a controller that is enclosed by other controllers, - * and since they are always offline, they do not have the usual sub-states. - */ - public enum ControllerRenderType implements IStringSerializable - { - block, column_x, column_y, column_z, inside_a, inside_b; + @Override + public String getName() { + return this.name(); + } - @Override - public String getName() - { - return this.name(); - } + } - } + public static final PropertyEnum CONTROLLER_STATE = PropertyEnum.create("state", ControllerBlockState.class); - public static final PropertyEnum CONTROLLER_STATE = PropertyEnum.create( "state", ControllerBlockState.class ); + public static final PropertyEnum CONTROLLER_TYPE = PropertyEnum.create("type", ControllerRenderType.class); - public static final PropertyEnum CONTROLLER_TYPE = PropertyEnum.create( "type", ControllerRenderType.class ); + public BlockController() { + super(Material.IRON); + this.setHardness(6); + this.setDefaultState(this.getDefaultState() + .withProperty(CONTROLLER_STATE, ControllerBlockState.offline) + .withProperty(CONTROLLER_TYPE, ControllerRenderType.block)); + } - public BlockController() - { - super( Material.IRON ); - this.setHardness( 6 ); - this.setDefaultState( this.getDefaultState() - .withProperty( CONTROLLER_STATE, ControllerBlockState.offline ) - .withProperty( CONTROLLER_TYPE, ControllerRenderType.block ) ); - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{CONTROLLER_STATE, CONTROLLER_TYPE}; + } - @Override - protected IProperty[] getAEStates() - { - return new IProperty[] { CONTROLLER_STATE, CONTROLLER_TYPE }; - } + @Override + protected BlockStateContainer createBlockState() { + return new BlockStateContainer(this, this.getAEStates()); + } - @Override - protected BlockStateContainer createBlockState() - { - return new BlockStateContainer( this, this.getAEStates() ); - } + /** + * This will compute the AE_BLOCK_FORWARD, AE_BLOCK_UP and CONTROLLER_TYPE block states based on adjacent + * controllers and the network state of this controller (offline, online, conflicted). This is used to + * get a rudimentary connected texture feel for the controller based on how it is placed. + */ + @Override + public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) { - /** - * This will compute the AE_BLOCK_FORWARD, AE_BLOCK_UP and CONTROLLER_TYPE block states based on adjacent - * controllers and the network state of this controller (offline, online, conflicted). This is used to - * get a rudimentary connected texture feel for the controller based on how it is placed. - */ - @Override - public IBlockState getActualState( IBlockState state, IBlockAccess world, BlockPos pos ) - { + // Only used for columns, really + ControllerRenderType type = ControllerRenderType.block; - // Only used for columns, really - ControllerRenderType type = ControllerRenderType.block; + int x = pos.getX(); + int y = pos.getY(); + int z = pos.getZ(); - int x = pos.getX(); - int y = pos.getY(); - int z = pos.getZ(); + // Detect whether controllers are on both sides of the x, y, and z axes + final boolean xx = this.getTileEntity(world, x - 1, y, z) instanceof TileController && this.getTileEntity(world, x + 1, y, + z) instanceof TileController; + final boolean yy = this.getTileEntity(world, x, y - 1, z) instanceof TileController && this.getTileEntity(world, x, y + 1, + z) instanceof TileController; + final boolean zz = this.getTileEntity(world, x, y, z - 1) instanceof TileController && this.getTileEntity(world, x, y, + z + 1) instanceof TileController; - // Detect whether controllers are on both sides of the x, y, and z axes - final boolean xx = this.getTileEntity( world, x - 1, y, z ) instanceof TileController && this.getTileEntity( world, x + 1, y, - z ) instanceof TileController; - final boolean yy = this.getTileEntity( world, x, y - 1, z ) instanceof TileController && this.getTileEntity( world, x, y + 1, - z ) instanceof TileController; - final boolean zz = this.getTileEntity( world, x, y, z - 1 ) instanceof TileController && this.getTileEntity( world, x, y, - z + 1 ) instanceof TileController; + if (xx && !yy && !zz) { + type = ControllerRenderType.column_x; + } else if (!xx && yy && !zz) { + type = ControllerRenderType.column_y; + } else if (!xx && !yy && zz) { + type = ControllerRenderType.column_z; + } else if ((xx ? 1 : 0) + (yy ? 1 : 0) + (zz ? 1 : 0) >= 2) { + final int v = (Math.abs(x) + Math.abs(y) + Math.abs(z)) % 2; - if( xx && !yy && !zz ) - { - type = ControllerRenderType.column_x; - } - else if( !xx && yy && !zz ) - { - type = ControllerRenderType.column_y; - } - else if( !xx && !yy && zz ) - { - type = ControllerRenderType.column_z; - } - else if( ( xx ? 1 : 0 ) + ( yy ? 1 : 0 ) + ( zz ? 1 : 0 ) >= 2 ) - { - final int v = ( Math.abs( x ) + Math.abs( y ) + Math.abs( z ) ) % 2; + // While i'd like this to be based on the blockstate randomization feature, this generates + // an alternating pattern based on world position, so this is not 100% doable with blockstates. + if (v == 0) { + type = ControllerRenderType.inside_a; + } else { + type = ControllerRenderType.inside_b; + } + } - // While i'd like this to be based on the blockstate randomization feature, this generates - // an alternating pattern based on world position, so this is not 100% doable with blockstates. - if( v == 0 ) - { - type = ControllerRenderType.inside_a; - } - else - { - type = ControllerRenderType.inside_b; - } - } + return state.withProperty(CONTROLLER_TYPE, type); + } - return state.withProperty( CONTROLLER_TYPE, type ); - } + @Override + public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { + return state; + } - @Override - public IBlockState getExtendedState( IBlockState state, IBlockAccess world, BlockPos pos ) - { - return state; - } + @Override + public int getMetaFromState(final IBlockState state) { + return state.getValue(CONTROLLER_STATE).ordinal(); + } - @Override - public int getMetaFromState( final IBlockState state ) - { - return state.getValue( CONTROLLER_STATE ).ordinal(); - } + @Override + public IBlockState getStateFromMeta(final int meta) { + ControllerBlockState state = ControllerBlockState.values()[meta]; + return this.getDefaultState().withProperty(CONTROLLER_STATE, state); + } - @Override - public IBlockState getStateFromMeta( final int meta ) - { - ControllerBlockState state = ControllerBlockState.values()[meta]; - return this.getDefaultState().withProperty( CONTROLLER_STATE, state ); - } + @Override + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } - @Override - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } - - @Override - public void neighborChanged( IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos ) - { - final TileController tc = this.getTileEntity( world, pos ); - if( tc != null ) - { - tc.onNeighborChange( false ); - } - } + @Override + public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { + final TileController tc = this.getTileEntity(world, pos); + if (tc != null) { + tc.onNeighborChange(false); + } + } } diff --git a/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java b/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java index 73f773a28..c748c65f1 100644 --- a/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java +++ b/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java @@ -23,11 +23,9 @@ import appeng.block.AEBaseTileBlock; import appeng.helpers.AEGlassMaterial; -public class BlockCreativeEnergyCell extends AEBaseTileBlock -{ +public class BlockCreativeEnergyCell extends AEBaseTileBlock { - public BlockCreativeEnergyCell() - { - super( AEGlassMaterial.INSTANCE ); - } + public BlockCreativeEnergyCell() { + super(AEGlassMaterial.INSTANCE); + } } diff --git a/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java b/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java index 7ff50c435..5e4a3b56f 100644 --- a/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java +++ b/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java @@ -19,17 +19,14 @@ package appeng.block.networking; -public class BlockDenseEnergyCell extends BlockEnergyCell -{ +public class BlockDenseEnergyCell extends BlockEnergyCell { - public BlockDenseEnergyCell() - { + public BlockDenseEnergyCell() { - } + } - @Override - public double getMaxPower() - { - return 200000.0 * 8.0; - } + @Override + public double getMaxPower() { + return 200000.0 * 8.0; + } } diff --git a/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java b/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java index eefd04c5e..399164ee5 100644 --- a/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java +++ b/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java @@ -19,16 +19,13 @@ package appeng.block.networking; +import appeng.block.AEBaseTileBlock; import net.minecraft.block.material.Material; -import appeng.block.AEBaseTileBlock; +public class BlockEnergyAcceptor extends AEBaseTileBlock { -public class BlockEnergyAcceptor extends AEBaseTileBlock -{ - - public BlockEnergyAcceptor() - { - super( Material.IRON ); - } + public BlockEnergyAcceptor() { + super(Material.IRON); + } } diff --git a/src/main/java/appeng/block/networking/BlockEnergyCell.java b/src/main/java/appeng/block/networking/BlockEnergyCell.java index a4e13b026..45482d7ec 100644 --- a/src/main/java/appeng/block/networking/BlockEnergyCell.java +++ b/src/main/java/appeng/block/networking/BlockEnergyCell.java @@ -19,6 +19,9 @@ package appeng.block.networking; +import appeng.block.AEBaseTileBlock; +import appeng.helpers.AEGlassMaterial; +import appeng.util.Platform; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; import net.minecraft.block.state.IBlockState; @@ -29,56 +32,45 @@ import net.minecraft.util.NonNullList; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.block.AEBaseTileBlock; -import appeng.helpers.AEGlassMaterial; -import appeng.util.Platform; +public class BlockEnergyCell extends AEBaseTileBlock { -public class BlockEnergyCell extends AEBaseTileBlock -{ + public static final PropertyInteger ENERGY_STORAGE = PropertyInteger.create("fullness", 0, 7); - public static final PropertyInteger ENERGY_STORAGE = PropertyInteger.create( "fullness", 0, 7 ); + @Override + public int getMetaFromState(final IBlockState state) { + return state.getValue(ENERGY_STORAGE); + } - @Override - public int getMetaFromState( final IBlockState state ) - { - return state.getValue( ENERGY_STORAGE ); - } + @Override + public IBlockState getStateFromMeta(final int meta) { + return this.getDefaultState().withProperty(ENERGY_STORAGE, Math.min(7, Math.max(0, meta))); + } - @Override - public IBlockState getStateFromMeta( final int meta ) - { - return this.getDefaultState().withProperty( ENERGY_STORAGE, Math.min( 7, Math.max( 0, meta ) ) ); - } + public BlockEnergyCell() { + super(AEGlassMaterial.INSTANCE); + } - public BlockEnergyCell() - { - super( AEGlassMaterial.INSTANCE ); - } + @Override + @SideOnly(Side.CLIENT) + public void getSubBlocks(final CreativeTabs tabs, final NonNullList itemStacks) { + super.getSubBlocks(tabs, itemStacks); - @Override - @SideOnly( Side.CLIENT ) - public void getSubBlocks( final CreativeTabs tabs, final NonNullList itemStacks ) - { - super.getSubBlocks( tabs, itemStacks ); + final ItemStack charged = new ItemStack(this, 1); + final NBTTagCompound tag = Platform.openNbtData(charged); + tag.setDouble("internalCurrentPower", this.getMaxPower()); + tag.setDouble("internalMaxPower", this.getMaxPower()); - final ItemStack charged = new ItemStack( this, 1 ); - final NBTTagCompound tag = Platform.openNbtData( charged ); - tag.setDouble( "internalCurrentPower", this.getMaxPower() ); - tag.setDouble( "internalMaxPower", this.getMaxPower() ); + itemStacks.add(charged); + } - itemStacks.add( charged ); - } + public double getMaxPower() { + return 200000.0; + } - public double getMaxPower() - { - return 200000.0; - } - - @Override - protected IProperty[] getAEStates() - { - return new IProperty[] { ENERGY_STORAGE }; - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{ENERGY_STORAGE}; + } } diff --git a/src/main/java/appeng/block/networking/BlockEnergyCellRendering.java b/src/main/java/appeng/block/networking/BlockEnergyCellRendering.java index 90cdd1d50..ca212a375 100644 --- a/src/main/java/appeng/block/networking/BlockEnergyCellRendering.java +++ b/src/main/java/appeng/block/networking/BlockEnergyCellRendering.java @@ -19,62 +19,55 @@ package appeng.block.networking; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - import appeng.api.implementations.items.IAEItemPowerStorage; import appeng.block.AEBaseItemBlockChargeable; import appeng.bootstrap.BlockRenderingCustomizer; import appeng.bootstrap.IBlockRendering; import appeng.bootstrap.IItemRendering; import appeng.tile.networking.TileEnergyCell; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; -public class BlockEnergyCellRendering extends BlockRenderingCustomizer -{ +public class BlockEnergyCellRendering extends BlockRenderingCustomizer { - private final ResourceLocation baseModel; + private final ResourceLocation baseModel; - public BlockEnergyCellRendering( ResourceLocation baseModel ) - { - this.baseModel = baseModel; - } + public BlockEnergyCellRendering(ResourceLocation baseModel) { + this.baseModel = baseModel; + } - @Override - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - itemRendering.meshDefinition( this::getItemModel ); - // Note: Since we use the block models, we dont need to register custom variants - } + @Override + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + itemRendering.meshDefinition(this::getItemModel); + // Note: Since we use the block models, we dont need to register custom variants + } - /** - * Determines which version of the energy cell model should be used depending on the fill factor - * of the item stack. - */ - private ModelResourceLocation getItemModel( ItemStack is ) - { - double fillFactor = getFillFactor( is ); + /** + * Determines which version of the energy cell model should be used depending on the fill factor + * of the item stack. + */ + private ModelResourceLocation getItemModel(ItemStack is) { + double fillFactor = getFillFactor(is); - int storageLevel = TileEnergyCell.getStorageLevelFromFillFactor( fillFactor ); - return new ModelResourceLocation( this.baseModel, "fullness=" + storageLevel ); - } + int storageLevel = TileEnergyCell.getStorageLevelFromFillFactor(fillFactor); + return new ModelResourceLocation(this.baseModel, "fullness=" + storageLevel); + } - /** - * Helper method that returns the energy fill factor (between 0 and 1) of a given item stack. - * Returns 0 if the item stack has no fill factor. - */ - private static double getFillFactor( ItemStack is ) - { - if( !( is.getItem() instanceof IAEItemPowerStorage ) ) - { - return 0; - } + /** + * Helper method that returns the energy fill factor (between 0 and 1) of a given item stack. + * Returns 0 if the item stack has no fill factor. + */ + private static double getFillFactor(ItemStack is) { + if (!(is.getItem() instanceof IAEItemPowerStorage)) { + return 0; + } - AEBaseItemBlockChargeable itemChargeable = (AEBaseItemBlockChargeable) is.getItem(); - double curPower = itemChargeable.getAECurrentPower( is ); - double maxPower = itemChargeable.getAEMaxPower( is ); + AEBaseItemBlockChargeable itemChargeable = (AEBaseItemBlockChargeable) is.getItem(); + double curPower = itemChargeable.getAECurrentPower(is); + double maxPower = itemChargeable.getAEMaxPower(is); - return curPower / maxPower; - } + return curPower / maxPower; + } } diff --git a/src/main/java/appeng/block/networking/BlockWireless.java b/src/main/java/appeng/block/networking/BlockWireless.java index 92be630d3..7f500730c 100644 --- a/src/main/java/appeng/block/networking/BlockWireless.java +++ b/src/main/java/appeng/block/networking/BlockWireless.java @@ -19,9 +19,13 @@ package appeng.block.networking; -import java.util.Collections; -import java.util.List; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.core.sync.GuiBridge; +import appeng.helpers.AEGlassMaterial; +import appeng.helpers.ICustomCollision; +import appeng.tile.networking.TileWireless; +import appeng.util.Platform; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.IBlockState; @@ -36,224 +40,196 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.core.sync.GuiBridge; -import appeng.helpers.AEGlassMaterial; -import appeng.helpers.ICustomCollision; -import appeng.tile.networking.TileWireless; -import appeng.util.Platform; +import java.util.Collections; +import java.util.List; -public class BlockWireless extends AEBaseTileBlock implements ICustomCollision -{ +public class BlockWireless extends AEBaseTileBlock implements ICustomCollision { - enum State implements IStringSerializable - { - OFF, - ON, - HAS_CHANNEL; + enum State implements IStringSerializable { + OFF, + ON, + HAS_CHANNEL; - @Override - public String getName() - { - return this.name().toLowerCase(); - } - } + @Override + public String getName() { + return this.name().toLowerCase(); + } + } - public static final PropertyEnum STATE = PropertyEnum.create( "state", State.class ); + public static final PropertyEnum STATE = PropertyEnum.create("state", State.class); - public BlockWireless() - { - super( AEGlassMaterial.INSTANCE ); - this.setLightOpacity( 0 ); - this.setFullSize( false ); - this.setOpaque( false ); - this.setDefaultState( this.getDefaultState().withProperty( STATE, State.OFF ) ); - } + public BlockWireless() { + super(AEGlassMaterial.INSTANCE); + this.setLightOpacity(0); + this.setFullSize(false); + this.setOpaque(false); + this.setDefaultState(this.getDefaultState().withProperty(STATE, State.OFF)); + } - @Override - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } + @Override + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } - @Override - public IBlockState getActualState( IBlockState state, IBlockAccess worldIn, BlockPos pos ) - { - State teState = State.OFF; + @Override + public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { + State teState = State.OFF; - TileWireless te = this.getTileEntity( worldIn, pos ); - if( te != null ) - { - if( te.isActive() ) - { - teState = State.HAS_CHANNEL; - } - else if( te.isPowered() ) - { - teState = State.ON; - } - } + TileWireless te = this.getTileEntity(worldIn, pos); + if (te != null) { + if (te.isActive()) { + teState = State.HAS_CHANNEL; + } else if (te.isPowered()) { + teState = State.ON; + } + } - return super.getActualState( state, worldIn, pos ) - .withProperty( STATE, teState ); - } + return super.getActualState(state, worldIn, pos) + .withProperty(STATE, teState); + } - @Override - protected IProperty[] getAEStates() - { - return new IProperty[] { STATE }; - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{STATE}; + } - @Override - public boolean onBlockActivated( final World w, final BlockPos pos, final IBlockState state, final EntityPlayer player, final EnumHand hand, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - final TileWireless tg = this.getTileEntity( w, pos ); + @Override + public boolean onBlockActivated(final World w, final BlockPos pos, final IBlockState state, final EntityPlayer player, final EnumHand hand, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + final TileWireless tg = this.getTileEntity(w, pos); - if( tg != null && !player.isSneaking() ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_WIRELESS ); - } - return true; - } + if (tg != null && !player.isSneaking()) { + if (Platform.isServer()) { + Platform.openGUI(player, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_WIRELESS); + } + return true; + } - return super.onBlockActivated( w, pos, state, player, hand, side, hitX, hitY, hitZ ); - } + return super.onBlockActivated(w, pos, state, player, hand, side, hitX, hitY, hitZ); + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final BlockPos pos, final Entity thePlayer, final boolean b ) - { - final TileWireless tile = this.getTileEntity( w, pos ); - if( tile != null ) - { - final EnumFacing forward = tile.getForward(); + @Override + public Iterable getSelectedBoundingBoxesFromPool(final World w, final BlockPos pos, final Entity thePlayer, final boolean b) { + final TileWireless tile = this.getTileEntity(w, pos); + if (tile != null) { + final EnumFacing forward = tile.getForward(); - double minX = 0; - double minY = 0; - double minZ = 0; - double maxX = 1; - double maxY = 1; - double maxZ = 1; + double minX = 0; + double minY = 0; + double minZ = 0; + double maxX = 1; + double maxY = 1; + double maxZ = 1; - switch( forward ) - { - case DOWN: - minZ = minX = 3.0 / 16.0; - maxZ = maxX = 13.0 / 16.0; - maxY = 1.0; - minY = 5.0 / 16.0; - break; - case EAST: - minZ = minY = 3.0 / 16.0; - maxZ = maxY = 13.0 / 16.0; - maxX = 11.0 / 16.0; - minX = 0.0; - break; - case NORTH: - minY = minX = 3.0 / 16.0; - maxY = maxX = 13.0 / 16.0; - maxZ = 1.0; - minZ = 5.0 / 16.0; - break; - case SOUTH: - minY = minX = 3.0 / 16.0; - maxY = maxX = 13.0 / 16.0; - maxZ = 11.0 / 16.0; - minZ = 0.0; - break; - case UP: - minZ = minX = 3.0 / 16.0; - maxZ = maxX = 13.0 / 16.0; - maxY = 11.0 / 16.0; - minY = 0.0; - break; - case WEST: - minZ = minY = 3.0 / 16.0; - maxZ = maxY = 13.0 / 16.0; - maxX = 1.0; - minX = 5.0 / 16.0; - break; - default: - break; - } + switch (forward) { + case DOWN: + minZ = minX = 3.0 / 16.0; + maxZ = maxX = 13.0 / 16.0; + maxY = 1.0; + minY = 5.0 / 16.0; + break; + case EAST: + minZ = minY = 3.0 / 16.0; + maxZ = maxY = 13.0 / 16.0; + maxX = 11.0 / 16.0; + minX = 0.0; + break; + case NORTH: + minY = minX = 3.0 / 16.0; + maxY = maxX = 13.0 / 16.0; + maxZ = 1.0; + minZ = 5.0 / 16.0; + break; + case SOUTH: + minY = minX = 3.0 / 16.0; + maxY = maxX = 13.0 / 16.0; + maxZ = 11.0 / 16.0; + minZ = 0.0; + break; + case UP: + minZ = minX = 3.0 / 16.0; + maxZ = maxX = 13.0 / 16.0; + maxY = 11.0 / 16.0; + minY = 0.0; + break; + case WEST: + minZ = minY = 3.0 / 16.0; + maxZ = maxY = 13.0 / 16.0; + maxX = 1.0; + minX = 5.0 / 16.0; + break; + default: + break; + } - return Collections.singletonList( new AxisAlignedBB( minX, minY, minZ, maxX, maxY, maxZ ) ); - } - return Collections.singletonList( new AxisAlignedBB( 0.0, 0, 0.0, 1.0, 1.0, 1.0 ) ); - } + return Collections.singletonList(new AxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ)); + } + return Collections.singletonList(new AxisAlignedBB(0.0, 0, 0.0, 1.0, 1.0, 1.0)); + } - @Override - public void addCollidingBlockToList( final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e ) - { - final TileWireless tile = this.getTileEntity( w, pos ); - if( tile != null ) - { - final EnumFacing forward = tile.getForward(); + @Override + public void addCollidingBlockToList(final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e) { + final TileWireless tile = this.getTileEntity(w, pos); + if (tile != null) { + final EnumFacing forward = tile.getForward(); - double minX = 0; - double minY = 0; - double minZ = 0; - double maxX = 1; - double maxY = 1; - double maxZ = 1; + double minX = 0; + double minY = 0; + double minZ = 0; + double maxX = 1; + double maxY = 1; + double maxZ = 1; - switch( forward ) - { - case DOWN: - minZ = minX = 3.0 / 16.0; - maxZ = maxX = 13.0 / 16.0; - maxY = 1.0; - minY = 5.0 / 16.0; - break; - case EAST: - minZ = minY = 3.0 / 16.0; - maxZ = maxY = 13.0 / 16.0; - maxX = 11.0 / 16.0; - minX = 0.0; - break; - case NORTH: - minY = minX = 3.0 / 16.0; - maxY = maxX = 13.0 / 16.0; - maxZ = 1.0; - minZ = 5.0 / 16.0; - break; - case SOUTH: - minY = minX = 3.0 / 16.0; - maxY = maxX = 13.0 / 16.0; - maxZ = 11.0 / 16.0; - minZ = 0.0; - break; - case UP: - minZ = minX = 3.0 / 16.0; - maxZ = maxX = 13.0 / 16.0; - maxY = 11.0 / 16.0; - minY = 0.0; - break; - case WEST: - minZ = minY = 3.0 / 16.0; - maxZ = maxY = 13.0 / 16.0; - maxX = 1.0; - minX = 5.0 / 16.0; - break; - default: - break; - } + switch (forward) { + case DOWN: + minZ = minX = 3.0 / 16.0; + maxZ = maxX = 13.0 / 16.0; + maxY = 1.0; + minY = 5.0 / 16.0; + break; + case EAST: + minZ = minY = 3.0 / 16.0; + maxZ = maxY = 13.0 / 16.0; + maxX = 11.0 / 16.0; + minX = 0.0; + break; + case NORTH: + minY = minX = 3.0 / 16.0; + maxY = maxX = 13.0 / 16.0; + maxZ = 1.0; + minZ = 5.0 / 16.0; + break; + case SOUTH: + minY = minX = 3.0 / 16.0; + maxY = maxX = 13.0 / 16.0; + maxZ = 11.0 / 16.0; + minZ = 0.0; + break; + case UP: + minZ = minX = 3.0 / 16.0; + maxZ = maxX = 13.0 / 16.0; + maxY = 11.0 / 16.0; + minY = 0.0; + break; + case WEST: + minZ = minY = 3.0 / 16.0; + maxZ = maxY = 13.0 / 16.0; + maxX = 1.0; + minX = 5.0 / 16.0; + break; + default: + break; + } - out.add( new AxisAlignedBB( minX, minY, minZ, maxX, maxY, maxZ ) ); - } - else - { - out.add( new AxisAlignedBB( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ) ); - } - } + out.add(new AxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ)); + } else { + out.add(new AxisAlignedBB(0.0, 0.0, 0.0, 1.0, 1.0, 1.0)); + } + } - @Override - public boolean isFullCube( IBlockState state ) - { - return false; - } + @Override + public boolean isFullCube(IBlockState state) { + return false; + } } diff --git a/src/main/java/appeng/block/networking/CableBusColor.java b/src/main/java/appeng/block/networking/CableBusColor.java index beff3fbe3..a6785e93d 100644 --- a/src/main/java/appeng/block/networking/CableBusColor.java +++ b/src/main/java/appeng/block/networking/CableBusColor.java @@ -19,6 +19,8 @@ package appeng.block.networking; +import appeng.api.util.AEColor; +import appeng.client.render.cablebus.CableBusRenderState; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.color.IBlockColor; import net.minecraft.util.math.BlockPos; @@ -27,33 +29,26 @@ import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.util.AEColor; -import appeng.client.render.cablebus.CableBusRenderState; - /** * Exposes the cable bus color as tint indices 0 (dark variant), 1 (medium variant) and 2 (bright variant). */ -@SideOnly( Side.CLIENT ) -public class CableBusColor implements IBlockColor -{ +@SideOnly(Side.CLIENT) +public class CableBusColor implements IBlockColor { - @Override - public int colorMultiplier( IBlockState state, IBlockAccess worldIn, BlockPos pos, int color ) - { + @Override + public int colorMultiplier(IBlockState state, IBlockAccess worldIn, BlockPos pos, int color) { - AEColor busColor = AEColor.TRANSPARENT; + AEColor busColor = AEColor.TRANSPARENT; - if( state instanceof IExtendedBlockState ) - { - CableBusRenderState renderState = ( (IExtendedBlockState) state ).getValue( BlockCableBus.RENDER_STATE_PROPERTY ); - if( renderState != null ) - { - busColor = renderState.getCableColor(); - } - } + if (state instanceof IExtendedBlockState) { + CableBusRenderState renderState = ((IExtendedBlockState) state).getValue(BlockCableBus.RENDER_STATE_PROPERTY); + if (renderState != null) { + busColor = renderState.getCableColor(); + } + } - return busColor.getVariantByTintIndex( color ); + return busColor.getVariantByTintIndex(color); - } + } } diff --git a/src/main/java/appeng/block/networking/CableBusRendering.java b/src/main/java/appeng/block/networking/CableBusRendering.java index faea932a9..92cf12c24 100644 --- a/src/main/java/appeng/block/networking/CableBusRendering.java +++ b/src/main/java/appeng/block/networking/CableBusRendering.java @@ -19,34 +19,30 @@ package appeng.block.networking; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.bootstrap.BlockRenderingCustomizer; import appeng.bootstrap.IBlockRendering; import appeng.bootstrap.IItemRendering; import appeng.client.render.cablebus.CableBusModel; import appeng.core.features.registries.PartModels; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; /** * Customizes the rendering behavior for cable busses, which are the biggest multipart of AE2. */ -public class CableBusRendering extends BlockRenderingCustomizer -{ - private final PartModels partModels; +public class CableBusRendering extends BlockRenderingCustomizer { + private final PartModels partModels; - public CableBusRendering( PartModels partModels ) - { - this.partModels = partModels; - } + public CableBusRendering(PartModels partModels) { + this.partModels = partModels; + } - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - rendering.builtInModel( "models/block/builtin/cable_bus", new CableBusModel( this.partModels ) ); - rendering.blockColor( new CableBusColor() ); - rendering.modelCustomizer( ( loc, model ) -> model ); - } + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + rendering.builtInModel("models/block/builtin/cable_bus", new CableBusModel(this.partModels)); + rendering.blockColor(new CableBusColor()); + rendering.modelCustomizer((loc, model) -> model); + } } diff --git a/src/main/java/appeng/block/networking/ControllerRendering.java b/src/main/java/appeng/block/networking/ControllerRendering.java index fdc7113d6..926f826a3 100644 --- a/src/main/java/appeng/block/networking/ControllerRendering.java +++ b/src/main/java/appeng/block/networking/ControllerRendering.java @@ -24,12 +24,10 @@ import appeng.bootstrap.IBlockRendering; import appeng.bootstrap.IItemRendering; -public class ControllerRendering extends BlockRenderingCustomizer -{ - @Override - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - // Disables the default model rotator - rendering.modelCustomizer( ( loc, model ) -> model ); - } +public class ControllerRendering extends BlockRenderingCustomizer { + @Override + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + // Disables the default model rotator + rendering.modelCustomizer((loc, model) -> model); + } } diff --git a/src/main/java/appeng/block/networking/WirelessRendering.java b/src/main/java/appeng/block/networking/WirelessRendering.java index cca9f4ea0..770c2f375 100644 --- a/src/main/java/appeng/block/networking/WirelessRendering.java +++ b/src/main/java/appeng/block/networking/WirelessRendering.java @@ -1,23 +1,19 @@ - package appeng.block.networking; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.util.AEColor; import appeng.bootstrap.BlockRenderingCustomizer; import appeng.bootstrap.IBlockRendering; import appeng.bootstrap.IItemRendering; import appeng.client.render.StaticBlockColor; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class WirelessRendering extends BlockRenderingCustomizer -{ - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - rendering.blockColor( new StaticBlockColor( AEColor.TRANSPARENT ) ); - } +public class WirelessRendering extends BlockRenderingCustomizer { + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + rendering.blockColor(new StaticBlockColor(AEColor.TRANSPARENT)); + } } diff --git a/src/main/java/appeng/block/paint/BlockPaint.java b/src/main/java/appeng/block/paint/BlockPaint.java index be0af2a8d..9670f7889 100644 --- a/src/main/java/appeng/block/paint/BlockPaint.java +++ b/src/main/java/appeng/block/paint/BlockPaint.java @@ -19,10 +19,10 @@ package appeng.block.paint; -import java.util.Collection; -import java.util.Collections; -import java.util.Random; - +import appeng.block.AEBaseTileBlock; +import appeng.helpers.Splotch; +import appeng.tile.misc.TilePaint; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.MaterialLiquid; @@ -44,128 +44,108 @@ import net.minecraftforge.common.property.IUnlistedProperty; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.block.AEBaseTileBlock; -import appeng.helpers.Splotch; -import appeng.tile.misc.TilePaint; -import appeng.util.Platform; +import java.util.Collection; +import java.util.Collections; +import java.util.Random; -public class BlockPaint extends AEBaseTileBlock -{ +public class BlockPaint extends AEBaseTileBlock { - static final PaintSplotchesProperty SPLOTCHES = new PaintSplotchesProperty(); + static final PaintSplotchesProperty SPLOTCHES = new PaintSplotchesProperty(); - public BlockPaint() - { - super( new MaterialLiquid( MapColor.AIR ) ); + public BlockPaint() { + super(new MaterialLiquid(MapColor.AIR)); - this.setLightOpacity( 0 ); - this.setFullSize( false ); - this.setOpaque( false ); - } + this.setLightOpacity(0); + this.setFullSize(false); + this.setOpaque(false); + } - @Override - protected BlockStateContainer createBlockState() - { - return new ExtendedBlockState( this, new IProperty[0], new IUnlistedProperty[] { SPLOTCHES } ); - } + @Override + protected BlockStateContainer createBlockState() { + return new ExtendedBlockState(this, new IProperty[0], new IUnlistedProperty[]{SPLOTCHES}); + } - @Override - public IBlockState getExtendedState( IBlockState state, IBlockAccess world, BlockPos pos ) - { - IExtendedBlockState extState = (IExtendedBlockState) state; + @Override + public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { + IExtendedBlockState extState = (IExtendedBlockState) state; - TilePaint te = this.getTileEntity( world, pos ); + TilePaint te = this.getTileEntity(world, pos); - Collection splotches = Collections.emptyList(); - if( te != null ) - { - splotches = te.getDots(); - } + Collection splotches = Collections.emptyList(); + if (te != null) { + splotches = te.getDots(); + } - return extState.withProperty( SPLOTCHES, new PaintSplotches( splotches ) ); - } + return extState.withProperty(SPLOTCHES, new PaintSplotches(splotches)); + } - @Override - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } + @Override + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } - @Override - @SideOnly( Side.CLIENT ) - public void getSubBlocks( final CreativeTabs tabs, final NonNullList itemStacks ) - { - // do nothing - } + @Override + @SideOnly(Side.CLIENT) + public void getSubBlocks(final CreativeTabs tabs, final NonNullList itemStacks) { + // do nothing + } - @Override - public AxisAlignedBB getCollisionBoundingBox( IBlockState blockState, IBlockAccess worldIn, BlockPos pos ) - { - return null; - } + @Override + public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { + return null; + } - @Override - public boolean canCollideCheck( final IBlockState state, final boolean hitIfLiquid ) - { - return false; - } + @Override + public boolean canCollideCheck(final IBlockState state, final boolean hitIfLiquid) { + return false; + } - @Override - public void neighborChanged( IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos ) - { - final TilePaint tp = this.getTileEntity( world, pos ); + @Override + public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { + final TilePaint tp = this.getTileEntity(world, pos); - if( tp != null ) - { - tp.neighborChanged(); - } - } + if (tp != null) { + tp.neighborChanged(); + } + } - @Override - public Item getItemDropped( final IBlockState state, final Random rand, final int fortune ) - { - return null; - } + @Override + public Item getItemDropped(final IBlockState state, final Random rand, final int fortune) { + return null; + } - @Override - public void dropBlockAsItemWithChance( final World worldIn, final BlockPos pos, final IBlockState state, final float chance, final int fortune ) - { + @Override + public void dropBlockAsItemWithChance(final World worldIn, final BlockPos pos, final IBlockState state, final float chance, final int fortune) { - } + } - @Override - public void fillWithRain( final World w, final BlockPos pos ) - { - if( Platform.isServer() ) - { - w.setBlockToAir( pos ); - } - } + @Override + public void fillWithRain(final World w, final BlockPos pos) { + if (Platform.isServer()) { + w.setBlockToAir(pos); + } + } - @Override - public int getLightValue( final IBlockState state, final IBlockAccess w, final BlockPos pos ) - { - final TilePaint tp = this.getTileEntity( w, pos ); + @Override + public int getLightValue(final IBlockState state, final IBlockAccess w, final BlockPos pos) { + final TilePaint tp = this.getTileEntity(w, pos); - if( tp != null ) - { - return tp.getLightLevel(); - } + if (tp != null) { + return tp.getLightLevel(); + } - return 0; - } + return 0; + } - @Override - public boolean isAir( final IBlockState state, final IBlockAccess world, final BlockPos pos ) - { - return true; - } + @Override + public boolean isAir(final IBlockState state, final IBlockAccess world, final BlockPos pos) { + return true; + } - @Override - public boolean isReplaceable( final IBlockAccess worldIn, final BlockPos pos ) - { - return true; - } + @Override + public boolean isReplaceable(final IBlockAccess worldIn, final BlockPos pos) { + return true; + } } diff --git a/src/main/java/appeng/block/paint/PaintBakedModel.java b/src/main/java/appeng/block/paint/PaintBakedModel.java index da133ab25..7010e3f63 100644 --- a/src/main/java/appeng/block/paint/PaintBakedModel.java +++ b/src/main/java/appeng/block/paint/PaintBakedModel.java @@ -1,16 +1,10 @@ - package appeng.block.paint; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.function.Function; - -import javax.annotation.Nullable; - +import appeng.client.render.cablebus.CubeBuilder; +import appeng.core.AppEng; +import appeng.helpers.Splotch; import com.google.common.collect.ImmutableList; - import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -22,9 +16,11 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.property.IExtendedBlockState; -import appeng.client.render.cablebus.CubeBuilder; -import appeng.core.AppEng; -import appeng.helpers.Splotch; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; /** @@ -32,168 +28,150 @@ import appeng.helpers.Splotch; * a * matter cannon with paint balls. */ -class PaintBakedModel implements IBakedModel -{ +class PaintBakedModel implements IBakedModel { - private static final ResourceLocation TEXTURE_PAINT1 = new ResourceLocation( AppEng.MOD_ID, "blocks/paint1" ); - private static final ResourceLocation TEXTURE_PAINT2 = new ResourceLocation( AppEng.MOD_ID, "blocks/paint2" ); - private static final ResourceLocation TEXTURE_PAINT3 = new ResourceLocation( AppEng.MOD_ID, "blocks/paint3" ); + private static final ResourceLocation TEXTURE_PAINT1 = new ResourceLocation(AppEng.MOD_ID, "blocks/paint1"); + private static final ResourceLocation TEXTURE_PAINT2 = new ResourceLocation(AppEng.MOD_ID, "blocks/paint2"); + private static final ResourceLocation TEXTURE_PAINT3 = new ResourceLocation(AppEng.MOD_ID, "blocks/paint3"); - private final VertexFormat vertexFormat; + private final VertexFormat vertexFormat; - private final TextureAtlasSprite[] textures; + private final TextureAtlasSprite[] textures; - PaintBakedModel( VertexFormat vertexFormat, Function bakedTextureGetter ) - { - this.vertexFormat = vertexFormat; - this.textures = new TextureAtlasSprite[] { - bakedTextureGetter.apply( TEXTURE_PAINT1 ), - bakedTextureGetter.apply( TEXTURE_PAINT2 ), - bakedTextureGetter.apply( TEXTURE_PAINT3 ) - }; - } + PaintBakedModel(VertexFormat vertexFormat, Function bakedTextureGetter) { + this.vertexFormat = vertexFormat; + this.textures = new TextureAtlasSprite[]{ + bakedTextureGetter.apply(TEXTURE_PAINT1), + bakedTextureGetter.apply(TEXTURE_PAINT2), + bakedTextureGetter.apply(TEXTURE_PAINT3) + }; + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - if( side != null ) - { - return Collections.emptyList(); - } + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + if (side != null) { + return Collections.emptyList(); + } - if( !( state instanceof IExtendedBlockState ) ) - { - // This is the inventory model which should usually not be used other than in special cases - List quads = new ArrayList<>( 1 ); - CubeBuilder builder = new CubeBuilder( this.vertexFormat, quads ); - builder.setTexture( this.textures[0] ); - builder.addCube( 0, 0, 0, 16, 16, 16 ); - return quads; - } + if (!(state instanceof IExtendedBlockState)) { + // This is the inventory model which should usually not be used other than in special cases + List quads = new ArrayList<>(1); + CubeBuilder builder = new CubeBuilder(this.vertexFormat, quads); + builder.setTexture(this.textures[0]); + builder.addCube(0, 0, 0, 16, 16, 16); + return quads; + } - IExtendedBlockState extendedBlockState = (IExtendedBlockState) state; - PaintSplotches splotchesState = extendedBlockState.getValue( BlockPaint.SPLOTCHES ); + IExtendedBlockState extendedBlockState = (IExtendedBlockState) state; + PaintSplotches splotchesState = extendedBlockState.getValue(BlockPaint.SPLOTCHES); - if( splotchesState == null ) - { - return Collections.emptyList(); - } + if (splotchesState == null) { + return Collections.emptyList(); + } - List splotches = splotchesState.getSplotches(); + List splotches = splotchesState.getSplotches(); - CubeBuilder builder = new CubeBuilder( this.vertexFormat ); + CubeBuilder builder = new CubeBuilder(this.vertexFormat); - float offsetConstant = 0.001f; - for( final Splotch s : splotches ) - { + float offsetConstant = 0.001f; + for (final Splotch s : splotches) { - if( s.isLumen() ) - { - builder.setColorRGB( s.getColor().whiteVariant ); - builder.setRenderFullBright( true ); - } - else - { - builder.setColorRGB( s.getColor().mediumVariant ); - builder.setRenderFullBright( false ); - } + if (s.isLumen()) { + builder.setColorRGB(s.getColor().whiteVariant); + builder.setRenderFullBright(true); + } else { + builder.setColorRGB(s.getColor().mediumVariant); + builder.setRenderFullBright(false); + } - float offset = offsetConstant; - offsetConstant += 0.001f; + float offset = offsetConstant; + offsetConstant += 0.001f; - final float buffer = 0.1f; + final float buffer = 0.1f; - float pos_x = s.x(); - float pos_y = s.y(); + float pos_x = s.x(); + float pos_y = s.y(); - pos_x = Math.max( buffer, Math.min( 1.0f - buffer, pos_x ) ); - pos_y = Math.max( buffer, Math.min( 1.0f - buffer, pos_y ) ); + pos_x = Math.max(buffer, Math.min(1.0f - buffer, pos_x)); + pos_y = Math.max(buffer, Math.min(1.0f - buffer, pos_y)); - TextureAtlasSprite ico = this.textures[s.getSeed() % this.textures.length]; - builder.setTexture( ico ); - builder.setCustomUv( s.getSide().getOpposite(), 0, 0, 16, 16 ); + TextureAtlasSprite ico = this.textures[s.getSeed() % this.textures.length]; + builder.setTexture(ico); + builder.setCustomUv(s.getSide().getOpposite(), 0, 0, 16, 16); - switch( s.getSide() ) - { - case UP: - offset = 1.0f - offset; - builder.addQuad( EnumFacing.DOWN, pos_x - buffer, offset, pos_y - buffer, - pos_x + buffer, offset, pos_y + buffer ); - break; + switch (s.getSide()) { + case UP: + offset = 1.0f - offset; + builder.addQuad(EnumFacing.DOWN, pos_x - buffer, offset, pos_y - buffer, + pos_x + buffer, offset, pos_y + buffer); + break; - case DOWN: - builder.addQuad( EnumFacing.UP, pos_x - buffer, offset, pos_y - buffer, - pos_x + buffer, offset, pos_y + buffer ); - break; + case DOWN: + builder.addQuad(EnumFacing.UP, pos_x - buffer, offset, pos_y - buffer, + pos_x + buffer, offset, pos_y + buffer); + break; - case EAST: - offset = 1.0f - offset; - builder.addQuad( EnumFacing.WEST, offset, pos_x - buffer, pos_y - buffer, - offset, pos_x + buffer, pos_y + buffer ); - break; + case EAST: + offset = 1.0f - offset; + builder.addQuad(EnumFacing.WEST, offset, pos_x - buffer, pos_y - buffer, + offset, pos_x + buffer, pos_y + buffer); + break; - case WEST: - builder.addQuad( EnumFacing.EAST, offset, pos_x - buffer, pos_y - buffer, - offset, pos_x + buffer, pos_y + buffer ); - break; + case WEST: + builder.addQuad(EnumFacing.EAST, offset, pos_x - buffer, pos_y - buffer, + offset, pos_x + buffer, pos_y + buffer); + break; - case SOUTH: - offset = 1.0f - offset; - builder.addQuad( EnumFacing.NORTH, pos_x - buffer, pos_y - buffer, offset, - pos_x + buffer, pos_y + buffer, offset ); - break; + case SOUTH: + offset = 1.0f - offset; + builder.addQuad(EnumFacing.NORTH, pos_x - buffer, pos_y - buffer, offset, + pos_x + buffer, pos_y + buffer, offset); + break; - case NORTH: - builder.addQuad( EnumFacing.SOUTH, pos_x - buffer, pos_y - buffer, offset, - pos_x + buffer, pos_y + buffer, offset ); - break; + case NORTH: + builder.addQuad(EnumFacing.SOUTH, pos_x - buffer, pos_y - buffer, offset, + pos_x + buffer, pos_y + buffer, offset); + break; - default: - } - } + default: + } + } - return builder.getOutput(); - } + return builder.getOutput(); + } - @Override - public boolean isAmbientOcclusion() - { - return false; - } + @Override + public boolean isAmbientOcclusion() { + return false; + } - @Override - public boolean isGui3d() - { - return true; - } + @Override + public boolean isGui3d() { + return true; + } - @Override - public boolean isBuiltInRenderer() - { - return false; - } + @Override + public boolean isBuiltInRenderer() { + return false; + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.textures[0]; - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.textures[0]; + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return ItemCameraTransforms.DEFAULT; - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return ItemCameraTransforms.DEFAULT; + } - @Override - public ItemOverrideList getOverrides() - { - return ItemOverrideList.NONE; - } + @Override + public ItemOverrideList getOverrides() { + return ItemOverrideList.NONE; + } - static List getRequiredTextures() - { - return ImmutableList.of( - TEXTURE_PAINT1, TEXTURE_PAINT2, TEXTURE_PAINT3 ); - } + static List getRequiredTextures() { + return ImmutableList.of( + TEXTURE_PAINT1, TEXTURE_PAINT2, TEXTURE_PAINT3); + } } diff --git a/src/main/java/appeng/block/paint/PaintModel.java b/src/main/java/appeng/block/paint/PaintModel.java index b5b4c49af..5ff58daf4 100644 --- a/src/main/java/appeng/block/paint/PaintModel.java +++ b/src/main/java/appeng/block/paint/PaintModel.java @@ -1,11 +1,6 @@ - package appeng.block.paint; -import java.util.Collection; -import java.util.Collections; -import java.util.function.Function; - import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -14,32 +9,31 @@ import net.minecraftforge.client.model.IModel; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; +import java.util.Collection; +import java.util.Collections; +import java.util.function.Function; -class PaintModel implements IModel -{ - @Override - public Collection getDependencies() - { - return Collections.emptyList(); - } +class PaintModel implements IModel { - @Override - public Collection getTextures() - { - return PaintBakedModel.getRequiredTextures(); - } + @Override + public Collection getDependencies() { + return Collections.emptyList(); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - return new PaintBakedModel( format, bakedTextureGetter ); - } + @Override + public Collection getTextures() { + return PaintBakedModel.getRequiredTextures(); + } - @Override - public IModelState getDefaultState() - { - return TRSRTransformation.identity(); - } + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + return new PaintBakedModel(format, bakedTextureGetter); + } + + @Override + public IModelState getDefaultState() { + return TRSRTransformation.identity(); + } } diff --git a/src/main/java/appeng/block/paint/PaintRendering.java b/src/main/java/appeng/block/paint/PaintRendering.java index 192116b53..abf3bee33 100644 --- a/src/main/java/appeng/block/paint/PaintRendering.java +++ b/src/main/java/appeng/block/paint/PaintRendering.java @@ -1,24 +1,20 @@ - package appeng.block.paint; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.bootstrap.BlockRenderingCustomizer; import appeng.bootstrap.IBlockRendering; import appeng.bootstrap.IItemRendering; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class PaintRendering extends BlockRenderingCustomizer -{ +public class PaintRendering extends BlockRenderingCustomizer { - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - rendering.builtInModel( "models/block/paint", new PaintModel() ); - // Disable auto rotation - rendering.modelCustomizer( ( location, model ) -> model ); - } + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + rendering.builtInModel("models/block/paint", new PaintModel()); + // Disable auto rotation + rendering.modelCustomizer((location, model) -> model); + } } diff --git a/src/main/java/appeng/block/paint/PaintSplotches.java b/src/main/java/appeng/block/paint/PaintSplotches.java index 5e86d64e3..9ac990ca7 100644 --- a/src/main/java/appeng/block/paint/PaintSplotches.java +++ b/src/main/java/appeng/block/paint/PaintSplotches.java @@ -1,31 +1,26 @@ - package appeng.block.paint; -import java.util.Collection; -import java.util.List; - +import appeng.helpers.Splotch; import com.google.common.collect.ImmutableList; -import appeng.helpers.Splotch; +import java.util.Collection; +import java.util.List; /** * Used to transfer the state about paint splotches from the game thread to the render thread. */ -class PaintSplotches -{ +class PaintSplotches { - private final List splotches; + private final List splotches; - PaintSplotches( Collection splotches ) - { - this.splotches = ImmutableList.copyOf( splotches ); - } + PaintSplotches(Collection splotches) { + this.splotches = ImmutableList.copyOf(splotches); + } - List getSplotches() - { - return this.splotches; - } + List getSplotches() { + return this.splotches; + } } diff --git a/src/main/java/appeng/block/paint/PaintSplotchesProperty.java b/src/main/java/appeng/block/paint/PaintSplotchesProperty.java index 2fe61f9aa..98762d7dd 100644 --- a/src/main/java/appeng/block/paint/PaintSplotchesProperty.java +++ b/src/main/java/appeng/block/paint/PaintSplotchesProperty.java @@ -1,34 +1,28 @@ - package appeng.block.paint; import net.minecraftforge.common.property.IUnlistedProperty; -class PaintSplotchesProperty implements IUnlistedProperty -{ +class PaintSplotchesProperty implements IUnlistedProperty { - @Override - public String getName() - { - return "paint_splots"; - } + @Override + public String getName() { + return "paint_splots"; + } - @Override - public boolean isValid( PaintSplotches value ) - { - return value != null; - } + @Override + public boolean isValid(PaintSplotches value) { + return value != null; + } - @Override - public Class getType() - { - return PaintSplotches.class; - } + @Override + public Class getType() { + return PaintSplotches.class; + } - @Override - public String valueToString( PaintSplotches value ) - { - return null; - } + @Override + public String valueToString(PaintSplotches value) { + return null; + } } diff --git a/src/main/java/appeng/block/qnb/BlockQuantumBase.java b/src/main/java/appeng/block/qnb/BlockQuantumBase.java index 311f4501d..745b7cdcb 100644 --- a/src/main/java/appeng/block/qnb/BlockQuantumBase.java +++ b/src/main/java/appeng/block/qnb/BlockQuantumBase.java @@ -19,6 +19,9 @@ package appeng.block.qnb; +import appeng.block.AEBaseTileBlock; +import appeng.helpers.ICustomCollision; +import appeng.tile.qnb.TileQuantumBridge; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -34,97 +37,79 @@ import net.minecraftforge.common.property.ExtendedBlockState; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.common.property.IUnlistedProperty; -import appeng.block.AEBaseTileBlock; -import appeng.helpers.ICustomCollision; -import appeng.tile.qnb.TileQuantumBridge; +public abstract class BlockQuantumBase extends AEBaseTileBlock implements ICustomCollision { -public abstract class BlockQuantumBase extends AEBaseTileBlock implements ICustomCollision -{ + public static final PropertyBool FORMED = PropertyBool.create("formed"); - public static final PropertyBool FORMED = PropertyBool.create( "formed" ); + public static final QnbFormedStateProperty FORMED_STATE = new QnbFormedStateProperty(); - public static final QnbFormedStateProperty FORMED_STATE = new QnbFormedStateProperty(); + public BlockQuantumBase(final Material mat) { + super(mat); + final float shave = 2.0f / 16.0f; + this.boundingBox = new AxisAlignedBB(shave, shave, shave, 1.0f - shave, 1.0f - shave, 1.0f - shave); + this.setLightOpacity(0); + this.setFullSize(this.setOpaque(false)); + this.setDefaultState(this.getDefaultState().withProperty(FORMED, false)); + } - public BlockQuantumBase( final Material mat ) - { - super( mat ); - final float shave = 2.0f / 16.0f; - this.boundingBox = new AxisAlignedBB( shave, shave, shave, 1.0f - shave, 1.0f - shave, 1.0f - shave ); - this.setLightOpacity( 0 ); - this.setFullSize( this.setOpaque( false ) ); - this.setDefaultState( this.getDefaultState().withProperty( FORMED, false ) ); - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{FORMED}; + } - @Override - protected IProperty[] getAEStates() - { - return new IProperty[] { FORMED }; - } + @Override + protected BlockStateContainer createBlockState() { + return new ExtendedBlockState(this, this.getAEStates(), new IUnlistedProperty[]{FORMED_STATE}); + } - @Override - protected BlockStateContainer createBlockState() - { - return new ExtendedBlockState( this, this.getAEStates(), new IUnlistedProperty[] { FORMED_STATE } ); - } + @Override + public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { + IExtendedBlockState extState = (IExtendedBlockState) state; - @Override - public IBlockState getExtendedState( IBlockState state, IBlockAccess world, BlockPos pos ) - { - IExtendedBlockState extState = (IExtendedBlockState) state; + TileQuantumBridge bridge = this.getTileEntity(world, pos); + if (bridge != null) { + QnbFormedState formedState = new QnbFormedState(bridge.getAdjacentQuantumBridges(), bridge.isCorner(), bridge.isPowered()); + extState = extState.withProperty(FORMED_STATE, formedState); + } - TileQuantumBridge bridge = this.getTileEntity( world, pos ); - if( bridge != null ) - { - QnbFormedState formedState = new QnbFormedState( bridge.getAdjacentQuantumBridges(), bridge.isCorner(), bridge.isPowered() ); - extState = extState.withProperty( FORMED_STATE, formedState ); - } + return extState; + } - return extState; - } + @Override + public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { + TileQuantumBridge bridge = this.getTileEntity(worldIn, pos); + if (bridge != null) { + state = state.withProperty(FORMED, bridge.isFormed()); + } + return state; + } - @Override - public IBlockState getActualState( IBlockState state, IBlockAccess worldIn, BlockPos pos ) - { - TileQuantumBridge bridge = this.getTileEntity( worldIn, pos ); - if( bridge != null ) - { - state = state.withProperty( FORMED, bridge.isFormed() ); - } - return state; - } + @Override + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } - @Override - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } + @Override + public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { + final TileQuantumBridge bridge = this.getTileEntity(world, pos); + if (bridge != null) { + bridge.neighborUpdate(); + } + } - @Override - public void neighborChanged( IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos ) - { - final TileQuantumBridge bridge = this.getTileEntity( world, pos ); - if( bridge != null ) - { - bridge.neighborUpdate(); - } - } + @Override + public void breakBlock(final World w, final BlockPos pos, final IBlockState state) { + final TileQuantumBridge bridge = this.getTileEntity(w, pos); + if (bridge != null) { + bridge.breakCluster(); + } - @Override - public void breakBlock( final World w, final BlockPos pos, final IBlockState state ) - { - final TileQuantumBridge bridge = this.getTileEntity( w, pos ); - if( bridge != null ) - { - bridge.breakCluster(); - } + super.breakBlock(w, pos, state); + } - super.breakBlock( w, pos, state ); - } - - @Override - public boolean isFullCube( IBlockState state ) - { - return false; - } + @Override + public boolean isFullCube(IBlockState state) { + return false; + } } diff --git a/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java b/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java index 0072f1728..32bc46e92 100644 --- a/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java +++ b/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java @@ -19,12 +19,13 @@ package appeng.block.qnb; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.client.EffectType; +import appeng.core.AppEng; +import appeng.core.sync.GuiBridge; +import appeng.helpers.AEGlassMaterial; +import appeng.tile.qnb.TileQuantumBridge; +import appeng.util.Platform; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; @@ -35,70 +36,55 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.client.EffectType; -import appeng.core.AppEng; -import appeng.core.sync.GuiBridge; -import appeng.helpers.AEGlassMaterial; -import appeng.tile.qnb.TileQuantumBridge; -import appeng.util.Platform; +import javax.annotation.Nullable; +import java.util.Collections; +import java.util.List; +import java.util.Random; -public class BlockQuantumLinkChamber extends BlockQuantumBase -{ +public class BlockQuantumLinkChamber extends BlockQuantumBase { - public BlockQuantumLinkChamber() - { - super( AEGlassMaterial.INSTANCE ); - } + public BlockQuantumLinkChamber() { + super(AEGlassMaterial.INSTANCE); + } - @Override - public void randomDisplayTick( final IBlockState state, final World w, final BlockPos pos, final Random rand ) - { - final TileQuantumBridge bridge = this.getTileEntity( w, pos ); - if( bridge != null ) - { - if( bridge.hasQES() ) - { - if( AppEng.proxy.shouldAddParticles( rand ) ) - { - AppEng.proxy.spawnEffect( EffectType.Energy, w, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, null ); - } - } - } - } + @Override + public void randomDisplayTick(final IBlockState state, final World w, final BlockPos pos, final Random rand) { + final TileQuantumBridge bridge = this.getTileEntity(w, pos); + if (bridge != null) { + if (bridge.hasQES()) { + if (AppEng.proxy.shouldAddParticles(rand)) { + AppEng.proxy.spawnEffect(EffectType.Energy, w, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, null); + } + } + } + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileQuantumBridge tg = this.getTileEntity( w, pos ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_QNB ); - } - return true; - } - return false; - } + final TileQuantumBridge tg = this.getTileEntity(w, pos); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_QNB); + } + return true; + } + return false; + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final BlockPos pos, final Entity thePlayer, final boolean b ) - { - final double onePixel = 2.0 / 16.0; - return Collections.singletonList( new AxisAlignedBB( onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel ) ); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool(final World w, final BlockPos pos, final Entity thePlayer, final boolean b) { + final double onePixel = 2.0 / 16.0; + return Collections.singletonList(new AxisAlignedBB(onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel)); + } - @Override - public void addCollidingBlockToList( final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e ) - { - final double onePixel = 2.0 / 16.0; - out.add( new AxisAlignedBB( onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel ) ); - } + @Override + public void addCollidingBlockToList(final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e) { + final double onePixel = 2.0 / 16.0; + out.add(new AxisAlignedBB(onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel)); + } } diff --git a/src/main/java/appeng/block/qnb/BlockQuantumRing.java b/src/main/java/appeng/block/qnb/BlockQuantumRing.java index 636a41b91..046720585 100644 --- a/src/main/java/appeng/block/qnb/BlockQuantumRing.java +++ b/src/main/java/appeng/block/qnb/BlockQuantumRing.java @@ -19,55 +19,44 @@ package appeng.block.qnb; -import java.util.Collections; -import java.util.List; - +import appeng.tile.qnb.TileQuantumBridge; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.tile.qnb.TileQuantumBridge; +import java.util.Collections; +import java.util.List; -public class BlockQuantumRing extends BlockQuantumBase -{ +public class BlockQuantumRing extends BlockQuantumBase { - public BlockQuantumRing() - { - super( Material.IRON ); - } + public BlockQuantumRing() { + super(Material.IRON); + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final BlockPos pos, final Entity thePlayer, final boolean b ) - { - double onePixel = 2.0 / 16.0; - final TileQuantumBridge bridge = this.getTileEntity( w, pos ); - if( bridge != null && bridge.isCorner() ) - { - onePixel = 4.0 / 16.0; - } - else if( bridge != null && bridge.isFormed() ) - { - onePixel = 1.0 / 16.0; - } - return Collections.singletonList( new AxisAlignedBB( onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel ) ); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool(final World w, final BlockPos pos, final Entity thePlayer, final boolean b) { + double onePixel = 2.0 / 16.0; + final TileQuantumBridge bridge = this.getTileEntity(w, pos); + if (bridge != null && bridge.isCorner()) { + onePixel = 4.0 / 16.0; + } else if (bridge != null && bridge.isFormed()) { + onePixel = 1.0 / 16.0; + } + return Collections.singletonList(new AxisAlignedBB(onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel)); + } - @Override - public void addCollidingBlockToList( final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e ) - { - double onePixel = 2.0 / 16.0; - final TileQuantumBridge bridge = this.getTileEntity( w, pos ); - if( bridge != null && bridge.isCorner() ) - { - onePixel = 4.0 / 16.0; - } - else if( bridge != null && bridge.isFormed() ) - { - onePixel = 1.0 / 16.0; - } - out.add( new AxisAlignedBB( onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel ) ); - } + @Override + public void addCollidingBlockToList(final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e) { + double onePixel = 2.0 / 16.0; + final TileQuantumBridge bridge = this.getTileEntity(w, pos); + if (bridge != null && bridge.isCorner()) { + onePixel = 4.0 / 16.0; + } else if (bridge != null && bridge.isFormed()) { + onePixel = 1.0 / 16.0; + } + out.add(new AxisAlignedBB(onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel)); + } } diff --git a/src/main/java/appeng/block/qnb/QnbFormedBakedModel.java b/src/main/java/appeng/block/qnb/QnbFormedBakedModel.java index 39f290cae..fe4156a04 100644 --- a/src/main/java/appeng/block/qnb/QnbFormedBakedModel.java +++ b/src/main/java/appeng/block/qnb/QnbFormedBakedModel.java @@ -1,16 +1,10 @@ - package appeng.block.qnb; -import java.util.EnumSet; -import java.util.List; -import java.util.Set; -import java.util.function.Function; - -import javax.annotation.Nullable; - +import appeng.api.AEApi; +import appeng.client.render.cablebus.CubeBuilder; +import appeng.core.AppEng; import com.google.common.collect.ImmutableList; - import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; @@ -23,222 +17,195 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.property.IExtendedBlockState; -import appeng.api.AEApi; -import appeng.client.render.cablebus.CubeBuilder; -import appeng.core.AppEng; +import javax.annotation.Nullable; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; +import java.util.function.Function; -class QnbFormedBakedModel implements IBakedModel -{ +class QnbFormedBakedModel implements IBakedModel { - private static final ResourceLocation TEXTURE_LINK = new ResourceLocation( AppEng.MOD_ID, "blocks/quantum_link" ); - private static final ResourceLocation TEXTURE_RING = new ResourceLocation( AppEng.MOD_ID, "blocks/quantum_ring" ); - private static final ResourceLocation TEXTURE_RING_LIGHT = new ResourceLocation( AppEng.MOD_ID, "blocks/quantum_ring_light" ); - private static final ResourceLocation TEXTURE_RING_LIGHT_CORNER = new ResourceLocation( AppEng.MOD_ID, "blocks/quantum_ring_light_corner" ); - private static final ResourceLocation TEXTURE_CABLE_GLASS = new ResourceLocation( AppEng.MOD_ID, "parts/cable/glass/transparent" ); - private static final ResourceLocation TEXTURE_COVERED_CABLE = new ResourceLocation( AppEng.MOD_ID, "parts/cable/covered/transparent" ); + private static final ResourceLocation TEXTURE_LINK = new ResourceLocation(AppEng.MOD_ID, "blocks/quantum_link"); + private static final ResourceLocation TEXTURE_RING = new ResourceLocation(AppEng.MOD_ID, "blocks/quantum_ring"); + private static final ResourceLocation TEXTURE_RING_LIGHT = new ResourceLocation(AppEng.MOD_ID, "blocks/quantum_ring_light"); + private static final ResourceLocation TEXTURE_RING_LIGHT_CORNER = new ResourceLocation(AppEng.MOD_ID, "blocks/quantum_ring_light_corner"); + private static final ResourceLocation TEXTURE_CABLE_GLASS = new ResourceLocation(AppEng.MOD_ID, "parts/cable/glass/transparent"); + private static final ResourceLocation TEXTURE_COVERED_CABLE = new ResourceLocation(AppEng.MOD_ID, "parts/cable/covered/transparent"); - private static final float DEFAULT_RENDER_MIN = 2.0f; - private static final float DEFAULT_RENDER_MAX = 14.0f; + private static final float DEFAULT_RENDER_MIN = 2.0f; + private static final float DEFAULT_RENDER_MAX = 14.0f; - private static final float CORNER_POWERED_RENDER_MIN = 3.9f; - private static final float CORNER_POWERED_RENDER_MAX = 12.1f; + private static final float CORNER_POWERED_RENDER_MIN = 3.9f; + private static final float CORNER_POWERED_RENDER_MAX = 12.1f; - private static final float CENTER_POWERED_RENDER_MIN = -0.01f; - private static final float CENTER_POWERED_RENDER_MAX = 16.01f; + private static final float CENTER_POWERED_RENDER_MIN = -0.01f; + private static final float CENTER_POWERED_RENDER_MAX = 16.01f; - private final VertexFormat vertexFormat; + private final VertexFormat vertexFormat; - private final IBakedModel baseModel; + private final IBakedModel baseModel; - private final Block linkBlock; + private final Block linkBlock; - private final TextureAtlasSprite linkTexture; - private final TextureAtlasSprite ringTexture; - private final TextureAtlasSprite glassCableTexture; - private final TextureAtlasSprite coveredCableTexture; - private final TextureAtlasSprite lightTexture; - private final TextureAtlasSprite lightCornerTexture; + private final TextureAtlasSprite linkTexture; + private final TextureAtlasSprite ringTexture; + private final TextureAtlasSprite glassCableTexture; + private final TextureAtlasSprite coveredCableTexture; + private final TextureAtlasSprite lightTexture; + private final TextureAtlasSprite lightCornerTexture; - public QnbFormedBakedModel( VertexFormat vertexFormat, IBakedModel baseModel, Function bakedTextureGetter ) - { - this.vertexFormat = vertexFormat; - this.baseModel = baseModel; - this.linkTexture = bakedTextureGetter.apply( TEXTURE_LINK ); - this.ringTexture = bakedTextureGetter.apply( TEXTURE_RING ); - this.glassCableTexture = bakedTextureGetter.apply( TEXTURE_CABLE_GLASS ); - this.coveredCableTexture = bakedTextureGetter.apply( TEXTURE_COVERED_CABLE ); - this.lightTexture = bakedTextureGetter.apply( TEXTURE_RING_LIGHT ); - this.lightCornerTexture = bakedTextureGetter.apply( TEXTURE_RING_LIGHT_CORNER ); - this.linkBlock = AEApi.instance().definitions().blocks().quantumLink().maybeBlock().orElse( null ); - } + public QnbFormedBakedModel(VertexFormat vertexFormat, IBakedModel baseModel, Function bakedTextureGetter) { + this.vertexFormat = vertexFormat; + this.baseModel = baseModel; + this.linkTexture = bakedTextureGetter.apply(TEXTURE_LINK); + this.ringTexture = bakedTextureGetter.apply(TEXTURE_RING); + this.glassCableTexture = bakedTextureGetter.apply(TEXTURE_CABLE_GLASS); + this.coveredCableTexture = bakedTextureGetter.apply(TEXTURE_COVERED_CABLE); + this.lightTexture = bakedTextureGetter.apply(TEXTURE_RING_LIGHT); + this.lightCornerTexture = bakedTextureGetter.apply(TEXTURE_RING_LIGHT_CORNER); + this.linkBlock = AEApi.instance().definitions().blocks().quantumLink().maybeBlock().orElse(null); + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - // Get the correct base model - if( !( state instanceof IExtendedBlockState ) ) - { - return this.baseModel.getQuads( state, side, rand ); - } + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + // Get the correct base model + if (!(state instanceof IExtendedBlockState)) { + return this.baseModel.getQuads(state, side, rand); + } - IExtendedBlockState extendedBlockState = (IExtendedBlockState) state; - QnbFormedState formedState = extendedBlockState.getValue( BlockQuantumBase.FORMED_STATE ); + IExtendedBlockState extendedBlockState = (IExtendedBlockState) state; + QnbFormedState formedState = extendedBlockState.getValue(BlockQuantumBase.FORMED_STATE); - return this.getQuads( formedState, state, side, rand ); - } + return this.getQuads(formedState, state, side, rand); + } - private List getQuads( QnbFormedState formedState, IBlockState state, EnumFacing side, long rand ) - { - CubeBuilder builder = new CubeBuilder( this.vertexFormat ); + private List getQuads(QnbFormedState formedState, IBlockState state, EnumFacing side, long rand) { + CubeBuilder builder = new CubeBuilder(this.vertexFormat); - if( state.getBlock() == this.linkBlock ) - { - Set sides = formedState.getAdjacentQuantumBridges(); + if (state.getBlock() == this.linkBlock) { + Set sides = formedState.getAdjacentQuantumBridges(); - this.renderCableAt( builder, 0.11f * 16, this.glassCableTexture, 0.141f * 16, sides ); + this.renderCableAt(builder, 0.11f * 16, this.glassCableTexture, 0.141f * 16, sides); - this.renderCableAt( builder, 0.188f * 16, this.coveredCableTexture, 0.1875f * 16, sides ); + this.renderCableAt(builder, 0.188f * 16, this.coveredCableTexture, 0.1875f * 16, sides); - builder.setTexture( this.linkTexture ); - builder.addCube( DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX ); - } - else - { - if( formedState.isCorner() ) - { - this.renderCableAt( builder, 0.188f * 16, this.coveredCableTexture, 0.05f * 16, formedState.getAdjacentQuantumBridges() ); + builder.setTexture(this.linkTexture); + builder.addCube(DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX); + } else { + if (formedState.isCorner()) { + this.renderCableAt(builder, 0.188f * 16, this.coveredCableTexture, 0.05f * 16, formedState.getAdjacentQuantumBridges()); - builder.setTexture( this.ringTexture ); - builder.addCube( DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX ); + builder.setTexture(this.ringTexture); + builder.addCube(DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX); - if( formedState.isPowered() ) - { - builder.setTexture( this.lightCornerTexture ); - builder.setRenderFullBright( true ); - for( EnumFacing facing : EnumFacing.values() ) - { - // Offset the face by a slight amount so that it is drawn over the already drawn ring texture - // (avoids z-fighting) - float xOffset = Math.abs( facing.getFrontOffsetX() * 0.01f ); - float yOffset = Math.abs( facing.getFrontOffsetY() * 0.01f ); - float zOffset = Math.abs( facing.getFrontOffsetZ() * 0.01f ); + if (formedState.isPowered()) { + builder.setTexture(this.lightCornerTexture); + builder.setRenderFullBright(true); + for (EnumFacing facing : EnumFacing.values()) { + // Offset the face by a slight amount so that it is drawn over the already drawn ring texture + // (avoids z-fighting) + float xOffset = Math.abs(facing.getFrontOffsetX() * 0.01f); + float yOffset = Math.abs(facing.getFrontOffsetY() * 0.01f); + float zOffset = Math.abs(facing.getFrontOffsetZ() * 0.01f); - builder.setDrawFaces( EnumSet.of( facing ) ); - builder.addCube( - DEFAULT_RENDER_MIN - xOffset, DEFAULT_RENDER_MIN - yOffset, DEFAULT_RENDER_MIN - zOffset, - DEFAULT_RENDER_MAX + xOffset, DEFAULT_RENDER_MAX + yOffset, DEFAULT_RENDER_MAX + zOffset ); - } - } - } - else - { - builder.setTexture( this.ringTexture ); + builder.setDrawFaces(EnumSet.of(facing)); + builder.addCube( + DEFAULT_RENDER_MIN - xOffset, DEFAULT_RENDER_MIN - yOffset, DEFAULT_RENDER_MIN - zOffset, + DEFAULT_RENDER_MAX + xOffset, DEFAULT_RENDER_MAX + yOffset, DEFAULT_RENDER_MAX + zOffset); + } + } + } else { + builder.setTexture(this.ringTexture); - builder.addCube( 0, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, 16, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX ); + builder.addCube(0, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, 16, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX); - builder.addCube( DEFAULT_RENDER_MIN, 0, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, 16, DEFAULT_RENDER_MAX ); + builder.addCube(DEFAULT_RENDER_MIN, 0, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, 16, DEFAULT_RENDER_MAX); - builder.addCube( DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, 0, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, 16 ); + builder.addCube(DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, 0, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, 16); - if( formedState.isPowered() ) - { - builder.setTexture( this.lightTexture ); - builder.setRenderFullBright( true ); - for( EnumFacing facing : EnumFacing.values() ) - { - // Offset the face by a slight amount so that it is drawn over the already drawn ring texture - // (avoids z-fighting) - float xOffset = Math.abs( facing.getFrontOffsetX() * 0.01f ); - float yOffset = Math.abs( facing.getFrontOffsetY() * 0.01f ); - float zOffset = Math.abs( facing.getFrontOffsetZ() * 0.01f ); + if (formedState.isPowered()) { + builder.setTexture(this.lightTexture); + builder.setRenderFullBright(true); + for (EnumFacing facing : EnumFacing.values()) { + // Offset the face by a slight amount so that it is drawn over the already drawn ring texture + // (avoids z-fighting) + float xOffset = Math.abs(facing.getFrontOffsetX() * 0.01f); + float yOffset = Math.abs(facing.getFrontOffsetY() * 0.01f); + float zOffset = Math.abs(facing.getFrontOffsetZ() * 0.01f); - builder.setDrawFaces( EnumSet.of( facing ) ); - builder.addCube( - -xOffset, -yOffset, -zOffset, - 16 + xOffset, 16 + yOffset, 16 + zOffset ); - } - } - } - } + builder.setDrawFaces(EnumSet.of(facing)); + builder.addCube( + -xOffset, -yOffset, -zOffset, + 16 + xOffset, 16 + yOffset, 16 + zOffset); + } + } + } + } - return builder.getOutput(); - } + return builder.getOutput(); + } - private void renderCableAt( CubeBuilder builder, float thickness, TextureAtlasSprite texture, float pull, Set connections ) - { - builder.setTexture( texture ); + private void renderCableAt(CubeBuilder builder, float thickness, TextureAtlasSprite texture, float pull, Set connections) { + builder.setTexture(texture); - if( connections.contains( EnumFacing.WEST ) ) - { - builder.addCube( 0, 8 - thickness, 8 - thickness, 8 - thickness - pull, 8 + thickness, 8 + thickness ); - } + if (connections.contains(EnumFacing.WEST)) { + builder.addCube(0, 8 - thickness, 8 - thickness, 8 - thickness - pull, 8 + thickness, 8 + thickness); + } - if( connections.contains( EnumFacing.EAST ) ) - { - builder.addCube( 8 + thickness + pull, 8 - thickness, 8 - thickness, 16, 8 + thickness, 8 + thickness ); - } + if (connections.contains(EnumFacing.EAST)) { + builder.addCube(8 + thickness + pull, 8 - thickness, 8 - thickness, 16, 8 + thickness, 8 + thickness); + } - if( connections.contains( EnumFacing.NORTH ) ) - { - builder.addCube( 8 - thickness, 8 - thickness, 0, 8 + thickness, 8 + thickness, 8 - thickness - pull ); - } + if (connections.contains(EnumFacing.NORTH)) { + builder.addCube(8 - thickness, 8 - thickness, 0, 8 + thickness, 8 + thickness, 8 - thickness - pull); + } - if( connections.contains( EnumFacing.SOUTH ) ) - { - builder.addCube( 8 - thickness, 8 - thickness, 8 + thickness + pull, 8 + thickness, 8 + thickness, 16 ); - } + if (connections.contains(EnumFacing.SOUTH)) { + builder.addCube(8 - thickness, 8 - thickness, 8 + thickness + pull, 8 + thickness, 8 + thickness, 16); + } - if( connections.contains( EnumFacing.DOWN ) ) - { - builder.addCube( 8 - thickness, 0, 8 - thickness, 8 + thickness, 8 - thickness - pull, 8 + thickness ); - } + if (connections.contains(EnumFacing.DOWN)) { + builder.addCube(8 - thickness, 0, 8 - thickness, 8 + thickness, 8 - thickness - pull, 8 + thickness); + } - if( connections.contains( EnumFacing.UP ) ) - { - builder.addCube( 8 - thickness, 8 + thickness + pull, 8 - thickness, 8 + thickness, 16, 8 + thickness ); - } - } + if (connections.contains(EnumFacing.UP)) { + builder.addCube(8 - thickness, 8 + thickness + pull, 8 - thickness, 8 + thickness, 16, 8 + thickness); + } + } - @Override - public boolean isAmbientOcclusion() - { - return this.baseModel.isAmbientOcclusion(); - } + @Override + public boolean isAmbientOcclusion() { + return this.baseModel.isAmbientOcclusion(); + } - @Override - public boolean isGui3d() - { - return true; - } + @Override + public boolean isGui3d() { + return true; + } - @Override - public boolean isBuiltInRenderer() - { - return false; - } + @Override + public boolean isBuiltInRenderer() { + return false; + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.baseModel.getParticleTexture(); - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.baseModel.getParticleTexture(); + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return this.baseModel.getItemCameraTransforms(); - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return this.baseModel.getItemCameraTransforms(); + } - @Override - public ItemOverrideList getOverrides() - { - return this.baseModel.getOverrides(); - } + @Override + public ItemOverrideList getOverrides() { + return this.baseModel.getOverrides(); + } - public static List getRequiredTextures() - { - return ImmutableList.of( - TEXTURE_LINK, TEXTURE_RING, TEXTURE_CABLE_GLASS, TEXTURE_COVERED_CABLE, TEXTURE_RING_LIGHT, TEXTURE_RING_LIGHT_CORNER ); - } + public static List getRequiredTextures() { + return ImmutableList.of( + TEXTURE_LINK, TEXTURE_RING, TEXTURE_CABLE_GLASS, TEXTURE_COVERED_CABLE, TEXTURE_RING_LIGHT, TEXTURE_RING_LIGHT_CORNER); + } } diff --git a/src/main/java/appeng/block/qnb/QnbFormedModel.java b/src/main/java/appeng/block/qnb/QnbFormedModel.java index e4884e650..c9241e258 100644 --- a/src/main/java/appeng/block/qnb/QnbFormedModel.java +++ b/src/main/java/appeng/block/qnb/QnbFormedModel.java @@ -1,12 +1,8 @@ - package appeng.block.qnb; -import java.util.Collection; -import java.util.function.Function; - +import appeng.core.AppEng; import com.google.common.collect.ImmutableList; - import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -16,49 +12,41 @@ import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; -import appeng.core.AppEng; +import java.util.Collection; +import java.util.function.Function; -public class QnbFormedModel implements IModel -{ +public class QnbFormedModel implements IModel { - private static final ResourceLocation MODEL_RING = new ResourceLocation( AppEng.MOD_ID, "block/qnb/ring" ); + private static final ResourceLocation MODEL_RING = new ResourceLocation(AppEng.MOD_ID, "block/qnb/ring"); - @Override - public Collection getDependencies() - { - return ImmutableList.of( MODEL_RING ); - } + @Override + public Collection getDependencies() { + return ImmutableList.of(MODEL_RING); + } - @Override - public Collection getTextures() - { - return QnbFormedBakedModel.getRequiredTextures(); - } + @Override + public Collection getTextures() { + return QnbFormedBakedModel.getRequiredTextures(); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - IBakedModel ringModel = this.getBaseModel( MODEL_RING, state, format, bakedTextureGetter ); - return new QnbFormedBakedModel( format, ringModel, bakedTextureGetter ); - } + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + IBakedModel ringModel = this.getBaseModel(MODEL_RING, state, format, bakedTextureGetter); + return new QnbFormedBakedModel(format, ringModel, bakedTextureGetter); + } - @Override - public IModelState getDefaultState() - { - return TRSRTransformation.identity(); - } + @Override + public IModelState getDefaultState() { + return TRSRTransformation.identity(); + } - private IBakedModel getBaseModel( ResourceLocation model, IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - // Load the base model - try - { - return ModelLoaderRegistry.getModel( model ).bake( state, format, bakedTextureGetter ); - } - catch( Exception e ) - { - throw new RuntimeException( e ); - } - } + private IBakedModel getBaseModel(ResourceLocation model, IModelState state, VertexFormat format, Function bakedTextureGetter) { + // Load the base model + try { + return ModelLoaderRegistry.getModel(model).bake(state, format, bakedTextureGetter); + } catch (Exception e) { + throw new RuntimeException(e); + } + } } diff --git a/src/main/java/appeng/block/qnb/QnbFormedState.java b/src/main/java/appeng/block/qnb/QnbFormedState.java index 43664dcff..ae171e741 100644 --- a/src/main/java/appeng/block/qnb/QnbFormedState.java +++ b/src/main/java/appeng/block/qnb/QnbFormedState.java @@ -1,41 +1,35 @@ - package appeng.block.qnb; -import java.util.Set; - import net.minecraft.util.EnumFacing; +import java.util.Set; -public class QnbFormedState -{ - private final Set adjacentQuantumBridges; +public class QnbFormedState { - private final boolean corner; + private final Set adjacentQuantumBridges; - private final boolean powered; + private final boolean corner; - public QnbFormedState( Set adjacentQuantumBridges, boolean corner, boolean powered ) - { - this.adjacentQuantumBridges = adjacentQuantumBridges; - this.corner = corner; - this.powered = powered; - } + private final boolean powered; - public Set getAdjacentQuantumBridges() - { - return this.adjacentQuantumBridges; - } + public QnbFormedState(Set adjacentQuantumBridges, boolean corner, boolean powered) { + this.adjacentQuantumBridges = adjacentQuantumBridges; + this.corner = corner; + this.powered = powered; + } - public boolean isCorner() - { - return this.corner; - } + public Set getAdjacentQuantumBridges() { + return this.adjacentQuantumBridges; + } - public boolean isPowered() - { - return this.powered; - } + public boolean isCorner() { + return this.corner; + } + + public boolean isPowered() { + return this.powered; + } } diff --git a/src/main/java/appeng/block/qnb/QnbFormedStateProperty.java b/src/main/java/appeng/block/qnb/QnbFormedStateProperty.java index 7beb5a9ba..f060cfdf3 100644 --- a/src/main/java/appeng/block/qnb/QnbFormedStateProperty.java +++ b/src/main/java/appeng/block/qnb/QnbFormedStateProperty.java @@ -1,34 +1,28 @@ - package appeng.block.qnb; import net.minecraftforge.common.property.IUnlistedProperty; -public class QnbFormedStateProperty implements IUnlistedProperty -{ +public class QnbFormedStateProperty implements IUnlistedProperty { - @Override - public String getName() - { - return "qnb_formed"; - } + @Override + public String getName() { + return "qnb_formed"; + } - @Override - public boolean isValid( QnbFormedState value ) - { - return value != null; - } + @Override + public boolean isValid(QnbFormedState value) { + return value != null; + } - @Override - public Class getType() - { - return QnbFormedState.class; - } + @Override + public Class getType() { + return QnbFormedState.class; + } - @Override - public String valueToString( QnbFormedState value ) - { - return null; - } + @Override + public String valueToString(QnbFormedState value) { + return null; + } } diff --git a/src/main/java/appeng/block/qnb/QuantumBridgeRendering.java b/src/main/java/appeng/block/qnb/QuantumBridgeRendering.java index 2dd02823e..71263c7c8 100644 --- a/src/main/java/appeng/block/qnb/QuantumBridgeRendering.java +++ b/src/main/java/appeng/block/qnb/QuantumBridgeRendering.java @@ -1,24 +1,20 @@ - package appeng.block.qnb; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.bootstrap.BlockRenderingCustomizer; import appeng.bootstrap.IBlockRendering; import appeng.bootstrap.IItemRendering; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class QuantumBridgeRendering extends BlockRenderingCustomizer -{ +public class QuantumBridgeRendering extends BlockRenderingCustomizer { - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - rendering.builtInModel( "models/block/qnb/qnb_formed", new QnbFormedModel() ); - // Disable auto rotation - rendering.modelCustomizer( ( location, model ) -> model ); - } + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + rendering.builtInModel("models/block/qnb/qnb_formed", new QnbFormedModel()); + // Disable auto rotation + rendering.modelCustomizer((location, model) -> model); + } } diff --git a/src/main/java/appeng/block/spatial/BlockMatrixFrame.java b/src/main/java/appeng/block/spatial/BlockMatrixFrame.java index 876611f28..d39967fe9 100644 --- a/src/main/java/appeng/block/spatial/BlockMatrixFrame.java +++ b/src/main/java/appeng/block/spatial/BlockMatrixFrame.java @@ -19,9 +19,8 @@ package appeng.block.spatial; -import java.util.Arrays; -import java.util.List; - +import appeng.block.AEBaseBlock; +import appeng.helpers.ICustomCollision; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; @@ -36,57 +35,49 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.block.AEBaseBlock; -import appeng.helpers.ICustomCollision; +import java.util.Arrays; +import java.util.List; -public class BlockMatrixFrame extends AEBaseBlock implements ICustomCollision -{ +public class BlockMatrixFrame extends AEBaseBlock implements ICustomCollision { - public BlockMatrixFrame() - { - super( Material.ANVIL ); - this.setResistance( 6000000.0F ); - this.setBlockUnbreakable(); - this.setLightOpacity( 0 ); - this.setOpaque( false ); - } + public BlockMatrixFrame() { + super(Material.ANVIL); + this.setResistance(6000000.0F); + this.setBlockUnbreakable(); + this.setLightOpacity(0); + this.setOpaque(false); + } - @Override - @SideOnly( Side.CLIENT ) - public void getSubBlocks( final CreativeTabs tabs, final NonNullList itemStacks ) - { - // do nothing - } + @Override + @SideOnly(Side.CLIENT) + public void getSubBlocks(final CreativeTabs tabs, final NonNullList itemStacks) { + // do nothing + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final BlockPos pos, final Entity thePlayer, final boolean b ) - { - return Arrays.asList( new AxisAlignedBB[] {} );// AxisAlignedBB.getBoundingBox( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) - // } ); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool(final World w, final BlockPos pos, final Entity thePlayer, final boolean b) { + return Arrays.asList(new AxisAlignedBB[]{});// AxisAlignedBB.getBoundingBox( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) + // } ); + } - @Override - public void addCollidingBlockToList( final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e ) - { - out.add( new AxisAlignedBB( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ) ); - } + @Override + public void addCollidingBlockToList(final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e) { + out.add(new AxisAlignedBB(0.0, 0.0, 0.0, 1.0, 1.0, 1.0)); + } - @Override - public boolean canPlaceBlockAt( final World worldIn, final BlockPos pos ) - { - return false; - } + @Override + public boolean canPlaceBlockAt(final World worldIn, final BlockPos pos) { + return false; + } - @Override - public void onBlockExploded( final World world, final BlockPos pos, final Explosion explosion ) - { - // Don't explode. - } + @Override + public void onBlockExploded(final World world, final BlockPos pos, final Explosion explosion) { + // Don't explode. + } - @Override - public boolean canEntityDestroy( final IBlockState state, final IBlockAccess world, final BlockPos pos, final Entity entity ) - { - return false; - } + @Override + public boolean canEntityDestroy(final IBlockState state, final IBlockAccess world, final BlockPos pos, final Entity entity) { + return false; + } } diff --git a/src/main/java/appeng/block/spatial/BlockSpatialIOPort.java b/src/main/java/appeng/block/spatial/BlockSpatialIOPort.java index 0199a3b3e..b0134c08c 100644 --- a/src/main/java/appeng/block/spatial/BlockSpatialIOPort.java +++ b/src/main/java/appeng/block/spatial/BlockSpatialIOPort.java @@ -19,8 +19,11 @@ package appeng.block.spatial; -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.core.sync.GuiBridge; +import appeng.tile.spatial.TileSpatialIOPort; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -31,48 +34,36 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.core.sync.GuiBridge; -import appeng.tile.spatial.TileSpatialIOPort; -import appeng.util.Platform; +import javax.annotation.Nullable; -public class BlockSpatialIOPort extends AEBaseTileBlock -{ +public class BlockSpatialIOPort extends AEBaseTileBlock { - public BlockSpatialIOPort() - { - super( Material.IRON ); - } + public BlockSpatialIOPort() { + super(Material.IRON); + } - @Override - public void neighborChanged( IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos ) - { - final TileSpatialIOPort te = this.getTileEntity( world, pos ); - if( te != null ) - { - te.updateRedstoneState(); - } - } + @Override + public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { + final TileSpatialIOPort te = this.getTileEntity(world, pos); + if (te != null) { + te.updateRedstoneState(); + } + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileSpatialIOPort tg = this.getTileEntity( w, pos ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_SPATIAL_IO_PORT ); - } - return true; - } - return false; - } + final TileSpatialIOPort tg = this.getTileEntity(w, pos); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_SPATIAL_IO_PORT); + } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/spatial/BlockSpatialPylon.java b/src/main/java/appeng/block/spatial/BlockSpatialPylon.java index ae465ebea..367f1ec2b 100644 --- a/src/main/java/appeng/block/spatial/BlockSpatialPylon.java +++ b/src/main/java/appeng/block/spatial/BlockSpatialPylon.java @@ -19,6 +19,10 @@ package appeng.block.spatial; +import appeng.block.AEBaseTileBlock; +import appeng.client.render.spatial.SpatialPylonStateProperty; +import appeng.helpers.AEGlassMaterial; +import appeng.tile.spatial.TileSpatialPylon; import net.minecraft.block.Block; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; @@ -30,73 +34,57 @@ import net.minecraftforge.common.property.ExtendedBlockState; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.common.property.IUnlistedProperty; -import appeng.block.AEBaseTileBlock; -import appeng.client.render.spatial.SpatialPylonStateProperty; -import appeng.helpers.AEGlassMaterial; -import appeng.tile.spatial.TileSpatialPylon; +public class BlockSpatialPylon extends AEBaseTileBlock { -public class BlockSpatialPylon extends AEBaseTileBlock -{ + public static final SpatialPylonStateProperty STATE = new SpatialPylonStateProperty(); - public static final SpatialPylonStateProperty STATE = new SpatialPylonStateProperty(); + public BlockSpatialPylon() { + super(AEGlassMaterial.INSTANCE); + } - public BlockSpatialPylon() - { - super( AEGlassMaterial.INSTANCE ); - } + @Override + protected BlockStateContainer createBlockState() { + return new ExtendedBlockState(this, this.getAEStates(), new IUnlistedProperty[]{STATE}); + } - @Override - protected BlockStateContainer createBlockState() - { - return new ExtendedBlockState( this, this.getAEStates(), new IUnlistedProperty[] { STATE } ); - } + @Override + public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { + IExtendedBlockState extState = (IExtendedBlockState) state; - @Override - public IBlockState getExtendedState( IBlockState state, IBlockAccess world, BlockPos pos ) - { - IExtendedBlockState extState = (IExtendedBlockState) state; + return extState.withProperty(STATE, this.getDisplayState(world, pos)); + } - return extState.withProperty( STATE, this.getDisplayState( world, pos ) ); - } + @Override + public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { + final TileSpatialPylon tsp = this.getTileEntity(world, pos); + if (tsp != null) { + tsp.neighborChanged(); + } + } - @Override - public void neighborChanged( IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos ) - { - final TileSpatialPylon tsp = this.getTileEntity( world, pos ); - if( tsp != null ) - { - tsp.neighborChanged(); - } - } + @Override + public int getLightValue(final IBlockState state, final IBlockAccess w, final BlockPos pos) { + final TileSpatialPylon tsp = this.getTileEntity(w, pos); + if (tsp != null) { + return tsp.getLightValue(); + } + return super.getLightValue(state, w, pos); + } - @Override - public int getLightValue( final IBlockState state, final IBlockAccess w, final BlockPos pos ) - { - final TileSpatialPylon tsp = this.getTileEntity( w, pos ); - if( tsp != null ) - { - return tsp.getLightValue(); - } - return super.getLightValue( state, w, pos ); - } + private int getDisplayState(IBlockAccess world, BlockPos pos) { + TileSpatialPylon te = this.getTileEntity(world, pos); - private int getDisplayState( IBlockAccess world, BlockPos pos ) - { - TileSpatialPylon te = this.getTileEntity( world, pos ); + if (te == null) { + return 0; + } - if( te == null ) - { - return 0; - } + return te.getDisplayBits(); + } - return te.getDisplayBits(); - } - - @Override - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } + @Override + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } } diff --git a/src/main/java/appeng/block/storage/BlockChest.java b/src/main/java/appeng/block/storage/BlockChest.java index 8ce89a037..ecacb9257 100644 --- a/src/main/java/appeng/block/storage/BlockChest.java +++ b/src/main/java/appeng/block/storage/BlockChest.java @@ -19,8 +19,12 @@ package appeng.block.storage; -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.core.localization.PlayerMessages; +import appeng.core.sync.GuiBridge; +import appeng.tile.storage.TileChest; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; @@ -34,87 +38,67 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.core.localization.PlayerMessages; -import appeng.core.sync.GuiBridge; -import appeng.tile.storage.TileChest; -import appeng.util.Platform; +import javax.annotation.Nullable; -public class BlockChest extends AEBaseTileBlock -{ +public class BlockChest extends AEBaseTileBlock { - private final static PropertyEnum SLOT_STATE = PropertyEnum.create( "slot_state", DriveSlotState.class ); + private final static PropertyEnum SLOT_STATE = PropertyEnum.create("slot_state", DriveSlotState.class); - public BlockChest() - { - super( Material.IRON ); - this.setDefaultState( this.getDefaultState().withProperty( SLOT_STATE, DriveSlotState.EMPTY ) ); - } + public BlockChest() { + super(Material.IRON); + this.setDefaultState(this.getDefaultState().withProperty(SLOT_STATE, DriveSlotState.EMPTY)); + } - @Override - protected IProperty[] getAEStates() - { - return new IProperty[] { SLOT_STATE }; - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{SLOT_STATE}; + } - @Override - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } + @Override + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } - @Override - public IBlockState getActualState( IBlockState state, IBlockAccess worldIn, BlockPos pos ) - { - DriveSlotState slotState = DriveSlotState.EMPTY; + @Override + public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { + DriveSlotState slotState = DriveSlotState.EMPTY; - TileChest te = this.getTileEntity( worldIn, pos ); + TileChest te = this.getTileEntity(worldIn, pos); - if( te != null ) - { - if( te.getCellCount() >= 1 ) - { - slotState = DriveSlotState.fromCellStatus( te.getCellStatus( 0 ) ); - } - // Power-state has to be checked separately - if( !te.isPowered() && slotState != DriveSlotState.EMPTY ) - { - slotState = DriveSlotState.OFFLINE; - } - } + if (te != null) { + if (te.getCellCount() >= 1) { + slotState = DriveSlotState.fromCellStatus(te.getCellStatus(0)); + } + // Power-state has to be checked separately + if (!te.isPowered() && slotState != DriveSlotState.EMPTY) { + slotState = DriveSlotState.OFFLINE; + } + } - return super.getActualState( state, worldIn, pos ) - .withProperty( SLOT_STATE, slotState ); - } + return super.getActualState(state, worldIn, pos) + .withProperty(SLOT_STATE, slotState); + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - final TileChest tg = this.getTileEntity( w, pos ); - if( tg != null && !p.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + final TileChest tg = this.getTileEntity(w, pos); + if (tg != null && !p.isSneaking()) { + if (Platform.isClient()) { + return true; + } - if( side != tg.getUp() ) - { - Platform.openGUI( p, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_CHEST ); - } - else - { - if( !tg.openGui( p ) ) - { - p.sendMessage( PlayerMessages.ChestCannotReadStorageCell.get() ); - } - } + if (side != tg.getUp()) { + Platform.openGUI(p, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_CHEST); + } else { + if (!tg.openGui(p)) { + p.sendMessage(PlayerMessages.ChestCannotReadStorageCell.get()); + } + } - return true; - } + return true; + } - return false; - } + return false; + } } diff --git a/src/main/java/appeng/block/storage/BlockDrive.java b/src/main/java/appeng/block/storage/BlockDrive.java index 58cd93e05..27014f2fc 100644 --- a/src/main/java/appeng/block/storage/BlockDrive.java +++ b/src/main/java/appeng/block/storage/BlockDrive.java @@ -19,8 +19,12 @@ package appeng.block.storage; -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.client.UnlistedProperty; +import appeng.core.sync.GuiBridge; +import appeng.tile.storage.TileDrive; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; @@ -36,65 +40,51 @@ import net.minecraftforge.common.property.ExtendedBlockState; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.common.property.IUnlistedProperty; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.client.UnlistedProperty; -import appeng.core.sync.GuiBridge; -import appeng.tile.storage.TileDrive; -import appeng.util.Platform; +import javax.annotation.Nullable; -public class BlockDrive extends AEBaseTileBlock -{ +public class BlockDrive extends AEBaseTileBlock { - public static final UnlistedProperty SLOTS_STATE = new UnlistedProperty<>( "drive_slots_state", DriveSlotsState.class ); + public static final UnlistedProperty SLOTS_STATE = new UnlistedProperty<>("drive_slots_state", DriveSlotsState.class); - public BlockDrive() - { - super( Material.IRON ); - } + public BlockDrive() { + super(Material.IRON); + } - @Override - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } + @Override + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } - @Override - protected BlockStateContainer createBlockState() - { - return new ExtendedBlockState( this, this.getAEStates(), new IUnlistedProperty[] { - SLOTS_STATE, - FORWARD, - UP - } ); - } + @Override + protected BlockStateContainer createBlockState() { + return new ExtendedBlockState(this, this.getAEStates(), new IUnlistedProperty[]{ + SLOTS_STATE, + FORWARD, + UP + }); + } - @Override - public IBlockState getExtendedState( IBlockState state, IBlockAccess world, BlockPos pos ) - { - TileDrive te = this.getTileEntity( world, pos ); - IExtendedBlockState extState = (IExtendedBlockState) super.getExtendedState( state, world, pos ); - return extState.withProperty( SLOTS_STATE, te == null ? DriveSlotsState.createEmpty( 10 ) : DriveSlotsState.fromChestOrDrive( te ) ); - } + @Override + public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { + TileDrive te = this.getTileEntity(world, pos); + IExtendedBlockState extState = (IExtendedBlockState) super.getExtendedState(state, world, pos); + return extState.withProperty(SLOTS_STATE, te == null ? DriveSlotsState.createEmpty(10) : DriveSlotsState.fromChestOrDrive(te)); + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileDrive tg = this.getTileEntity( w, pos ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_DRIVE ); - } - return true; - } - return false; - } + final TileDrive tg = this.getTileEntity(w, pos); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_DRIVE); + } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/storage/BlockIOPort.java b/src/main/java/appeng/block/storage/BlockIOPort.java index 36b4f15b7..5457046f8 100644 --- a/src/main/java/appeng/block/storage/BlockIOPort.java +++ b/src/main/java/appeng/block/storage/BlockIOPort.java @@ -19,8 +19,11 @@ package appeng.block.storage; -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.core.sync.GuiBridge; +import appeng.tile.storage.TileIOPort; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -31,48 +34,36 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.core.sync.GuiBridge; -import appeng.tile.storage.TileIOPort; -import appeng.util.Platform; +import javax.annotation.Nullable; -public class BlockIOPort extends AEBaseTileBlock -{ +public class BlockIOPort extends AEBaseTileBlock { - public BlockIOPort() - { - super( Material.IRON ); - } + public BlockIOPort() { + super(Material.IRON); + } - @Override - public void neighborChanged( IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos ) - { - final TileIOPort te = this.getTileEntity( world, pos ); - if( te != null ) - { - te.updateRedstoneState(); - } - } + @Override + public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { + final TileIOPort te = this.getTileEntity(world, pos); + if (te != null) { + te.updateRedstoneState(); + } + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileIOPort tg = this.getTileEntity( w, pos ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_IOPORT ); - } - return true; - } - return false; - } + final TileIOPort tg = this.getTileEntity(w, pos); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_IOPORT); + } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/storage/BlockSkyChest.java b/src/main/java/appeng/block/storage/BlockSkyChest.java index 3289176ec..8e0c9c81f 100644 --- a/src/main/java/appeng/block/storage/BlockSkyChest.java +++ b/src/main/java/appeng/block/storage/BlockSkyChest.java @@ -19,11 +19,12 @@ package appeng.block.storage; -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.core.sync.GuiBridge; +import appeng.helpers.ICustomCollision; +import appeng.tile.storage.TileSkyChest; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; @@ -36,94 +37,81 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.core.sync.GuiBridge; -import appeng.helpers.ICustomCollision; -import appeng.tile.storage.TileSkyChest; -import appeng.util.Platform; +import javax.annotation.Nullable; +import java.util.Collections; +import java.util.List; -public class BlockSkyChest extends AEBaseTileBlock implements ICustomCollision -{ +public class BlockSkyChest extends AEBaseTileBlock implements ICustomCollision { - private static final double AABB_OFFSET_BOTTOM = 0.00; - private static final double AABB_OFFSET_SIDES = 0.06; - private static final double AABB_OFFSET_TOP = 0.125; + private static final double AABB_OFFSET_BOTTOM = 0.00; + private static final double AABB_OFFSET_SIDES = 0.06; + private static final double AABB_OFFSET_TOP = 0.125; - public enum SkyChestType - { - STONE, BLOCK - }; + public enum SkyChestType { + STONE, BLOCK + } - public final SkyChestType type; + public final SkyChestType type; - public BlockSkyChest( final SkyChestType type ) - { - super( Material.ROCK ); - this.setOpaque( this.setFullSize( false ) ); - this.lightOpacity = 0; - this.setHardness( 50 ); - this.blockResistance = 150.0f; - this.type = type; - } + public BlockSkyChest(final SkyChestType type) { + super(Material.ROCK); + this.setOpaque(this.setFullSize(false)); + this.lightOpacity = 0; + this.setHardness(50); + this.blockResistance = 150.0f; + this.type = type; + } - @Override - public EnumBlockRenderType getRenderType( IBlockState state ) - { - return EnumBlockRenderType.ENTITYBLOCK_ANIMATED; - } + @Override + public EnumBlockRenderType getRenderType(IBlockState state) { + return EnumBlockRenderType.ENTITYBLOCK_ANIMATED; + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getTileEntity( w, pos ), AEPartLocation.fromFacing( side ), GuiBridge.GUI_SKYCHEST ); - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getTileEntity(w, pos), AEPartLocation.fromFacing(side), GuiBridge.GUI_SKYCHEST); + } - return true; - } + return true; + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final BlockPos pos, final Entity thePlayer, final boolean b ) - { - final AxisAlignedBB aabb = this.computeAABB( w, pos ); + @Override + public Iterable getSelectedBoundingBoxesFromPool(final World w, final BlockPos pos, final Entity thePlayer, final boolean b) { + final AxisAlignedBB aabb = this.computeAABB(w, pos); - return Collections.singletonList( aabb ); - } + return Collections.singletonList(aabb); + } - @Override - public void addCollidingBlockToList( final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e ) - { - final AxisAlignedBB aabb = this.computeAABB( w, pos ); + @Override + public void addCollidingBlockToList(final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e) { + final AxisAlignedBB aabb = this.computeAABB(w, pos); - out.add( aabb ); - } + out.add(aabb); + } - private AxisAlignedBB computeAABB( final World w, final BlockPos pos ) - { - final TileSkyChest sk = this.getTileEntity( w, pos ); - EnumFacing o = EnumFacing.UP; + private AxisAlignedBB computeAABB(final World w, final BlockPos pos) { + final TileSkyChest sk = this.getTileEntity(w, pos); + EnumFacing o = EnumFacing.UP; - if( sk != null ) - { - o = sk.getUp(); - } + if (sk != null) { + o = sk.getUp(); + } - final double offsetX = o.getFrontOffsetX() == 0 ? AABB_OFFSET_SIDES : 0.0; - final double offsetY = o.getFrontOffsetY() == 0 ? AABB_OFFSET_SIDES : 0.0; - final double offsetZ = o.getFrontOffsetZ() == 0 ? AABB_OFFSET_SIDES : 0.0; + final double offsetX = o.getFrontOffsetX() == 0 ? AABB_OFFSET_SIDES : 0.0; + final double offsetY = o.getFrontOffsetY() == 0 ? AABB_OFFSET_SIDES : 0.0; + final double offsetZ = o.getFrontOffsetZ() == 0 ? AABB_OFFSET_SIDES : 0.0; - // for x/z top and bottom is swapped - final double minX = Math.max( 0.0, offsetX + ( o.getFrontOffsetX() < 0 ? AABB_OFFSET_BOTTOM : ( o.getFrontOffsetX() * AABB_OFFSET_TOP ) ) ); - final double minY = Math.max( 0.0, offsetY + ( o.getFrontOffsetY() < 0 ? AABB_OFFSET_TOP : ( o.getFrontOffsetY() * AABB_OFFSET_BOTTOM ) ) ); - final double minZ = Math.max( 0.0, offsetZ + ( o.getFrontOffsetZ() < 0 ? AABB_OFFSET_BOTTOM : ( o.getFrontOffsetZ() * AABB_OFFSET_TOP ) ) ); + // for x/z top and bottom is swapped + final double minX = Math.max(0.0, offsetX + (o.getFrontOffsetX() < 0 ? AABB_OFFSET_BOTTOM : (o.getFrontOffsetX() * AABB_OFFSET_TOP))); + final double minY = Math.max(0.0, offsetY + (o.getFrontOffsetY() < 0 ? AABB_OFFSET_TOP : (o.getFrontOffsetY() * AABB_OFFSET_BOTTOM))); + final double minZ = Math.max(0.0, offsetZ + (o.getFrontOffsetZ() < 0 ? AABB_OFFSET_BOTTOM : (o.getFrontOffsetZ() * AABB_OFFSET_TOP))); - final double maxX = Math.min( 1.0, 1.0 - offsetX - ( o.getFrontOffsetX() < 0 ? AABB_OFFSET_TOP : ( o.getFrontOffsetX() * AABB_OFFSET_BOTTOM ) ) ); - final double maxY = Math.min( 1.0, 1.0 - offsetY - ( o.getFrontOffsetY() < 0 ? AABB_OFFSET_BOTTOM : ( o.getFrontOffsetY() * AABB_OFFSET_TOP ) ) ); - final double maxZ = Math.min( 1.0, 1.0 - offsetZ - ( o.getFrontOffsetZ() < 0 ? AABB_OFFSET_TOP : ( o.getFrontOffsetZ() * AABB_OFFSET_BOTTOM ) ) ); + final double maxX = Math.min(1.0, 1.0 - offsetX - (o.getFrontOffsetX() < 0 ? AABB_OFFSET_TOP : (o.getFrontOffsetX() * AABB_OFFSET_BOTTOM))); + final double maxY = Math.min(1.0, 1.0 - offsetY - (o.getFrontOffsetY() < 0 ? AABB_OFFSET_BOTTOM : (o.getFrontOffsetY() * AABB_OFFSET_TOP))); + final double maxZ = Math.min(1.0, 1.0 - offsetZ - (o.getFrontOffsetZ() < 0 ? AABB_OFFSET_TOP : (o.getFrontOffsetZ() * AABB_OFFSET_BOTTOM))); - return new AxisAlignedBB( minX, minY, minZ, maxX, maxY, maxZ ); - } + return new AxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ); + } } diff --git a/src/main/java/appeng/block/storage/ChestRendering.java b/src/main/java/appeng/block/storage/ChestRendering.java index 1e3334781..539dd26c7 100644 --- a/src/main/java/appeng/block/storage/ChestRendering.java +++ b/src/main/java/appeng/block/storage/ChestRendering.java @@ -19,27 +19,24 @@ package appeng.block.storage; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.util.AEColor; import appeng.bootstrap.BlockRenderingCustomizer; import appeng.bootstrap.IBlockRendering; import appeng.bootstrap.IItemRendering; import appeng.client.render.ColorableTileBlockColor; import appeng.client.render.StaticItemColor; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class ChestRendering extends BlockRenderingCustomizer -{ +public class ChestRendering extends BlockRenderingCustomizer { - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - // I checked, the ME chest doesn't keep its color in item form - itemRendering.color( new StaticItemColor( AEColor.TRANSPARENT ) ); - rendering.blockColor( new ColorableTileBlockColor() ); - } + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + // I checked, the ME chest doesn't keep its color in item form + itemRendering.color(new StaticItemColor(AEColor.TRANSPARENT)); + rendering.blockColor(new ColorableTileBlockColor()); + } } diff --git a/src/main/java/appeng/block/storage/DriveRendering.java b/src/main/java/appeng/block/storage/DriveRendering.java index dad878872..7436f655e 100644 --- a/src/main/java/appeng/block/storage/DriveRendering.java +++ b/src/main/java/appeng/block/storage/DriveRendering.java @@ -25,11 +25,9 @@ import appeng.bootstrap.IItemRendering; import appeng.client.render.model.DriveModel; -public class DriveRendering extends BlockRenderingCustomizer -{ - @Override - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - rendering.builtInModel( "models/block/builtin/drive", new DriveModel() ); - } +public class DriveRendering extends BlockRenderingCustomizer { + @Override + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + rendering.builtInModel("models/block/builtin/drive", new DriveModel()); + } } diff --git a/src/main/java/appeng/block/storage/DriveSlotState.java b/src/main/java/appeng/block/storage/DriveSlotState.java index ffd8b9a2f..15b2dce3b 100644 --- a/src/main/java/appeng/block/storage/DriveSlotState.java +++ b/src/main/java/appeng/block/storage/DriveSlotState.java @@ -25,51 +25,46 @@ import net.minecraft.util.IStringSerializable; /** * Describes the different states a single slot of a BlockDrive can be in in terms of rendering. */ -public enum DriveSlotState implements IStringSerializable -{ +public enum DriveSlotState implements IStringSerializable { - // No cell in slot - EMPTY( "empty" ), + // No cell in slot + EMPTY("empty"), - // Cell in slot, but unpowered - OFFLINE( "offline" ), + // Cell in slot, but unpowered + OFFLINE("offline"), - // Online and free space - ONLINE( "online" ), + // Online and free space + ONLINE("online"), - // Types full, space left - TYPES_FULL( "types_full" ), + // Types full, space left + TYPES_FULL("types_full"), - // Completely full - FULL( "full" ); + // Completely full + FULL("full"); - private final String name; + private final String name; - DriveSlotState( String name ) - { - this.name = name; - } + DriveSlotState(String name) { + this.name = name; + } - @Override - public String getName() - { - return this.name; - } + @Override + public String getName() { + return this.name; + } - public static DriveSlotState fromCellStatus( int cellStatus ) - { - switch( cellStatus ) - { - default: - case 0: - return DriveSlotState.EMPTY; - case 1: - return DriveSlotState.ONLINE; - case 2: - return DriveSlotState.TYPES_FULL; - case 3: - return DriveSlotState.FULL; - } - } + public static DriveSlotState fromCellStatus(int cellStatus) { + switch (cellStatus) { + default: + case 0: + return DriveSlotState.EMPTY; + case 1: + return DriveSlotState.ONLINE; + case 2: + return DriveSlotState.TYPES_FULL; + case 3: + return DriveSlotState.FULL; + } + } } diff --git a/src/main/java/appeng/block/storage/DriveSlotsState.java b/src/main/java/appeng/block/storage/DriveSlotsState.java index 48a6d4d74..dc43ca299 100644 --- a/src/main/java/appeng/block/storage/DriveSlotsState.java +++ b/src/main/java/appeng/block/storage/DriveSlotsState.java @@ -25,64 +25,49 @@ import appeng.api.implementations.tiles.IChestOrDrive; /** * Contains the full information about what the state of the slots in a BlockDrive is. */ -public class DriveSlotsState -{ +public class DriveSlotsState { - private final DriveSlotState[] slots; + private final DriveSlotState[] slots; - private DriveSlotsState( DriveSlotState[] slots ) - { - this.slots = slots; - } + private DriveSlotsState(DriveSlotState[] slots) { + this.slots = slots; + } - public DriveSlotState getState( int index ) - { - if( index >= this.slots.length ) - { - return DriveSlotState.EMPTY; - } - return this.slots[index]; - } + public DriveSlotState getState(int index) { + if (index >= this.slots.length) { + return DriveSlotState.EMPTY; + } + return this.slots[index]; + } - public int getSlotCount() - { - return this.slots.length; - } + public int getSlotCount() { + return this.slots.length; + } - /** - * Retrieve an array that describes the state of each slot in this drive or chest. - */ - public static DriveSlotsState fromChestOrDrive( IChestOrDrive chestOrDrive ) - { - DriveSlotState[] slots = new DriveSlotState[chestOrDrive.getCellCount()]; - for( int i = 0; i < chestOrDrive.getCellCount(); i++ ) - { - if( !chestOrDrive.isPowered() ) - { - if( chestOrDrive.getCellStatus( i ) != 0 ) - { - slots[i] = DriveSlotState.OFFLINE; - } - else - { - slots[i] = DriveSlotState.EMPTY; - } - } - else - { - slots[i] = DriveSlotState.fromCellStatus( chestOrDrive.getCellStatus( i ) ); - } - } - return new DriveSlotsState( slots ); - } + /** + * Retrieve an array that describes the state of each slot in this drive or chest. + */ + public static DriveSlotsState fromChestOrDrive(IChestOrDrive chestOrDrive) { + DriveSlotState[] slots = new DriveSlotState[chestOrDrive.getCellCount()]; + for (int i = 0; i < chestOrDrive.getCellCount(); i++) { + if (!chestOrDrive.isPowered()) { + if (chestOrDrive.getCellStatus(i) != 0) { + slots[i] = DriveSlotState.OFFLINE; + } else { + slots[i] = DriveSlotState.EMPTY; + } + } else { + slots[i] = DriveSlotState.fromCellStatus(chestOrDrive.getCellStatus(i)); + } + } + return new DriveSlotsState(slots); + } - public static DriveSlotsState createEmpty( int slotCount ) - { - DriveSlotState[] slots = new DriveSlotState[slotCount]; - for( int i = 0; i < slotCount; i++ ) - { - slots[i] = DriveSlotState.EMPTY; - } - return new DriveSlotsState( slots ); - } + public static DriveSlotsState createEmpty(int slotCount) { + DriveSlotState[] slots = new DriveSlotState[slotCount]; + for (int i = 0; i < slotCount; i++) { + slots[i] = DriveSlotState.EMPTY; + } + return new DriveSlotsState(slots); + } } diff --git a/src/main/java/appeng/block/storage/SkyChestRenderingCustomizer.java b/src/main/java/appeng/block/storage/SkyChestRenderingCustomizer.java index 59ec68cf9..c7193eb23 100644 --- a/src/main/java/appeng/block/storage/SkyChestRenderingCustomizer.java +++ b/src/main/java/appeng/block/storage/SkyChestRenderingCustomizer.java @@ -19,51 +19,45 @@ package appeng.block.storage; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.bootstrap.BlockRenderingCustomizer; import appeng.bootstrap.IBlockRendering; import appeng.bootstrap.IItemRendering; import appeng.client.render.tesr.SkyChestTESR; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class SkyChestRenderingCustomizer extends BlockRenderingCustomizer -{ +public class SkyChestRenderingCustomizer extends BlockRenderingCustomizer { - private final BlockSkyChest.SkyChestType type; + private final BlockSkyChest.SkyChestType type; - public SkyChestRenderingCustomizer( BlockSkyChest.SkyChestType type ) - { - this.type = type; - } + public SkyChestRenderingCustomizer(BlockSkyChest.SkyChestType type) { + this.type = type; + } - @SideOnly( Side.CLIENT ) - @Override - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - rendering.tesr( new SkyChestTESR() ); + @SideOnly(Side.CLIENT) + @Override + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + rendering.tesr(new SkyChestTESR()); - // Register a custom non-tesr item model - String modelName = this.getModelFromType(); - ModelResourceLocation model = new ModelResourceLocation( "appliedenergistics2:" + modelName, "inventory" ); - itemRendering.model( model ).variants( model ); - } + // Register a custom non-tesr item model + String modelName = this.getModelFromType(); + ModelResourceLocation model = new ModelResourceLocation("appliedenergistics2:" + modelName, "inventory"); + itemRendering.model(model).variants(model); + } - private String getModelFromType() - { - final String modelName; - switch( this.type ) - { - default: - case STONE: - modelName = "sky_stone_chest"; - break; - case BLOCK: - modelName = "smooth_sky_stone_chest"; - break; - } - return modelName; - } + private String getModelFromType() { + final String modelName; + switch (this.type) { + default: + case STONE: + modelName = "sky_stone_chest"; + break; + case BLOCK: + modelName = "smooth_sky_stone_chest"; + break; + } + return modelName; + } } diff --git a/src/main/java/appeng/bootstrap/BlockDefinitionBuilder.java b/src/main/java/appeng/bootstrap/BlockDefinitionBuilder.java index 629c1df49..bfc96e3c1 100644 --- a/src/main/java/appeng/bootstrap/BlockDefinitionBuilder.java +++ b/src/main/java/appeng/bootstrap/BlockDefinitionBuilder.java @@ -19,25 +19,6 @@ package appeng.bootstrap; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Supplier; - -import javax.annotation.Nullable; - -import net.minecraft.block.Block; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.item.Item; -import net.minecraft.item.ItemBlock; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.definitions.IBlockDefinition; import appeng.block.AEBaseBlock; import appeng.block.AEBaseItemBlock; @@ -49,233 +30,209 @@ import appeng.bootstrap.definitions.TileEntityDefinition; import appeng.core.AEConfig; import appeng.core.AppEng; import appeng.core.CreativeTab; -import appeng.core.features.AEFeature; -import appeng.core.features.ActivityState; -import appeng.core.features.BlockDefinition; -import appeng.core.features.BlockStackSrc; -import appeng.core.features.TileDefinition; +import appeng.core.features.*; import appeng.tile.AEBaseTile; import appeng.util.Platform; +import net.minecraft.block.Block; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemBlock; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Supplier; -class BlockDefinitionBuilder implements IBlockBuilder -{ +class BlockDefinitionBuilder implements IBlockBuilder { - private final FeatureFactory factory; + private final FeatureFactory factory; - private final String registryName; + private final String registryName; - private final Supplier blockSupplier; + private final Supplier blockSupplier; - private final List> bootstrapComponents = new ArrayList<>(); + private final List> bootstrapComponents = new ArrayList<>(); - private final EnumSet features = EnumSet.noneOf( AEFeature.class ); + private final EnumSet features = EnumSet.noneOf(AEFeature.class); - private CreativeTabs creativeTab = CreativeTab.instance; + private final CreativeTabs creativeTab = CreativeTab.instance; - private TileEntityDefinition tileEntityDefinition; + private TileEntityDefinition tileEntityDefinition; - private boolean disableItem = false; + private boolean disableItem = false; - private Function itemFactory; + private Function itemFactory; - @SideOnly( Side.CLIENT ) - private BlockRendering blockRendering; + @SideOnly(Side.CLIENT) + private BlockRendering blockRendering; - @SideOnly( Side.CLIENT ) - private ItemRendering itemRendering; + @SideOnly(Side.CLIENT) + private ItemRendering itemRendering; - BlockDefinitionBuilder( FeatureFactory factory, String id, Supplier blockSupplier ) - { - this.factory = factory; - this.registryName = id; - this.blockSupplier = blockSupplier; + BlockDefinitionBuilder(FeatureFactory factory, String id, Supplier blockSupplier) { + this.factory = factory; + this.registryName = id; + this.blockSupplier = blockSupplier; - if( Platform.isClient() ) - { - this.blockRendering = new BlockRendering(); - this.itemRendering = new ItemRendering(); - } - } + if (Platform.isClient()) { + this.blockRendering = new BlockRendering(); + this.itemRendering = new ItemRendering(); + } + } - @Override - public BlockDefinitionBuilder bootstrap( BiFunction callback ) - { - this.bootstrapComponents.add( callback ); - return this; - } + @Override + public BlockDefinitionBuilder bootstrap(BiFunction callback) { + this.bootstrapComponents.add(callback); + return this; + } - @Override - public IBlockBuilder features( AEFeature... features ) - { - this.features.clear(); - this.addFeatures( features ); - return this; - } + @Override + public IBlockBuilder features(AEFeature... features) { + this.features.clear(); + this.addFeatures(features); + return this; + } - @Override - public IBlockBuilder addFeatures( AEFeature... features ) - { - Collections.addAll( this.features, features ); - return this; - } + @Override + public IBlockBuilder addFeatures(AEFeature... features) { + Collections.addAll(this.features, features); + return this; + } - @Override - public BlockDefinitionBuilder rendering( BlockRenderingCustomizer callback ) - { - if( Platform.isClient() ) - { - this.customizeForClient( callback ); - } + @Override + public BlockDefinitionBuilder rendering(BlockRenderingCustomizer callback) { + if (Platform.isClient()) { + this.customizeForClient(callback); + } - return this; - } + return this; + } - @Override - public IBlockBuilder tileEntity( TileEntityDefinition tileEntityDefinition ) - { - this.tileEntityDefinition = tileEntityDefinition; - return this; - } + @Override + public IBlockBuilder tileEntity(TileEntityDefinition tileEntityDefinition) { + this.tileEntityDefinition = tileEntityDefinition; + return this; + } - @Override - public IBlockBuilder useCustomItemModel() - { - this.rendering( new BlockRenderingCustomizer() - { - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - ModelResourceLocation model = new ModelResourceLocation( new ResourceLocation( AppEng.MOD_ID, BlockDefinitionBuilder.this.registryName ), "inventory" ); - itemRendering.model( model ).variants( model ); - } - } ); + @Override + public IBlockBuilder useCustomItemModel() { + this.rendering(new BlockRenderingCustomizer() { + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + ModelResourceLocation model = new ModelResourceLocation(new ResourceLocation(AppEng.MOD_ID, BlockDefinitionBuilder.this.registryName), "inventory"); + itemRendering.model(model).variants(model); + } + }); - return this; - } + return this; + } - @Override - public IBlockBuilder item( Function factory ) - { - this.itemFactory = factory; - return this; - } + @Override + public IBlockBuilder item(Function factory) { + this.itemFactory = factory; + return this; + } - @Override - public IBlockBuilder disableItem() - { - this.disableItem = true; - return this; - } + @Override + public IBlockBuilder disableItem() { + this.disableItem = true; + return this; + } - @SideOnly( Side.CLIENT ) - private void customizeForClient( BlockRenderingCustomizer callback ) - { - callback.customize( this.blockRendering, this.itemRendering ); - } + @SideOnly(Side.CLIENT) + private void customizeForClient(BlockRenderingCustomizer callback) { + callback.customize(this.blockRendering, this.itemRendering); + } - @SuppressWarnings( "unchecked" ) - @Override - public T build() - { - if( !AEConfig.instance().areFeaturesEnabled( this.features ) ) - { - return (T) new TileDefinition( this.registryName, null, null ); - } + @SuppressWarnings("unchecked") + @Override + public T build() { + if (!AEConfig.instance().areFeaturesEnabled(this.features)) { + return (T) new TileDefinition(this.registryName, null, null); + } - // Create block and matching item, and set factory name of both - Block block = this.blockSupplier.get(); - block.setRegistryName( AppEng.MOD_ID, this.registryName ); - block.setUnlocalizedName( "appliedenergistics2." + this.registryName ); + // Create block and matching item, and set factory name of both + Block block = this.blockSupplier.get(); + block.setRegistryName(AppEng.MOD_ID, this.registryName); + block.setUnlocalizedName("appliedenergistics2." + this.registryName); - ItemBlock item = this.constructItemFromBlock( block ); - if( item != null ) - { - item.setRegistryName( AppEng.MOD_ID, this.registryName ); - } + ItemBlock item = this.constructItemFromBlock(block); + if (item != null) { + item.setRegistryName(AppEng.MOD_ID, this.registryName); + } - // Register the item and block with the game - this.factory.addBootstrapComponent( (IBlockRegistrationComponent) ( side, registry ) -> registry.register( block ) ); - if( item != null ) - { - this.factory.addBootstrapComponent( (IItemRegistrationComponent) ( side, registry ) -> registry.register( item ) ); - } + // Register the item and block with the game + this.factory.addBootstrapComponent((IBlockRegistrationComponent) (side, registry) -> registry.register(block)); + if (item != null) { + this.factory.addBootstrapComponent((IItemRegistrationComponent) (side, registry) -> registry.register(item)); + } - block.setCreativeTab( this.creativeTab ); + block.setCreativeTab(this.creativeTab); - // Register all extra handlers - this.bootstrapComponents.forEach( component -> this.factory.addBootstrapComponent( component.apply( block, item ) ) ); + // Register all extra handlers + this.bootstrapComponents.forEach(component -> this.factory.addBootstrapComponent(component.apply(block, item))); - if( this.tileEntityDefinition != null && block instanceof AEBaseTileBlock ) - { - ( (AEBaseTileBlock) block ).setTileEntity( this.tileEntityDefinition.getTileEntityClass() ); - if( this.tileEntityDefinition.getName() == null ) - { - this.tileEntityDefinition.setName( this.registryName ); - } + if (this.tileEntityDefinition != null && block instanceof AEBaseTileBlock) { + ((AEBaseTileBlock) block).setTileEntity(this.tileEntityDefinition.getTileEntityClass()); + if (this.tileEntityDefinition.getName() == null) { + this.tileEntityDefinition.setName(this.registryName); + } - } + } - if( Platform.isClient() ) - { - if( block instanceof AEBaseTileBlock ) - { - AEBaseTileBlock tileBlock = (AEBaseTileBlock) block; - this.blockRendering.apply( this.factory, block, tileBlock.getTileEntityClass() ); - } - else - { - this.blockRendering.apply( this.factory, block, null ); - } + if (Platform.isClient()) { + if (block instanceof AEBaseTileBlock) { + AEBaseTileBlock tileBlock = (AEBaseTileBlock) block; + this.blockRendering.apply(this.factory, block, tileBlock.getTileEntityClass()); + } else { + this.blockRendering.apply(this.factory, block, null); + } - if( item != null ) - { - this.itemRendering.apply( this.factory, item ); - } - } + if (item != null) { + this.itemRendering.apply(this.factory, item); + } + } - if( block instanceof AEBaseTileBlock ) - { - this.factory.addBootstrapComponent( (IPreInitComponent) side -> - { - AEBaseTile.registerTileItem( - this.tileEntityDefinition == null ? ( (AEBaseTileBlock) block ).getTileEntityClass() : this.tileEntityDefinition.getTileEntityClass(), - new BlockStackSrc( block, 0, ActivityState.Enabled ) ); - } ); + if (block instanceof AEBaseTileBlock) { + this.factory.addBootstrapComponent((IPreInitComponent) side -> + { + AEBaseTile.registerTileItem( + this.tileEntityDefinition == null ? ((AEBaseTileBlock) block).getTileEntityClass() : this.tileEntityDefinition.getTileEntityClass(), + new BlockStackSrc(block, 0, ActivityState.Enabled)); + }); - if( this.tileEntityDefinition != null ) - { - this.factory.tileEntityComponent.addTileEntity( this.tileEntityDefinition ); - } + if (this.tileEntityDefinition != null) { + this.factory.tileEntityComponent.addTileEntity(this.tileEntityDefinition); + } - return (T) new TileDefinition( this.registryName, (AEBaseTileBlock) block, item ); - } - else - { - return (T) new BlockDefinition( this.registryName, block, item ); - } - } + return (T) new TileDefinition(this.registryName, (AEBaseTileBlock) block, item); + } else { + return (T) new BlockDefinition(this.registryName, block, item); + } + } - @Nullable - private ItemBlock constructItemFromBlock( Block block ) - { - if( this.disableItem ) - { - return null; - } + @Nullable + private ItemBlock constructItemFromBlock(Block block) { + if (this.disableItem) { + return null; + } - if( this.itemFactory != null ) - { - return this.itemFactory.apply( block ); - } - else if( block instanceof AEBaseBlock ) - { - return new AEBaseItemBlock( block ); - } - else - { - return new ItemBlock( block ); - } - } + if (this.itemFactory != null) { + return this.itemFactory.apply(block); + } else if (block instanceof AEBaseBlock) { + return new AEBaseItemBlock(block); + } else { + return new ItemBlock(block); + } + } } diff --git a/src/main/java/appeng/bootstrap/BlockRendering.java b/src/main/java/appeng/bootstrap/BlockRendering.java index 70a0c5778..aaa095849 100644 --- a/src/main/java/appeng/bootstrap/BlockRendering.java +++ b/src/main/java/appeng/bootstrap/BlockRendering.java @@ -19,10 +19,11 @@ package appeng.bootstrap; -import java.util.HashMap; -import java.util.Map; -import java.util.function.BiFunction; - +import appeng.block.AEBaseTileBlock; +import appeng.bootstrap.components.BlockColorComponent; +import appeng.bootstrap.components.StateMapperComponent; +import appeng.bootstrap.components.TesrComponent; +import appeng.client.render.model.AutoRotatingModel; import net.minecraft.block.Block; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelResourceLocation; @@ -33,103 +34,87 @@ import net.minecraftforge.client.model.IModel; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.block.AEBaseTileBlock; -import appeng.bootstrap.components.BlockColorComponent; -import appeng.bootstrap.components.StateMapperComponent; -import appeng.bootstrap.components.TesrComponent; -import appeng.client.render.model.AutoRotatingModel; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; -class BlockRendering implements IBlockRendering -{ +class BlockRendering implements IBlockRendering { - @SideOnly( Side.CLIENT ) - private BiFunction modelCustomizer; + @SideOnly(Side.CLIENT) + private BiFunction modelCustomizer; - @SideOnly( Side.CLIENT ) - private IBlockColor blockColor; + @SideOnly(Side.CLIENT) + private IBlockColor blockColor; - @SideOnly( Side.CLIENT ) - private TileEntitySpecialRenderer tesr; + @SideOnly(Side.CLIENT) + private TileEntitySpecialRenderer tesr; - @SideOnly( Side.CLIENT ) - private IStateMapper stateMapper; + @SideOnly(Side.CLIENT) + private IStateMapper stateMapper; - @SideOnly( Side.CLIENT ) - private Map builtInModels = new HashMap<>(); + @SideOnly(Side.CLIENT) + private final Map builtInModels = new HashMap<>(); - @Override - @SideOnly( Side.CLIENT ) - public IBlockRendering modelCustomizer( BiFunction customizer ) - { - this.modelCustomizer = customizer; - return this; - } + @Override + @SideOnly(Side.CLIENT) + public IBlockRendering modelCustomizer(BiFunction customizer) { + this.modelCustomizer = customizer; + return this; + } - @SideOnly( Side.CLIENT ) - @Override - public IBlockRendering blockColor( IBlockColor blockColor ) - { - this.blockColor = blockColor; - return this; - } + @SideOnly(Side.CLIENT) + @Override + public IBlockRendering blockColor(IBlockColor blockColor) { + this.blockColor = blockColor; + return this; + } - @SideOnly( Side.CLIENT ) - @Override - public IBlockRendering tesr( TileEntitySpecialRenderer tesr ) - { - this.tesr = tesr; - return this; - } + @SideOnly(Side.CLIENT) + @Override + public IBlockRendering tesr(TileEntitySpecialRenderer tesr) { + this.tesr = tesr; + return this; + } - @Override - public IBlockRendering builtInModel( String name, IModel model ) - { - this.builtInModels.put( name, model ); - return this; - } + @Override + public IBlockRendering builtInModel(String name, IModel model) { + this.builtInModels.put(name, model); + return this; + } - @SideOnly( Side.CLIENT ) - @Override - public IBlockRendering stateMapper( IStateMapper mapper ) - { - this.stateMapper = mapper; - return this; - } + @SideOnly(Side.CLIENT) + @Override + public IBlockRendering stateMapper(IStateMapper mapper) { + this.stateMapper = mapper; + return this; + } - void apply( FeatureFactory factory, Block block, Class tileEntityClass ) - { - if( this.tesr != null ) - { - if( tileEntityClass == null ) - { - throw new IllegalStateException( "Tried to register a TESR for " + block + " even though no tile entity has been specified." ); - } - factory.addBootstrapComponent( new TesrComponent( tileEntityClass, this.tesr ) ); - } + void apply(FeatureFactory factory, Block block, Class tileEntityClass) { + if (this.tesr != null) { + if (tileEntityClass == null) { + throw new IllegalStateException("Tried to register a TESR for " + block + " even though no tile entity has been specified."); + } + factory.addBootstrapComponent(new TesrComponent(tileEntityClass, this.tesr)); + } - if( this.modelCustomizer != null ) - { - factory.addModelOverride( block.getRegistryName().getResourcePath(), this.modelCustomizer ); - } - else if( block instanceof AEBaseTileBlock ) - { - // This is a default rotating model if the base-block uses an AE tile entity which exposes UP/FRONT as - // extended props - factory.addModelOverride( block.getRegistryName().getResourcePath(), ( l, m ) -> new AutoRotatingModel( m ) ); - } + if (this.modelCustomizer != null) { + factory.addModelOverride(block.getRegistryName().getResourcePath(), this.modelCustomizer); + } else if (block instanceof AEBaseTileBlock) { + // This is a default rotating model if the base-block uses an AE tile entity which exposes UP/FRONT as + // extended props + factory.addModelOverride(block.getRegistryName().getResourcePath(), (l, m) -> new AutoRotatingModel(m)); + } - // TODO : 1.12 - this.builtInModels.forEach( factory::addBuiltInModel ); + // TODO : 1.12 + this.builtInModels.forEach(factory::addBuiltInModel); - if( this.blockColor != null ) - { - factory.addBootstrapComponent( new BlockColorComponent( block, this.blockColor ) ); - } + if (this.blockColor != null) { + factory.addBootstrapComponent(new BlockColorComponent(block, this.blockColor)); + } - if( this.stateMapper != null ) - { - factory.addBootstrapComponent( new StateMapperComponent( block, this.stateMapper ) ); - } - } + if (this.stateMapper != null) { + factory.addBootstrapComponent(new StateMapperComponent(block, this.stateMapper)); + } + } } diff --git a/src/main/java/appeng/bootstrap/BlockRenderingCustomizer.java b/src/main/java/appeng/bootstrap/BlockRenderingCustomizer.java index 40e306bc2..f93ad51d9 100644 --- a/src/main/java/appeng/bootstrap/BlockRenderingCustomizer.java +++ b/src/main/java/appeng/bootstrap/BlockRenderingCustomizer.java @@ -28,10 +28,9 @@ import net.minecraftforge.fml.relauncher.SideOnly; * used * due to them not being able to be annotated with @SideOnly(CLIENT). */ -public abstract class BlockRenderingCustomizer -{ +public abstract class BlockRenderingCustomizer { - @SideOnly( Side.CLIENT ) - public abstract void customize( IBlockRendering rendering, IItemRendering itemRendering ); + @SideOnly(Side.CLIENT) + public abstract void customize(IBlockRendering rendering, IItemRendering itemRendering); } diff --git a/src/main/java/appeng/bootstrap/FeatureFactory.java b/src/main/java/appeng/bootstrap/FeatureFactory.java index bce43cfaa..48054a597 100644 --- a/src/main/java/appeng/bootstrap/FeatureFactory.java +++ b/src/main/java/appeng/bootstrap/FeatureFactory.java @@ -19,24 +19,6 @@ package appeng.bootstrap; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.function.BiFunction; -import java.util.function.Supplier; - -import net.minecraft.block.Block; -import net.minecraft.client.renderer.block.model.IBakedModel; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.item.Item; -import net.minecraftforge.client.model.IModel; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.definitions.IItemDefinition; import appeng.api.util.AEColor; import appeng.api.util.AEColoredItemDefinition; @@ -48,111 +30,107 @@ import appeng.core.features.ActivityState; import appeng.core.features.ColoredItemDefinition; import appeng.core.features.ItemStackSrc; import appeng.util.Platform; +import net.minecraft.block.Block; +import net.minecraft.client.renderer.block.model.IBakedModel; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.item.Item; +import net.minecraftforge.client.model.IModel; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import java.util.*; +import java.util.function.BiFunction; +import java.util.function.Supplier; -public class FeatureFactory -{ +public class FeatureFactory { - private final AEFeature[] defaultFeatures; + private final AEFeature[] defaultFeatures; - private final Map, List> bootstrapComponents; + private final Map, List> bootstrapComponents; - @SideOnly( Side.CLIENT ) - private ModelOverrideComponent modelOverrideComponent; + @SideOnly(Side.CLIENT) + private ModelOverrideComponent modelOverrideComponent; - @SideOnly( Side.CLIENT ) - private BuiltInModelComponent builtInModelComponent; + @SideOnly(Side.CLIENT) + private BuiltInModelComponent builtInModelComponent; - public final TileEntityComponent tileEntityComponent; + public final TileEntityComponent tileEntityComponent; - public FeatureFactory() - { - this.defaultFeatures = new AEFeature[] { AEFeature.CORE }; - this.bootstrapComponents = new HashMap<>(); + public FeatureFactory() { + this.defaultFeatures = new AEFeature[]{AEFeature.CORE}; + this.bootstrapComponents = new HashMap<>(); - this.tileEntityComponent = new TileEntityComponent(); - this.addBootstrapComponent( this.tileEntityComponent ); + this.tileEntityComponent = new TileEntityComponent(); + this.addBootstrapComponent(this.tileEntityComponent); - if( Platform.isClient() ) - { - this.modelOverrideComponent = new ModelOverrideComponent(); - this.addBootstrapComponent( this.modelOverrideComponent ); + if (Platform.isClient()) { + this.modelOverrideComponent = new ModelOverrideComponent(); + this.addBootstrapComponent(this.modelOverrideComponent); - this.builtInModelComponent = new BuiltInModelComponent(); - this.addBootstrapComponent( this.builtInModelComponent ); - } - } + this.builtInModelComponent = new BuiltInModelComponent(); + this.addBootstrapComponent(this.builtInModelComponent); + } + } - private FeatureFactory( FeatureFactory parent, AEFeature... defaultFeatures ) - { - this.defaultFeatures = defaultFeatures.clone(); - this.bootstrapComponents = parent.bootstrapComponents; - this.tileEntityComponent = parent.tileEntityComponent; - if( Platform.isClient() ) - { - this.modelOverrideComponent = parent.modelOverrideComponent; - this.builtInModelComponent = parent.builtInModelComponent; - } - } + private FeatureFactory(FeatureFactory parent, AEFeature... defaultFeatures) { + this.defaultFeatures = defaultFeatures.clone(); + this.bootstrapComponents = parent.bootstrapComponents; + this.tileEntityComponent = parent.tileEntityComponent; + if (Platform.isClient()) { + this.modelOverrideComponent = parent.modelOverrideComponent; + this.builtInModelComponent = parent.builtInModelComponent; + } + } - public IBlockBuilder block( String id, Supplier block ) - { - return new BlockDefinitionBuilder( this, id, block ).features( this.defaultFeatures ); - } + public IBlockBuilder block(String id, Supplier block) { + return new BlockDefinitionBuilder(this, id, block).features(this.defaultFeatures); + } - public IItemBuilder item( String id, Supplier item ) - { - return new ItemDefinitionBuilder( this, id, item ).features( this.defaultFeatures ); - } + public IItemBuilder item(String id, Supplier item) { + return new ItemDefinitionBuilder(this, id, item).features(this.defaultFeatures); + } - public AEColoredItemDefinition colored( IItemDefinition target, int offset ) - { - ColoredItemDefinition definition = new ColoredItemDefinition(); + public AEColoredItemDefinition colored(IItemDefinition target, int offset) { + ColoredItemDefinition definition = new ColoredItemDefinition(); - target.maybeItem().ifPresent( targetItem -> - { - for( final AEColor color : AEColor.VALID_COLORS ) - { - final ActivityState state = ActivityState.from( target.isEnabled() ); + target.maybeItem().ifPresent(targetItem -> + { + for (final AEColor color : AEColor.VALID_COLORS) { + final ActivityState state = ActivityState.from(target.isEnabled()); - definition.add( color, new ItemStackSrc( targetItem, offset + color.ordinal(), state ) ); - } - } ); + definition.add(color, new ItemStackSrc(targetItem, offset + color.ordinal(), state)); + } + }); - return definition; - } + return definition; + } - public FeatureFactory features( AEFeature... features ) - { - return new FeatureFactory( this, features ); - } + public FeatureFactory features(AEFeature... features) { + return new FeatureFactory(this, features); + } - public void addBootstrapComponent( IBootstrapComponent component ) - { - Arrays.stream( component.getClass().getInterfaces() ) - .filter( i -> IBootstrapComponent.class.isAssignableFrom( i ) ) - .forEach( i -> this.addBootstrapComponent( (Class) i, component ) ); - } + public void addBootstrapComponent(IBootstrapComponent component) { + Arrays.stream(component.getClass().getInterfaces()) + .filter(i -> IBootstrapComponent.class.isAssignableFrom(i)) + .forEach(i -> this.addBootstrapComponent((Class) i, component)); + } - private void addBootstrapComponent( Class eventType, T component ) - { - this.bootstrapComponents.computeIfAbsent( eventType, c -> new ArrayList() ).add( component ); - } + private void addBootstrapComponent(Class eventType, T component) { + this.bootstrapComponents.computeIfAbsent(eventType, c -> new ArrayList()).add(component); + } - @SideOnly( Side.CLIENT ) - void addBuiltInModel( String path, IModel model ) - { - this.builtInModelComponent.addModel( path, model ); - } + @SideOnly(Side.CLIENT) + void addBuiltInModel(String path, IModel model) { + this.builtInModelComponent.addModel(path, model); + } - @SideOnly( Side.CLIENT ) - void addModelOverride( String resourcePath, BiFunction customizer ) - { - this.modelOverrideComponent.addOverride( resourcePath, customizer ); - } + @SideOnly(Side.CLIENT) + void addModelOverride(String resourcePath, BiFunction customizer) { + this.modelOverrideComponent.addOverride(resourcePath, customizer); + } - public Iterator getBootstrapComponents( Class eventType ) - { - return (Iterator) this.bootstrapComponents.getOrDefault( eventType, Collections.emptyList() ).iterator(); - } + public Iterator getBootstrapComponents(Class eventType) { + return (Iterator) this.bootstrapComponents.getOrDefault(eventType, Collections.emptyList()).iterator(); + } } diff --git a/src/main/java/appeng/bootstrap/IBlockBuilder.java b/src/main/java/appeng/bootstrap/IBlockBuilder.java index 1b75d8526..05b020812 100644 --- a/src/main/java/appeng/bootstrap/IBlockBuilder.java +++ b/src/main/java/appeng/bootstrap/IBlockBuilder.java @@ -19,42 +19,40 @@ package appeng.bootstrap; -import java.util.function.BiFunction; -import java.util.function.Function; - +import appeng.api.definitions.IBlockDefinition; +import appeng.bootstrap.definitions.TileEntityDefinition; +import appeng.core.features.AEFeature; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; -import appeng.api.definitions.IBlockDefinition; -import appeng.bootstrap.definitions.TileEntityDefinition; -import appeng.core.features.AEFeature; +import java.util.function.BiFunction; +import java.util.function.Function; -public interface IBlockBuilder -{ - IBlockBuilder bootstrap( BiFunction component ); +public interface IBlockBuilder { + IBlockBuilder bootstrap(BiFunction component); - IBlockBuilder features( AEFeature... features ); + IBlockBuilder features(AEFeature... features); - IBlockBuilder addFeatures( AEFeature... features ); + IBlockBuilder addFeatures(AEFeature... features); - IBlockBuilder rendering( BlockRenderingCustomizer callback ); + IBlockBuilder rendering(BlockRenderingCustomizer callback); - IBlockBuilder tileEntity( TileEntityDefinition tileEntityDefinition ); + IBlockBuilder tileEntity(TileEntityDefinition tileEntityDefinition); - /** - * Don't register an item for this block. - */ - IBlockBuilder disableItem(); + /** + * Don't register an item for this block. + */ + IBlockBuilder disableItem(); - /** - * Forces this block's item to uses a custom model, instead of using the default block state as the item model. - * The model has the same name as the registry name. - */ - IBlockBuilder useCustomItemModel(); + /** + * Forces this block's item to uses a custom model, instead of using the default block state as the item model. + * The model has the same name as the registry name. + */ + IBlockBuilder useCustomItemModel(); - IBlockBuilder item( Function factory ); + IBlockBuilder item(Function factory); - T build(); + T build(); } diff --git a/src/main/java/appeng/bootstrap/IBlockRendering.java b/src/main/java/appeng/bootstrap/IBlockRendering.java index 50caf9836..3329ab575 100644 --- a/src/main/java/appeng/bootstrap/IBlockRendering.java +++ b/src/main/java/appeng/bootstrap/IBlockRendering.java @@ -19,8 +19,6 @@ package appeng.bootstrap; -import java.util.function.BiFunction; - import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.block.statemap.IStateMapper; @@ -30,29 +28,30 @@ import net.minecraftforge.client.model.IModel; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import java.util.function.BiFunction; + /** * Allows for client-side rendering to be customized in the context of block/item registration. */ -public interface IBlockRendering -{ +public interface IBlockRendering { - @SideOnly( Side.CLIENT ) - IBlockRendering modelCustomizer( BiFunction customizer ); + @SideOnly(Side.CLIENT) + IBlockRendering modelCustomizer(BiFunction customizer); - @SideOnly( Side.CLIENT ) - IBlockRendering blockColor( IBlockColor blockColor ); + @SideOnly(Side.CLIENT) + IBlockRendering blockColor(IBlockColor blockColor); - @SideOnly( Side.CLIENT ) - IBlockRendering stateMapper( IStateMapper mapper ); + @SideOnly(Side.CLIENT) + IBlockRendering stateMapper(IStateMapper mapper); - @SideOnly( Side.CLIENT ) - IBlockRendering tesr( TileEntitySpecialRenderer tesr ); + @SideOnly(Side.CLIENT) + IBlockRendering tesr(TileEntitySpecialRenderer tesr); - /** - * Registers a built-in model under the given resource path. - */ - @SideOnly( Side.CLIENT ) - IBlockRendering builtInModel( String name, IModel model ); + /** + * Registers a built-in model under the given resource path. + */ + @SideOnly(Side.CLIENT) + IBlockRendering builtInModel(String name, IModel model); } diff --git a/src/main/java/appeng/bootstrap/IBootstrapComponent.java b/src/main/java/appeng/bootstrap/IBootstrapComponent.java index 717271d55..3f03af426 100644 --- a/src/main/java/appeng/bootstrap/IBootstrapComponent.java +++ b/src/main/java/appeng/bootstrap/IBootstrapComponent.java @@ -23,6 +23,5 @@ package appeng.bootstrap; * Bootstrap components can be registered to take part in the various initialization phases of Forge. * See the individual subclasses for a specific forge initalization event. */ -public interface IBootstrapComponent -{ +public interface IBootstrapComponent { } diff --git a/src/main/java/appeng/bootstrap/ICriterionTriggerRegistry.java b/src/main/java/appeng/bootstrap/ICriterionTriggerRegistry.java index c62ab00fd..1a43ab24f 100644 --- a/src/main/java/appeng/bootstrap/ICriterionTriggerRegistry.java +++ b/src/main/java/appeng/bootstrap/ICriterionTriggerRegistry.java @@ -24,7 +24,6 @@ import net.minecraft.advancements.ICriterionTrigger; @FunctionalInterface -public interface ICriterionTriggerRegistry -{ - void register( ICriterionTrigger trigger ); +public interface ICriterionTriggerRegistry { + void register(ICriterionTrigger trigger); } diff --git a/src/main/java/appeng/bootstrap/IItemBuilder.java b/src/main/java/appeng/bootstrap/IItemBuilder.java index 4e787ce26..f1e7821a3 100644 --- a/src/main/java/appeng/bootstrap/IItemBuilder.java +++ b/src/main/java/appeng/bootstrap/IItemBuilder.java @@ -19,37 +19,35 @@ package appeng.bootstrap; -import java.util.function.Function; -import java.util.function.Supplier; - +import appeng.core.features.AEFeature; +import appeng.core.features.ItemDefinition; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.dispenser.IBehaviorDispenseItem; import net.minecraft.item.Item; -import appeng.core.features.AEFeature; -import appeng.core.features.ItemDefinition; +import java.util.function.Function; +import java.util.function.Supplier; /** * Allows an item to be defined and registered with the game. * The item is only registered once build is called. */ -public interface IItemBuilder -{ - IItemBuilder bootstrap( Function component ); +public interface IItemBuilder { + IItemBuilder bootstrap(Function component); - IItemBuilder features( AEFeature... features ); + IItemBuilder features(AEFeature... features); - IItemBuilder addFeatures( AEFeature... features ); + IItemBuilder addFeatures(AEFeature... features); - IItemBuilder creativeTab( CreativeTabs tab ); + IItemBuilder creativeTab(CreativeTabs tab); - IItemBuilder rendering( ItemRenderingCustomizer callback ); + IItemBuilder rendering(ItemRenderingCustomizer callback); - /** - * Registers a custom dispenser behavior for this item. - */ - IItemBuilder dispenserBehavior( Supplier behavior ); + /** + * Registers a custom dispenser behavior for this item. + */ + IItemBuilder dispenserBehavior(Supplier behavior); - ItemDefinition build(); + ItemDefinition build(); } diff --git a/src/main/java/appeng/bootstrap/IItemRendering.java b/src/main/java/appeng/bootstrap/IItemRendering.java index 2e81b23bb..09fb97e53 100644 --- a/src/main/java/appeng/bootstrap/IItemRendering.java +++ b/src/main/java/appeng/bootstrap/IItemRendering.java @@ -19,9 +19,6 @@ package appeng.bootstrap; -import java.util.Arrays; -import java.util.Collection; - import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.color.IItemColor; @@ -30,66 +27,66 @@ import net.minecraftforge.client.model.IModel; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import java.util.Arrays; +import java.util.Collection; + /** * Allows the rendering of an item to be customized. */ -public interface IItemRendering -{ +public interface IItemRendering { - /** - * Registers a custom item mesh definition that will be used to dynamically determine the - * item model to be used for rendering by inspecting the item stack (i.e. for NBT data). - * Please - */ - @SideOnly( Side.CLIENT ) - IItemRendering meshDefinition( ItemMeshDefinition meshDefinition ); + /** + * Registers a custom item mesh definition that will be used to dynamically determine the + * item model to be used for rendering by inspecting the item stack (i.e. for NBT data). + * Please + */ + @SideOnly(Side.CLIENT) + IItemRendering meshDefinition(ItemMeshDefinition meshDefinition); - /** - * Registers an item model for meta=0, see {@link #model(int, ModelResourceLocation)}. - */ - @SideOnly( Side.CLIENT ) - default IItemRendering model( ModelResourceLocation model ) - { - return model( 0, model ); - } + /** + * Registers an item model for meta=0, see {@link #model(int, ModelResourceLocation)}. + */ + @SideOnly(Side.CLIENT) + default IItemRendering model(ModelResourceLocation model) { + return model(0, model); + } - /** - * Registers an item model for a given meta. - */ - @SideOnly( Side.CLIENT ) - IItemRendering model( int meta, ModelResourceLocation model ); + /** + * Registers an item model for a given meta. + */ + @SideOnly(Side.CLIENT) + IItemRendering model(int meta, ModelResourceLocation model); - /** - * Convenient override for {@link #variants(Collection)}. - */ - @SideOnly( Side.CLIENT ) - default IItemRendering variants( ResourceLocation... resources ) - { - return variants( Arrays.asList( resources ) ); - } + /** + * Convenient override for {@link #variants(Collection)}. + */ + @SideOnly(Side.CLIENT) + default IItemRendering variants(ResourceLocation... resources) { + return variants(Arrays.asList(resources)); + } - /** - * Registers the item variants of this item. This are all models that need to be loaded for this item. - * This has no direct effect on rendering, but is used to load models that are used for example by - * the ItemMeshDefinition. - * - * Models registered via {@link #model(int, ModelResourceLocation)} are automatically added here. - */ - @SideOnly( Side.CLIENT ) - IItemRendering variants( Collection resources ); + /** + * Registers the item variants of this item. This are all models that need to be loaded for this item. + * This has no direct effect on rendering, but is used to load models that are used for example by + * the ItemMeshDefinition. + *

+ * Models registered via {@link #model(int, ModelResourceLocation)} are automatically added here. + */ + @SideOnly(Side.CLIENT) + IItemRendering variants(Collection resources); - /** - * Registers a custom item color definition that inspects an item stack and tint and - * returns a color multiplier. - */ - @SideOnly( Side.CLIENT ) - IItemRendering color( IItemColor itemColor ); + /** + * Registers a custom item color definition that inspects an item stack and tint and + * returns a color multiplier. + */ + @SideOnly(Side.CLIENT) + IItemRendering color(IItemColor itemColor); - /** - * Registers a built-in model under the given resource path. - */ - @SideOnly( Side.CLIENT ) - IItemRendering builtInModel( String name, IModel model ); + /** + * Registers a built-in model under the given resource path. + */ + @SideOnly(Side.CLIENT) + IItemRendering builtInModel(String name, IModel model); } diff --git a/src/main/java/appeng/bootstrap/IModelRegistry.java b/src/main/java/appeng/bootstrap/IModelRegistry.java index 15f114944..1f449de56 100644 --- a/src/main/java/appeng/bootstrap/IModelRegistry.java +++ b/src/main/java/appeng/bootstrap/IModelRegistry.java @@ -27,13 +27,12 @@ import net.minecraft.item.Item; import net.minecraft.util.ResourceLocation; -public interface IModelRegistry -{ - void registerItemVariants( Item item, ResourceLocation... names ); +public interface IModelRegistry { + void registerItemVariants(Item item, ResourceLocation... names); - void setCustomModelResourceLocation( Item item, int metadata, ModelResourceLocation model ); + void setCustomModelResourceLocation(Item item, int metadata, ModelResourceLocation model); - void setCustomMeshDefinition( Item item, ItemMeshDefinition meshDefinition ); + void setCustomMeshDefinition(Item item, ItemMeshDefinition meshDefinition); - void setCustomStateMapper( Block block, IStateMapper mapper ); + void setCustomStateMapper(Block block, IStateMapper mapper); } diff --git a/src/main/java/appeng/bootstrap/ItemDefinitionBuilder.java b/src/main/java/appeng/bootstrap/ItemDefinitionBuilder.java index 39b469815..4e0c9c33a 100644 --- a/src/main/java/appeng/bootstrap/ItemDefinitionBuilder.java +++ b/src/main/java/appeng/bootstrap/ItemDefinitionBuilder.java @@ -19,20 +19,6 @@ package appeng.bootstrap; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; -import java.util.function.Function; -import java.util.function.Supplier; - -import net.minecraft.block.BlockDispenser; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.dispenser.IBehaviorDispenseItem; -import net.minecraft.item.Item; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.bootstrap.components.IItemRegistrationComponent; import appeng.bootstrap.components.IPostInitComponent; import appeng.core.AEConfig; @@ -41,129 +27,127 @@ import appeng.core.CreativeTab; import appeng.core.features.AEFeature; import appeng.core.features.ItemDefinition; import appeng.util.Platform; +import net.minecraft.block.BlockDispenser; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.dispenser.IBehaviorDispenseItem; +import net.minecraft.item.Item; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; -class ItemDefinitionBuilder implements IItemBuilder -{ +class ItemDefinitionBuilder implements IItemBuilder { - private final FeatureFactory factory; + private final FeatureFactory factory; - private final String registryName; + private final String registryName; - private final Supplier itemSupplier; + private final Supplier itemSupplier; - private final EnumSet features = EnumSet.noneOf( AEFeature.class ); + private final EnumSet features = EnumSet.noneOf(AEFeature.class); - private final List> boostrapComponents = new ArrayList<>(); + private final List> boostrapComponents = new ArrayList<>(); - private Supplier dispenserBehaviorSupplier; + private Supplier dispenserBehaviorSupplier; - @SideOnly( Side.CLIENT ) - private ItemRendering itemRendering; + @SideOnly(Side.CLIENT) + private ItemRendering itemRendering; - private CreativeTabs creativeTab = CreativeTab.instance; + private CreativeTabs creativeTab = CreativeTab.instance; - ItemDefinitionBuilder( FeatureFactory factory, String registryName, Supplier itemSupplier ) - { - this.factory = factory; - this.registryName = registryName; - this.itemSupplier = itemSupplier; - if( Platform.isClient() ) - { - this.itemRendering = new ItemRendering(); - } - } + ItemDefinitionBuilder(FeatureFactory factory, String registryName, Supplier itemSupplier) { + this.factory = factory; + this.registryName = registryName; + this.itemSupplier = itemSupplier; + if (Platform.isClient()) { + this.itemRendering = new ItemRendering(); + } + } - @Override - public IItemBuilder bootstrap( Function component ) - { - this.boostrapComponents.add( component ); - return this; - } + @Override + public IItemBuilder bootstrap(Function component) { + this.boostrapComponents.add(component); + return this; + } - @Override - public IItemBuilder features( AEFeature... features ) - { - this.features.clear(); - this.addFeatures( features ); - return this; - } + @Override + public IItemBuilder features(AEFeature... features) { + this.features.clear(); + this.addFeatures(features); + return this; + } - @Override - public IItemBuilder addFeatures( AEFeature... features ) - { - Collections.addAll( this.features, features ); - return this; - } + @Override + public IItemBuilder addFeatures(AEFeature... features) { + Collections.addAll(this.features, features); + return this; + } - @Override - public IItemBuilder creativeTab( CreativeTabs tab ) - { - this.creativeTab = tab; - return this; - } + @Override + public IItemBuilder creativeTab(CreativeTabs tab) { + this.creativeTab = tab; + return this; + } - @Override - public IItemBuilder rendering( ItemRenderingCustomizer callback ) - { - if( Platform.isClient() ) - { - this.customizeForClient( callback ); - } + @Override + public IItemBuilder rendering(ItemRenderingCustomizer callback) { + if (Platform.isClient()) { + this.customizeForClient(callback); + } - return this; - } + return this; + } - @Override - public IItemBuilder dispenserBehavior( Supplier behavior ) - { - this.dispenserBehaviorSupplier = behavior; - return this; - } + @Override + public IItemBuilder dispenserBehavior(Supplier behavior) { + this.dispenserBehaviorSupplier = behavior; + return this; + } - @SideOnly( Side.CLIENT ) - private void customizeForClient( ItemRenderingCustomizer callback ) - { - callback.customize( this.itemRendering ); - } + @SideOnly(Side.CLIENT) + private void customizeForClient(ItemRenderingCustomizer callback) { + callback.customize(this.itemRendering); + } - @Override - public ItemDefinition build() - { - if( !AEConfig.instance().areFeaturesEnabled( this.features ) ) - { - return new ItemDefinition( this.registryName, null ); - } + @Override + public ItemDefinition build() { + if (!AEConfig.instance().areFeaturesEnabled(this.features)) { + return new ItemDefinition(this.registryName, null); + } - Item item = this.itemSupplier.get(); - item.setRegistryName( AppEng.MOD_ID, this.registryName ); + Item item = this.itemSupplier.get(); + item.setRegistryName(AppEng.MOD_ID, this.registryName); - ItemDefinition definition = new ItemDefinition( this.registryName, item ); + ItemDefinition definition = new ItemDefinition(this.registryName, item); - item.setUnlocalizedName( "appliedenergistics2." + this.registryName ); - item.setCreativeTab( this.creativeTab ); + item.setUnlocalizedName("appliedenergistics2." + this.registryName); + item.setCreativeTab(this.creativeTab); - // Register all extra handlers - this.boostrapComponents.forEach( component -> this.factory.addBootstrapComponent( component.apply( item ) ) ); + // Register all extra handlers + this.boostrapComponents.forEach(component -> this.factory.addBootstrapComponent(component.apply(item))); - // Register custom dispenser behavior if requested - if( this.dispenserBehaviorSupplier != null ) - { - this.factory.addBootstrapComponent( (IPostInitComponent) side -> - { - IBehaviorDispenseItem behavior = this.dispenserBehaviorSupplier.get(); - BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject( item, behavior ); - } ); - } + // Register custom dispenser behavior if requested + if (this.dispenserBehaviorSupplier != null) { + this.factory.addBootstrapComponent((IPostInitComponent) side -> + { + IBehaviorDispenseItem behavior = this.dispenserBehaviorSupplier.get(); + BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(item, behavior); + }); + } - this.factory.addBootstrapComponent( (IItemRegistrationComponent) ( side, reg ) -> reg.register( item ) ); + this.factory.addBootstrapComponent((IItemRegistrationComponent) (side, reg) -> reg.register(item)); - if( Platform.isClient() ) - { - this.itemRendering.apply( this.factory, item ); - } + if (Platform.isClient()) { + this.itemRendering.apply(this.factory, item); + } - return definition; - } + return definition; + } } diff --git a/src/main/java/appeng/bootstrap/ItemRendering.java b/src/main/java/appeng/bootstrap/ItemRendering.java index 4f34a5cd3..740116600 100644 --- a/src/main/java/appeng/bootstrap/ItemRendering.java +++ b/src/main/java/appeng/bootstrap/ItemRendering.java @@ -19,15 +19,11 @@ package appeng.bootstrap; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - +import appeng.bootstrap.components.ItemColorComponent; +import appeng.bootstrap.components.ItemMeshDefinitionComponent; +import appeng.bootstrap.components.ItemModelComponent; +import appeng.bootstrap.components.ItemVariantsComponent; import com.google.common.collect.ImmutableMap; - import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.ItemMeshDefinition; @@ -41,137 +37,114 @@ import net.minecraftforge.client.model.IModel; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.bootstrap.components.ItemColorComponent; -import appeng.bootstrap.components.ItemMeshDefinitionComponent; -import appeng.bootstrap.components.ItemModelComponent; -import appeng.bootstrap.components.ItemVariantsComponent; +import java.util.*; -class ItemRendering implements IItemRendering -{ +class ItemRendering implements IItemRendering { - @SideOnly( Side.CLIENT ) - private IItemColor itemColor; + @SideOnly(Side.CLIENT) + private IItemColor itemColor; - @SideOnly( Side.CLIENT ) - private ItemMeshDefinition itemMeshDefinition; + @SideOnly(Side.CLIENT) + private ItemMeshDefinition itemMeshDefinition; - @SideOnly( Side.CLIENT ) - private Map itemModels = new HashMap<>(); + @SideOnly(Side.CLIENT) + private final Map itemModels = new HashMap<>(); - @SideOnly( Side.CLIENT ) - private Set variants = new HashSet<>(); + @SideOnly(Side.CLIENT) + private final Set variants = new HashSet<>(); - @SideOnly( Side.CLIENT ) - private Map builtInModels = new HashMap<>(); + @SideOnly(Side.CLIENT) + private final Map builtInModels = new HashMap<>(); - @Override - @SideOnly( Side.CLIENT ) - public IItemRendering meshDefinition( ItemMeshDefinition meshDefinition ) - { - this.itemMeshDefinition = meshDefinition; - return this; - } + @Override + @SideOnly(Side.CLIENT) + public IItemRendering meshDefinition(ItemMeshDefinition meshDefinition) { + this.itemMeshDefinition = meshDefinition; + return this; + } - @Override - @SideOnly( Side.CLIENT ) - public IItemRendering model( int meta, ModelResourceLocation model ) - { - this.itemModels.put( meta, model ); - return this; - } + @Override + @SideOnly(Side.CLIENT) + public IItemRendering model(int meta, ModelResourceLocation model) { + this.itemModels.put(meta, model); + return this; + } - @Override - public IItemRendering variants( Collection resources ) - { - this.variants.addAll( resources ); - return this; - } + @Override + public IItemRendering variants(Collection resources) { + this.variants.addAll(resources); + return this; + } - @Override - @SideOnly( Side.CLIENT ) - public IItemRendering color( IItemColor itemColor ) - { - this.itemColor = itemColor; - return this; - } + @Override + @SideOnly(Side.CLIENT) + public IItemRendering color(IItemColor itemColor) { + this.itemColor = itemColor; + return this; + } - @Override - public IItemRendering builtInModel( String name, IModel model ) - { - this.builtInModels.put( name, model ); - return this; - } + @Override + public IItemRendering builtInModel(String name, IModel model) { + this.builtInModels.put(name, model); + return this; + } - void apply( FeatureFactory factory, Item item ) - { - if( this.itemMeshDefinition != null ) - { - factory.addBootstrapComponent( new ItemMeshDefinitionComponent( item, this.itemMeshDefinition ) ); - } + void apply(FeatureFactory factory, Item item) { + if (this.itemMeshDefinition != null) { + factory.addBootstrapComponent(new ItemMeshDefinitionComponent(item, this.itemMeshDefinition)); + } - if( !this.itemModels.isEmpty() ) - { - factory.addBootstrapComponent( new ItemModelComponent( item, this.itemModels ) ); - } + if (!this.itemModels.isEmpty()) { + factory.addBootstrapComponent(new ItemModelComponent(item, this.itemModels)); + } - Set resources = new HashSet<>( this.variants ); + Set resources = new HashSet<>(this.variants); - // Register a default item model if neither items by meta nor an item mesh definition exist - if( this.itemMeshDefinition == null && this.itemModels.isEmpty() ) - { - ModelResourceLocation model; + // Register a default item model if neither items by meta nor an item mesh definition exist + if (this.itemMeshDefinition == null && this.itemModels.isEmpty()) { + ModelResourceLocation model; - // For block items, the default will try to use the default state of the associated block - if( item instanceof ItemBlock ) - { - Block block = ( (ItemBlock) item ).getBlock(); + // For block items, the default will try to use the default state of the associated block + if (item instanceof ItemBlock) { + Block block = ((ItemBlock) item).getBlock(); - // We can only do this once the blocks are actually registered... - StateMapperHelper helper = new StateMapperHelper( item.getRegistryName() ); - model = helper.getModelResourceLocation( block.getDefaultState() ); - } - else - { - model = new ModelResourceLocation( item.getRegistryName(), "inventory" ); - } - factory.addBootstrapComponent( new ItemModelComponent( item, ImmutableMap.of( 0, model ) ) ); - } + // We can only do this once the blocks are actually registered... + StateMapperHelper helper = new StateMapperHelper(item.getRegistryName()); + model = helper.getModelResourceLocation(block.getDefaultState()); + } else { + model = new ModelResourceLocation(item.getRegistryName(), "inventory"); + } + factory.addBootstrapComponent(new ItemModelComponent(item, ImmutableMap.of(0, model))); + } - // TODO : 1.12 - this.builtInModels.forEach( factory::addBuiltInModel ); + // TODO : 1.12 + this.builtInModels.forEach(factory::addBuiltInModel); - if( !resources.isEmpty() ) - { - factory.addBootstrapComponent( new ItemVariantsComponent( item, resources ) ); - } - else if( this.itemMeshDefinition != null ) - { - // Adding an empty variant list here will prevent Vanilla from trying to load the default item model in this - // case - factory.addBootstrapComponent( new ItemVariantsComponent( item, Collections.emptyList() ) ); - } + if (!resources.isEmpty()) { + factory.addBootstrapComponent(new ItemVariantsComponent(item, resources)); + } else if (this.itemMeshDefinition != null) { + // Adding an empty variant list here will prevent Vanilla from trying to load the default item model in this + // case + factory.addBootstrapComponent(new ItemVariantsComponent(item, Collections.emptyList())); + } - if( this.itemColor != null ) - { - factory.addBootstrapComponent( new ItemColorComponent( item, this.itemColor ) ); - } - } + if (this.itemColor != null) { + factory.addBootstrapComponent(new ItemColorComponent(item, this.itemColor)); + } + } - private static class StateMapperHelper extends StateMapperBase - { + private static class StateMapperHelper extends StateMapperBase { - private final ResourceLocation registryName; + private final ResourceLocation registryName; - public StateMapperHelper( ResourceLocation registryName ) - { - this.registryName = registryName; - } + public StateMapperHelper(ResourceLocation registryName) { + this.registryName = registryName; + } - @Override - protected ModelResourceLocation getModelResourceLocation( IBlockState state ) - { - return new ModelResourceLocation( this.registryName, this.getPropertyString( state.getProperties() ) ); - } - } + @Override + protected ModelResourceLocation getModelResourceLocation(IBlockState state) { + return new ModelResourceLocation(this.registryName, this.getPropertyString(state.getProperties())); + } + } } diff --git a/src/main/java/appeng/bootstrap/ItemRenderingCustomizer.java b/src/main/java/appeng/bootstrap/ItemRenderingCustomizer.java index 56335d3b5..a260ce804 100644 --- a/src/main/java/appeng/bootstrap/ItemRenderingCustomizer.java +++ b/src/main/java/appeng/bootstrap/ItemRenderingCustomizer.java @@ -28,9 +28,8 @@ import net.minecraftforge.fml.relauncher.SideOnly; * used * due to them not being able to be annotated with @SideOnly(CLIENT). */ -public abstract class ItemRenderingCustomizer -{ +public abstract class ItemRenderingCustomizer { - @SideOnly( Side.CLIENT ) - public abstract void customize( IItemRendering rendering ); + @SideOnly(Side.CLIENT) + public abstract void customize(IItemRendering rendering); } diff --git a/src/main/java/appeng/bootstrap/components/BlockColorComponent.java b/src/main/java/appeng/bootstrap/components/BlockColorComponent.java index 9a69afcb0..83220a0aa 100644 --- a/src/main/java/appeng/bootstrap/components/BlockColorComponent.java +++ b/src/main/java/appeng/bootstrap/components/BlockColorComponent.java @@ -25,23 +25,20 @@ import net.minecraft.client.renderer.color.IBlockColor; import net.minecraftforge.fml.relauncher.Side; -public class BlockColorComponent implements IInitComponent -{ +public class BlockColorComponent implements IInitComponent { - private final Block block; + private final Block block; - private final IBlockColor blockColor; + private final IBlockColor blockColor; - public BlockColorComponent( Block block, IBlockColor blockColor ) - { - this.block = block; - this.blockColor = blockColor; - } + public BlockColorComponent(Block block, IBlockColor blockColor) { + this.block = block; + this.blockColor = blockColor; + } - @Override - public void initialize( Side side ) - { - Minecraft.getMinecraft().getBlockColors().registerBlockColorHandler( this.blockColor, this.block ); - } + @Override + public void initialize(Side side) { + Minecraft.getMinecraft().getBlockColors().registerBlockColorHandler(this.blockColor, this.block); + } } diff --git a/src/main/java/appeng/bootstrap/components/BuiltInModelComponent.java b/src/main/java/appeng/bootstrap/components/BuiltInModelComponent.java index acca358a7..400823380 100644 --- a/src/main/java/appeng/bootstrap/components/BuiltInModelComponent.java +++ b/src/main/java/appeng/bootstrap/components/BuiltInModelComponent.java @@ -19,39 +19,34 @@ package appeng.bootstrap.components; -import java.util.HashMap; -import java.util.Map; - +import appeng.client.render.model.BuiltInModelLoader; import com.google.common.base.Preconditions; - import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.client.render.model.BuiltInModelLoader; +import java.util.HashMap; +import java.util.Map; -@SideOnly( Side.CLIENT ) -public class BuiltInModelComponent implements IPreInitComponent -{ +@SideOnly(Side.CLIENT) +public class BuiltInModelComponent implements IPreInitComponent { - private final Map builtInModels = new HashMap<>(); + private final Map builtInModels = new HashMap<>(); - private boolean hasInitialized = false; + private boolean hasInitialized = false; - public void addModel( String path, IModel model ) - { - Preconditions.checkState( !this.hasInitialized ); - this.builtInModels.put( path, model ); - } + public void addModel(String path, IModel model) { + Preconditions.checkState(!this.hasInitialized); + this.builtInModels.put(path, model); + } - @Override - public void preInitialize( Side side ) - { - this.hasInitialized = true; + @Override + public void preInitialize(Side side) { + this.hasInitialized = true; - BuiltInModelLoader loader = new BuiltInModelLoader( this.builtInModels ); - ModelLoaderRegistry.registerLoader( loader ); - } + BuiltInModelLoader loader = new BuiltInModelLoader(this.builtInModels); + ModelLoaderRegistry.registerLoader(loader); + } } diff --git a/src/main/java/appeng/bootstrap/components/IBlockRegistrationComponent.java b/src/main/java/appeng/bootstrap/components/IBlockRegistrationComponent.java index d53f2f1aa..c2a95c715 100644 --- a/src/main/java/appeng/bootstrap/components/IBlockRegistrationComponent.java +++ b/src/main/java/appeng/bootstrap/components/IBlockRegistrationComponent.java @@ -1,16 +1,13 @@ - package appeng.bootstrap.components; +import appeng.bootstrap.IBootstrapComponent; import net.minecraft.block.Block; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.registries.IForgeRegistry; -import appeng.bootstrap.IBootstrapComponent; - @FunctionalInterface -public interface IBlockRegistrationComponent extends IBootstrapComponent -{ - void blockRegistration( Side side, IForgeRegistry blockRegistry ); +public interface IBlockRegistrationComponent extends IBootstrapComponent { + void blockRegistration(Side side, IForgeRegistry blockRegistry); } diff --git a/src/main/java/appeng/bootstrap/components/IEntityRegistrationComponent.java b/src/main/java/appeng/bootstrap/components/IEntityRegistrationComponent.java index 9fe17b436..c1d32983c 100644 --- a/src/main/java/appeng/bootstrap/components/IEntityRegistrationComponent.java +++ b/src/main/java/appeng/bootstrap/components/IEntityRegistrationComponent.java @@ -1,15 +1,12 @@ - package appeng.bootstrap.components; +import appeng.bootstrap.IBootstrapComponent; import net.minecraftforge.fml.common.registry.EntityEntry; import net.minecraftforge.registries.IForgeRegistry; -import appeng.bootstrap.IBootstrapComponent; - @FunctionalInterface -public interface IEntityRegistrationComponent extends IBootstrapComponent -{ - void entityRegistration( IForgeRegistry entityRegistry ); +public interface IEntityRegistrationComponent extends IBootstrapComponent { + void entityRegistration(IForgeRegistry entityRegistry); } diff --git a/src/main/java/appeng/bootstrap/components/IInitComponent.java b/src/main/java/appeng/bootstrap/components/IInitComponent.java index f6f4dc233..bdb4963f8 100644 --- a/src/main/java/appeng/bootstrap/components/IInitComponent.java +++ b/src/main/java/appeng/bootstrap/components/IInitComponent.java @@ -19,13 +19,11 @@ package appeng.bootstrap.components; -import net.minecraftforge.fml.relauncher.Side; - import appeng.bootstrap.IBootstrapComponent; +import net.minecraftforge.fml.relauncher.Side; @FunctionalInterface -public interface IInitComponent extends IBootstrapComponent -{ - void initialize( Side side ); +public interface IInitComponent extends IBootstrapComponent { + void initialize(Side side); } diff --git a/src/main/java/appeng/bootstrap/components/IItemRegistrationComponent.java b/src/main/java/appeng/bootstrap/components/IItemRegistrationComponent.java index bcbd548df..5685ab37f 100644 --- a/src/main/java/appeng/bootstrap/components/IItemRegistrationComponent.java +++ b/src/main/java/appeng/bootstrap/components/IItemRegistrationComponent.java @@ -1,16 +1,13 @@ - package appeng.bootstrap.components; +import appeng.bootstrap.IBootstrapComponent; import net.minecraft.item.Item; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.registries.IForgeRegistry; -import appeng.bootstrap.IBootstrapComponent; - @FunctionalInterface -public interface IItemRegistrationComponent extends IBootstrapComponent -{ - void itemRegistration( Side side, IForgeRegistry itemRegistry ); +public interface IItemRegistrationComponent extends IBootstrapComponent { + void itemRegistration(Side side, IForgeRegistry itemRegistry); } diff --git a/src/main/java/appeng/bootstrap/components/IModelRegistrationComponent.java b/src/main/java/appeng/bootstrap/components/IModelRegistrationComponent.java index 5b1ea9cab..31ec41d5c 100644 --- a/src/main/java/appeng/bootstrap/components/IModelRegistrationComponent.java +++ b/src/main/java/appeng/bootstrap/components/IModelRegistrationComponent.java @@ -19,10 +19,9 @@ package appeng.bootstrap.components; -import net.minecraftforge.fml.relauncher.Side; - import appeng.bootstrap.IBootstrapComponent; import appeng.bootstrap.IModelRegistry; +import net.minecraftforge.fml.relauncher.Side; /** @@ -30,7 +29,6 @@ import appeng.bootstrap.IModelRegistry; */ @FunctionalInterface -public interface IModelRegistrationComponent extends IBootstrapComponent -{ - void modelRegistration( Side side, IModelRegistry registry ); +public interface IModelRegistrationComponent extends IBootstrapComponent { + void modelRegistration(Side side, IModelRegistry registry); } diff --git a/src/main/java/appeng/bootstrap/components/IOreDictComponent.java b/src/main/java/appeng/bootstrap/components/IOreDictComponent.java index cfb704e79..1e03011a3 100644 --- a/src/main/java/appeng/bootstrap/components/IOreDictComponent.java +++ b/src/main/java/appeng/bootstrap/components/IOreDictComponent.java @@ -19,13 +19,11 @@ package appeng.bootstrap.components; -import net.minecraftforge.fml.relauncher.Side; - import appeng.bootstrap.IBootstrapComponent; +import net.minecraftforge.fml.relauncher.Side; @FunctionalInterface -public interface IOreDictComponent extends IBootstrapComponent -{ - void oreRegistration( Side side ); +public interface IOreDictComponent extends IBootstrapComponent { + void oreRegistration(Side side); } diff --git a/src/main/java/appeng/bootstrap/components/IPostInitComponent.java b/src/main/java/appeng/bootstrap/components/IPostInitComponent.java index 3c779d3f8..0c54893d6 100644 --- a/src/main/java/appeng/bootstrap/components/IPostInitComponent.java +++ b/src/main/java/appeng/bootstrap/components/IPostInitComponent.java @@ -19,13 +19,11 @@ package appeng.bootstrap.components; -import net.minecraftforge.fml.relauncher.Side; - import appeng.bootstrap.IBootstrapComponent; +import net.minecraftforge.fml.relauncher.Side; @FunctionalInterface -public interface IPostInitComponent extends IBootstrapComponent -{ - void postInitialize( Side side ); +public interface IPostInitComponent extends IBootstrapComponent { + void postInitialize(Side side); } diff --git a/src/main/java/appeng/bootstrap/components/IPreInitComponent.java b/src/main/java/appeng/bootstrap/components/IPreInitComponent.java index 390756d78..ce26f5e27 100644 --- a/src/main/java/appeng/bootstrap/components/IPreInitComponent.java +++ b/src/main/java/appeng/bootstrap/components/IPreInitComponent.java @@ -19,13 +19,11 @@ package appeng.bootstrap.components; -import net.minecraftforge.fml.relauncher.Side; - import appeng.bootstrap.IBootstrapComponent; +import net.minecraftforge.fml.relauncher.Side; @FunctionalInterface -public interface IPreInitComponent extends IBootstrapComponent -{ - void preInitialize( Side side ); +public interface IPreInitComponent extends IBootstrapComponent { + void preInitialize(Side side); } diff --git a/src/main/java/appeng/bootstrap/components/IRecipeRegistrationComponent.java b/src/main/java/appeng/bootstrap/components/IRecipeRegistrationComponent.java index 5d6763d8b..638fbc977 100644 --- a/src/main/java/appeng/bootstrap/components/IRecipeRegistrationComponent.java +++ b/src/main/java/appeng/bootstrap/components/IRecipeRegistrationComponent.java @@ -1,16 +1,13 @@ - package appeng.bootstrap.components; +import appeng.bootstrap.IBootstrapComponent; import net.minecraft.item.crafting.IRecipe; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.registries.IForgeRegistry; -import appeng.bootstrap.IBootstrapComponent; - @FunctionalInterface -public interface IRecipeRegistrationComponent extends IBootstrapComponent -{ - void recipeRegistration( Side side, IForgeRegistry recipeRegistry ); +public interface IRecipeRegistrationComponent extends IBootstrapComponent { + void recipeRegistration(Side side, IForgeRegistry recipeRegistry); } diff --git a/src/main/java/appeng/bootstrap/components/ItemColorComponent.java b/src/main/java/appeng/bootstrap/components/ItemColorComponent.java index 6ec871511..3375d39a9 100644 --- a/src/main/java/appeng/bootstrap/components/ItemColorComponent.java +++ b/src/main/java/appeng/bootstrap/components/ItemColorComponent.java @@ -25,22 +25,19 @@ import net.minecraft.item.Item; import net.minecraftforge.fml.relauncher.Side; -public class ItemColorComponent implements IInitComponent -{ +public class ItemColorComponent implements IInitComponent { - private final Item item; + private final Item item; - private final IItemColor itemColor; + private final IItemColor itemColor; - public ItemColorComponent( Item item, IItemColor itemColor ) - { - this.item = item; - this.itemColor = itemColor; - } + public ItemColorComponent(Item item, IItemColor itemColor) { + this.item = item; + this.itemColor = itemColor; + } - @Override - public void initialize( Side side ) - { - Minecraft.getMinecraft().getItemColors().registerItemColorHandler( this.itemColor, this.item ); - } + @Override + public void initialize(Side side) { + Minecraft.getMinecraft().getItemColors().registerItemColorHandler(this.itemColor, this.item); + } } diff --git a/src/main/java/appeng/bootstrap/components/ItemMeshDefinitionComponent.java b/src/main/java/appeng/bootstrap/components/ItemMeshDefinitionComponent.java index 55de5887c..8d5bbd656 100644 --- a/src/main/java/appeng/bootstrap/components/ItemMeshDefinitionComponent.java +++ b/src/main/java/appeng/bootstrap/components/ItemMeshDefinitionComponent.java @@ -19,35 +19,31 @@ package appeng.bootstrap.components; -import javax.annotation.Nonnull; - +import appeng.bootstrap.IModelRegistry; import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.item.Item; import net.minecraftforge.fml.relauncher.Side; -import appeng.bootstrap.IModelRegistry; +import javax.annotation.Nonnull; /** * Registers a custom item mesh definition that can be used to dynamically determine the item model based on * item stack properties. */ -public class ItemMeshDefinitionComponent implements IModelRegistrationComponent -{ +public class ItemMeshDefinitionComponent implements IModelRegistrationComponent { - private final Item item; + private final Item item; - private final ItemMeshDefinition meshDefinition; + private final ItemMeshDefinition meshDefinition; - public ItemMeshDefinitionComponent( @Nonnull Item item, @Nonnull ItemMeshDefinition meshDefinition ) - { - this.item = item; - this.meshDefinition = meshDefinition; - } + public ItemMeshDefinitionComponent(@Nonnull Item item, @Nonnull ItemMeshDefinition meshDefinition) { + this.item = item; + this.meshDefinition = meshDefinition; + } - @Override - public void modelRegistration( Side side, IModelRegistry registry ) - { - registry.setCustomMeshDefinition( this.item, this.meshDefinition ); - } + @Override + public void modelRegistration(Side side, IModelRegistry registry) { + registry.setCustomMeshDefinition(this.item, this.meshDefinition); + } } diff --git a/src/main/java/appeng/bootstrap/components/ItemModelComponent.java b/src/main/java/appeng/bootstrap/components/ItemModelComponent.java index a7ec341da..d903fd855 100644 --- a/src/main/java/appeng/bootstrap/components/ItemModelComponent.java +++ b/src/main/java/appeng/bootstrap/components/ItemModelComponent.java @@ -19,41 +19,36 @@ package appeng.bootstrap.components; -import java.util.Map; - -import javax.annotation.Nonnull; - +import appeng.bootstrap.IModelRegistry; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.fml.relauncher.Side; -import appeng.bootstrap.IModelRegistry; +import javax.annotation.Nonnull; +import java.util.Map; /** * Registers the models that should by used for an item, including the ability to * distinguish by meta. */ -public class ItemModelComponent implements IModelRegistrationComponent -{ +public class ItemModelComponent implements IModelRegistrationComponent { - private final Item item; + private final Item item; - private final Map modelsByMeta; + private final Map modelsByMeta; - public ItemModelComponent( @Nonnull Item item, @Nonnull Map modelsByMeta ) - { - this.item = item; - this.modelsByMeta = modelsByMeta; - } + public ItemModelComponent(@Nonnull Item item, @Nonnull Map modelsByMeta) { + this.item = item; + this.modelsByMeta = modelsByMeta; + } - @Override - public void modelRegistration( Side side, IModelRegistry registry ) - { - this.modelsByMeta.forEach( ( meta, model ) -> - { - registry.setCustomModelResourceLocation( this.item, meta, model ); - } ); - } + @Override + public void modelRegistration(Side side, IModelRegistry registry) { + this.modelsByMeta.forEach((meta, model) -> + { + registry.setCustomModelResourceLocation(this.item, meta, model); + }); + } } diff --git a/src/main/java/appeng/bootstrap/components/ItemVariantsComponent.java b/src/main/java/appeng/bootstrap/components/ItemVariantsComponent.java index bf4e5c80d..39335aa2d 100644 --- a/src/main/java/appeng/bootstrap/components/ItemVariantsComponent.java +++ b/src/main/java/appeng/bootstrap/components/ItemVariantsComponent.java @@ -19,32 +19,28 @@ package appeng.bootstrap.components; -import java.util.Collection; - +import appeng.bootstrap.IModelRegistry; import net.minecraft.item.Item; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; -import appeng.bootstrap.IModelRegistry; +import java.util.Collection; -public class ItemVariantsComponent implements IModelRegistrationComponent -{ +public class ItemVariantsComponent implements IModelRegistrationComponent { - private final Item item; + private final Item item; - private final Collection resources; + private final Collection resources; - public ItemVariantsComponent( Item item, Collection resources ) - { - this.item = item; - this.resources = resources; - } + public ItemVariantsComponent(Item item, Collection resources) { + this.item = item; + this.resources = resources; + } - @Override - public void modelRegistration( Side side, IModelRegistry registry ) - { - ResourceLocation[] resourceArr = this.resources.toArray( new ResourceLocation[0] ); - registry.registerItemVariants( this.item, resourceArr ); - } + @Override + public void modelRegistration(Side side, IModelRegistry registry) { + ResourceLocation[] resourceArr = this.resources.toArray(new ResourceLocation[0]); + registry.registerItemVariants(this.item, resourceArr); + } } diff --git a/src/main/java/appeng/bootstrap/components/ModelOverrideComponent.java b/src/main/java/appeng/bootstrap/components/ModelOverrideComponent.java index 215ccc2cb..febf6dcbd 100644 --- a/src/main/java/appeng/bootstrap/components/ModelOverrideComponent.java +++ b/src/main/java/appeng/bootstrap/components/ModelOverrideComponent.java @@ -19,13 +19,8 @@ package appeng.bootstrap.components; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.function.BiFunction; - +import appeng.core.AppEng; import com.google.common.collect.Sets; - import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.util.registry.IRegistry; @@ -36,61 +31,55 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; -import appeng.core.AppEng; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.function.BiFunction; -public class ModelOverrideComponent implements IPreInitComponent -{ +public class ModelOverrideComponent implements IPreInitComponent { - private static final ModelResourceLocation MODEL_MISSING = new ModelResourceLocation( "builtin/missing", "missing" ); + private static final ModelResourceLocation MODEL_MISSING = new ModelResourceLocation("builtin/missing", "missing"); - // Maps from resource path to customizer - private final Map> customizer = new HashMap<>(); + // Maps from resource path to customizer + private final Map> customizer = new HashMap<>(); - public void addOverride( String resourcePath, BiFunction customizer ) - { - this.customizer.put( resourcePath, customizer ); - } + public void addOverride(String resourcePath, BiFunction customizer) { + this.customizer.put(resourcePath, customizer); + } - @Override - public void preInitialize( Side side ) - { - MinecraftForge.EVENT_BUS.register( this ); - } + @Override + public void preInitialize(Side side) { + MinecraftForge.EVENT_BUS.register(this); + } - @SubscribeEvent - public void onModelBakeEvent( final ModelBakeEvent event ) - { - IRegistry modelRegistry = event.getModelRegistry(); - Set keys = Sets.newHashSet( modelRegistry.getKeys() ); - // IBakedModel missingModel = modelRegistry.getObject( MODEL_MISSING ); - IModel missingModel = ModelLoaderRegistry.getMissingModel(); + @SubscribeEvent + public void onModelBakeEvent(final ModelBakeEvent event) { + IRegistry modelRegistry = event.getModelRegistry(); + Set keys = Sets.newHashSet(modelRegistry.getKeys()); + // IBakedModel missingModel = modelRegistry.getObject( MODEL_MISSING ); + IModel missingModel = ModelLoaderRegistry.getMissingModel(); - for( ModelResourceLocation location : keys ) - { - if( !location.getResourceDomain().equals( AppEng.MOD_ID ) ) - { - continue; - } + for (ModelResourceLocation location : keys) { + if (!location.getResourceDomain().equals(AppEng.MOD_ID)) { + continue; + } - IBakedModel orgModel = modelRegistry.getObject( location ); + IBakedModel orgModel = modelRegistry.getObject(location); - // Don't customize the missing model. This causes Forge to swallow exceptions - if( orgModel == missingModel ) - { - continue; - } + // Don't customize the missing model. This causes Forge to swallow exceptions + if (orgModel == missingModel) { + continue; + } - BiFunction customizer = this.customizer.get( location.getResourcePath() ); - if( customizer != null ) - { - IBakedModel newModel = customizer.apply( location, orgModel ); + BiFunction customizer = this.customizer.get(location.getResourcePath()); + if (customizer != null) { + IBakedModel newModel = customizer.apply(location, orgModel); - if( newModel != orgModel ) - { - modelRegistry.putObject( location, newModel ); - } - } - } - } + if (newModel != orgModel) { + modelRegistry.putObject(location, newModel); + } + } + } + } } diff --git a/src/main/java/appeng/bootstrap/components/StateMapperComponent.java b/src/main/java/appeng/bootstrap/components/StateMapperComponent.java index cd44242e6..2d0697123 100644 --- a/src/main/java/appeng/bootstrap/components/StateMapperComponent.java +++ b/src/main/java/appeng/bootstrap/components/StateMapperComponent.java @@ -19,6 +19,7 @@ package appeng.bootstrap.components; +import appeng.bootstrap.IModelRegistry; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.statemap.IStateMapper; @@ -26,33 +27,27 @@ import net.minecraft.client.resources.IReloadableResourceManager; import net.minecraft.client.resources.IResourceManagerReloadListener; import net.minecraftforge.fml.relauncher.Side; -import appeng.bootstrap.IModelRegistry; - /** * Registers a custom state mapper for a given block. */ -public class StateMapperComponent implements IModelRegistrationComponent -{ +public class StateMapperComponent implements IModelRegistrationComponent { - private final Block block; + private final Block block; - private final IStateMapper stateMapper; + private final IStateMapper stateMapper; - public StateMapperComponent( Block block, IStateMapper stateMapper ) - { - this.block = block; - this.stateMapper = stateMapper; - } + public StateMapperComponent(Block block, IStateMapper stateMapper) { + this.block = block; + this.stateMapper = stateMapper; + } - @Override - public void modelRegistration( Side side, IModelRegistry registry ) - { - registry.setCustomStateMapper( this.block, this.stateMapper ); - if( this.stateMapper instanceof IResourceManagerReloadListener ) - { - ( (IReloadableResourceManager) Minecraft.getMinecraft().getResourceManager() ) - .registerReloadListener( (IResourceManagerReloadListener) this.stateMapper ); - } - } + @Override + public void modelRegistration(Side side, IModelRegistry registry) { + registry.setCustomStateMapper(this.block, this.stateMapper); + if (this.stateMapper instanceof IResourceManagerReloadListener) { + ((IReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()) + .registerReloadListener((IResourceManagerReloadListener) this.stateMapper); + } + } } diff --git a/src/main/java/appeng/bootstrap/components/TesrComponent.java b/src/main/java/appeng/bootstrap/components/TesrComponent.java index 03c6b5670..7f91fe808 100644 --- a/src/main/java/appeng/bootstrap/components/TesrComponent.java +++ b/src/main/java/appeng/bootstrap/components/TesrComponent.java @@ -19,12 +19,11 @@ package appeng.bootstrap.components; +import appeng.tile.AEBaseTile; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.relauncher.Side; -import appeng.tile.AEBaseTile; - /** * Registers a TESR for a given tile entity class. @@ -32,23 +31,20 @@ import appeng.tile.AEBaseTile; * @param */ // public class TesrComponent implements ModelRegComponent -public class TesrComponent implements IPreInitComponent -{ +public class TesrComponent implements IPreInitComponent { - private final Class tileEntityClass; + private final Class tileEntityClass; - private final TileEntitySpecialRenderer tesr; + private final TileEntitySpecialRenderer tesr; - public TesrComponent( Class tileEntityClass, TileEntitySpecialRenderer tesr ) - { - this.tileEntityClass = tileEntityClass; - this.tesr = tesr; - } + public TesrComponent(Class tileEntityClass, TileEntitySpecialRenderer tesr) { + this.tileEntityClass = tileEntityClass; + this.tesr = tesr; + } - @Override - // public void modelReg( Side side ) - public void preInitialize( Side side ) - { - ClientRegistry.bindTileEntitySpecialRenderer( this.tileEntityClass, this.tesr ); - } + @Override + // public void modelReg( Side side ) + public void preInitialize(Side side) { + ClientRegistry.bindTileEntitySpecialRenderer(this.tileEntityClass, this.tesr); + } } diff --git a/src/main/java/appeng/bootstrap/components/TileEntityComponent.java b/src/main/java/appeng/bootstrap/components/TileEntityComponent.java index 0d847bf72..4479ae8e5 100644 --- a/src/main/java/appeng/bootstrap/components/TileEntityComponent.java +++ b/src/main/java/appeng/bootstrap/components/TileEntityComponent.java @@ -1,46 +1,37 @@ - package appeng.bootstrap.components; -import java.util.ArrayList; -import java.util.List; - +import appeng.bootstrap.definitions.TileEntityDefinition; +import appeng.core.AppEng; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.relauncher.Side; -import appeng.bootstrap.definitions.TileEntityDefinition; -import appeng.core.AppEng; +import java.util.ArrayList; +import java.util.List; /** * @author GuntherDW */ -public class TileEntityComponent implements IPreInitComponent -{ - private List tileEntityDefinitions = new ArrayList<>(); +public class TileEntityComponent implements IPreInitComponent { + private final List tileEntityDefinitions = new ArrayList<>(); - public TileEntityComponent() - { - } + public TileEntityComponent() { + } - public void addTileEntity( TileEntityDefinition tileEntityDefinition ) - { - if( !this.tileEntityDefinitions.contains( tileEntityDefinition ) ) - { - this.tileEntityDefinitions.add( tileEntityDefinition ); - } - } + public void addTileEntity(TileEntityDefinition tileEntityDefinition) { + if (!this.tileEntityDefinitions.contains(tileEntityDefinition)) { + this.tileEntityDefinitions.add(tileEntityDefinition); + } + } - @Override - public void preInitialize( Side side ) - { - for( TileEntityDefinition tileEntityDefinition : this.tileEntityDefinitions ) - { - if( !tileEntityDefinition.isRegistered() ) - { - GameRegistry.registerTileEntity( tileEntityDefinition.getTileEntityClass(), AppEng.MOD_ID + ":" + tileEntityDefinition.getName() ); - tileEntityDefinition.setRegistered( true ); - } - } - } + @Override + public void preInitialize(Side side) { + for (TileEntityDefinition tileEntityDefinition : this.tileEntityDefinitions) { + if (!tileEntityDefinition.isRegistered()) { + GameRegistry.registerTileEntity(tileEntityDefinition.getTileEntityClass(), AppEng.MOD_ID + ":" + tileEntityDefinition.getName()); + tileEntityDefinition.setRegistered(true); + } + } + } } diff --git a/src/main/java/appeng/bootstrap/definitions/TileEntityDefinition.java b/src/main/java/appeng/bootstrap/definitions/TileEntityDefinition.java index e10113ce9..fd1824bf8 100644 --- a/src/main/java/appeng/bootstrap/definitions/TileEntityDefinition.java +++ b/src/main/java/appeng/bootstrap/definitions/TileEntityDefinition.java @@ -25,48 +25,40 @@ import appeng.tile.AEBaseTile; /** * @author GuntherDW */ -public class TileEntityDefinition -{ +public class TileEntityDefinition { - private final Class tileEntityClass; - private String name; - private boolean isRegistered = false; + private final Class tileEntityClass; + private String name; + private boolean isRegistered = false; - // This signals the BlockDefinitionBuilder to set the name of the TE to the blockname. - public TileEntityDefinition( Class tileEntityClass ) - { - this.tileEntityClass = tileEntityClass; - this.name = null; - } + // This signals the BlockDefinitionBuilder to set the name of the TE to the blockname. + public TileEntityDefinition(Class tileEntityClass) { + this.tileEntityClass = tileEntityClass; + this.name = null; + } - public TileEntityDefinition( Class tileEntityClass, String optionalName ) - { - this.tileEntityClass = tileEntityClass; - this.name = optionalName; - } + public TileEntityDefinition(Class tileEntityClass, String optionalName) { + this.tileEntityClass = tileEntityClass; + this.name = optionalName; + } - public Class getTileEntityClass() - { - return this.tileEntityClass; - } + public Class getTileEntityClass() { + return this.tileEntityClass; + } - public void setName( String name ) - { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getName() - { - return this.name; - } + public String getName() { + return this.name; + } - public boolean isRegistered() - { - return this.isRegistered; - } + public boolean isRegistered() { + return this.isRegistered; + } - public void setRegistered( boolean registered ) - { - this.isRegistered = registered; - } + public void setRegistered(boolean registered) { + this.isRegistered = registered; + } } diff --git a/src/main/java/appeng/capabilities/Capabilities.java b/src/main/java/appeng/capabilities/Capabilities.java index 5994504aa..a561814b0 100644 --- a/src/main/java/appeng/capabilities/Capabilities.java +++ b/src/main/java/appeng/capabilities/Capabilities.java @@ -19,6 +19,10 @@ package appeng.capabilities; +import appeng.api.storage.ISpatialDimension; +import appeng.api.storage.IStorageMonitorableAccessor; +import appeng.integration.IntegrationRegistry; +import appeng.integration.IntegrationType; import com.jaquadro.minecraft.storagedrawers.api.capabilities.IItemRepository; import gregtech.api.capability.IEnergyContainer; import net.darkhax.tesla.api.ITeslaConsumer; @@ -30,112 +34,90 @@ import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.energy.IEnergyStorage; -import appeng.api.storage.ISpatialDimension; -import appeng.api.storage.IStorageMonitorableAccessor; -import appeng.integration.IntegrationRegistry; -import appeng.integration.IntegrationType; - /** * Utility class that holds various capabilities, both by AE2 and other Mods. */ -public final class Capabilities -{ +public final class Capabilities { - private Capabilities() - { - } + private Capabilities() { + } - public static Capability STORAGE_MONITORABLE_ACCESSOR; + public static Capability STORAGE_MONITORABLE_ACCESSOR; - public static Capability SPATIAL_DIMENSION; + public static Capability SPATIAL_DIMENSION; - public static Capability TESLA_CONSUMER; + public static Capability TESLA_CONSUMER; - public static Capability TESLA_HOLDER; + public static Capability TESLA_HOLDER; - public static Capability FORGE_ENERGY; + public static Capability FORGE_ENERGY; - public static Capability ITEM_REPOSITORY_CAPABILITY; + public static Capability ITEM_REPOSITORY_CAPABILITY; - public static Capability GTCE_ENERGY; + public static Capability GTCE_ENERGY; - /** - * Register AE2 provided capabilities. - */ - public static void register() - { - CapabilityManager.INSTANCE.register( IStorageMonitorableAccessor.class, createNullStorage(), NullMENetworkAccessor::new ); - CapabilityManager.INSTANCE.register( ISpatialDimension.class, createNullStorage(), NullSpatialDimension::new ); - } + /** + * Register AE2 provided capabilities. + */ + public static void register() { + CapabilityManager.INSTANCE.register(IStorageMonitorableAccessor.class, createNullStorage(), NullMENetworkAccessor::new); + CapabilityManager.INSTANCE.register(ISpatialDimension.class, createNullStorage(), NullSpatialDimension::new); + } - @CapabilityInject( IStorageMonitorableAccessor.class ) - private static void capIStorageMonitorableAccessorRegistered( Capability cap ) - { - STORAGE_MONITORABLE_ACCESSOR = cap; - } + @CapabilityInject(IStorageMonitorableAccessor.class) + private static void capIStorageMonitorableAccessorRegistered(Capability cap) { + STORAGE_MONITORABLE_ACCESSOR = cap; + } - @CapabilityInject( ISpatialDimension.class ) - private static void capISpatialDimensionRegistered( Capability cap ) - { - SPATIAL_DIMENSION = cap; - } + @CapabilityInject(ISpatialDimension.class) + private static void capISpatialDimensionRegistered(Capability cap) { + SPATIAL_DIMENSION = cap; + } - @CapabilityInject( ITeslaConsumer.class ) - private static void capITeslaConsumerRegistered( Capability cap ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.TESLA ) ) - { - TESLA_CONSUMER = cap; - } - } + @CapabilityInject(ITeslaConsumer.class) + private static void capITeslaConsumerRegistered(Capability cap) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.TESLA)) { + TESLA_CONSUMER = cap; + } + } - @CapabilityInject( ITeslaHolder.class ) - private static void capITeslaHolderRegistered( Capability cap ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.TESLA ) ) - { - TESLA_HOLDER = cap; - } - } + @CapabilityInject(ITeslaHolder.class) + private static void capITeslaHolderRegistered(Capability cap) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.TESLA)) { + TESLA_HOLDER = cap; + } + } - @CapabilityInject( IEnergyStorage.class ) - private static void capIEnergyStorageRegistered( Capability cap ) - { - FORGE_ENERGY = cap; - } + @CapabilityInject(IEnergyStorage.class) + private static void capIEnergyStorageRegistered(Capability cap) { + FORGE_ENERGY = cap; + } - @CapabilityInject( IItemRepository.class ) - private static void capIItemRepositoryRegistered( Capability cap ) - { - ITEM_REPOSITORY_CAPABILITY = cap; - } + @CapabilityInject(IItemRepository.class) + private static void capIItemRepositoryRegistered(Capability cap) { + ITEM_REPOSITORY_CAPABILITY = cap; + } - @CapabilityInject( IEnergyContainer.class ) - private static void capIEnergyContainerRegistered( Capability cap ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.GTCE ) ) - { - GTCE_ENERGY = cap; - } - } + @CapabilityInject(IEnergyContainer.class) + private static void capIEnergyContainerRegistered(Capability cap) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.GTCE)) { + GTCE_ENERGY = cap; + } + } - // Create a storage implementation that does not do anything - private static Capability.IStorage createNullStorage() - { - return new Capability.IStorage() - { - @Override - public NBTBase writeNBT( Capability capability, T instance, EnumFacing side ) - { - return null; - } + // Create a storage implementation that does not do anything + private static Capability.IStorage createNullStorage() { + return new Capability.IStorage() { + @Override + public NBTBase writeNBT(Capability capability, T instance, EnumFacing side) { + return null; + } - @Override - public void readNBT( Capability capability, T instance, EnumFacing side, NBTBase nbt ) - { + @Override + public void readNBT(Capability capability, T instance, EnumFacing side, NBTBase nbt) { - } - }; - } + } + }; + } } diff --git a/src/main/java/appeng/capabilities/NullMENetworkAccessor.java b/src/main/java/appeng/capabilities/NullMENetworkAccessor.java index c4b67f000..467dc0a86 100644 --- a/src/main/java/appeng/capabilities/NullMENetworkAccessor.java +++ b/src/main/java/appeng/capabilities/NullMENetworkAccessor.java @@ -24,13 +24,11 @@ import appeng.api.storage.IStorageMonitorable; import appeng.api.storage.IStorageMonitorableAccessor; -class NullMENetworkAccessor implements IStorageMonitorableAccessor -{ +class NullMENetworkAccessor implements IStorageMonitorableAccessor { - @Override - public IStorageMonitorable getInventory( IActionSource src ) - { - return null; - } + @Override + public IStorageMonitorable getInventory(IActionSource src) { + return null; + } } diff --git a/src/main/java/appeng/capabilities/NullSpatialDimension.java b/src/main/java/appeng/capabilities/NullSpatialDimension.java index eaffd7f23..055155ed2 100644 --- a/src/main/java/appeng/capabilities/NullSpatialDimension.java +++ b/src/main/java/appeng/capabilities/NullSpatialDimension.java @@ -19,52 +19,43 @@ package appeng.capabilities; +import appeng.api.storage.ISpatialDimension; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.api.storage.ISpatialDimension; +class NullSpatialDimension implements ISpatialDimension { + @Override + public int createNewCellDimension(BlockPos size, int owner) { + return -1; + } -class NullSpatialDimension implements ISpatialDimension -{ - @Override - public int createNewCellDimension( BlockPos size, int owner ) - { - return -1; - } + @Override + public void deleteCellDimension(int cellStorageId) { + } - @Override - public void deleteCellDimension( int cellStorageId ) - { - } + @Override + public int getCellDimensionOwner(int cellStorageId) { + return -1; + } - @Override - public int getCellDimensionOwner( int cellStorageId ) - { - return -1; - } + @Override + public BlockPos getCellDimensionOrigin(int cellStorageId) { + return null; + } - @Override - public BlockPos getCellDimensionOrigin( int cellStorageId ) - { - return null; - } + @Override + public World getWorld() { + return null; + } - @Override - public World getWorld() - { - return null; - } + @Override + public boolean isCellDimension(int cellDimID) { + return false; + } - @Override - public boolean isCellDimension( int cellDimID ) - { - return false; - } - - @Override - public BlockPos getCellContentSize( int cellDimId ) - { - return null; - } + @Override + public BlockPos getCellContentSize(int cellDimId) { + return null; + } } diff --git a/src/main/java/appeng/client/ActionKey.java b/src/main/java/appeng/client/ActionKey.java index 1ef32dc48..626a55566 100644 --- a/src/main/java/appeng/client/ActionKey.java +++ b/src/main/java/appeng/client/ActionKey.java @@ -1,28 +1,23 @@ - package appeng.client; import org.lwjgl.input.Keyboard; -public enum ActionKey -{ - TOGGLE_FOCUS( Keyboard.KEY_TAB ); +public enum ActionKey { + TOGGLE_FOCUS(Keyboard.KEY_TAB); - private final int defaultKey; + private final int defaultKey; - private ActionKey( int defaultKey ) - { - this.defaultKey = defaultKey; - } + ActionKey(int defaultKey) { + this.defaultKey = defaultKey; + } - public String getTranslationKey() - { - return "key." + this.name().toLowerCase() + ".desc"; - } + public String getTranslationKey() { + return "key." + this.name().toLowerCase() + ".desc"; + } - public int getDefaultKey() - { - return this.defaultKey; - } + public int getDefaultKey() { + return this.defaultKey; + } } diff --git a/src/main/java/appeng/client/ClientHelper.java b/src/main/java/appeng/client/ClientHelper.java index f4258ee3d..912425100 100644 --- a/src/main/java/appeng/client/ClientHelper.java +++ b/src/main/java/appeng/client/ClientHelper.java @@ -19,15 +19,31 @@ package appeng.client; -import java.io.IOException; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.Random; - +import appeng.api.parts.CableRenderMode; +import appeng.api.util.AEColor; +import appeng.block.AEBaseBlock; import appeng.client.gui.AEBaseGui; +import appeng.client.render.effects.*; +import appeng.client.render.model.UVLModelLoader; +import appeng.client.render.tesr.InscriberTESR; +import appeng.client.render.textures.ParticleTextures; import appeng.container.interfaces.IJEIGhostIngredients; +import appeng.core.AEConfig; +import appeng.core.AELog; +import appeng.core.AppEng; +import appeng.core.sync.network.NetworkHandler; +import appeng.core.sync.packets.PacketAssemblerAnimation; +import appeng.core.sync.packets.PacketValueConfig; +import appeng.entity.EntityFloatingItem; +import appeng.entity.EntityTinyTNTPrimed; +import appeng.entity.RenderFloatingItem; +import appeng.entity.RenderTinyTNTPrimed; import appeng.helpers.HighlighterHandler; +import appeng.helpers.IMouseWheelItem; +import appeng.hooks.TickHandler; +import appeng.hooks.TickHandler.PlayerColor; +import appeng.server.ServerHelper; +import appeng.util.Platform; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; @@ -47,343 +63,270 @@ import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; - -import appeng.api.parts.CableRenderMode; -import appeng.api.util.AEColor; -import appeng.block.AEBaseBlock; -import appeng.client.render.effects.AssemblerFX; -import appeng.client.render.effects.CraftingFx; -import appeng.client.render.effects.EnergyFx; -import appeng.client.render.effects.LightningArcFX; -import appeng.client.render.effects.LightningFX; -import appeng.client.render.effects.VibrantFX; -import appeng.client.render.model.UVLModelLoader; -import appeng.client.render.tesr.InscriberTESR; -import appeng.client.render.textures.ParticleTextures; -import appeng.core.AEConfig; -import appeng.core.AELog; -import appeng.core.AppEng; -import appeng.core.sync.network.NetworkHandler; -import appeng.core.sync.packets.PacketAssemblerAnimation; -import appeng.core.sync.packets.PacketValueConfig; -import appeng.entity.EntityFloatingItem; -import appeng.entity.EntityTinyTNTPrimed; -import appeng.entity.RenderFloatingItem; -import appeng.entity.RenderTinyTNTPrimed; -import appeng.helpers.IMouseWheelItem; -import appeng.hooks.TickHandler; -import appeng.hooks.TickHandler.PlayerColor; -import appeng.server.ServerHelper; -import appeng.util.Platform; import org.lwjgl.input.Mouse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Random; -public class ClientHelper extends ServerHelper -{ - private final static String KEY_CATEGORY = "key.appliedenergistics2.category"; - private final EnumMap bindings = new EnumMap<>( ActionKey.class ); +public class ClientHelper extends ServerHelper { + private final static String KEY_CATEGORY = "key.appliedenergistics2.category"; - @Override - public void preinit() - { - MinecraftForge.EVENT_BUS.register( this ); - // Do not register the Fullbright hacks if Optifine is present or if the Forge lighting is disabled - if( !FMLClientHandler.instance().hasOptifine() && ForgeModContainer.forgeLightPipelineEnabled ) - { - ModelLoaderRegistry.registerLoader( UVLModelLoader.INSTANCE ); - } + private final EnumMap bindings = new EnumMap<>(ActionKey.class); - RenderingRegistry.registerEntityRenderingHandler( EntityTinyTNTPrimed.class, manager -> new RenderTinyTNTPrimed( manager ) ); - RenderingRegistry.registerEntityRenderingHandler( EntityFloatingItem.class, manager -> new RenderFloatingItem( manager ) ); - } + @Override + public void preinit() { + MinecraftForge.EVENT_BUS.register(this); + // Do not register the Fullbright hacks if Optifine is present or if the Forge lighting is disabled + if (!FMLClientHandler.instance().hasOptifine() && ForgeModContainer.forgeLightPipelineEnabled) { + ModelLoaderRegistry.registerLoader(UVLModelLoader.INSTANCE); + } - @Override - public void init() - { - for( ActionKey key : ActionKey.values() ) - { - final KeyBinding binding = new KeyBinding( key.getTranslationKey(), key.getDefaultKey(), KEY_CATEGORY ); - ClientRegistry.registerKeyBinding( binding ); - this.bindings.put( key, binding ); - } - } + RenderingRegistry.registerEntityRenderingHandler(EntityTinyTNTPrimed.class, manager -> new RenderTinyTNTPrimed(manager)); + RenderingRegistry.registerEntityRenderingHandler(EntityFloatingItem.class, manager -> new RenderFloatingItem(manager)); + } - @SubscribeEvent - public void renderWorldLastEvent( RenderWorldLastEvent event) { - HighlighterHandler.tick(event); - } + @Override + public void init() { + for (ActionKey key : ActionKey.values()) { + final KeyBinding binding = new KeyBinding(key.getTranslationKey(), key.getDefaultKey(), KEY_CATEGORY); + ClientRegistry.registerKeyBinding(binding); + this.bindings.put(key, binding); + } + } - @Override - public World getWorld() - { - if( Platform.isClient() ) - { - return Minecraft.getMinecraft().world; - } - else - { - return super.getWorld(); - } - } + @SubscribeEvent + public void renderWorldLastEvent(RenderWorldLastEvent event) { + HighlighterHandler.tick(event); + } - @Override - public void bindTileEntitySpecialRenderer( final Class tile, final AEBaseBlock blk ) - { + @Override + public World getWorld() { + if (Platform.isClient()) { + return Minecraft.getMinecraft().world; + } else { + return super.getWorld(); + } + } - } + @Override + public void bindTileEntitySpecialRenderer(final Class tile, final AEBaseBlock blk) { - @Override - public List getPlayers() - { - if( Platform.isClient() ) - { - final List o = new ArrayList<>(); - o.add( Minecraft.getMinecraft().player ); - return o; - } - else - { - return super.getPlayers(); - } - } + } - @Override - public void spawnEffect( final EffectType effect, final World world, final double posX, final double posY, final double posZ, final Object o ) - { - if( AEConfig.instance().isEnableEffects() ) - { - switch( effect ) - { - case Assembler: - this.spawnAssembler( world, posX, posY, posZ, o ); - return; - case Vibrant: - this.spawnVibrant( world, posX, posY, posZ ); - return; - case Crafting: - this.spawnCrafting( world, posX, posY, posZ ); - return; - case Energy: - this.spawnEnergy( world, posX, posY, posZ ); - return; - case Lightning: - this.spawnLightning( world, posX, posY, posZ ); - return; - case LightningArc: - this.spawnLightningArc( world, posX, posY, posZ, (Vec3d) o ); - return; - default: - } - } - } + @Override + public List getPlayers() { + if (Platform.isClient()) { + final List o = new ArrayList<>(); + o.add(Minecraft.getMinecraft().player); + return o; + } else { + return super.getPlayers(); + } + } - @Override - public boolean shouldAddParticles( final Random r ) - { - final int setting = Minecraft.getMinecraft().gameSettings.particleSetting; - if( setting == 2 ) - { - return false; - } - if( setting == 0 ) - { - return true; - } - return r.nextInt( 2 * ( setting + 1 ) ) == 0; - } + @Override + public void spawnEffect(final EffectType effect, final World world, final double posX, final double posY, final double posZ, final Object o) { + if (AEConfig.instance().isEnableEffects()) { + switch (effect) { + case Assembler: + this.spawnAssembler(world, posX, posY, posZ, o); + return; + case Vibrant: + this.spawnVibrant(world, posX, posY, posZ); + return; + case Crafting: + this.spawnCrafting(world, posX, posY, posZ); + return; + case Energy: + this.spawnEnergy(world, posX, posY, posZ); + return; + case Lightning: + this.spawnLightning(world, posX, posY, posZ); + return; + case LightningArc: + this.spawnLightningArc(world, posX, posY, posZ, (Vec3d) o); + return; + default: + } + } + } - @Override - public RayTraceResult getRTR() - { - return Minecraft.getMinecraft().objectMouseOver; - } + @Override + public boolean shouldAddParticles(final Random r) { + final int setting = Minecraft.getMinecraft().gameSettings.particleSetting; + if (setting == 2) { + return false; + } + if (setting == 0) { + return true; + } + return r.nextInt(2 * (setting + 1)) == 0; + } - @Override - public void postInit() - { - } + @Override + public RayTraceResult getRTR() { + return Minecraft.getMinecraft().objectMouseOver; + } - @Override - public CableRenderMode getRenderMode() - { - if( Platform.isServer() ) - { - return super.getRenderMode(); - } + @Override + public void postInit() { + } - final Minecraft mc = Minecraft.getMinecraft(); - final EntityPlayer player = mc.player; + @Override + public CableRenderMode getRenderMode() { + if (Platform.isServer()) { + return super.getRenderMode(); + } - return this.renderModeForPlayer( player ); - } + final Minecraft mc = Minecraft.getMinecraft(); + final EntityPlayer player = mc.player; - @Override - public void triggerUpdates() - { - final Minecraft mc = Minecraft.getMinecraft(); - if( mc == null || mc.player == null || mc.world == null ) - { - return; - } + return this.renderModeForPlayer(player); + } - final EntityPlayer player = mc.player; + @Override + public void triggerUpdates() { + final Minecraft mc = Minecraft.getMinecraft(); + if (mc == null || mc.player == null || mc.world == null) { + return; + } - final int x = (int) player.posX; - final int y = (int) player.posY; - final int z = (int) player.posZ; + final EntityPlayer player = mc.player; - final int range = 16 * 16; + final int x = (int) player.posX; + final int y = (int) player.posY; + final int z = (int) player.posZ; - mc.world.markBlockRangeForRenderUpdate( x - range, y - range, z - range, x + range, y + range, z + range ); - } + final int range = 16 * 16; - @SubscribeEvent - public void postPlayerRender( final RenderLivingEvent.Pre p ) - { - final PlayerColor player = TickHandler.INSTANCE.getPlayerColors().get( p.getEntity().getEntityId() ); - if( player != null ) - { - final AEColor col = player.myColor; + mc.world.markBlockRangeForRenderUpdate(x - range, y - range, z - range, x + range, y + range, z + range); + } - final float r = 0xff & ( col.mediumVariant >> 16 ); - final float g = 0xff & ( col.mediumVariant >> 8 ); - final float b = 0xff & ( col.mediumVariant ); - GlStateManager.color( r / 255.0f, g / 255.0f, b / 255.0f ); - } - } + @SubscribeEvent + public void postPlayerRender(final RenderLivingEvent.Pre p) { + final PlayerColor player = TickHandler.INSTANCE.getPlayerColors().get(p.getEntity().getEntityId()); + if (player != null) { + final AEColor col = player.myColor; - private void spawnAssembler( final World world, final double posX, final double posY, final double posZ, final Object o ) - { - final PacketAssemblerAnimation paa = (PacketAssemblerAnimation) o; + final float r = 0xff & (col.mediumVariant >> 16); + final float g = 0xff & (col.mediumVariant >> 8); + final float b = 0xff & (col.mediumVariant); + GlStateManager.color(r / 255.0f, g / 255.0f, b / 255.0f); + } + } - final AssemblerFX fx = new AssemblerFX( world, posX, posY, posZ, 0.0D, 0.0D, 0.0D, paa.rate, paa.is ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } + private void spawnAssembler(final World world, final double posX, final double posY, final double posZ, final Object o) { + final PacketAssemblerAnimation paa = (PacketAssemblerAnimation) o; - private void spawnVibrant( final World w, final double x, final double y, final double z ) - { - if( AppEng.proxy.shouldAddParticles( Platform.getRandom() ) ) - { - final double d0 = ( Platform.getRandomFloat() - 0.5F ) * 0.26D; - final double d1 = ( Platform.getRandomFloat() - 0.5F ) * 0.26D; - final double d2 = ( Platform.getRandomFloat() - 0.5F ) * 0.26D; + final AssemblerFX fx = new AssemblerFX(world, posX, posY, posZ, 0.0D, 0.0D, 0.0D, paa.rate, paa.is); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } - final VibrantFX fx = new VibrantFX( w, x + d0, y + d1, z + d2, 0.0D, 0.0D, 0.0D ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } + private void spawnVibrant(final World w, final double x, final double y, final double z) { + if (AppEng.proxy.shouldAddParticles(Platform.getRandom())) { + final double d0 = (Platform.getRandomFloat() - 0.5F) * 0.26D; + final double d1 = (Platform.getRandomFloat() - 0.5F) * 0.26D; + final double d2 = (Platform.getRandomFloat() - 0.5F) * 0.26D; - private void spawnCrafting( final World w, final double posX, final double posY, final double posZ ) - { - final float x = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - final float y = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - final float z = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; + final VibrantFX fx = new VibrantFX(w, x + d0, y + d1, z + d2, 0.0D, 0.0D, 0.0D); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } - final CraftingFx fx = new CraftingFx( w, posX + x, posY + y, posZ + z, Items.DIAMOND ); + private void spawnCrafting(final World w, final double posX, final double posY, final double posZ) { + final float x = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + final float y = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + final float z = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; - fx.setMotionX( -x * 0.2f ); - fx.setMotionY( -y * 0.2f ); - fx.setMotionZ( -z * 0.2f ); + final CraftingFx fx = new CraftingFx(w, posX + x, posY + y, posZ + z, Items.DIAMOND); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } + fx.setMotionX(-x * 0.2f); + fx.setMotionY(-y * 0.2f); + fx.setMotionZ(-z * 0.2f); - private void spawnEnergy( final World w, final double posX, final double posY, final double posZ ) - { - final float x = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - final float y = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - final float z = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } - final EnergyFx fx = new EnergyFx( w, posX + x, posY + y, posZ + z, Items.DIAMOND ); + private void spawnEnergy(final World w, final double posX, final double posY, final double posZ) { + final float x = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + final float y = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + final float z = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; - fx.setMotionX( -x * 0.1f ); - fx.setMotionY( -y * 0.1f ); - fx.setMotionZ( -z * 0.1f ); + final EnergyFx fx = new EnergyFx(w, posX + x, posY + y, posZ + z, Items.DIAMOND); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } + fx.setMotionX(-x * 0.1f); + fx.setMotionY(-y * 0.1f); + fx.setMotionZ(-z * 0.1f); - private void spawnLightning( final World world, final double posX, final double posY, final double posZ ) - { - final LightningFX fx = new LightningFX( world, posX, posY + 0.3f, posZ, 0.0f, 0.0f, 0.0f ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } - private void spawnLightningArc( final World world, final double posX, final double posY, final double posZ, final Vec3d second ) - { - final LightningFX fx = new LightningArcFX( world, posX, posY, posZ, second.x, second.y, second.z, 0.0f, 0.0f, 0.0f ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } + private void spawnLightning(final World world, final double posX, final double posY, final double posZ) { + final LightningFX fx = new LightningFX(world, posX, posY + 0.3f, posZ, 0.0f, 0.0f, 0.0f); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } - @SubscribeEvent - public void MouseClickEvent( final GuiScreenEvent.MouseInputEvent.Pre me ) - { - final Minecraft mc = Minecraft.getMinecraft(); - if( mc.currentScreen instanceof IJEIGhostIngredients ) - { - AEBaseGui gui = ( (AEBaseGui) mc.currentScreen ); - Object ingredient = gui.getBookmarkedIngredient(); - if( ingredient != null ) - { - if( GuiScreen.isShiftKeyDown() ) - { - me.setCanceled( true ); - } - else if( Mouse.isButtonDown( 0 ) ) - { - me.setCanceled( true ); - } - } - } - } + private void spawnLightningArc(final World world, final double posX, final double posY, final double posZ, final Vec3d second) { + final LightningFX fx = new LightningArcFX(world, posX, posY, posZ, second.x, second.y, second.z, 0.0f, 0.0f, 0.0f); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } - @SubscribeEvent - public void wheelEvent( final MouseEvent me ) - { - if( me.getDwheel() == 0 ) - { - return; - } + @SubscribeEvent + public void MouseClickEvent(final GuiScreenEvent.MouseInputEvent.Pre me) { + final Minecraft mc = Minecraft.getMinecraft(); + if (mc.currentScreen instanceof IJEIGhostIngredients) { + AEBaseGui gui = ((AEBaseGui) mc.currentScreen); + Object ingredient = gui.getBookmarkedIngredient(); + if (ingredient != null) { + if (GuiScreen.isShiftKeyDown()) { + me.setCanceled(true); + } else if (Mouse.isButtonDown(0)) { + me.setCanceled(true); + } + } + } + } - final Minecraft mc = Minecraft.getMinecraft(); - final EntityPlayer player = mc.player; - if( player.isSneaking() ) - { - final boolean mainHand = player.getHeldItem( EnumHand.MAIN_HAND ).getItem() instanceof IMouseWheelItem; - final boolean offHand = player.getHeldItem( EnumHand.OFF_HAND ).getItem() instanceof IMouseWheelItem; + @SubscribeEvent + public void wheelEvent(final MouseEvent me) { + if (me.getDwheel() == 0) { + return; + } - if( mainHand || offHand ) - { - try - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "Item", me.getDwheel() > 0 ? "WheelUp" : "WheelDown" ) ); - me.setCanceled( true ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } + final Minecraft mc = Minecraft.getMinecraft(); + final EntityPlayer player = mc.player; + if (player.isSneaking()) { + final boolean mainHand = player.getHeldItem(EnumHand.MAIN_HAND).getItem() instanceof IMouseWheelItem; + final boolean offHand = player.getHeldItem(EnumHand.OFF_HAND).getItem() instanceof IMouseWheelItem; - @SubscribeEvent - public void onTextureStitch( final TextureStitchEvent.Pre event ) - { - ParticleTextures.registerSprite( event ); - InscriberTESR.registerTexture( event ); - } + if (mainHand || offHand) { + try { + NetworkHandler.instance().sendToServer(new PacketValueConfig("Item", me.getDwheel() > 0 ? "WheelUp" : "WheelDown")); + me.setCanceled(true); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } - @Override - public boolean isKeyPressed( ActionKey key ) - { - return this.bindings.get( key ).isPressed(); - } + @SubscribeEvent + public void onTextureStitch(final TextureStitchEvent.Pre event) { + ParticleTextures.registerSprite(event); + InscriberTESR.registerTexture(event); + } - @Override - public boolean isActionKey( ActionKey key, int pressedKeyCode ) - { - return this.bindings.get( key ).isActiveAndMatches( pressedKeyCode ); - } + @Override + public boolean isKeyPressed(ActionKey key) { + return this.bindings.get(key).isPressed(); + } + + @Override + public boolean isActionKey(ActionKey key, int pressedKeyCode) { + return this.bindings.get(key).isActiveAndMatches(pressedKeyCode); + } } \ No newline at end of file diff --git a/src/main/java/appeng/client/EffectType.java b/src/main/java/appeng/client/EffectType.java index 8929909e5..cdd2fafb1 100644 --- a/src/main/java/appeng/client/EffectType.java +++ b/src/main/java/appeng/client/EffectType.java @@ -19,7 +19,6 @@ package appeng.client; -public enum EffectType -{ - Energy, Lightning, Vibrant, Crafting, Assembler, LightningArc +public enum EffectType { + Energy, Lightning, Vibrant, Crafting, Assembler, LightningArc } diff --git a/src/main/java/appeng/client/UnlistedProperty.java b/src/main/java/appeng/client/UnlistedProperty.java index 7c45fcca8..26c380ccd 100644 --- a/src/main/java/appeng/client/UnlistedProperty.java +++ b/src/main/java/appeng/client/UnlistedProperty.java @@ -27,41 +27,35 @@ import net.minecraftforge.common.property.IUnlistedProperty; * * @param */ -public class UnlistedProperty implements IUnlistedProperty -{ +public class UnlistedProperty implements IUnlistedProperty { - private final String name; + private final String name; - private final Class clazz; + private final Class clazz; - public UnlistedProperty( String name, Class clazz ) - { - this.name = name; - this.clazz = clazz; - } + public UnlistedProperty(String name, Class clazz) { + this.name = name; + this.clazz = clazz; + } - @Override - public String getName() - { - return this.name; - } + @Override + public String getName() { + return this.name; + } - @Override - public boolean isValid( T value ) - { - return value != null; - } + @Override + public boolean isValid(T value) { + return value != null; + } - @Override - public Class getType() - { - return this.clazz; - } + @Override + public Class getType() { + return this.clazz; + } - @Override - public String valueToString( T value ) - { - return value.toString(); - } + @Override + public String valueToString(T value) { + return value.toString(); + } } diff --git a/src/main/java/appeng/client/gui/AEBaseGui.java b/src/main/java/appeng/client/gui/AEBaseGui.java index 7ae8df1bf..2ec5b3d3c 100644 --- a/src/main/java/appeng/client/gui/AEBaseGui.java +++ b/src/main/java/appeng/client/gui/AEBaseGui.java @@ -19,30 +19,33 @@ package appeng.client.gui; -import java.awt.*; -import java.io.IOException; -import java.text.DecimalFormat; -import java.text.ParseException; -import java.util.*; -import java.util.List; -import java.util.concurrent.TimeUnit; - +import appeng.api.storage.data.IAEFluidStack; +import appeng.api.storage.data.IAEItemStack; +import appeng.client.gui.widgets.GuiCustomSlot; +import appeng.client.gui.widgets.GuiScrollbar; +import appeng.client.gui.widgets.ITooltip; +import appeng.client.me.InternalSlotME; +import appeng.client.me.SlotDisconnected; +import appeng.client.me.SlotME; +import appeng.client.render.StackSizeRenderer; +import appeng.container.AEBaseContainer; import appeng.container.slot.*; +import appeng.container.slot.AppEngSlot.hasCalculatedValidness; +import appeng.core.AELog; +import appeng.core.AppEng; +import appeng.core.sync.network.NetworkHandler; +import appeng.core.sync.packets.PacketInventoryAction; +import appeng.core.sync.packets.PacketSwapSlots; +import appeng.fluids.client.render.FluidStackSizeRenderer; +import appeng.fluids.container.slots.IMEFluidSlot; +import appeng.helpers.InventoryAction; import appeng.util.Platform; import com.google.common.base.Joiner; import com.google.common.base.Stopwatch; import com.google.common.collect.Lists; - import mezz.jei.api.gui.IGhostIngredientHandler; -import net.minecraft.client.gui.Gui; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fml.common.Optional; -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.GL11; - import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.BufferBuilder; @@ -60,1132 +63,908 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.fluids.Fluid; - -import appeng.api.storage.data.IAEFluidStack; -import appeng.api.storage.data.IAEItemStack; -import appeng.client.gui.widgets.GuiCustomSlot; -import appeng.client.gui.widgets.GuiScrollbar; -import appeng.client.gui.widgets.ITooltip; -import appeng.client.me.InternalSlotME; -import appeng.client.me.SlotDisconnected; -import appeng.client.me.SlotME; -import appeng.client.render.StackSizeRenderer; -import appeng.container.AEBaseContainer; -import appeng.container.slot.AppEngSlot.hasCalculatedValidness; -import appeng.core.AELog; -import appeng.core.AppEng; -import appeng.core.sync.network.NetworkHandler; -import appeng.core.sync.packets.PacketInventoryAction; -import appeng.core.sync.packets.PacketSwapSlots; -import appeng.fluids.client.render.FluidStackSizeRenderer; -import appeng.fluids.container.slots.IMEFluidSlot; -import appeng.helpers.InventoryAction; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; +import net.minecraftforge.fml.common.Optional; +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; import yalter.mousetweaks.api.IMTModGuiContainer2; +import java.awt.*; +import java.io.IOException; +import java.text.DecimalFormat; +import java.text.ParseException; +import java.util.List; +import java.util.*; +import java.util.concurrent.TimeUnit; + import static appeng.integration.modules.jei.JEIPlugin.aeGuiHandler; import static appeng.integration.modules.jei.JEIPlugin.runtime; -@Optional.Interface( iface = "yalter.mousetweaks.api.IMTModGuiContainer2", modid = "mousetweaks" ) -public abstract class AEBaseGui extends GuiContainer implements IMTModGuiContainer2 -{ - private final List meSlots = new ArrayList<>(); - // drag y - private final Set drag_click = new HashSet<>(); - private final StackSizeRenderer stackSizeRenderer = new StackSizeRenderer(); - private final FluidStackSizeRenderer fluidStackSizeRenderer = new FluidStackSizeRenderer(); - private GuiScrollbar myScrollBar = null; - private boolean disableShiftClick = false; - private Stopwatch dbl_clickTimer = Stopwatch.createStarted(); - private ItemStack dbl_whichItem = ItemStack.EMPTY; - private Slot bl_clicked; - private Stopwatch lastClicked = Stopwatch.createStarted(); - private List> hoveredIngredientTargets = new ArrayList<>(); - private Object bookmarkedIngredient; - private boolean isDraggingJeiGhostItem; - private boolean haltDragging = false; - - public void setJeiGhostItem( boolean jeiGhostItem ) - { - isJeiGhostItem = jeiGhostItem; - } - - private boolean isJeiGhostItem; - - public Object getBookmarkedIngredient() - { - return bookmarkedIngredient; - } - - public List getGuiSlots() - { - return guiSlots; - } - - protected final List guiSlots = new ArrayList<>(); - - public AEBaseGui( final Container container ) - { - super( container ); - } - - protected static String join( final Collection toolTip, final String delimiter ) - { - final Joiner joiner = Joiner.on( delimiter ); - - return joiner.join( toolTip ); - } - - protected int getQty( final GuiButton btn ) - { - try - { - final DecimalFormat df = new DecimalFormat( "+#;-#" ); - return df.parse( btn.displayString ).intValue(); - } - catch( final ParseException e ) - { - return 0; - } - } - - @Override - public void initGui() - { - super.initGui(); - - final List slots = this.getInventorySlots(); - final Iterator i = slots.iterator(); - while ( i.hasNext() ) - { - if( i.next() instanceof SlotME ) - { - i.remove(); - } - } - - for( final InternalSlotME me : this.meSlots ) - { - slots.add( new SlotME( me ) ); - } - } - - private List getInventorySlots() - { - return this.inventorySlots.inventorySlots; - } - - @Override - public void drawScreen( final int mouseX, final int mouseY, final float partialTicks ) - { - super.drawDefaultBackground(); - super.drawScreen( mouseX, mouseY, partialTicks ); - - GlStateManager.pushMatrix(); - GlStateManager.translate( this.guiLeft, this.guiTop, 0.0F ); - GlStateManager.enableDepth(); - for( final GuiCustomSlot c : this.guiSlots ) - { - this.drawGuiSlot( c, mouseX, mouseY, partialTicks ); - } - GlStateManager.disableDepth(); - for( final GuiCustomSlot c : this.guiSlots ) - { - this.drawTooltip( c, mouseX - this.guiLeft, mouseY - this.guiTop ); - } - GlStateManager.popMatrix(); - - this.renderHoveredToolTip( mouseX, mouseY ); - - for( final Object c : this.buttonList ) - { - if( c instanceof ITooltip ) - { - this.drawTooltip( (ITooltip) c, mouseX, mouseY ); - } - } - GlStateManager.enableDepth(); - if( Platform.isModLoaded( "jei" ) ) - { - bookmarkedJEIghostItem( mouseX, mouseY ); - } - GlStateManager.disableDepth(); - } - - public List getJEIExclusionArea() { - return Collections.emptyList(); - } - - @Optional.Method( modid = "jei" ) - void bookmarkedJEIghostItem( final int mouseX, final int mouseY ) - { - if( !isJeiGhostItem ) - { - bookmarkedIngredient = runtime.getBookmarkOverlay().getIngredientUnderMouse(); - } - - if( bookmarkedIngredient != null ) - { - hoveredIngredientTargets = aeGuiHandler.getTargets( this, bookmarkedIngredient, false ); - ItemStack dragItem = ItemStack.EMPTY; - if( hoveredIngredientTargets.size() > 0 ) - { - if( isShiftKeyDown() && Mouse.isButtonDown( 0 ) && this.lastClicked.elapsed( TimeUnit.MILLISECONDS ) > 200 ) - { - this.lastClicked = Stopwatch.createStarted(); - aeGuiHandler.getTargets( this, bookmarkedIngredient, true ); - } - else if( Mouse.isButtonDown( 0 ) && this.lastClicked.elapsed( TimeUnit.MILLISECONDS ) > 200 ) - { - this.lastClicked = Stopwatch.createStarted(); - if( bookmarkedIngredient instanceof ItemStack ) - { - dragItem = ( (ItemStack) bookmarkedIngredient ); - } - else if( bookmarkedIngredient instanceof FluidStack ) - { - dragItem = FluidUtil.getFilledBucket( ( (FluidStack) bookmarkedIngredient ) ); - } - mc.player.inventory.setItemStack( dragItem.copy() ); - this.isJeiGhostItem = true; - } - drawTargets( mouseX, mouseY ); - } - } - } - - private void drawTargets( int mouseX, int mouseY ) - { - GlStateManager.disableLighting(); - for( IGhostIngredientHandler.Target target : hoveredIngredientTargets ) - { - Rectangle area = target.getArea(); - Color color; - if( area.contains( mouseX, mouseY ) ) - { - color = new Color( 76, 201, 25, 128 ); - } - else - { - color = new Color( 19, 201, 10, 64 ); - } - Gui.drawRect( area.x, area.y, area.x + area.width, area.y + area.height, color.getRGB() ); - } - GlStateManager.color( 1f, 1f, 1f, 1f ); - GlStateManager.enableDepth(); - } - - protected void drawGuiSlot( GuiCustomSlot slot, int mouseX, int mouseY, float partialTicks ) - { - if( slot.isSlotEnabled() ) - { - final int left = slot.xPos(); - final int top = slot.yPos(); - final int right = left + slot.getWidth(); - final int bottom = top + slot.getHeight(); - - slot.drawContent( this.mc, mouseX, mouseY, partialTicks ); - - if( this.isPointInRegion( left, top, slot.getWidth(), slot.getHeight(), mouseX, mouseY ) && slot.canClick( this.mc.player ) ) - { - GlStateManager.disableLighting(); - GlStateManager.colorMask( true, true, true, false ); - this.drawGradientRect( left, top, right, bottom, -2130706433, -2130706433 ); - GlStateManager.colorMask( true, true, true, true ); - GlStateManager.enableLighting(); - } - } - } - - private void drawTooltip( ITooltip tooltip, int mouseX, int mouseY ) - { - final int x = tooltip.xPos(); // ((GuiImgButton) c).x; - int y = tooltip.yPos(); // ((GuiImgButton) c).y; - - if( x < mouseX && x + tooltip.getWidth() > mouseX && tooltip.isVisible() ) - { - if( y < mouseY && y + tooltip.getHeight() > mouseY ) - { - if( y < 15 ) - { - y = 15; - } - - final String msg = tooltip.getMessage(); - if( msg != null ) - { - this.drawTooltip( x + 11, y + 4, msg ); - } - } - } - } - - protected void drawTooltip( int x, int y, String message ) - { - String[] lines = message.split( "\n" ); - this.drawTooltip( x, y, Arrays.asList( lines ) ); - } - - protected void drawTooltip( int x, int y, List lines ) - { - if( lines.isEmpty() ) - { - return; - } - - // For an explanation of the formatting codes, see http://minecraft.gamepedia.com/Formatting_codes - lines = Lists.newArrayList( lines ); // Make a copy - - // Make the first line white - lines.set( 0, TextFormatting.WHITE + lines.get( 0 ) ); - - // All lines after the first are colored gray - for( int i = 1; i < lines.size(); i++ ) - { - lines.set( i, TextFormatting.GRAY + lines.get( i ) ); - } - - this.drawHoveringText( lines, x, y, this.fontRenderer ); - } - - @Override - protected final void drawGuiContainerForegroundLayer( final int x, final int y ) - { - final int ox = this.guiLeft; // (width - xSize) / 2; - final int oy = this.guiTop; // (height - ySize) / 2; - GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); - - if( this.getScrollBar() != null ) - { - this.getScrollBar().draw( this ); - } - - this.drawFG( ox, oy, x, y ); - } - - public abstract void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ); - - @Override - protected final void drawGuiContainerBackgroundLayer( final float f, final int x, final int y ) - { - final int ox = this.guiLeft; // (width - xSize) / 2; - final int oy = this.guiTop; // (height - ySize) / 2; - GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); - this.drawBG( ox, oy, x, y ); - - final List slots = this.getInventorySlots(); - for( final Slot slot : slots ) - { - if( slot instanceof IOptionalSlot ) - { - final IOptionalSlot optionalSlot = (IOptionalSlot) slot; - if( optionalSlot.isRenderDisabled() ) - { - final AppEngSlot aeSlot = (AppEngSlot) slot; - if( aeSlot.isSlotEnabled() ) - { - this.drawTexturedModalRect( ox + aeSlot.xPos - 1, oy + aeSlot.yPos - 1, optionalSlot.getSourceX() - 1, optionalSlot.getSourceY() - 1, 18, 18 ); - } - else - { - GlStateManager.color( 1.0F, 1.0F, 1.0F, 0.4F ); - GlStateManager.enableBlend(); - this.drawTexturedModalRect( ox + aeSlot.xPos - 1, oy + aeSlot.yPos - 1, optionalSlot.getSourceX() - 1, optionalSlot.getSourceY() - 1, 18, 18 ); - GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); - } - } - } - } - - for( final GuiCustomSlot slot : this.guiSlots ) - { - slot.drawBackground( ox, oy ); - } - } - - @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) throws IOException - { - this.drag_click.clear(); - - if( btn == 1 ) - { - for( final Object o : this.buttonList ) - { - final GuiButton guibutton = (GuiButton) o; - if( guibutton.mousePressed( this.mc, xCoord, yCoord ) ) - { - super.mouseClicked( xCoord, yCoord, 0 ); - return; - } - } - } - - for( GuiCustomSlot slot : this.guiSlots ) - { - if( this.isPointInRegion( slot.xPos(), slot.yPos(), slot.getWidth(), slot.getHeight(), xCoord, yCoord ) && slot.canClick( this.mc.player ) ) - { - slot.slotClicked( this.mc.player.inventory.getItemStack(), btn ); - } - } - - if( this.getScrollBar() != null ) - { - this.getScrollBar().click( this, xCoord - this.guiLeft, yCoord - this.guiTop ); - } - - super.mouseClicked( xCoord, yCoord, btn ); - } - - @Override - protected void mouseReleased( int mouseX, int mouseY, int state ) - { - this.drag_click.clear(); - this.haltDragging = false; - - super.mouseReleased( mouseX, mouseY, state ); - } - - @Override - protected void mouseClickMove( final int x, final int y, final int c, final long d ) - { - final Slot slot = this.getSlot( x, y ); - final ItemStack itemstack = this.mc.player.inventory.getItemStack(); - - if( this.getScrollBar() != null ) - { - this.getScrollBar().click( this, x - this.guiLeft, y - this.guiTop ); - } - - if( slot instanceof SlotFake && !itemstack.isEmpty() ) - { - if( this.drag_click.add( slot ) ) - { - final PacketInventoryAction p = new PacketInventoryAction( c == 0 ? InventoryAction.PICKUP_OR_SET_DOWN : InventoryAction.PLACE_SINGLE, slot.slotNumber, 0 ); - NetworkHandler.instance().sendToServer( p ); - } - } - else if( slot instanceof SlotDisconnected ) - { - if( !haltDragging && this.drag_click.add( slot ) ) - { - if( !itemstack.isEmpty() ) - { - if( slot.getStack().isEmpty() ) - { - InventoryAction action; - if( slot.getSlotStackLimit() == 1 ) - { - action = InventoryAction.SPLIT_OR_PLACE_SINGLE; - } - else - { - action = InventoryAction.PICKUP_OR_SET_DOWN; - } - final PacketInventoryAction p = new PacketInventoryAction( action, slot.getSlotIndex(), ( (SlotDisconnected) slot ).getSlot().getId() ); - NetworkHandler.instance().sendToServer( p ); - } - } - } - - else if( isShiftKeyDown() ) - { - for( final Slot dr : this.drag_click ) - { - InventoryAction action = null; - if( !slot.getStack().isEmpty() ) - { - action = InventoryAction.SHIFT_CLICK; - } - if( action != null ) - { - final PacketInventoryAction p = new PacketInventoryAction( action, dr.getSlotIndex(), ( (SlotDisconnected) slot ).getSlot().getId() ); - NetworkHandler.instance().sendToServer( p ); - } - } - } - } - - else - { - super.mouseClickMove( x, y, c, d ); - } - } - - // TODO 1.9.4 aftermath - Whole ClickType thing, to be checked. - @Override - protected void handleMouseClick( final Slot slot, final int slotIdx, final int mouseButton, final ClickType clickType ) - { - final EntityPlayer player = Minecraft.getMinecraft().player; - - if( this.isJeiGhostItem && isDraggingJeiGhostItem ) - { - for( IGhostIngredientHandler.Target target : hoveredIngredientTargets ) - { - Rectangle area = target.getArea(); - final int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - final int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; - - if( area.contains( x, y ) ) - { - target.accept( bookmarkedIngredient ); - break; - } - } - this.isJeiGhostItem = false; - this.isDraggingJeiGhostItem = false; - - ItemStack dragItem = ItemStack.EMPTY; - if( runtime.getBookmarkOverlay().getIngredientUnderMouse() != null ) - { - bookmarkedJEIghostItem( Mouse.getX(), this.mc.displayHeight - Mouse.getY() ); - if( bookmarkedIngredient instanceof ItemStack ) - { - dragItem = ( (ItemStack) bookmarkedIngredient ); - } - else if( bookmarkedIngredient instanceof FluidStack ) - { - dragItem = FluidUtil.getFilledBucket( ( (FluidStack) bookmarkedIngredient ) ); - } - mc.player.inventory.setItemStack( dragItem.copy() ); - this.isJeiGhostItem = true; - } - else - { - mc.player.inventory.setItemStack( dragItem ); - } - } - - else if( slot instanceof SlotFake ) - { - final InventoryAction action; - action = mouseButton == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; - - if( this.drag_click.size() > 1 ) - { - return; - } - - PacketInventoryAction p = new PacketInventoryAction( action, slotIdx, 0 ); - NetworkHandler.instance().sendToServer( p ); - return; - } - - if( slot instanceof SlotPatternTerm ) - { - if( mouseButton == 6 ) - { - return; // prevent weird double clicks.. - } - - try - { - NetworkHandler.instance().sendToServer( ( (SlotPatternTerm) slot ).getRequest( isShiftKeyDown() ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - else if( slot instanceof SlotCraftingTerm ) - { - if( mouseButton == 6 ) - { - return; // prevent weird double clicks.. - } - - InventoryAction action = null; - if( isShiftKeyDown() ) - { - action = InventoryAction.CRAFT_SHIFT; - } - else - { - // Craft stack on right-click, craft single on left-click - action = ( mouseButton == 1 ) ? InventoryAction.CRAFT_STACK : InventoryAction.CRAFT_ITEM; - } - - final PacketInventoryAction p = new PacketInventoryAction( action, slotIdx, 0 ); - NetworkHandler.instance().sendToServer( p ); - - return; - } - - if( Keyboard.isKeyDown( Keyboard.KEY_SPACE ) ) - { - if( this.enableSpaceClicking() ) - { - IAEItemStack stack = null; - if( slot instanceof SlotME ) - { - stack = ( (SlotME) slot ).getAEStack(); - } - - int slotNum = this.getInventorySlots().size(); - - if( !( slot instanceof SlotME ) && slot != null ) - { - slotNum = slot.slotNumber; - } - - ( (AEBaseContainer) this.inventorySlots ).setTargetStack( stack ); - final PacketInventoryAction p = new PacketInventoryAction( InventoryAction.MOVE_REGION, slotNum, 0 ); - NetworkHandler.instance().sendToServer( p ); - return; - } - } - - if( slot instanceof SlotDisconnected ) - { - if( this.drag_click.size() >= 1 ) - { - return; - } - - InventoryAction action = null; - - switch ( clickType ) - { - case PICKUP: // pickup / set-down. - if( mouseButton == 1 ) - { - action = InventoryAction.SPLIT_OR_PLACE_SINGLE; - } - else - { - action = InventoryAction.PICKUP_OR_SET_DOWN; - } - break; - case QUICK_MOVE: - action = ( mouseButton == 1 ) ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; - break; - - case CLONE: // creative dupe: - - if( player.capabilities.isCreativeMode ) - { - action = InventoryAction.CREATIVE_DUPLICATE; - } - - break; - - default: - case THROW: // drop item: - } - - if( action != null ) - { - final PacketInventoryAction p = new PacketInventoryAction( action, slot.getSlotIndex(), ( (SlotDisconnected) slot ).getSlot().getId() ); - NetworkHandler.instance().sendToServer( p ); - } - - return; - } - - if( slot instanceof SlotME ) - { - InventoryAction action = null; - IAEItemStack stack = null; - - switch ( clickType ) - { - case PICKUP: // pickup / set-down. - action = ( mouseButton == 1 ) ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; - stack = ( (SlotME) slot ).getAEStack(); - - if( stack != null && action == InventoryAction.PICKUP_OR_SET_DOWN && stack.getStackSize() == 0 && player.inventory.getItemStack().isEmpty() ) - { - action = InventoryAction.AUTO_CRAFT; - } - - break; - case QUICK_MOVE: - action = ( mouseButton == 1 ) ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; - stack = ( (SlotME) slot ).getAEStack(); - break; - - case CLONE: // creative dupe: - - stack = ( (SlotME) slot ).getAEStack(); - if( stack != null && stack.isCraftable() ) - { - action = InventoryAction.AUTO_CRAFT; - } - else if( player.capabilities.isCreativeMode ) - { - final IAEItemStack slotItem = ( (SlotME) slot ).getAEStack(); - if( slotItem != null ) - { - action = InventoryAction.CREATIVE_DUPLICATE; - } - } - break; - - default: - case THROW: // drop item: - } - - if( action != null ) - { - ( (AEBaseContainer) this.inventorySlots ).setTargetStack( stack ); - final PacketInventoryAction p = new PacketInventoryAction( action, this.getInventorySlots().size(), 0 ); - NetworkHandler.instance().sendToServer( p ); - } - - return; - } - - if( !this.disableShiftClick && isShiftKeyDown() && mouseButton == 0 ) - { - this.disableShiftClick = true; - - if( this.dbl_whichItem.isEmpty() || this.bl_clicked != slot || this.dbl_clickTimer.elapsed( TimeUnit.MILLISECONDS ) > 250 ) - { - // some simple double click logic. - this.bl_clicked = slot; - this.dbl_clickTimer = Stopwatch.createStarted(); - if( slot != null ) - { - this.dbl_whichItem = slot.getHasStack() ? slot.getStack().copy() : ItemStack.EMPTY; - } - else - { - this.dbl_whichItem = ItemStack.EMPTY; - } - } - else if( !this.dbl_whichItem.isEmpty() ) - { - // a replica of the weird broken vanilla feature. - - final List slots = this.getInventorySlots(); - for( final Slot inventorySlot : slots ) - { - if( inventorySlot != null && inventorySlot.canTakeStack( this.mc.player ) && inventorySlot.getHasStack() && inventorySlot.isSameInventory( slot ) && Container.canAddItemToSlot( inventorySlot, this.dbl_whichItem, true ) ) - { - this.handleMouseClick( inventorySlot, inventorySlot.slotNumber, 0, ClickType.QUICK_MOVE ); - } - } - this.dbl_whichItem = ItemStack.EMPTY; - } - - this.disableShiftClick = false; - } - - if( clickType == ClickType.PICKUP && isJeiGhostItem && !isDraggingJeiGhostItem ) - { - this.isDraggingJeiGhostItem = true; - return; - } - - super.handleMouseClick( slot, slotIdx, mouseButton, clickType ); - } - - @Override - protected boolean checkHotbarKeys( final int keyCode ) - { - final Slot theSlot = this.getSlotUnderMouse(); - - if( this.mc.player.inventory.getItemStack().isEmpty() && theSlot != null ) - { - for( int j = 0; j < 9; ++j ) - { - if( keyCode == this.mc.gameSettings.keyBindsHotbar[j].getKeyCode() ) - { - final List slots = this.getInventorySlots(); - for( final Slot s : slots ) - { - if( s.getSlotIndex() == j && s.inventory == ( (AEBaseContainer) this.inventorySlots ).getPlayerInv() ) - { - if( !s.canTakeStack( ( (AEBaseContainer) this.inventorySlots ).getPlayerInv().player ) ) - { - return false; - } - } - } - - if( theSlot.getSlotStackLimit() == 64 ) - { - this.handleMouseClick( theSlot, theSlot.slotNumber, j, ClickType.SWAP ); - return true; - } - else - { - for( final Slot s : slots ) - { - if( s.getSlotIndex() == j && s.inventory == ( (AEBaseContainer) this.inventorySlots ).getPlayerInv() ) - { - NetworkHandler.instance().sendToServer( new PacketSwapSlots( s.slotNumber, theSlot.slotNumber ) ); - return true; - } - } - } - } - } - } - - return false; - } - - @Override - public void onGuiClosed() - { - super.onGuiClosed(); - } - - protected Slot getSlot( final int mouseX, final int mouseY ) - { - final List slots = this.getInventorySlots(); - for( final Slot slot : slots ) - { - // isPointInRegion - if( this.isPointInRegion( slot.xPos, slot.yPos, 16, 16, mouseX, mouseY ) ) - { - return slot; - } - } - - return null; - } - - public abstract void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ); - - @Override - public void handleMouseInput() throws IOException - { - super.handleMouseInput(); - - final int i = Mouse.getEventDWheel(); - if( i != 0 && isShiftKeyDown() ) - { - final int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - final int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; - this.mouseWheelEvent( x, y, i / Math.abs( i ) ); - } - else if( i != 0 && this.getScrollBar() != null ) - { - this.getScrollBar().wheel( i ); - } - } - - protected void mouseWheelEvent( final int x, final int y, final int wheel ) - { - final Slot slot = this.getSlot( x, y ); - if( slot instanceof SlotME ) - { - final IAEItemStack item = ( (SlotME) slot ).getAEStack(); - if( item != null ) - { - ( (AEBaseContainer) this.inventorySlots ).setTargetStack( item ); - final InventoryAction direction = wheel > 0 ? InventoryAction.ROLL_DOWN : InventoryAction.ROLL_UP; - final int times = Math.abs( wheel ); - final int inventorySize = this.getInventorySlots().size(); - for( int h = 0; h < times; h++ ) - { - final PacketInventoryAction p = new PacketInventoryAction( direction, inventorySize, 0 ); - NetworkHandler.instance().sendToServer( p ); - } - } - } - if( slot instanceof SlotFake ) - { - final ItemStack stack = ( (SlotFake) slot ).getStack(); - if( stack != ItemStack.EMPTY ) - { - InventoryAction direction = wheel > 0 ? InventoryAction.PLACE_SINGLE : InventoryAction.PICKUP_SINGLE; - final PacketInventoryAction p = new PacketInventoryAction( direction, slot.slotNumber, 0 ); - NetworkHandler.instance().sendToServer( p ); - } - } - } - - protected boolean enableSpaceClicking() - { - return true; - } - - public void bindTexture( final String base, final String file ) - { - final ResourceLocation loc = new ResourceLocation( base, "textures/" + file ); - this.mc.getTextureManager().bindTexture( loc ); - } - - protected void drawItem( final int x, final int y, final ItemStack is ) - { - this.zLevel = 100.0F; - this.itemRender.zLevel = 100.0F; - - RenderHelper.enableGUIStandardItemLighting(); - GlStateManager.enableDepth(); - this.itemRender.renderItemAndEffectIntoGUI( is, x, y ); - GlStateManager.disableDepth(); - - this.itemRender.zLevel = 0.0F; - this.zLevel = 0.0F; - } - - protected String getGuiDisplayName( final String in ) - { - return this.hasCustomInventoryName() ? this.getInventoryName() : in; - } - - private boolean hasCustomInventoryName() - { - if( this.inventorySlots instanceof AEBaseContainer ) - { - return ( (AEBaseContainer) this.inventorySlots ).getCustomName() != null; - } - return false; - } - - private String getInventoryName() - { - return ( (AEBaseContainer) this.inventorySlots ).getCustomName(); - } - - /** - * This overrides the base-class method through some access transformer hackery... - */ - @Override - public void drawSlot( Slot s ) - { - if( s instanceof SlotME ) - { - - try - { - this.zLevel = 100.0F; - this.itemRender.zLevel = 100.0F; - - if( !this.isPowered() ) - { - drawRect( s.xPos, s.yPos, 16 + s.xPos, 16 + s.yPos, 0x66111111 ); - } - - this.zLevel = 0.0F; - this.itemRender.zLevel = 0.0F; - - // Annoying but easier than trying to splice into render item - super.drawSlot( new Size1Slot( (SlotME) s ) ); - - this.stackSizeRenderer.renderStackSize( this.fontRenderer, ( (SlotME) s ).getAEStack(), s.xPos, s.yPos ); - - } - catch( final Exception err ) - { - AELog.warn( "[AppEng] AE prevented crash while drawing slot: " + err.toString() ); - } - - return; - } - else if( s instanceof IMEFluidSlot && ( (IMEFluidSlot) s ).shouldRenderAsFluid() ) - { - final IMEFluidSlot slot = (IMEFluidSlot) s; - final IAEFluidStack fs = slot.getAEFluidStack(); - - if( fs != null && this.isPowered() ) - { - GlStateManager.disableLighting(); - GlStateManager.disableBlend(); - final Fluid fluid = fs.getFluid(); - Minecraft.getMinecraft().getTextureManager().bindTexture( TextureMap.LOCATION_BLOCKS_TEXTURE ); - final TextureAtlasSprite sprite = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite( fluid.getStill().toString() ); - - // Set color for dynamic fluids - // Convert int color to RGB - float red = ( fluid.getColor() >> 16 & 255 ) / 255.0F; - float green = ( fluid.getColor() >> 8 & 255 ) / 255.0F; - float blue = ( fluid.getColor() & 255 ) / 255.0F; - GlStateManager.color( red, green, blue ); - - this.drawTexturedModalRect( s.xPos, s.yPos, sprite, 16, 16 ); - GlStateManager.enableLighting(); - GlStateManager.enableBlend(); - - this.fluidStackSizeRenderer.renderStackSize( this.fontRenderer, fs, s.xPos, s.yPos ); - } - else if( !this.isPowered() ) - { - drawRect( s.xPos, s.yPos, 16 + s.xPos, 16 + s.yPos, 0x66111111 ); - } - - return; - } - else - { - try - { - final ItemStack is = s.getStack(); - if( s instanceof AppEngSlot && ( ( (AppEngSlot) s ).renderIconWithItem() || is.isEmpty() ) && ( ( (AppEngSlot) s ).shouldDisplay() ) ) - { - final AppEngSlot aes = (AppEngSlot) s; - if( aes.getIcon() >= 0 ) - { - this.bindTexture( "guis/states.png" ); - - try - { - final int uv_y = (int) Math.floor( aes.getIcon() / 16 ); - final int uv_x = aes.getIcon() - uv_y * 16; - - GlStateManager.enableBlend(); - GlStateManager.disableLighting(); - GlStateManager.enableTexture2D(); - GlStateManager.blendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); - GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f ); - final float par1 = aes.xPos; - final float par2 = aes.yPos; - final float par3 = uv_x * 16; - final float par4 = uv_y * 16; - - final Tessellator tessellator = Tessellator.getInstance(); - final BufferBuilder vb = tessellator.getBuffer(); - - vb.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR ); - - final float f1 = 0.00390625F; - final float f = 0.00390625F; - final float par6 = 16; - vb.pos( par1 + 0, par2 + par6, this.zLevel ).tex( ( par3 + 0 ) * f, ( par4 + par6 ) * f1 ).color( 1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon() ).endVertex(); - final float par5 = 16; - vb.pos( par1 + par5, par2 + par6, this.zLevel ).tex( ( par3 + par5 ) * f, ( par4 + par6 ) * f1 ).color( 1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon() ).endVertex(); - vb.pos( par1 + par5, par2 + 0, this.zLevel ).tex( ( par3 + par5 ) * f, ( par4 + 0 ) * f1 ).color( 1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon() ).endVertex(); - vb.pos( par1 + 0, par2 + 0, this.zLevel ).tex( ( par3 + 0 ) * f, ( par4 + 0 ) * f1 ).color( 1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon() ).endVertex(); - tessellator.draw(); - - } - catch( final Exception err ) - { - } - } - } - - if( !is.isEmpty() && s instanceof AppEngSlot ) - { - if( ( (AppEngSlot) s ).getIsValid() == hasCalculatedValidness.NotAvailable ) - { - boolean isValid = s.isItemValid( is ) || s instanceof SlotOutput || s instanceof AppEngCraftingSlot || s instanceof SlotDisabled || s instanceof SlotInaccessible || s instanceof SlotFake || s instanceof SlotRestrictedInput || s instanceof SlotDisconnected; - if( isValid && s instanceof SlotRestrictedInput ) - { - try - { - isValid = ( (SlotRestrictedInput) s ).isValid( is, this.mc.world ); - } - catch( final Exception err ) - { - AELog.debug( err ); - } - } - ( (AppEngSlot) s ).setIsValid( isValid ? hasCalculatedValidness.Valid : hasCalculatedValidness.Invalid ); - } - - if( ( (AppEngSlot) s ).getIsValid() == hasCalculatedValidness.Invalid ) - { - this.zLevel = 100.0F; - this.itemRender.zLevel = 100.0F; - - GlStateManager.disableLighting(); - drawRect( s.xPos, s.yPos, 16 + s.xPos, 16 + s.yPos, 0x66ff6666 ); - GlStateManager.enableLighting(); - - this.zLevel = 0.0F; - this.itemRender.zLevel = 0.0F; - } - } - - if( s instanceof AppEngSlot ) - { - ( (AppEngSlot) s ).setDisplay( true ); - super.drawSlot( s ); - } - else - { - super.drawSlot( s ); - } - - return; - } - catch( final Exception err ) - { - AELog.warn( "[AppEng] AE prevented crash while drawing slot: " + err.toString() ); - } - } - // do the usual for non-ME Slots. - super.drawSlot( s ); - } - - protected boolean isPowered() - { - return true; - } - - public void bindTexture( final String file ) - { - final ResourceLocation loc = new ResourceLocation( AppEng.MOD_ID, "textures/" + file ); - this.mc.getTextureManager().bindTexture( loc ); - } - - protected GuiScrollbar getScrollBar() - { - return this.myScrollBar; - } - - protected void setScrollBar( final GuiScrollbar myScrollBar ) - { - this.myScrollBar = myScrollBar; - } - - protected List getMeSlots() - { - return this.meSlots; - } - - @Override - @Optional.Method( modid = "mousetweaks" ) - public boolean MT_isMouseTweaksDisabled() - { - return false; - } - - @Override - @Optional.Method( modid = "mousetweaks" ) - public boolean MT_isWheelTweakDisabled() - { - return true; - } - - @Override - @Optional.Method( modid = "mousetweaks" ) - public Container MT_getContainer() - { - return this.inventorySlots; - } - - @Override - @Optional.Method( modid = "mousetweaks" ) - public Slot MT_getSlotUnderMouse() - { - return getSlotUnderMouse(); - } - - @Override - @Optional.Method( modid = "mousetweaks" ) - public boolean MT_isCraftingOutput( Slot slot ) - { - return slot instanceof SlotOutput || slot instanceof AppEngCraftingSlot; - } - - @Override - @Optional.Method( modid = "mousetweaks" ) - public boolean MT_isIgnored( Slot slot ) - { - return false; - } - - @Override - @Optional.Method( modid = "mousetweaks" ) - public boolean MT_disableRMBDraggingFunctionality() - { - return false; - } +@Optional.Interface(iface = "yalter.mousetweaks.api.IMTModGuiContainer2", modid = "mousetweaks") +public abstract class AEBaseGui extends GuiContainer implements IMTModGuiContainer2 { + private final List meSlots = new ArrayList<>(); + // drag y + private final Set drag_click = new HashSet<>(); + private final StackSizeRenderer stackSizeRenderer = new StackSizeRenderer(); + private final FluidStackSizeRenderer fluidStackSizeRenderer = new FluidStackSizeRenderer(); + private GuiScrollbar myScrollBar = null; + private boolean disableShiftClick = false; + private Stopwatch dbl_clickTimer = Stopwatch.createStarted(); + private ItemStack dbl_whichItem = ItemStack.EMPTY; + private Slot bl_clicked; + private Stopwatch lastClicked = Stopwatch.createStarted(); + private List> hoveredIngredientTargets = new ArrayList<>(); + private Object bookmarkedIngredient; + private boolean isDraggingJeiGhostItem; + private boolean haltDragging = false; + + public void setJeiGhostItem(boolean jeiGhostItem) { + isJeiGhostItem = jeiGhostItem; + } + + private boolean isJeiGhostItem; + + public Object getBookmarkedIngredient() { + return bookmarkedIngredient; + } + + public List getGuiSlots() { + return guiSlots; + } + + protected final List guiSlots = new ArrayList<>(); + + public AEBaseGui(final Container container) { + super(container); + } + + protected static String join(final Collection toolTip, final String delimiter) { + final Joiner joiner = Joiner.on(delimiter); + + return joiner.join(toolTip); + } + + protected int getQty(final GuiButton btn) { + try { + final DecimalFormat df = new DecimalFormat("+#;-#"); + return df.parse(btn.displayString).intValue(); + } catch (final ParseException e) { + return 0; + } + } + + @Override + public void initGui() { + super.initGui(); + + final List slots = this.getInventorySlots(); + final Iterator i = slots.iterator(); + while (i.hasNext()) { + if (i.next() instanceof SlotME) { + i.remove(); + } + } + + for (final InternalSlotME me : this.meSlots) { + slots.add(new SlotME(me)); + } + } + + private List getInventorySlots() { + return this.inventorySlots.inventorySlots; + } + + @Override + public void drawScreen(final int mouseX, final int mouseY, final float partialTicks) { + super.drawDefaultBackground(); + super.drawScreen(mouseX, mouseY, partialTicks); + + GlStateManager.pushMatrix(); + GlStateManager.translate(this.guiLeft, this.guiTop, 0.0F); + GlStateManager.enableDepth(); + for (final GuiCustomSlot c : this.guiSlots) { + this.drawGuiSlot(c, mouseX, mouseY, partialTicks); + } + GlStateManager.disableDepth(); + for (final GuiCustomSlot c : this.guiSlots) { + this.drawTooltip(c, mouseX - this.guiLeft, mouseY - this.guiTop); + } + GlStateManager.popMatrix(); + + this.renderHoveredToolTip(mouseX, mouseY); + + for (final Object c : this.buttonList) { + if (c instanceof ITooltip) { + this.drawTooltip((ITooltip) c, mouseX, mouseY); + } + } + GlStateManager.enableDepth(); + if (Platform.isModLoaded("jei")) { + bookmarkedJEIghostItem(mouseX, mouseY); + } + GlStateManager.disableDepth(); + } + + public List getJEIExclusionArea() { + return Collections.emptyList(); + } + + @Optional.Method(modid = "jei") + void bookmarkedJEIghostItem(final int mouseX, final int mouseY) { + if (!isJeiGhostItem) { + bookmarkedIngredient = runtime.getBookmarkOverlay().getIngredientUnderMouse(); + } + + if (bookmarkedIngredient != null) { + hoveredIngredientTargets = aeGuiHandler.getTargets(this, bookmarkedIngredient, false); + ItemStack dragItem = ItemStack.EMPTY; + if (hoveredIngredientTargets.size() > 0) { + if (isShiftKeyDown() && Mouse.isButtonDown(0) && this.lastClicked.elapsed(TimeUnit.MILLISECONDS) > 200) { + this.lastClicked = Stopwatch.createStarted(); + aeGuiHandler.getTargets(this, bookmarkedIngredient, true); + } else if (Mouse.isButtonDown(0) && this.lastClicked.elapsed(TimeUnit.MILLISECONDS) > 200) { + this.lastClicked = Stopwatch.createStarted(); + if (bookmarkedIngredient instanceof ItemStack) { + dragItem = ((ItemStack) bookmarkedIngredient); + } else if (bookmarkedIngredient instanceof FluidStack) { + dragItem = FluidUtil.getFilledBucket(((FluidStack) bookmarkedIngredient)); + } + mc.player.inventory.setItemStack(dragItem.copy()); + this.isJeiGhostItem = true; + } + drawTargets(mouseX, mouseY); + } + } + } + + private void drawTargets(int mouseX, int mouseY) { + GlStateManager.disableLighting(); + for (IGhostIngredientHandler.Target target : hoveredIngredientTargets) { + Rectangle area = target.getArea(); + Color color; + if (area.contains(mouseX, mouseY)) { + color = new Color(76, 201, 25, 128); + } else { + color = new Color(19, 201, 10, 64); + } + Gui.drawRect(area.x, area.y, area.x + area.width, area.y + area.height, color.getRGB()); + } + GlStateManager.color(1f, 1f, 1f, 1f); + GlStateManager.enableDepth(); + } + + protected void drawGuiSlot(GuiCustomSlot slot, int mouseX, int mouseY, float partialTicks) { + if (slot.isSlotEnabled()) { + final int left = slot.xPos(); + final int top = slot.yPos(); + final int right = left + slot.getWidth(); + final int bottom = top + slot.getHeight(); + + slot.drawContent(this.mc, mouseX, mouseY, partialTicks); + + if (this.isPointInRegion(left, top, slot.getWidth(), slot.getHeight(), mouseX, mouseY) && slot.canClick(this.mc.player)) { + GlStateManager.disableLighting(); + GlStateManager.colorMask(true, true, true, false); + this.drawGradientRect(left, top, right, bottom, -2130706433, -2130706433); + GlStateManager.colorMask(true, true, true, true); + GlStateManager.enableLighting(); + } + } + } + + private void drawTooltip(ITooltip tooltip, int mouseX, int mouseY) { + final int x = tooltip.xPos(); // ((GuiImgButton) c).x; + int y = tooltip.yPos(); // ((GuiImgButton) c).y; + + if (x < mouseX && x + tooltip.getWidth() > mouseX && tooltip.isVisible()) { + if (y < mouseY && y + tooltip.getHeight() > mouseY) { + if (y < 15) { + y = 15; + } + + final String msg = tooltip.getMessage(); + if (msg != null) { + this.drawTooltip(x + 11, y + 4, msg); + } + } + } + } + + protected void drawTooltip(int x, int y, String message) { + String[] lines = message.split("\n"); + this.drawTooltip(x, y, Arrays.asList(lines)); + } + + protected void drawTooltip(int x, int y, List lines) { + if (lines.isEmpty()) { + return; + } + + // For an explanation of the formatting codes, see http://minecraft.gamepedia.com/Formatting_codes + lines = Lists.newArrayList(lines); // Make a copy + + // Make the first line white + lines.set(0, TextFormatting.WHITE + lines.get(0)); + + // All lines after the first are colored gray + for (int i = 1; i < lines.size(); i++) { + lines.set(i, TextFormatting.GRAY + lines.get(i)); + } + + this.drawHoveringText(lines, x, y, this.fontRenderer); + } + + @Override + protected final void drawGuiContainerForegroundLayer(final int x, final int y) { + final int ox = this.guiLeft; // (width - xSize) / 2; + final int oy = this.guiTop; // (height - ySize) / 2; + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + + if (this.getScrollBar() != null) { + this.getScrollBar().draw(this); + } + + this.drawFG(ox, oy, x, y); + } + + public abstract void drawFG(int offsetX, int offsetY, int mouseX, int mouseY); + + @Override + protected final void drawGuiContainerBackgroundLayer(final float f, final int x, final int y) { + final int ox = this.guiLeft; // (width - xSize) / 2; + final int oy = this.guiTop; // (height - ySize) / 2; + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.drawBG(ox, oy, x, y); + + final List slots = this.getInventorySlots(); + for (final Slot slot : slots) { + if (slot instanceof IOptionalSlot) { + final IOptionalSlot optionalSlot = (IOptionalSlot) slot; + if (optionalSlot.isRenderDisabled()) { + final AppEngSlot aeSlot = (AppEngSlot) slot; + if (aeSlot.isSlotEnabled()) { + this.drawTexturedModalRect(ox + aeSlot.xPos - 1, oy + aeSlot.yPos - 1, optionalSlot.getSourceX() - 1, optionalSlot.getSourceY() - 1, 18, 18); + } else { + GlStateManager.color(1.0F, 1.0F, 1.0F, 0.4F); + GlStateManager.enableBlend(); + this.drawTexturedModalRect(ox + aeSlot.xPos - 1, oy + aeSlot.yPos - 1, optionalSlot.getSourceX() - 1, optionalSlot.getSourceY() - 1, 18, 18); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + } + } + } + } + + for (final GuiCustomSlot slot : this.guiSlots) { + slot.drawBackground(ox, oy); + } + } + + @Override + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) throws IOException { + this.drag_click.clear(); + + if (btn == 1) { + for (final Object o : this.buttonList) { + final GuiButton guibutton = (GuiButton) o; + if (guibutton.mousePressed(this.mc, xCoord, yCoord)) { + super.mouseClicked(xCoord, yCoord, 0); + return; + } + } + } + + for (GuiCustomSlot slot : this.guiSlots) { + if (this.isPointInRegion(slot.xPos(), slot.yPos(), slot.getWidth(), slot.getHeight(), xCoord, yCoord) && slot.canClick(this.mc.player)) { + slot.slotClicked(this.mc.player.inventory.getItemStack(), btn); + } + } + + if (this.getScrollBar() != null) { + this.getScrollBar().click(this, xCoord - this.guiLeft, yCoord - this.guiTop); + } + + super.mouseClicked(xCoord, yCoord, btn); + } + + @Override + protected void mouseReleased(int mouseX, int mouseY, int state) { + this.drag_click.clear(); + this.haltDragging = false; + + super.mouseReleased(mouseX, mouseY, state); + } + + @Override + protected void mouseClickMove(final int x, final int y, final int c, final long d) { + final Slot slot = this.getSlot(x, y); + final ItemStack itemstack = this.mc.player.inventory.getItemStack(); + + if (this.getScrollBar() != null) { + this.getScrollBar().click(this, x - this.guiLeft, y - this.guiTop); + } + + if (slot instanceof SlotFake && !itemstack.isEmpty()) { + if (this.drag_click.add(slot)) { + final PacketInventoryAction p = new PacketInventoryAction(c == 0 ? InventoryAction.PICKUP_OR_SET_DOWN : InventoryAction.PLACE_SINGLE, slot.slotNumber, 0); + NetworkHandler.instance().sendToServer(p); + } + } else if (slot instanceof SlotDisconnected) { + if (!haltDragging && this.drag_click.add(slot)) { + if (!itemstack.isEmpty()) { + if (slot.getStack().isEmpty()) { + InventoryAction action; + if (slot.getSlotStackLimit() == 1) { + action = InventoryAction.SPLIT_OR_PLACE_SINGLE; + } else { + action = InventoryAction.PICKUP_OR_SET_DOWN; + } + final PacketInventoryAction p = new PacketInventoryAction(action, slot.getSlotIndex(), ((SlotDisconnected) slot).getSlot().getId()); + NetworkHandler.instance().sendToServer(p); + } + } + } else if (isShiftKeyDown()) { + for (final Slot dr : this.drag_click) { + InventoryAction action = null; + if (!slot.getStack().isEmpty()) { + action = InventoryAction.SHIFT_CLICK; + } + if (action != null) { + final PacketInventoryAction p = new PacketInventoryAction(action, dr.getSlotIndex(), ((SlotDisconnected) slot).getSlot().getId()); + NetworkHandler.instance().sendToServer(p); + } + } + } + } else { + super.mouseClickMove(x, y, c, d); + } + } + + // TODO 1.9.4 aftermath - Whole ClickType thing, to be checked. + @Override + protected void handleMouseClick(final Slot slot, final int slotIdx, final int mouseButton, final ClickType clickType) { + final EntityPlayer player = Minecraft.getMinecraft().player; + + if (this.isJeiGhostItem && isDraggingJeiGhostItem) { + for (IGhostIngredientHandler.Target target : hoveredIngredientTargets) { + Rectangle area = target.getArea(); + final int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + final int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; + + if (area.contains(x, y)) { + target.accept(bookmarkedIngredient); + break; + } + } + this.isJeiGhostItem = false; + this.isDraggingJeiGhostItem = false; + + ItemStack dragItem = ItemStack.EMPTY; + if (runtime.getBookmarkOverlay().getIngredientUnderMouse() != null) { + bookmarkedJEIghostItem(Mouse.getX(), this.mc.displayHeight - Mouse.getY()); + if (bookmarkedIngredient instanceof ItemStack) { + dragItem = ((ItemStack) bookmarkedIngredient); + } else if (bookmarkedIngredient instanceof FluidStack) { + dragItem = FluidUtil.getFilledBucket(((FluidStack) bookmarkedIngredient)); + } + mc.player.inventory.setItemStack(dragItem.copy()); + this.isJeiGhostItem = true; + } else { + mc.player.inventory.setItemStack(dragItem); + } + } else if (slot instanceof SlotFake) { + final InventoryAction action; + action = mouseButton == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; + + if (this.drag_click.size() > 1) { + return; + } + + PacketInventoryAction p = new PacketInventoryAction(action, slotIdx, 0); + NetworkHandler.instance().sendToServer(p); + return; + } + + if (slot instanceof SlotPatternTerm) { + if (mouseButton == 6) { + return; // prevent weird double clicks.. + } + + try { + NetworkHandler.instance().sendToServer(((SlotPatternTerm) slot).getRequest(isShiftKeyDown())); + } catch (final IOException e) { + AELog.debug(e); + } + } else if (slot instanceof SlotCraftingTerm) { + if (mouseButton == 6) { + return; // prevent weird double clicks.. + } + + InventoryAction action = null; + if (isShiftKeyDown()) { + action = InventoryAction.CRAFT_SHIFT; + } else { + // Craft stack on right-click, craft single on left-click + action = (mouseButton == 1) ? InventoryAction.CRAFT_STACK : InventoryAction.CRAFT_ITEM; + } + + final PacketInventoryAction p = new PacketInventoryAction(action, slotIdx, 0); + NetworkHandler.instance().sendToServer(p); + + return; + } + + if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) { + if (this.enableSpaceClicking()) { + IAEItemStack stack = null; + if (slot instanceof SlotME) { + stack = ((SlotME) slot).getAEStack(); + } + + int slotNum = this.getInventorySlots().size(); + + if (!(slot instanceof SlotME) && slot != null) { + slotNum = slot.slotNumber; + } + + ((AEBaseContainer) this.inventorySlots).setTargetStack(stack); + final PacketInventoryAction p = new PacketInventoryAction(InventoryAction.MOVE_REGION, slotNum, 0); + NetworkHandler.instance().sendToServer(p); + return; + } + } + + if (slot instanceof SlotDisconnected) { + if (this.drag_click.size() >= 1) { + return; + } + + InventoryAction action = null; + + switch (clickType) { + case PICKUP: // pickup / set-down. + if (mouseButton == 1) { + action = InventoryAction.SPLIT_OR_PLACE_SINGLE; + } else { + action = InventoryAction.PICKUP_OR_SET_DOWN; + } + break; + case QUICK_MOVE: + action = (mouseButton == 1) ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; + break; + + case CLONE: // creative dupe: + + if (player.capabilities.isCreativeMode) { + action = InventoryAction.CREATIVE_DUPLICATE; + } + + break; + + default: + case THROW: // drop item: + } + + if (action != null) { + final PacketInventoryAction p = new PacketInventoryAction(action, slot.getSlotIndex(), ((SlotDisconnected) slot).getSlot().getId()); + NetworkHandler.instance().sendToServer(p); + } + + return; + } + + if (slot instanceof SlotME) { + InventoryAction action = null; + IAEItemStack stack = null; + + switch (clickType) { + case PICKUP: // pickup / set-down. + action = (mouseButton == 1) ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; + stack = ((SlotME) slot).getAEStack(); + + if (stack != null && action == InventoryAction.PICKUP_OR_SET_DOWN && stack.getStackSize() == 0 && player.inventory.getItemStack().isEmpty()) { + action = InventoryAction.AUTO_CRAFT; + } + + break; + case QUICK_MOVE: + action = (mouseButton == 1) ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; + stack = ((SlotME) slot).getAEStack(); + break; + + case CLONE: // creative dupe: + + stack = ((SlotME) slot).getAEStack(); + if (stack != null && stack.isCraftable()) { + action = InventoryAction.AUTO_CRAFT; + } else if (player.capabilities.isCreativeMode) { + final IAEItemStack slotItem = ((SlotME) slot).getAEStack(); + if (slotItem != null) { + action = InventoryAction.CREATIVE_DUPLICATE; + } + } + break; + + default: + case THROW: // drop item: + } + + if (action != null) { + ((AEBaseContainer) this.inventorySlots).setTargetStack(stack); + final PacketInventoryAction p = new PacketInventoryAction(action, this.getInventorySlots().size(), 0); + NetworkHandler.instance().sendToServer(p); + } + + return; + } + + if (!this.disableShiftClick && isShiftKeyDown() && mouseButton == 0) { + this.disableShiftClick = true; + + if (this.dbl_whichItem.isEmpty() || this.bl_clicked != slot || this.dbl_clickTimer.elapsed(TimeUnit.MILLISECONDS) > 250) { + // some simple double click logic. + this.bl_clicked = slot; + this.dbl_clickTimer = Stopwatch.createStarted(); + if (slot != null) { + this.dbl_whichItem = slot.getHasStack() ? slot.getStack().copy() : ItemStack.EMPTY; + } else { + this.dbl_whichItem = ItemStack.EMPTY; + } + } else if (!this.dbl_whichItem.isEmpty()) { + // a replica of the weird broken vanilla feature. + + final List slots = this.getInventorySlots(); + for (final Slot inventorySlot : slots) { + if (inventorySlot != null && inventorySlot.canTakeStack(this.mc.player) && inventorySlot.getHasStack() && inventorySlot.isSameInventory(slot) && Container.canAddItemToSlot(inventorySlot, this.dbl_whichItem, true)) { + this.handleMouseClick(inventorySlot, inventorySlot.slotNumber, 0, ClickType.QUICK_MOVE); + } + } + this.dbl_whichItem = ItemStack.EMPTY; + } + + this.disableShiftClick = false; + } + + if (clickType == ClickType.PICKUP && isJeiGhostItem && !isDraggingJeiGhostItem) { + this.isDraggingJeiGhostItem = true; + return; + } + + super.handleMouseClick(slot, slotIdx, mouseButton, clickType); + } + + @Override + protected boolean checkHotbarKeys(final int keyCode) { + final Slot theSlot = this.getSlotUnderMouse(); + + if (this.mc.player.inventory.getItemStack().isEmpty() && theSlot != null) { + for (int j = 0; j < 9; ++j) { + if (keyCode == this.mc.gameSettings.keyBindsHotbar[j].getKeyCode()) { + final List slots = this.getInventorySlots(); + for (final Slot s : slots) { + if (s.getSlotIndex() == j && s.inventory == ((AEBaseContainer) this.inventorySlots).getPlayerInv()) { + if (!s.canTakeStack(((AEBaseContainer) this.inventorySlots).getPlayerInv().player)) { + return false; + } + } + } + + if (theSlot.getSlotStackLimit() == 64) { + this.handleMouseClick(theSlot, theSlot.slotNumber, j, ClickType.SWAP); + return true; + } else { + for (final Slot s : slots) { + if (s.getSlotIndex() == j && s.inventory == ((AEBaseContainer) this.inventorySlots).getPlayerInv()) { + NetworkHandler.instance().sendToServer(new PacketSwapSlots(s.slotNumber, theSlot.slotNumber)); + return true; + } + } + } + } + } + } + + return false; + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + } + + protected Slot getSlot(final int mouseX, final int mouseY) { + final List slots = this.getInventorySlots(); + for (final Slot slot : slots) { + // isPointInRegion + if (this.isPointInRegion(slot.xPos, slot.yPos, 16, 16, mouseX, mouseY)) { + return slot; + } + } + + return null; + } + + public abstract void drawBG(int offsetX, int offsetY, int mouseX, int mouseY); + + @Override + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + + final int i = Mouse.getEventDWheel(); + if (i != 0 && isShiftKeyDown()) { + final int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + final int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; + this.mouseWheelEvent(x, y, i / Math.abs(i)); + } else if (i != 0 && this.getScrollBar() != null) { + this.getScrollBar().wheel(i); + } + } + + protected void mouseWheelEvent(final int x, final int y, final int wheel) { + final Slot slot = this.getSlot(x, y); + if (slot instanceof SlotME) { + final IAEItemStack item = ((SlotME) slot).getAEStack(); + if (item != null) { + ((AEBaseContainer) this.inventorySlots).setTargetStack(item); + final InventoryAction direction = wheel > 0 ? InventoryAction.ROLL_DOWN : InventoryAction.ROLL_UP; + final int times = Math.abs(wheel); + final int inventorySize = this.getInventorySlots().size(); + for (int h = 0; h < times; h++) { + final PacketInventoryAction p = new PacketInventoryAction(direction, inventorySize, 0); + NetworkHandler.instance().sendToServer(p); + } + } + } + if (slot instanceof SlotFake) { + final ItemStack stack = slot.getStack(); + if (stack != ItemStack.EMPTY) { + InventoryAction direction = wheel > 0 ? InventoryAction.PLACE_SINGLE : InventoryAction.PICKUP_SINGLE; + final PacketInventoryAction p = new PacketInventoryAction(direction, slot.slotNumber, 0); + NetworkHandler.instance().sendToServer(p); + } + } + } + + protected boolean enableSpaceClicking() { + return true; + } + + public void bindTexture(final String base, final String file) { + final ResourceLocation loc = new ResourceLocation(base, "textures/" + file); + this.mc.getTextureManager().bindTexture(loc); + } + + protected void drawItem(final int x, final int y, final ItemStack is) { + this.zLevel = 100.0F; + this.itemRender.zLevel = 100.0F; + + RenderHelper.enableGUIStandardItemLighting(); + GlStateManager.enableDepth(); + this.itemRender.renderItemAndEffectIntoGUI(is, x, y); + GlStateManager.disableDepth(); + + this.itemRender.zLevel = 0.0F; + this.zLevel = 0.0F; + } + + protected String getGuiDisplayName(final String in) { + return this.hasCustomInventoryName() ? this.getInventoryName() : in; + } + + private boolean hasCustomInventoryName() { + if (this.inventorySlots instanceof AEBaseContainer) { + return ((AEBaseContainer) this.inventorySlots).getCustomName() != null; + } + return false; + } + + private String getInventoryName() { + return ((AEBaseContainer) this.inventorySlots).getCustomName(); + } + + /** + * This overrides the base-class method through some access transformer hackery... + */ + @Override + public void drawSlot(Slot s) { + if (s instanceof SlotME) { + + try { + this.zLevel = 100.0F; + this.itemRender.zLevel = 100.0F; + + if (!this.isPowered()) { + drawRect(s.xPos, s.yPos, 16 + s.xPos, 16 + s.yPos, 0x66111111); + } + + this.zLevel = 0.0F; + this.itemRender.zLevel = 0.0F; + + // Annoying but easier than trying to splice into render item + super.drawSlot(new Size1Slot((SlotME) s)); + + this.stackSizeRenderer.renderStackSize(this.fontRenderer, ((SlotME) s).getAEStack(), s.xPos, s.yPos); + + } catch (final Exception err) { + AELog.warn("[AppEng] AE prevented crash while drawing slot: " + err); + } + + return; + } else if (s instanceof IMEFluidSlot && ((IMEFluidSlot) s).shouldRenderAsFluid()) { + final IMEFluidSlot slot = (IMEFluidSlot) s; + final IAEFluidStack fs = slot.getAEFluidStack(); + + if (fs != null && this.isPowered()) { + GlStateManager.disableLighting(); + GlStateManager.disableBlend(); + final Fluid fluid = fs.getFluid(); + Minecraft.getMinecraft().getTextureManager().bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); + final TextureAtlasSprite sprite = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(fluid.getStill().toString()); + + // Set color for dynamic fluids + // Convert int color to RGB + float red = (fluid.getColor() >> 16 & 255) / 255.0F; + float green = (fluid.getColor() >> 8 & 255) / 255.0F; + float blue = (fluid.getColor() & 255) / 255.0F; + GlStateManager.color(red, green, blue); + + this.drawTexturedModalRect(s.xPos, s.yPos, sprite, 16, 16); + GlStateManager.enableLighting(); + GlStateManager.enableBlend(); + + this.fluidStackSizeRenderer.renderStackSize(this.fontRenderer, fs, s.xPos, s.yPos); + } else if (!this.isPowered()) { + drawRect(s.xPos, s.yPos, 16 + s.xPos, 16 + s.yPos, 0x66111111); + } + + return; + } else { + try { + final ItemStack is = s.getStack(); + if (s instanceof AppEngSlot && (((AppEngSlot) s).renderIconWithItem() || is.isEmpty()) && (((AppEngSlot) s).shouldDisplay())) { + final AppEngSlot aes = (AppEngSlot) s; + if (aes.getIcon() >= 0) { + this.bindTexture("guis/states.png"); + + try { + final int uv_y = (int) Math.floor(aes.getIcon() / 16); + final int uv_x = aes.getIcon() - uv_y * 16; + + GlStateManager.enableBlend(); + GlStateManager.disableLighting(); + GlStateManager.enableTexture2D(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + final float par1 = aes.xPos; + final float par2 = aes.yPos; + final float par3 = uv_x * 16; + final float par4 = uv_y * 16; + + final Tessellator tessellator = Tessellator.getInstance(); + final BufferBuilder vb = tessellator.getBuffer(); + + vb.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); + + final float f1 = 0.00390625F; + final float f = 0.00390625F; + final float par6 = 16; + vb.pos(par1 + 0, par2 + par6, this.zLevel).tex((par3 + 0) * f, (par4 + par6) * f1).color(1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon()).endVertex(); + final float par5 = 16; + vb.pos(par1 + par5, par2 + par6, this.zLevel).tex((par3 + par5) * f, (par4 + par6) * f1).color(1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon()).endVertex(); + vb.pos(par1 + par5, par2 + 0, this.zLevel).tex((par3 + par5) * f, (par4 + 0) * f1).color(1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon()).endVertex(); + vb.pos(par1 + 0, par2 + 0, this.zLevel).tex((par3 + 0) * f, (par4 + 0) * f1).color(1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon()).endVertex(); + tessellator.draw(); + + } catch (final Exception err) { + } + } + } + + if (!is.isEmpty() && s instanceof AppEngSlot) { + if (((AppEngSlot) s).getIsValid() == hasCalculatedValidness.NotAvailable) { + boolean isValid = s.isItemValid(is) || s instanceof SlotOutput || s instanceof AppEngCraftingSlot || s instanceof SlotDisabled || s instanceof SlotInaccessible || s instanceof SlotFake || s instanceof SlotRestrictedInput || s instanceof SlotDisconnected; + if (isValid && s instanceof SlotRestrictedInput) { + try { + isValid = ((SlotRestrictedInput) s).isValid(is, this.mc.world); + } catch (final Exception err) { + AELog.debug(err); + } + } + ((AppEngSlot) s).setIsValid(isValid ? hasCalculatedValidness.Valid : hasCalculatedValidness.Invalid); + } + + if (((AppEngSlot) s).getIsValid() == hasCalculatedValidness.Invalid) { + this.zLevel = 100.0F; + this.itemRender.zLevel = 100.0F; + + GlStateManager.disableLighting(); + drawRect(s.xPos, s.yPos, 16 + s.xPos, 16 + s.yPos, 0x66ff6666); + GlStateManager.enableLighting(); + + this.zLevel = 0.0F; + this.itemRender.zLevel = 0.0F; + } + } + + if (s instanceof AppEngSlot) { + ((AppEngSlot) s).setDisplay(true); + super.drawSlot(s); + } else { + super.drawSlot(s); + } + + return; + } catch (final Exception err) { + AELog.warn("[AppEng] AE prevented crash while drawing slot: " + err); + } + } + // do the usual for non-ME Slots. + super.drawSlot(s); + } + + protected boolean isPowered() { + return true; + } + + public void bindTexture(final String file) { + final ResourceLocation loc = new ResourceLocation(AppEng.MOD_ID, "textures/" + file); + this.mc.getTextureManager().bindTexture(loc); + } + + protected GuiScrollbar getScrollBar() { + return this.myScrollBar; + } + + protected void setScrollBar(final GuiScrollbar myScrollBar) { + this.myScrollBar = myScrollBar; + } + + protected List getMeSlots() { + return this.meSlots; + } + + @Override + @Optional.Method(modid = "mousetweaks") + public boolean MT_isMouseTweaksDisabled() { + return false; + } + + @Override + @Optional.Method(modid = "mousetweaks") + public boolean MT_isWheelTweakDisabled() { + return true; + } + + @Override + @Optional.Method(modid = "mousetweaks") + public Container MT_getContainer() { + return this.inventorySlots; + } + + @Override + @Optional.Method(modid = "mousetweaks") + public Slot MT_getSlotUnderMouse() { + return getSlotUnderMouse(); + } + + @Override + @Optional.Method(modid = "mousetweaks") + public boolean MT_isCraftingOutput(Slot slot) { + return slot instanceof SlotOutput || slot instanceof AppEngCraftingSlot; + } + + @Override + @Optional.Method(modid = "mousetweaks") + public boolean MT_isIgnored(Slot slot) { + return false; + } + + @Override + @Optional.Method(modid = "mousetweaks") + public boolean MT_disableRMBDraggingFunctionality() { + return false; + } } diff --git a/src/main/java/appeng/client/gui/AEBaseMEGui.java b/src/main/java/appeng/client/gui/AEBaseMEGui.java index 4932b488c..83d4ac6f3 100644 --- a/src/main/java/appeng/client/gui/AEBaseMEGui.java +++ b/src/main/java/appeng/client/gui/AEBaseMEGui.java @@ -19,88 +19,75 @@ package appeng.client.gui; -import java.text.NumberFormat; -import java.util.List; -import java.util.Locale; - +import appeng.api.storage.data.IAEItemStack; +import appeng.client.me.SlotME; +import appeng.core.AEConfig; +import appeng.core.localization.ButtonToolTips; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.util.text.TextFormatting; -import appeng.api.storage.data.IAEItemStack; -import appeng.client.me.SlotME; -import appeng.core.AEConfig; -import appeng.core.localization.ButtonToolTips; +import java.text.NumberFormat; +import java.util.List; +import java.util.Locale; -public abstract class AEBaseMEGui extends AEBaseGui -{ +public abstract class AEBaseMEGui extends AEBaseGui { - public AEBaseMEGui( final Container container ) - { - super( container ); - } + public AEBaseMEGui(final Container container) { + super(container); + } - @Override - protected void renderToolTip( final ItemStack stack, final int x, final int y ) - { - final Slot s = this.getSlot( x, y ); + @Override + protected void renderToolTip(final ItemStack stack, final int x, final int y) { + final Slot s = this.getSlot(x, y); - if( s instanceof SlotME && !stack.isEmpty() ) - { - final int bigNumber = AEConfig.instance().useTerminalUseLargeFont() ? 999 : 9999; + if (s instanceof SlotME && !stack.isEmpty()) { + final int bigNumber = AEConfig.instance().useTerminalUseLargeFont() ? 999 : 9999; - IAEItemStack myStack = null; - final List currentToolTip = this.getItemToolTip( stack ); + IAEItemStack myStack = null; + final List currentToolTip = this.getItemToolTip(stack); - try - { - final SlotME theSlotField = (SlotME) s; - myStack = theSlotField.getAEStack(); - } - catch( final Throwable ignore ) - { - } + try { + final SlotME theSlotField = (SlotME) s; + myStack = theSlotField.getAEStack(); + } catch (final Throwable ignore) { + } - if( myStack != null ) - { - if( myStack.getStackSize() > bigNumber || ( myStack.getStackSize() > 1 && stack.isItemDamaged() ) ) - { - final String local = ButtonToolTips.ItemsStored.getLocal(); - final String formattedAmount = NumberFormat.getNumberInstance( Locale.US ).format( myStack.getStackSize() ); - final String format = String.format( local, formattedAmount ); + if (myStack != null) { + if (myStack.getStackSize() > bigNumber || (myStack.getStackSize() > 1 && stack.isItemDamaged())) { + final String local = ButtonToolTips.ItemsStored.getLocal(); + final String formattedAmount = NumberFormat.getNumberInstance(Locale.US).format(myStack.getStackSize()); + final String format = String.format(local, formattedAmount); - currentToolTip.add( TextFormatting.GRAY + format ); - } + currentToolTip.add(TextFormatting.GRAY + format); + } - if( myStack.getCountRequestable() > 0 ) - { - final String local = ButtonToolTips.ItemsRequestable.getLocal(); - final String formattedAmount = NumberFormat.getNumberInstance( Locale.US ).format( myStack.getCountRequestable() ); - final String format = String.format( local, formattedAmount ); + if (myStack.getCountRequestable() > 0) { + final String local = ButtonToolTips.ItemsRequestable.getLocal(); + final String formattedAmount = NumberFormat.getNumberInstance(Locale.US).format(myStack.getCountRequestable()); + final String format = String.format(local, formattedAmount); - currentToolTip.add( format ); - } + currentToolTip.add(format); + } - this.drawHoveringText( currentToolTip, x, y, this.fontRenderer ); + this.drawHoveringText(currentToolTip, x, y, this.fontRenderer); - return; - } - else if( stack.getCount() > bigNumber ) - { - final String local = ButtonToolTips.ItemsStored.getLocal(); - final String formattedAmount = NumberFormat.getNumberInstance( Locale.US ).format( stack.getCount() ); - final String format = String.format( local, formattedAmount ); + return; + } else if (stack.getCount() > bigNumber) { + final String local = ButtonToolTips.ItemsStored.getLocal(); + final String formattedAmount = NumberFormat.getNumberInstance(Locale.US).format(stack.getCount()); + final String format = String.format(local, formattedAmount); - currentToolTip.add( TextFormatting.GRAY + format ); + currentToolTip.add(TextFormatting.GRAY + format); - this.drawHoveringText( currentToolTip, x, y, this.fontRenderer ); + this.drawHoveringText(currentToolTip, x, y, this.fontRenderer); - return; - } - } + return; + } + } - super.renderToolTip( stack, x, y ); - } + super.renderToolTip(stack, x, y); + } } \ No newline at end of file diff --git a/src/main/java/appeng/client/gui/AEGuiHandler.java b/src/main/java/appeng/client/gui/AEGuiHandler.java index 4fbb0e4c8..b7cd7c29b 100644 --- a/src/main/java/appeng/client/gui/AEGuiHandler.java +++ b/src/main/java/appeng/client/gui/AEGuiHandler.java @@ -1,7 +1,5 @@ package appeng.client.gui; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import appeng.api.storage.data.IAEItemStack; import appeng.client.gui.implementations.*; import appeng.container.interfaces.IJEIGhostIngredients; @@ -12,119 +10,95 @@ import mezz.jei.api.gui.IGhostIngredientHandler; import net.minecraft.client.gui.GuiScreen; import org.lwjgl.input.Mouse; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.awt.*; import java.util.ArrayList; -import java.util.Collections; import java.util.List; -public class AEGuiHandler implements IAdvancedGuiHandler, IGhostIngredientHandler -{ +public class AEGuiHandler implements IAdvancedGuiHandler, IGhostIngredientHandler { @Override @Nonnull - public Class getGuiContainerClass() - { + public Class getGuiContainerClass() { return AEBaseGui.class; } @Nullable @Override - public List getGuiExtraAreas( @Nonnull AEBaseGui guiContainer ) - { + public List getGuiExtraAreas(@Nonnull AEBaseGui guiContainer) { return guiContainer.getJEIExclusionArea(); } @Nullable @Override - public Object getIngredientUnderMouse( @Nonnull AEBaseGui guiContainer, int mouseX, int mouseY ) - { + public Object getIngredientUnderMouse(@Nonnull AEBaseGui guiContainer, int mouseX, int mouseY) { List visual; int guiSlotIdx; Object result = null; - if( guiContainer instanceof GuiCraftConfirm ) - { - guiSlotIdx = getSlotidx( guiContainer, mouseX, mouseY, ( (GuiCraftConfirm) guiContainer ).getDisplayedRows() ); - visual = ( (GuiCraftConfirm) guiContainer ).getVisual(); - if( guiSlotIdx < visual.size() && guiSlotIdx != -1 ) - { - result = visual.get( guiSlotIdx ).getDefinition(); - } - else - { + if (guiContainer instanceof GuiCraftConfirm) { + guiSlotIdx = getSlotidx(guiContainer, mouseX, mouseY, ((GuiCraftConfirm) guiContainer).getDisplayedRows()); + visual = ((GuiCraftConfirm) guiContainer).getVisual(); + if (guiSlotIdx < visual.size() && guiSlotIdx != -1) { + result = visual.get(guiSlotIdx).getDefinition(); + } else { return null; } } - if( guiContainer instanceof GuiCraftingCPU ) - { - guiSlotIdx = getSlotidx( guiContainer, mouseX, mouseY, ( (GuiCraftingCPU) guiContainer ).getDisplayedRows() ); - visual = ( (GuiCraftingCPU) guiContainer ).getVisual(); - if( guiSlotIdx < visual.size() && guiSlotIdx != -1 ) - { - result = visual.get( guiSlotIdx ).getDefinition(); - } - else - { + if (guiContainer instanceof GuiCraftingCPU) { + guiSlotIdx = getSlotidx(guiContainer, mouseX, mouseY, ((GuiCraftingCPU) guiContainer).getDisplayedRows()); + visual = ((GuiCraftingCPU) guiContainer).getVisual(); + if (guiSlotIdx < visual.size() && guiSlotIdx != -1) { + result = visual.get(guiSlotIdx).getDefinition(); + } else { return null; } } - - if( guiContainer instanceof GuiCraftAmount ) - { - if( guiContainer.getSlotUnderMouse() != null ) - { + + if (guiContainer instanceof GuiCraftAmount) { + if (guiContainer.getSlotUnderMouse() != null) { result = guiContainer.getSlotUnderMouse().getStack(); } } return result; } - private int getSlotidx(AEBaseGui guiContainer, int mouseX, int mouseY, int rows) - { + private int getSlotidx(AEBaseGui guiContainer, int mouseX, int mouseY, int rows) { int guileft = guiContainer.getGuiLeft(); int guitop = guiContainer.getGuiTop(); int currentScroll = guiContainer.getScrollBar().getCurrentScroll(); final int xo = 9; final int yo = 19; - int guiSlotx = ( mouseX - guileft - xo ) / 67; - if( guiSlotx > 2 || mouseX < guileft + xo ) return -1; - int guiSloty = ( mouseY - guitop - yo ) / 23; - if( guiSloty > ( rows - 1 ) || mouseY < guitop + yo ) return -1; - return ( guiSloty * 3 ) + guiSlotx + ( currentScroll * 3 ); + int guiSlotx = (mouseX - guileft - xo) / 67; + if (guiSlotx > 2 || mouseX < guileft + xo) return -1; + int guiSloty = (mouseY - guitop - yo) / 23; + if (guiSloty > (rows - 1) || mouseY < guitop + yo) return -1; + return (guiSloty * 3) + guiSlotx + (currentScroll * 3); } @Override @Nonnull - public List> getTargets( @Nonnull AEBaseGui gui, @Nonnull I ingredient, boolean doStart ) - { + public List> getTargets(@Nonnull AEBaseGui gui, @Nonnull I ingredient, boolean doStart) { ArrayList> targets = new ArrayList<>(); - if( gui instanceof IJEIGhostIngredients ) - { + if (gui instanceof IJEIGhostIngredients) { IJEIGhostIngredients g = (IJEIGhostIngredients) gui; - List> phantomTargets = g.getPhantomTargets( ingredient ); - targets.addAll( (List>) (Object) phantomTargets ); + List> phantomTargets = g.getPhantomTargets(ingredient); + targets.addAll((List>) (Object) phantomTargets); } - if( doStart && GuiScreen.isShiftKeyDown() && Mouse.isButtonDown( 0 ) ) - { - if( gui instanceof GuiUpgradeable || gui instanceof GuiPatternTerm || gui instanceof GuiExpandedProcessingPatternTerm ) - { - IJEIGhostIngredients ghostGui = ( (IJEIGhostIngredients) gui ); - for( Target target : targets ) - { - if( ghostGui.getFakeSlotTargetMap().get( target ) instanceof SlotFake ) - { - if( ( (SlotFake) ghostGui.getFakeSlotTargetMap().get( target ) ).getStack().isEmpty() ) - { - target.accept( ingredient ); + if (doStart && GuiScreen.isShiftKeyDown() && Mouse.isButtonDown(0)) { + if (gui instanceof GuiUpgradeable || gui instanceof GuiPatternTerm || gui instanceof GuiExpandedProcessingPatternTerm) { + IJEIGhostIngredients ghostGui = ((IJEIGhostIngredients) gui); + for (Target target : targets) { + if (ghostGui.getFakeSlotTargetMap().get(target) instanceof SlotFake) { + if (((SlotFake) ghostGui.getFakeSlotTargetMap().get(target)).getStack().isEmpty()) { + target.accept(ingredient); break; } - } - else if( ghostGui.getFakeSlotTargetMap().get( target ) instanceof GuiFluidSlot ) - { - if( ( (GuiFluidSlot) ghostGui.getFakeSlotTargetMap().get( target ) ).getFluidStack() == null ) - { - target.accept( ingredient ); + } else if (ghostGui.getFakeSlotTargetMap().get(target) instanceof GuiFluidSlot) { + if (((GuiFluidSlot) ghostGui.getFakeSlotTargetMap().get(target)).getFluidStack() == null) { + target.accept(ingredient); break; } } @@ -135,12 +109,11 @@ public class AEGuiHandler implements IAdvancedGuiHandler, IGhostIngre } @Override - public void onComplete(){ + public void onComplete() { } @Override - public boolean shouldHighlightTargets() - { + public boolean shouldHighlightTargets() { return true; } diff --git a/src/main/java/appeng/client/gui/GuiNull.java b/src/main/java/appeng/client/gui/GuiNull.java index e8ac394d6..337554862 100644 --- a/src/main/java/appeng/client/gui/GuiNull.java +++ b/src/main/java/appeng/client/gui/GuiNull.java @@ -22,22 +22,18 @@ package appeng.client.gui; import net.minecraft.inventory.Container; -public class GuiNull extends AEBaseGui -{ +public class GuiNull extends AEBaseGui { - public GuiNull( final Container container ) - { - super( container ); - } + public GuiNull(final Container container) { + super(container); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { - } + } } diff --git a/src/main/java/appeng/client/gui/Size1Slot.java b/src/main/java/appeng/client/gui/Size1Slot.java index c969651a4..315428839 100644 --- a/src/main/java/appeng/client/gui/Size1Slot.java +++ b/src/main/java/appeng/client/gui/Size1Slot.java @@ -1,10 +1,6 @@ - package appeng.client.gui; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; @@ -15,105 +11,93 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.SlotItemHandler; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + /** * A proxy for a slot that will always return an itemstack with size 1, if there is an item in the slot. * Used to prevent the default item count from rendering. */ -class Size1Slot extends SlotItemHandler -{ +class Size1Slot extends SlotItemHandler { - private final SlotItemHandler delegate; + private final SlotItemHandler delegate; - public Size1Slot( SlotItemHandler delegate ) - { - super( delegate.getItemHandler(), delegate.getSlotIndex(), delegate.xPos, delegate.yPos ); - this.delegate = delegate; - } + public Size1Slot(SlotItemHandler delegate) { + super(delegate.getItemHandler(), delegate.getSlotIndex(), delegate.xPos, delegate.yPos); + this.delegate = delegate; + } - @Override - @Nonnull - public ItemStack getStack() - { - ItemStack orgStack = this.delegate.getStack(); - if( !orgStack.isEmpty() ) - { - ItemStack modifiedStack = orgStack.copy(); - modifiedStack.setCount( 1 ); - return modifiedStack; - } + @Override + @Nonnull + public ItemStack getStack() { + ItemStack orgStack = this.delegate.getStack(); + if (!orgStack.isEmpty()) { + ItemStack modifiedStack = orgStack.copy(); + modifiedStack.setCount(1); + return modifiedStack; + } - return ItemStack.EMPTY; - } + return ItemStack.EMPTY; + } - @Override - public boolean getHasStack() - { - return this.delegate.getHasStack(); - } + @Override + public boolean getHasStack() { + return this.delegate.getHasStack(); + } - @Override - public boolean isHere( IInventory inv, int slotIn ) - { - return this.delegate.isHere( inv, slotIn ); - } + @Override + public boolean isHere(IInventory inv, int slotIn) { + return this.delegate.isHere(inv, slotIn); + } - @Override - public int getSlotStackLimit() - { - return this.delegate.getSlotStackLimit(); - } + @Override + public int getSlotStackLimit() { + return this.delegate.getSlotStackLimit(); + } - @Override - public int getItemStackLimit( ItemStack stack ) - { - return this.delegate.getItemStackLimit( stack ); - } + @Override + public int getItemStackLimit(ItemStack stack) { + return this.delegate.getItemStackLimit(stack); + } - @Override - @Nullable - @SideOnly( Side.CLIENT ) - public String getSlotTexture() - { - return this.delegate.getSlotTexture(); - } + @Override + @Nullable + @SideOnly(Side.CLIENT) + public String getSlotTexture() { + return this.delegate.getSlotTexture(); + } - @Override - public boolean canTakeStack( EntityPlayer playerIn ) - { - return this.delegate.canTakeStack( playerIn ); - } + @Override + public boolean canTakeStack(EntityPlayer playerIn) { + return this.delegate.canTakeStack(playerIn); + } - @Override - @SideOnly( Side.CLIENT ) - public boolean isEnabled() - { - return this.delegate.isEnabled(); - } + @Override + @SideOnly(Side.CLIENT) + public boolean isEnabled() { + return this.delegate.isEnabled(); + } - @Override - @SideOnly( Side.CLIENT ) - public ResourceLocation getBackgroundLocation() - { - return this.delegate.getBackgroundLocation(); - } + @Override + @SideOnly(Side.CLIENT) + public ResourceLocation getBackgroundLocation() { + return this.delegate.getBackgroundLocation(); + } - @Override - @SideOnly( Side.CLIENT ) - public TextureAtlasSprite getBackgroundSprite() - { - return this.delegate.getBackgroundSprite(); - } + @Override + @SideOnly(Side.CLIENT) + public TextureAtlasSprite getBackgroundSprite() { + return this.delegate.getBackgroundSprite(); + } - @Override - public int getSlotIndex() - { - return this.delegate.getSlotIndex(); - } + @Override + public int getSlotIndex() { + return this.delegate.getSlotIndex(); + } - @Override - public boolean isSameInventory( Slot other ) - { - return this.delegate.isSameInventory( other ); - } + @Override + public boolean isSameInventory(Slot other) { + return this.delegate.isSameInventory(other); + } } diff --git a/src/main/java/appeng/client/gui/config/AEConfigGui.java b/src/main/java/appeng/client/gui/config/AEConfigGui.java index 461a5a71b..9188714fd 100644 --- a/src/main/java/appeng/client/gui/config/AEConfigGui.java +++ b/src/main/java/appeng/client/gui/config/AEConfigGui.java @@ -19,54 +19,46 @@ package appeng.client.gui.config; -import java.util.ArrayList; -import java.util.List; - +import appeng.core.AEConfig; +import appeng.core.AppEng; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.IConfigElement; -import appeng.core.AEConfig; -import appeng.core.AppEng; +import java.util.ArrayList; +import java.util.List; -public class AEConfigGui extends GuiConfig -{ +public class AEConfigGui extends GuiConfig { - public AEConfigGui( final GuiScreen parent ) - { - super( parent, getConfigElements(), AppEng.MOD_ID, false, false, GuiConfig.getAbridgedConfigPath( AEConfig.instance().getFilePath() ) ); - } + public AEConfigGui(final GuiScreen parent) { + super(parent, getConfigElements(), AppEng.MOD_ID, false, false, GuiConfig.getAbridgedConfigPath(AEConfig.instance().getFilePath())); + } - private static List getConfigElements() - { - final List list = new ArrayList<>(); + private static List getConfigElements() { + final List list = new ArrayList<>(); - for( final String cat : AEConfig.instance().getCategoryNames() ) - { - if( cat.equals( "versionchecker" ) ) - { - continue; - } + for (final String cat : AEConfig.instance().getCategoryNames()) { + if (cat.equals("versionchecker")) { + continue; + } - if( cat.equals( "settings" ) ) - { - continue; - } + if (cat.equals("settings")) { + continue; + } - final ConfigCategory cc = AEConfig.instance().getCategory( cat ); + final ConfigCategory cc = AEConfig.instance().getCategory(cat); - if( cc.isChild() ) - { - continue; - } + if (cc.isChild()) { + continue; + } - final ConfigElement ce = new ConfigElement( cc ); - list.add( ce ); - } + final ConfigElement ce = new ConfigElement(cc); + list.add(ce); + } - return list; - } + return list; + } } diff --git a/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java b/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java index 300491300..c1b68676c 100644 --- a/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java +++ b/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java @@ -19,63 +19,58 @@ package appeng.client.gui.config; -import java.util.Set; - import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.fml.client.IModGuiFactory; +import java.util.Set; -public class AEConfigGuiFactory implements IModGuiFactory -{ - @Override - public void initialize( final Minecraft minecraftInstance ) - { +public class AEConfigGuiFactory implements IModGuiFactory { - } + @Override + public void initialize(final Minecraft minecraftInstance) { - /** - * If this method returns false, the config button in the mod list will be disabled - * - * @return true if this object provides a config gui screen, false otherwise - */ - @Override - public boolean hasConfigGui() - { - return false; - } + } - /** - * Return an initialized {@link GuiScreen}. This screen will be displayed - * when the "config" button is pressed in the mod list. It will - * have a single argument constructor - the "parent" screen, the same as all - * Minecraft GUIs. The expected behaviour is that this screen will replace the - * "mod list" screen completely, and will return to the mod list screen through - * the parent link, once the appropriate action is taken from the config screen. - *

- * This config GUI is anticipated to provide configuration to the mod in a friendly - * visual way. It should not be abused to set internals such as IDs (they're gonna - * keep disappearing anyway), but rather, interesting behaviours. This config GUI - * is never run when a server game is running, and should be used to configure - * desired behaviours that affect server state. Costs, mod game modes, stuff like that - * can be changed here. - * - * @param parentScreen The screen to which must be returned when closing the - * returned screen. - * @return A class that will be instantiated on clicks on the config button - * or null if no GUI is desired. - */ - @Override - public GuiScreen createConfigGui( GuiScreen parentScreen ) - { - return new AEConfigGui( parentScreen ); - } + /** + * If this method returns false, the config button in the mod list will be disabled + * + * @return true if this object provides a config gui screen, false otherwise + */ + @Override + public boolean hasConfigGui() { + return false; + } - @Override - public Set runtimeGuiCategories() - { - return null; - } + /** + * Return an initialized {@link GuiScreen}. This screen will be displayed + * when the "config" button is pressed in the mod list. It will + * have a single argument constructor - the "parent" screen, the same as all + * Minecraft GUIs. The expected behaviour is that this screen will replace the + * "mod list" screen completely, and will return to the mod list screen through + * the parent link, once the appropriate action is taken from the config screen. + *

+ * This config GUI is anticipated to provide configuration to the mod in a friendly + * visual way. It should not be abused to set internals such as IDs (they're gonna + * keep disappearing anyway), but rather, interesting behaviours. This config GUI + * is never run when a server game is running, and should be used to configure + * desired behaviours that affect server state. Costs, mod game modes, stuff like that + * can be changed here. + * + * @param parentScreen The screen to which must be returned when closing the + * returned screen. + * @return A class that will be instantiated on clicks on the config button + * or null if no GUI is desired. + */ + @Override + public GuiScreen createConfigGui(GuiScreen parentScreen) { + return new AEConfigGui(parentScreen); + } + + @Override + public Set runtimeGuiCategories() { + return null; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCellWorkbench.java b/src/main/java/appeng/client/gui/implementations/GuiCellWorkbench.java index 80aa32481..a62264b39 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCellWorkbench.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCellWorkbench.java @@ -19,20 +19,7 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandler; - -import appeng.api.config.ActionItems; -import appeng.api.config.CopyMode; -import appeng.api.config.FuzzyMode; -import appeng.api.config.Settings; -import appeng.api.config.Upgrades; +import appeng.api.config.*; import appeng.api.implementations.items.IUpgradeModule; import appeng.client.gui.widgets.GuiImgButton; import appeng.client.gui.widgets.GuiToggleButton; @@ -42,167 +29,137 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; import appeng.tile.misc.TileCellWorkbench; import appeng.util.Platform; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraftforge.items.IItemHandler; +import org.lwjgl.input.Mouse; + +import java.io.IOException; -public class GuiCellWorkbench extends GuiUpgradeable -{ +public class GuiCellWorkbench extends GuiUpgradeable { - private final ContainerCellWorkbench workbench; + private final ContainerCellWorkbench workbench; - private GuiImgButton clear; - private GuiImgButton partition; - private GuiToggleButton copyMode; + private GuiImgButton clear; + private GuiImgButton partition; + private GuiToggleButton copyMode; - public GuiCellWorkbench( final InventoryPlayer inventoryPlayer, final TileCellWorkbench te ) - { - super( new ContainerCellWorkbench( inventoryPlayer, te ) ); - this.workbench = (ContainerCellWorkbench) this.inventorySlots; - this.ySize = 251; - } + public GuiCellWorkbench(final InventoryPlayer inventoryPlayer, final TileCellWorkbench te) { + super(new ContainerCellWorkbench(inventoryPlayer, te)); + this.workbench = (ContainerCellWorkbench) this.inventorySlots; + this.ySize = 251; + } - @Override - protected void addButtons() - { - this.clear = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE ); - this.partition = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH ); - this.copyMode = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 48, 11 * 16 + 5, 12 * 16 + 5, GuiText.CopyMode.getLocal(), GuiText.CopyModeDesc - .getLocal() ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 68, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); + @Override + protected void addButtons() { + this.clear = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE); + this.partition = new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH); + this.copyMode = new GuiToggleButton(this.guiLeft - 18, this.guiTop + 48, 11 * 16 + 5, 12 * 16 + 5, GuiText.CopyMode.getLocal(), GuiText.CopyModeDesc + .getLocal()); + this.fuzzyMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 68, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); - this.buttonList.add( this.fuzzyMode ); - this.buttonList.add( this.partition ); - this.buttonList.add( this.clear ); - this.buttonList.add( this.copyMode ); - } + this.buttonList.add(this.fuzzyMode); + this.buttonList.add(this.partition); + this.buttonList.add(this.clear); + this.buttonList.add(this.copyMode); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.handleButtonVisibility(); + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.handleButtonVisibility(); - this.bindTexture( this.getBackground() ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, 211 - 34, this.ySize ); - if( this.drawUpgrades() ) - { - if( this.workbench.availableUpgrades() <= 8 ) - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 7 + this.workbench.availableUpgrades() * 18 ); - this.drawTexturedModalRect( offsetX + 177, offsetY + ( 7 + ( this.workbench.availableUpgrades() ) * 18 ), 177, 151, 35, 7 ); - } - else if( this.workbench.availableUpgrades() <= 16 ) - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 7 + 8 * 18 ); - this.drawTexturedModalRect( offsetX + 177, offsetY + ( 7 + ( 8 ) * 18 ), 177, 151, 35, 7 ); + this.bindTexture(this.getBackground()); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, 211 - 34, this.ySize); + if (this.drawUpgrades()) { + if (this.workbench.availableUpgrades() <= 8) { + this.drawTexturedModalRect(offsetX + 177, offsetY, 177, 0, 35, 7 + this.workbench.availableUpgrades() * 18); + this.drawTexturedModalRect(offsetX + 177, offsetY + (7 + (this.workbench.availableUpgrades()) * 18), 177, 151, 35, 7); + } else if (this.workbench.availableUpgrades() <= 16) { + this.drawTexturedModalRect(offsetX + 177, offsetY, 177, 0, 35, 7 + 8 * 18); + this.drawTexturedModalRect(offsetX + 177, offsetY + (7 + (8) * 18), 177, 151, 35, 7); - final int dx = this.workbench.availableUpgrades() - 8; - this.drawTexturedModalRect( offsetX + 177 + 27, offsetY, 186, 0, 35 - 8, 7 + dx * 18 ); - if( dx == 8 ) - { - this.drawTexturedModalRect( offsetX + 177 + 27, offsetY + ( 7 + ( dx ) * 18 ), 186, 151, 35 - 8, 7 ); - } - else - { - this.drawTexturedModalRect( offsetX + 177 + 27 + 4, offsetY + ( 7 + ( dx ) * 18 ), 186 + 4, 151, 35 - 8, 7 ); - } - } - else - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 7 + 8 * 18 ); - this.drawTexturedModalRect( offsetX + 177, offsetY + ( 7 + ( 8 ) * 18 ), 177, 151, 35, 7 ); + final int dx = this.workbench.availableUpgrades() - 8; + this.drawTexturedModalRect(offsetX + 177 + 27, offsetY, 186, 0, 35 - 8, 7 + dx * 18); + if (dx == 8) { + this.drawTexturedModalRect(offsetX + 177 + 27, offsetY + (7 + (dx) * 18), 186, 151, 35 - 8, 7); + } else { + this.drawTexturedModalRect(offsetX + 177 + 27 + 4, offsetY + (7 + (dx) * 18), 186 + 4, 151, 35 - 8, 7); + } + } else { + this.drawTexturedModalRect(offsetX + 177, offsetY, 177, 0, 35, 7 + 8 * 18); + this.drawTexturedModalRect(offsetX + 177, offsetY + (7 + (8) * 18), 177, 151, 35, 7); - this.drawTexturedModalRect( offsetX + 177 + 27, offsetY, 186, 0, 35 - 8, 7 + 8 * 18 ); - this.drawTexturedModalRect( offsetX + 177 + 27, offsetY + ( 7 + ( 8 ) * 18 ), 186, 151, 35 - 8, 7 ); + this.drawTexturedModalRect(offsetX + 177 + 27, offsetY, 186, 0, 35 - 8, 7 + 8 * 18); + this.drawTexturedModalRect(offsetX + 177 + 27, offsetY + (7 + (8) * 18), 186, 151, 35 - 8, 7); - final int dx = this.workbench.availableUpgrades() - 16; - this.drawTexturedModalRect( offsetX + 177 + 27 + 18, offsetY, 186, 0, 35 - 8, 7 + dx * 18 ); - if( dx == 8 ) - { - this.drawTexturedModalRect( offsetX + 177 + 27 + 18, offsetY + ( 7 + ( dx ) * 18 ), 186, 151, 35 - 8, 7 ); - } - else - { - this.drawTexturedModalRect( offsetX + 177 + 27 + 18 + 4, offsetY + ( 7 + ( dx ) * 18 ), 186 + 4, 151, 35 - 8, 7 ); - } - } - } - if( this.hasToolbox() ) - { - this.drawTexturedModalRect( offsetX + 178, offsetY + this.ySize - 90, 178, 161, 68, 68 ); - } - } + final int dx = this.workbench.availableUpgrades() - 16; + this.drawTexturedModalRect(offsetX + 177 + 27 + 18, offsetY, 186, 0, 35 - 8, 7 + dx * 18); + if (dx == 8) { + this.drawTexturedModalRect(offsetX + 177 + 27 + 18, offsetY + (7 + (dx) * 18), 186, 151, 35 - 8, 7); + } else { + this.drawTexturedModalRect(offsetX + 177 + 27 + 18 + 4, offsetY + (7 + (dx) * 18), 186 + 4, 151, 35 - 8, 7); + } + } + } + if (this.hasToolbox()) { + this.drawTexturedModalRect(offsetX + 178, offsetY + this.ySize - 90, 178, 161, 68, 68); + } + } - @Override - protected void handleButtonVisibility() - { - this.copyMode.setState( this.workbench.getCopyMode() == CopyMode.CLEAR_ON_REMOVE ); + @Override + protected void handleButtonVisibility() { + this.copyMode.setState(this.workbench.getCopyMode() == CopyMode.CLEAR_ON_REMOVE); - boolean hasFuzzy = false; - final IItemHandler inv = this.workbench.getCellUpgradeInventory(); - for( int x = 0; x < inv.getSlots(); x++ ) - { - final ItemStack is = inv.getStackInSlot( x ); - if( !is.isEmpty() && is.getItem() instanceof IUpgradeModule ) - { - if( ( (IUpgradeModule) is.getItem() ).getType( is ) == Upgrades.FUZZY ) - { - hasFuzzy = true; - } - } - } - this.fuzzyMode.setVisibility( hasFuzzy ); - } + boolean hasFuzzy = false; + final IItemHandler inv = this.workbench.getCellUpgradeInventory(); + for (int x = 0; x < inv.getSlots(); x++) { + final ItemStack is = inv.getStackInSlot(x); + if (!is.isEmpty() && is.getItem() instanceof IUpgradeModule) { + if (((IUpgradeModule) is.getItem()).getType(is) == Upgrades.FUZZY) { + hasFuzzy = true; + } + } + } + this.fuzzyMode.setVisibility(hasFuzzy); + } - @Override - protected String getBackground() - { - return "guis/cellworkbench.png"; - } + @Override + protected String getBackground() { + return "guis/cellworkbench.png"; + } - @Override - protected boolean drawUpgrades() - { - return this.workbench.availableUpgrades() > 0; - } + @Override + protected boolean drawUpgrades() { + return this.workbench.availableUpgrades() > 0; + } - @Override - protected GuiText getName() - { - return GuiText.CellWorkbench; - } + @Override + protected GuiText getName() { + return GuiText.CellWorkbench; + } - @Override - protected void actionPerformed( final GuiButton btn ) - { - try - { - if( btn == this.copyMode ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "CellWorkbench.Action", "CopyMode" ) ); - } - else if( btn == this.partition ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "CellWorkbench.Action", "Partition" ) ); - } - else if( btn == this.clear ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "CellWorkbench.Action", "Clear" ) ); - } - else if( btn == this.fuzzyMode ) - { - final boolean backwards = Mouse.isButtonDown( 1 ); + @Override + protected void actionPerformed(final GuiButton btn) { + try { + if (btn == this.copyMode) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("CellWorkbench.Action", "CopyMode")); + } else if (btn == this.partition) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("CellWorkbench.Action", "Partition")); + } else if (btn == this.clear) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("CellWorkbench.Action", "Clear")); + } else if (btn == this.fuzzyMode) { + final boolean backwards = Mouse.isButtonDown(1); - FuzzyMode fz = (FuzzyMode) this.fuzzyMode.getCurrentValue(); - fz = Platform.rotateEnum( fz, backwards, Settings.FUZZY_MODE.getPossibleValues() ); + FuzzyMode fz = (FuzzyMode) this.fuzzyMode.getCurrentValue(); + fz = Platform.rotateEnum(fz, backwards, Settings.FUZZY_MODE.getPossibleValues()); - NetworkHandler.instance().sendToServer( new PacketValueConfig( "CellWorkbench.Fuzzy", fz.name() ) ); - } - else - { - super.actionPerformed( btn ); - } - } - catch( final IOException ignored ) - { - } - } + NetworkHandler.instance().sendToServer(new PacketValueConfig("CellWorkbench.Fuzzy", fz.name())); + } else { + super.actionPerformed(btn); + } + } catch (final IOException ignored) { + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiChest.java b/src/main/java/appeng/client/gui/implementations/GuiChest.java index 2c7c5e45b..dcfccda80 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiChest.java +++ b/src/main/java/appeng/client/gui/implementations/GuiChest.java @@ -19,11 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiTabButton; import appeng.container.implementations.ContainerChest; @@ -32,49 +27,46 @@ import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketSwitchGuis; import appeng.tile.storage.TileChest; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; + +import java.io.IOException; -public class GuiChest extends AEBaseGui -{ +public class GuiChest extends AEBaseGui { - private GuiTabButton priority; + private GuiTabButton priority; - public GuiChest( final InventoryPlayer inventoryPlayer, final TileChest te ) - { - super( new ContainerChest( inventoryPlayer, te ) ); - this.ySize = 166; - } + public GuiChest(final InventoryPlayer inventoryPlayer, final TileChest te) { + super(new ContainerChest(inventoryPlayer, te)); + this.ySize = 166; + } - @Override - protected void actionPerformed( final GuiButton par1GuiButton ) throws IOException - { - super.actionPerformed( par1GuiButton ); + @Override + protected void actionPerformed(final GuiButton par1GuiButton) throws IOException { + super.actionPerformed(par1GuiButton); - if( par1GuiButton == this.priority ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - } + if (par1GuiButton == this.priority) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender ) ); - } + this.buttonList.add(this.priority = new GuiTabButton(this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender)); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.Chest.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.Chest.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/chest.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/chest.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCondenser.java b/src/main/java/appeng/client/gui/implementations/GuiCondenser.java index 0d087f7b1..7f0c860f1 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCondenser.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCondenser.java @@ -19,13 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.config.Settings; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiImgButton; @@ -36,64 +29,62 @@ import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; import appeng.tile.misc.TileCondenser; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import org.lwjgl.input.Mouse; + +import java.io.IOException; -public class GuiCondenser extends AEBaseGui -{ +public class GuiCondenser extends AEBaseGui { - private final ContainerCondenser cvc; - private GuiProgressBar pb; - private GuiImgButton mode; + private final ContainerCondenser cvc; + private GuiProgressBar pb; + private GuiImgButton mode; - public GuiCondenser( final InventoryPlayer inventoryPlayer, final TileCondenser te ) - { - super( new ContainerCondenser( inventoryPlayer, te ) ); - this.cvc = (ContainerCondenser) this.inventorySlots; - this.ySize = 197; - } + public GuiCondenser(final InventoryPlayer inventoryPlayer, final TileCondenser te) { + super(new ContainerCondenser(inventoryPlayer, te)); + this.cvc = (ContainerCondenser) this.inventorySlots; + this.ySize = 197; + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - if( this.mode == btn ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( Settings.CONDENSER_OUTPUT, backwards ) ); - } - } + if (this.mode == btn) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(Settings.CONDENSER_OUTPUT, backwards)); + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.pb = new GuiProgressBar( this.cvc, "guis/condenser.png", 120 + this.guiLeft, 25 + this.guiTop, 178, 25, 6, 18, Direction.VERTICAL, GuiText.StoredEnergy - .getLocal() ); + this.pb = new GuiProgressBar(this.cvc, "guis/condenser.png", 120 + this.guiLeft, 25 + this.guiTop, 178, 25, 6, 18, Direction.VERTICAL, GuiText.StoredEnergy + .getLocal()); - this.mode = new GuiImgButton( 128 + this.guiLeft, 52 + this.guiTop, Settings.CONDENSER_OUTPUT, this.cvc.getOutput() ); + this.mode = new GuiImgButton(128 + this.guiLeft, 52 + this.guiTop, Settings.CONDENSER_OUTPUT, this.cvc.getOutput()); - this.buttonList.add( this.pb ); - this.buttonList.add( this.mode ); - } + this.buttonList.add(this.pb); + this.buttonList.add(this.mode); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.Condenser.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.Condenser.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); - this.mode.set( this.cvc.getOutput() ); - this.mode.setFillVar( String.valueOf( this.cvc.getOutput().requiredPower ) ); - } + this.mode.set(this.cvc.getOutput()); + this.mode.setFillVar(String.valueOf(this.cvc.getOutput().requiredPower)); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/condenser.png" ); + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/condenser.png"); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java b/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java index 5d2653d2f..f1d3a001c 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java @@ -19,13 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import appeng.parts.reporting.PartExpandedProcessingPatternTerminal; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.definitions.IParts; @@ -44,267 +37,229 @@ import appeng.core.sync.packets.PacketSwitchGuis; import appeng.helpers.Reflected; import appeng.helpers.WirelessTerminalGuiObject; import appeng.parts.reporting.PartCraftingTerminal; +import appeng.parts.reporting.PartExpandedProcessingPatternTerminal; import appeng.parts.reporting.PartPatternTerminal; import appeng.parts.reporting.PartTerminal; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; import org.lwjgl.input.Keyboard; +import java.io.IOException; -public class GuiCraftAmount extends AEBaseGui -{ - private GuiNumberBox amountToCraft; - private GuiTabButton originalGuiBtn; - private GuiButton next; +public class GuiCraftAmount extends AEBaseGui { + private GuiNumberBox amountToCraft; + private GuiTabButton originalGuiBtn; - private GuiButton plus1; - private GuiButton plus10; - private GuiButton plus100; - private GuiButton plus1000; - private GuiButton minus1; - private GuiButton minus10; - private GuiButton minus100; - private GuiButton minus1000; + private GuiButton next; - private GuiBridge originalGui; + private GuiButton plus1; + private GuiButton plus10; + private GuiButton plus100; + private GuiButton plus1000; + private GuiButton minus1; + private GuiButton minus10; + private GuiButton minus100; + private GuiButton minus1000; - @Reflected - public GuiCraftAmount( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( new ContainerCraftAmount( inventoryPlayer, te ) ); - } + private GuiBridge originalGui; - @Override - public void initGui() - { - super.initGui(); + @Reflected + public GuiCraftAmount(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(new ContainerCraftAmount(inventoryPlayer, te)); + } - final int a = AEConfig.instance().craftItemsByStackAmounts( 0 ); - final int b = AEConfig.instance().craftItemsByStackAmounts( 1 ); - final int c = AEConfig.instance().craftItemsByStackAmounts( 2 ); - final int d = AEConfig.instance().craftItemsByStackAmounts( 3 ); + @Override + public void initGui() { + super.initGui(); - this.buttonList.add( this.plus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 26, 22, 20, "+" + a ) ); - this.buttonList.add( this.plus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 26, 28, 20, "+" + b ) ); - this.buttonList.add( this.plus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 26, 32, 20, "+" + c ) ); - this.buttonList.add( this.plus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 26, 38, 20, "+" + d ) ); + final int a = AEConfig.instance().craftItemsByStackAmounts(0); + final int b = AEConfig.instance().craftItemsByStackAmounts(1); + final int c = AEConfig.instance().craftItemsByStackAmounts(2); + final int d = AEConfig.instance().craftItemsByStackAmounts(3); - this.buttonList.add( this.minus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 75, 22, 20, "-" + a ) ); - this.buttonList.add( this.minus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 75, 28, 20, "-" + b ) ); - this.buttonList.add( this.minus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 75, 32, 20, "-" + c ) ); - this.buttonList.add( this.minus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 75, 38, 20, "-" + d ) ); + this.buttonList.add(this.plus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 26, 22, 20, "+" + a)); + this.buttonList.add(this.plus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 26, 28, 20, "+" + b)); + this.buttonList.add(this.plus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 26, 32, 20, "+" + c)); + this.buttonList.add(this.plus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 26, 38, 20, "+" + d)); - this.buttonList.add( this.next = new GuiButton( 0, this.guiLeft + 128, this.guiTop + 51, 38, 20, GuiText.Next.getLocal() ) ); + this.buttonList.add(this.minus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 75, 22, 20, "-" + a)); + this.buttonList.add(this.minus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 75, 28, 20, "-" + b)); + this.buttonList.add(this.minus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 75, 32, 20, "-" + c)); + this.buttonList.add(this.minus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 75, 38, 20, "-" + d)); - ItemStack myIcon = null; - final Object target = ( (AEBaseContainer) this.inventorySlots ).getTarget(); - final IDefinitions definitions = AEApi.instance().definitions(); - final IParts parts = definitions.parts(); + this.buttonList.add(this.next = new GuiButton(0, this.guiLeft + 128, this.guiTop + 51, 38, 20, GuiText.Next.getLocal())); - if( target instanceof WirelessTerminalGuiObject ) - { - myIcon = definitions.items().wirelessTerminal().maybeStack( 1 ).orElse( myIcon ); + ItemStack myIcon = null; + final Object target = ((AEBaseContainer) this.inventorySlots).getTarget(); + final IDefinitions definitions = AEApi.instance().definitions(); + final IParts parts = definitions.parts(); - this.originalGui = GuiBridge.GUI_WIRELESS_TERM; - } + if (target instanceof WirelessTerminalGuiObject) { + myIcon = definitions.items().wirelessTerminal().maybeStack(1).orElse(myIcon); - if( target instanceof PartTerminal ) - { - myIcon = parts.terminal().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - this.originalGui = GuiBridge.GUI_ME; - } + this.originalGui = GuiBridge.GUI_WIRELESS_TERM; + } - if( target instanceof PartCraftingTerminal ) - { - myIcon = parts.craftingTerminal().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; - } + if (target instanceof PartTerminal) { + myIcon = parts.terminal().maybeStack(1).orElse(ItemStack.EMPTY); + this.originalGui = GuiBridge.GUI_ME; + } - if( target instanceof PartPatternTerminal ) - { - myIcon = parts.patternTerminal().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; - } + if (target instanceof PartCraftingTerminal) { + myIcon = parts.craftingTerminal().maybeStack(1).orElse(ItemStack.EMPTY); + this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; + } - if( target instanceof PartExpandedProcessingPatternTerminal ) - { - myIcon = parts.expandedProcessingPatternTerminal().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - this.originalGui = GuiBridge.GUI_EXPANDED_PROCESSING_PATTERN_TERMINAL; - } + if (target instanceof PartPatternTerminal) { + myIcon = parts.patternTerminal().maybeStack(1).orElse(ItemStack.EMPTY); + this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; + } - if( this.originalGui != null && !myIcon.isEmpty() ) - { - this.buttonList.add( this.originalGuiBtn = new GuiTabButton( this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), this.itemRender ) ); - } + if (target instanceof PartExpandedProcessingPatternTerminal) { + myIcon = parts.expandedProcessingPatternTerminal().maybeStack(1).orElse(ItemStack.EMPTY); + this.originalGui = GuiBridge.GUI_EXPANDED_PROCESSING_PATTERN_TERMINAL; + } - this.amountToCraft = new GuiNumberBox( this.fontRenderer, this.guiLeft + 62, this.guiTop + 57, 59, this.fontRenderer.FONT_HEIGHT, Integer.class ); - this.amountToCraft.setEnableBackgroundDrawing( false ); - this.amountToCraft.setMaxStringLength( 16 ); - this.amountToCraft.setTextColor( 0xFFFFFF ); - this.amountToCraft.setVisible( true ); - this.amountToCraft.setFocused( true ); - this.amountToCraft.setText( "1" ); - this.amountToCraft.setSelectionPos( 0 ); - } + if (this.originalGui != null && !myIcon.isEmpty()) { + this.buttonList.add(this.originalGuiBtn = new GuiTabButton(this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), this.itemRender)); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( GuiText.SelectAmount.getLocal(), 8, 6, 4210752 ); - } + this.amountToCraft = new GuiNumberBox(this.fontRenderer, this.guiLeft + 62, this.guiTop + 57, 59, this.fontRenderer.FONT_HEIGHT, Integer.class); + this.amountToCraft.setEnableBackgroundDrawing(false); + this.amountToCraft.setMaxStringLength(16); + this.amountToCraft.setTextColor(0xFFFFFF); + this.amountToCraft.setVisible(true); + this.amountToCraft.setFocused(true); + this.amountToCraft.setText("1"); + this.amountToCraft.setSelectionPos(0); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.next.displayString = isShiftKeyDown() ? GuiText.Start.getLocal() : GuiText.Next.getLocal(); + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(GuiText.SelectAmount.getLocal(), 8, 6, 4210752); + } - this.bindTexture( "guis/craft_amt.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.next.displayString = isShiftKeyDown() ? GuiText.Start.getLocal() : GuiText.Next.getLocal(); - try - { - long amt = Long.parseLong( this.amountToCraft.getText() ); - this.next.enabled = ( !this.amountToCraft.getText().isEmpty() && amt > 0 ); - } - catch( final NumberFormatException e ) - { - this.next.enabled = false; - } + this.bindTexture("guis/craft_amt.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); - this.amountToCraft.drawTextBox(); - } + try { + long amt = Long.parseLong(this.amountToCraft.getText()); + this.next.enabled = (!this.amountToCraft.getText().isEmpty() && amt > 0); + } catch (final NumberFormatException e) { + this.next.enabled = false; + } - @Override - protected void keyTyped( final char character, final int key ) throws IOException - { - if( !this.checkHotbarKeys( key ) ) - { - if( key == Keyboard.KEY_RETURN || key == Keyboard.KEY_NUMPADENTER ) - { - this.actionPerformed( this.next ); - } - if( ( key == 211 || key == 205 || key == 203 || key == 14 || character == '-' || Character.isDigit( character ) ) && this.amountToCraft - .textboxKeyTyped( character, key ) ) - { - try - { - String out = this.amountToCraft.getText(); + this.amountToCraft.drawTextBox(); + } - boolean fixed = false; - while ( out.startsWith( "0" ) && out.length() > 1 ) - { - out = out.substring( 1 ); - fixed = true; - } + @Override + protected void keyTyped(final char character, final int key) throws IOException { + if (!this.checkHotbarKeys(key)) { + if (key == Keyboard.KEY_RETURN || key == Keyboard.KEY_NUMPADENTER) { + this.actionPerformed(this.next); + } + if ((key == 211 || key == 205 || key == 203 || key == 14 || character == '-' || Character.isDigit(character)) && this.amountToCraft + .textboxKeyTyped(character, key)) { + try { + String out = this.amountToCraft.getText(); - if( fixed ) - { - this.amountToCraft.setText( out ); - } + boolean fixed = false; + while (out.startsWith("0") && out.length() > 1) { + out = out.substring(1); + fixed = true; + } - if( out.isEmpty() ) - { - out = "0"; - } + if (fixed) { + this.amountToCraft.setText(out); + } - final long result = Long.parseLong( out ); - if( result < 0 ) - { - this.amountToCraft.setText( "1" ); - } - } - catch( final NumberFormatException e ) - { - // :P - } - } - else - { - super.keyTyped( character, key ); - } - } - } + if (out.isEmpty()) { + out = "0"; + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + final long result = Long.parseLong(out); + if (result < 0) { + this.amountToCraft.setText("1"); + } + } catch (final NumberFormatException e) { + // :P + } + } else { + super.keyTyped(character, key); + } + } + } - try - { + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - if( btn == this.originalGuiBtn ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( this.originalGui ) ); - } + try { - if( btn == this.next ) - { - NetworkHandler.instance().sendToServer( new PacketCraftRequest( Integer.parseInt( this.amountToCraft.getText() ), isShiftKeyDown() ) ); - } - } - catch( final NumberFormatException e ) - { - // nope.. - this.amountToCraft.setText( "1" ); - } + if (btn == this.originalGuiBtn) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(this.originalGui)); + } - final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; - final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + if (btn == this.next) { + NetworkHandler.instance().sendToServer(new PacketCraftRequest(Integer.parseInt(this.amountToCraft.getText()), isShiftKeyDown())); + } + } catch (final NumberFormatException e) { + // nope.. + this.amountToCraft.setText("1"); + } - if( isPlus || isMinus ) - { - this.addQty( this.getQty( btn ) ); - } - } + final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; + final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; - private void addQty( final int i ) - { - try - { - String out = this.amountToCraft.getText(); + if (isPlus || isMinus) { + this.addQty(this.getQty(btn)); + } + } - boolean fixed = false; - while ( out.startsWith( "0" ) && out.length() > 1 ) - { - out = out.substring( 1 ); - fixed = true; - } + private void addQty(final int i) { + try { + String out = this.amountToCraft.getText(); - if( fixed ) - { - this.amountToCraft.setText( out ); - } + boolean fixed = false; + while (out.startsWith("0") && out.length() > 1) { + out = out.substring(1); + fixed = true; + } - if( out.isEmpty() ) - { - out = "0"; - } + if (fixed) { + this.amountToCraft.setText(out); + } - long result = Integer.parseInt( out ); + if (out.isEmpty()) { + out = "0"; + } - if( result == 1 && i > 1 ) - { - result = 0; - } + long result = Integer.parseInt(out); - result += i; - if( result < 1 ) - { - result = 1; - } + if (result == 1 && i > 1) { + result = 0; + } - out = Long.toString( result ); - Integer.parseInt( out ); - this.amountToCraft.setText( out ); - } - catch( final NumberFormatException e ) - { - // :P - } - } + result += i; + if (result < 1) { + result = 1; + } - protected String getBackground() - { - return "guis/craftAmt.png"; - } + out = Long.toString(result); + Integer.parseInt(out); + this.amountToCraft.setText(out); + } catch (final NumberFormatException e) { + // :P + } + } + + protected String getBackground() { + return "guis/craftAmt.png"; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java b/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java index 1e3b5e955..c379e4666 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java @@ -19,23 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import appeng.parts.reporting.PartExpandedProcessingPatternTerminal; -import com.google.common.base.Joiner; - -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.api.storage.ITerminalHost; import appeng.api.storage.channels.IItemStorageChannel; @@ -52,551 +35,475 @@ import appeng.core.sync.packets.PacketSwitchGuis; import appeng.core.sync.packets.PacketValueConfig; import appeng.helpers.WirelessTerminalGuiObject; import appeng.parts.reporting.PartCraftingTerminal; +import appeng.parts.reporting.PartExpandedProcessingPatternTerminal; import appeng.parts.reporting.PartPatternTerminal; import appeng.parts.reporting.PartTerminal; import appeng.util.Platform; +import com.google.common.base.Joiner; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; +import java.io.IOException; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; -public class GuiCraftConfirm extends AEBaseGui -{ - private final ContainerCraftConfirm ccc; +public class GuiCraftConfirm extends AEBaseGui { - private final int rows = 5; + private final ContainerCraftConfirm ccc; - private final IItemList storage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - private final IItemList pending = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - private final IItemList missing = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - - private final List visual = new ArrayList<>(); + private final int rows = 5; - private GuiBridge OriginalGui; - private GuiButton cancel; - private GuiButton start; - private GuiButton selectCPU; - private int tooltip = -1; - - public GuiCraftConfirm( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( new ContainerCraftConfirm( inventoryPlayer, te ) ); - this.xSize = 238; - this.ySize = 206; + private final IItemList storage = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + private final IItemList pending = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + private final IItemList missing = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); - final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - - this.ccc = (ContainerCraftConfirm) this.inventorySlots; - - if( te instanceof WirelessTerminalGuiObject ) - { - this.OriginalGui = GuiBridge.GUI_WIRELESS_TERM; - } - - if( te instanceof PartTerminal ) - { - this.OriginalGui = GuiBridge.GUI_ME; - } - - if( te instanceof PartCraftingTerminal ) - { - this.OriginalGui = GuiBridge.GUI_CRAFTING_TERMINAL; - } - - if( te instanceof PartPatternTerminal ) - { - this.OriginalGui = GuiBridge.GUI_PATTERN_TERMINAL; - } - - if( te instanceof PartExpandedProcessingPatternTerminal ) - { - this.OriginalGui = GuiBridge.GUI_EXPANDED_PROCESSING_PATTERN_TERMINAL; - } - } - - boolean isAutoStart() - { - return ( (ContainerCraftConfirm) this.inventorySlots ).isAutoStart(); - } - - @Override - public void initGui() - { - super.initGui(); - - this.start = new GuiButton( 0, this.guiLeft + 162, this.guiTop + this.ySize - 25, 50, 20, GuiText.Start.getLocal() ); - this.start.enabled = false; - this.buttonList.add( this.start ); - - this.selectCPU = new GuiButton( 0, this.guiLeft + ( 219 - 180 ) / 2, this.guiTop + this.ySize - 68, 180, 20, GuiText.CraftingCPU - .getLocal() + ": " + GuiText.Automatic ); - this.selectCPU.enabled = false; - this.buttonList.add( this.selectCPU ); - - if( this.OriginalGui != null ) - { - this.cancel = new GuiButton( 0, this.guiLeft + 6, this.guiTop + this.ySize - 25, 50, 20, GuiText.Cancel.getLocal() ); - } - - this.buttonList.add( this.cancel ); - } - - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - this.updateCPUButtonText(); - - this.start.enabled = !( this.ccc.hasNoCPU() || this.isSimulation() ); - this.selectCPU.enabled = !this.isSimulation(); - - final int gx = ( this.width - this.xSize ) / 2; - final int gy = ( this.height - this.ySize ) / 2; - - this.tooltip = -1; - - final int offY = 23; - int y = 0; - int x = 0; - for( int z = 0; z <= 4 * 5; z++ ) - { - final int minX = gx + 9 + x * 67; - final int minY = gy + 22 + y * offY; - - if( minX < mouseX && minX + 67 > mouseX ) - { - if( minY < mouseY && minY + offY - 2 > mouseY ) - { - this.tooltip = z; - break; - } - } - - x++; - - if( x > 2 ) - { - y++; - x = 0; - } - } - - super.drawScreen( mouseX, mouseY, btn ); - } - - private void updateCPUButtonText() - { - String btnTextText = GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic.getLocal(); - if( this.ccc.getSelectedCpu() >= 0 )// && status.selectedCpu < status.cpus.size() ) - { - if( this.ccc.getName().length() > 0 ) - { - final String name = this.ccc.getName().substring( 0, Math.min( 20, this.ccc.getName().length() ) ); - btnTextText = GuiText.CraftingCPU.getLocal() + ": " + name; - } - else - { - btnTextText = GuiText.CraftingCPU.getLocal() + ": #" + this.ccc.getSelectedCpu(); - } - } - - if( this.ccc.hasNoCPU() ) - { - btnTextText = GuiText.NoCraftingCPUs.getLocal(); - } - - this.selectCPU.displayString = btnTextText; - } - - private boolean isSimulation() - { - return ( (ContainerCraftConfirm) this.inventorySlots ).isSimulation(); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - final long BytesUsed = this.ccc.getUsedBytes(); - final String byteUsed = NumberFormat.getInstance().format( BytesUsed ); - final String Add = BytesUsed > 0 ? ( byteUsed + ' ' + GuiText.BytesUsed.getLocal() ) : GuiText.CalculatingWait.getLocal(); - this.fontRenderer.drawString( GuiText.CraftingPlan.getLocal() + " - " + Add, 8, 7, 4210752 ); - - String dsp = null; - - if( this.isSimulation() ) - { - dsp = GuiText.Simulation.getLocal(); - } - else - { - dsp = this.ccc.getCpuAvailableBytes() > 0 ? ( GuiText.Bytes.getLocal() + ": " + this.ccc.getCpuAvailableBytes() + " : " + GuiText.CoProcessors - .getLocal() + ": " + this.ccc.getCpuCoProcessors() ) : GuiText.Bytes.getLocal() + ": N/A : " + GuiText.CoProcessors.getLocal() + ": N/A"; - } - - final int offset = ( 219 - this.fontRenderer.getStringWidth( dsp ) ) / 2; - this.fontRenderer.drawString( dsp, offset, 165, 4210752 ); - - final int sectionLength = 67; - - int x = 0; - int y = 0; - final int xo = 9; - final int yo = 22; - final int viewStart = this.getScrollBar().getCurrentScroll() * 3; - final int viewEnd = viewStart + 3 * this.rows; - - String dspToolTip = ""; - final List lineList = new ArrayList<>(); - int toolPosX = 0; - int toolPosY = 0; - - final int offY = 23; - - for( int z = viewStart; z < Math.min( viewEnd, this.visual.size() ); z++ ) - { - final IAEItemStack refStack = this.visual.get( z );// repo.getReferenceItem( z ); - if( refStack != null ) - { - GlStateManager.pushMatrix(); - GlStateManager.scale( 0.5, 0.5, 0.5 ); - - final IAEItemStack stored = this.storage.findPrecise( refStack ); - final IAEItemStack pendingStack = this.pending.findPrecise( refStack ); - final IAEItemStack missingStack = this.missing.findPrecise( refStack ); - - int lines = 0; - - if( stored != null && stored.getStackSize() > 0 ) - { - lines++; - } - if( missingStack != null && missingStack.getStackSize() > 0 ) - { - lines++; - } - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - lines++; - } - - final int negY = ( ( lines - 1 ) * 5 ) / 2; - int downY = 0; - - if( stored != null && stored.getStackSize() > 0 ) - { - String str = Long.toString( stored.getStackSize() ); - if( stored.getStackSize() >= 10000 ) - { - str = Long.toString( stored.getStackSize() / 1000 ) + 'k'; - } - if( stored.getStackSize() >= 10000000 ) - { - str = Long.toString( stored.getStackSize() / 1000000 ) + 'm'; - } - - str = GuiText.FromStorage.getLocal() + ": " + str; - final int w = 4 + this.fontRenderer.getStringWidth( str ); - this.fontRenderer.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), - ( y * offY + yo + 6 - negY + downY ) * 2, 4210752 ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.FromStorage.getLocal() + ": " + Long.toString( stored.getStackSize() ) ); - } - - downY += 5; - } - - boolean red = false; - if( missingStack != null && missingStack.getStackSize() > 0 ) - { - String str = Long.toString( missingStack.getStackSize() ); - if( missingStack.getStackSize() >= 10000 ) - { - str = Long.toString( missingStack.getStackSize() / 1000 ) + 'k'; - } - if( missingStack.getStackSize() >= 10000000 ) - { - str = Long.toString( missingStack.getStackSize() / 1000000 ) + 'm'; - } - - str = GuiText.Missing.getLocal() + ": " + str; - final int w = 4 + this.fontRenderer.getStringWidth( str ); - this.fontRenderer.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), - ( y * offY + yo + 6 - negY + downY ) * 2, 4210752 ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.Missing.getLocal() + ": " + Long.toString( missingStack.getStackSize() ) ); - } - - red = true; - downY += 5; - } - - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - String str = Long.toString( pendingStack.getStackSize() ); - if( pendingStack.getStackSize() >= 10000 ) - { - str = Long.toString( pendingStack.getStackSize() / 1000 ) + 'k'; - } - if( pendingStack.getStackSize() >= 10000000 ) - { - str = Long.toString( pendingStack.getStackSize() / 1000000 ) + 'm'; - } - - str = GuiText.ToCraft.getLocal() + ": " + str; - final int w = 4 + this.fontRenderer.getStringWidth( str ); - this.fontRenderer.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), - ( y * offY + yo + 6 - negY + downY ) * 2, 4210752 ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.ToCraft.getLocal() + ": " + Long.toString( pendingStack.getStackSize() ) ); - } - } - - GlStateManager.popMatrix(); - final int posX = x * ( 1 + sectionLength ) + xo + sectionLength - 19; - final int posY = y * offY + yo; - - final ItemStack is = refStack.asItemStackRepresentation(); - - if( this.tooltip == z - viewStart ) - { - dspToolTip = Platform.getItemDisplayName( refStack ); - - if( lineList.size() > 0 ) - { - dspToolTip = dspToolTip + '\n' + Joiner.on( "\n" ).join( lineList ); - } - - toolPosX = x * ( 1 + sectionLength ) + xo + sectionLength - 8; - toolPosY = y * offY + yo; - } - - this.drawItem( posX, posY, is ); - - if( red ) - { - final int startX = x * ( 1 + sectionLength ) + xo; - final int startY = posY - 4; - drawRect( startX, startY, startX + sectionLength, startY + offY, 0x1AFF0000 ); - } - - x++; - - if( x > 2 ) - { - y++; - x = 0; - } - } - } - - if( this.tooltip >= 0 && !dspToolTip.isEmpty() ) - { - this.drawTooltip( toolPosX, toolPosY + 10, dspToolTip ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.setScrollBar(); - this.bindTexture( "guis/craftingreport.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - private void setScrollBar() - { - final int size = this.visual.size(); - - this.getScrollBar().setTop( 19 ).setLeft( 218 ).setHeight( 114 ); - this.getScrollBar().setRange( 0, ( size + 2 ) / 3 - this.rows, 1 ); - } - - public void postUpdate( final List list, final byte ref ) - { - switch ( ref ) - { - case 0: - for( final IAEItemStack l : list ) - { - this.handleInput( this.storage, l ); - } - break; - - case 1: - for( final IAEItemStack l : list ) - { - this.handleInput( this.pending, l ); - } - break; - - case 2: - for( final IAEItemStack l : list ) - { - this.handleInput( this.missing, l ); - } - break; - } - - for( final IAEItemStack l : list ) - { - final long amt = this.getTotal( l ); - - if( amt <= 0 ) - { - this.deleteVisualStack( l ); - } - else - { - final IAEItemStack is = this.findVisualStack( l ); - is.setStackSize( amt ); - } - } - - this.setScrollBar(); - } - - private void handleInput( final IItemList s, final IAEItemStack l ) - { - IAEItemStack a = s.findPrecise( l ); - - if( l.getStackSize() <= 0 ) - { - if( a != null ) - { - a.reset(); - } - } - else - { - if( a == null ) - { - s.add( l.copy() ); - a = s.findPrecise( l ); - } - - if( a != null ) - { - a.setStackSize( l.getStackSize() ); - } - } - } - - private long getTotal( final IAEItemStack is ) - { - final IAEItemStack a = this.storage.findPrecise( is ); - final IAEItemStack c = this.pending.findPrecise( is ); - final IAEItemStack m = this.missing.findPrecise( is ); - - long total = 0; - - if( a != null ) - { - total += a.getStackSize(); - } - - if( c != null ) - { - total += c.getStackSize(); - } - - if( m != null ) - { - total += m.getStackSize(); - } - - return total; - } - - private void deleteVisualStack( final IAEItemStack l ) - { - final Iterator i = this.visual.iterator(); - while ( i.hasNext() ) - { - final IAEItemStack o = i.next(); - if( o.equals( l ) ) - { - i.remove(); - return; - } - } - } - - private IAEItemStack findVisualStack( final IAEItemStack l ) - { - for( final IAEItemStack o : this.visual ) - { - if( o.equals( l ) ) - { - return o; - } - } - - final IAEItemStack stack = l.copy(); - this.visual.add( stack ); - return stack; - } - - @Override - protected void keyTyped( final char character, final int key ) throws IOException - { - if( !this.checkHotbarKeys( key ) ) - { - if( key == Keyboard.KEY_RETURN || key == Keyboard.KEY_NUMPADENTER ) - { - this.actionPerformed( this.start ); - } - super.keyTyped( character, key ); - } - } - - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); - - final boolean backwards = Mouse.isButtonDown( 1 ); - - if( btn == this.selectCPU ) - { - try - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "Terminal.Cpu", backwards ? "Prev" : "Next" ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - - if( btn == this.cancel ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( this.OriginalGui ) ); - } - - if( btn == this.start ) - { - try - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "Terminal.Start", "Start" ) ); - } - catch( final Throwable e ) - { - AELog.debug( e ); - } - } - } - - public List getVisual() - { - return visual; - } - - public int getDisplayedRows() - { - return this.rows; - } + private final List visual = new ArrayList<>(); + + private GuiBridge OriginalGui; + private GuiButton cancel; + private GuiButton start; + private GuiButton selectCPU; + private int tooltip = -1; + + public GuiCraftConfirm(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(new ContainerCraftConfirm(inventoryPlayer, te)); + this.xSize = 238; + this.ySize = 206; + + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar(scrollbar); + + this.ccc = (ContainerCraftConfirm) this.inventorySlots; + + if (te instanceof WirelessTerminalGuiObject) { + this.OriginalGui = GuiBridge.GUI_WIRELESS_TERM; + } + + if (te instanceof PartTerminal) { + this.OriginalGui = GuiBridge.GUI_ME; + } + + if (te instanceof PartCraftingTerminal) { + this.OriginalGui = GuiBridge.GUI_CRAFTING_TERMINAL; + } + + if (te instanceof PartPatternTerminal) { + this.OriginalGui = GuiBridge.GUI_PATTERN_TERMINAL; + } + + if (te instanceof PartExpandedProcessingPatternTerminal) { + this.OriginalGui = GuiBridge.GUI_EXPANDED_PROCESSING_PATTERN_TERMINAL; + } + } + + boolean isAutoStart() { + return ((ContainerCraftConfirm) this.inventorySlots).isAutoStart(); + } + + @Override + public void initGui() { + super.initGui(); + + this.start = new GuiButton(0, this.guiLeft + 162, this.guiTop + this.ySize - 25, 50, 20, GuiText.Start.getLocal()); + this.start.enabled = false; + this.buttonList.add(this.start); + + this.selectCPU = new GuiButton(0, this.guiLeft + (219 - 180) / 2, this.guiTop + this.ySize - 68, 180, 20, GuiText.CraftingCPU + .getLocal() + ": " + GuiText.Automatic); + this.selectCPU.enabled = false; + this.buttonList.add(this.selectCPU); + + if (this.OriginalGui != null) { + this.cancel = new GuiButton(0, this.guiLeft + 6, this.guiTop + this.ySize - 25, 50, 20, GuiText.Cancel.getLocal()); + } + + this.buttonList.add(this.cancel); + } + + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + this.updateCPUButtonText(); + + this.start.enabled = !(this.ccc.hasNoCPU() || this.isSimulation()); + this.selectCPU.enabled = !this.isSimulation(); + + final int gx = (this.width - this.xSize) / 2; + final int gy = (this.height - this.ySize) / 2; + + this.tooltip = -1; + + final int offY = 23; + int y = 0; + int x = 0; + for (int z = 0; z <= 4 * 5; z++) { + final int minX = gx + 9 + x * 67; + final int minY = gy + 22 + y * offY; + + if (minX < mouseX && minX + 67 > mouseX) { + if (minY < mouseY && minY + offY - 2 > mouseY) { + this.tooltip = z; + break; + } + } + + x++; + + if (x > 2) { + y++; + x = 0; + } + } + + super.drawScreen(mouseX, mouseY, btn); + } + + private void updateCPUButtonText() { + String btnTextText = GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic.getLocal(); + if (this.ccc.getSelectedCpu() >= 0)// && status.selectedCpu < status.cpus.size() ) + { + if (this.ccc.getName().length() > 0) { + final String name = this.ccc.getName().substring(0, Math.min(20, this.ccc.getName().length())); + btnTextText = GuiText.CraftingCPU.getLocal() + ": " + name; + } else { + btnTextText = GuiText.CraftingCPU.getLocal() + ": #" + this.ccc.getSelectedCpu(); + } + } + + if (this.ccc.hasNoCPU()) { + btnTextText = GuiText.NoCraftingCPUs.getLocal(); + } + + this.selectCPU.displayString = btnTextText; + } + + private boolean isSimulation() { + return ((ContainerCraftConfirm) this.inventorySlots).isSimulation(); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + final long BytesUsed = this.ccc.getUsedBytes(); + final String byteUsed = NumberFormat.getInstance().format(BytesUsed); + final String Add = BytesUsed > 0 ? (byteUsed + ' ' + GuiText.BytesUsed.getLocal()) : GuiText.CalculatingWait.getLocal(); + this.fontRenderer.drawString(GuiText.CraftingPlan.getLocal() + " - " + Add, 8, 7, 4210752); + + String dsp = null; + + if (this.isSimulation()) { + dsp = GuiText.Simulation.getLocal(); + } else { + dsp = this.ccc.getCpuAvailableBytes() > 0 ? (GuiText.Bytes.getLocal() + ": " + this.ccc.getCpuAvailableBytes() + " : " + GuiText.CoProcessors + .getLocal() + ": " + this.ccc.getCpuCoProcessors()) : GuiText.Bytes.getLocal() + ": N/A : " + GuiText.CoProcessors.getLocal() + ": N/A"; + } + + final int offset = (219 - this.fontRenderer.getStringWidth(dsp)) / 2; + this.fontRenderer.drawString(dsp, offset, 165, 4210752); + + final int sectionLength = 67; + + int x = 0; + int y = 0; + final int xo = 9; + final int yo = 22; + final int viewStart = this.getScrollBar().getCurrentScroll() * 3; + final int viewEnd = viewStart + 3 * this.rows; + + String dspToolTip = ""; + final List lineList = new ArrayList<>(); + int toolPosX = 0; + int toolPosY = 0; + + final int offY = 23; + + for (int z = viewStart; z < Math.min(viewEnd, this.visual.size()); z++) { + final IAEItemStack refStack = this.visual.get(z);// repo.getReferenceItem( z ); + if (refStack != null) { + GlStateManager.pushMatrix(); + GlStateManager.scale(0.5, 0.5, 0.5); + + final IAEItemStack stored = this.storage.findPrecise(refStack); + final IAEItemStack pendingStack = this.pending.findPrecise(refStack); + final IAEItemStack missingStack = this.missing.findPrecise(refStack); + + int lines = 0; + + if (stored != null && stored.getStackSize() > 0) { + lines++; + } + if (missingStack != null && missingStack.getStackSize() > 0) { + lines++; + } + if (pendingStack != null && pendingStack.getStackSize() > 0) { + lines++; + } + + final int negY = ((lines - 1) * 5) / 2; + int downY = 0; + + if (stored != null && stored.getStackSize() > 0) { + String str = Long.toString(stored.getStackSize()); + if (stored.getStackSize() >= 10000) { + str = Long.toString(stored.getStackSize() / 1000) + 'k'; + } + if (stored.getStackSize() >= 10000000) { + str = Long.toString(stored.getStackSize() / 1000000) + 'm'; + } + + str = GuiText.FromStorage.getLocal() + ": " + str; + final int w = 4 + this.fontRenderer.getStringWidth(str); + this.fontRenderer.drawString(str, (int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2), + (y * offY + yo + 6 - negY + downY) * 2, 4210752); + + if (this.tooltip == z - viewStart) { + lineList.add(GuiText.FromStorage.getLocal() + ": " + stored.getStackSize()); + } + + downY += 5; + } + + boolean red = false; + if (missingStack != null && missingStack.getStackSize() > 0) { + String str = Long.toString(missingStack.getStackSize()); + if (missingStack.getStackSize() >= 10000) { + str = Long.toString(missingStack.getStackSize() / 1000) + 'k'; + } + if (missingStack.getStackSize() >= 10000000) { + str = Long.toString(missingStack.getStackSize() / 1000000) + 'm'; + } + + str = GuiText.Missing.getLocal() + ": " + str; + final int w = 4 + this.fontRenderer.getStringWidth(str); + this.fontRenderer.drawString(str, (int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2), + (y * offY + yo + 6 - negY + downY) * 2, 4210752); + + if (this.tooltip == z - viewStart) { + lineList.add(GuiText.Missing.getLocal() + ": " + missingStack.getStackSize()); + } + + red = true; + downY += 5; + } + + if (pendingStack != null && pendingStack.getStackSize() > 0) { + String str = Long.toString(pendingStack.getStackSize()); + if (pendingStack.getStackSize() >= 10000) { + str = Long.toString(pendingStack.getStackSize() / 1000) + 'k'; + } + if (pendingStack.getStackSize() >= 10000000) { + str = Long.toString(pendingStack.getStackSize() / 1000000) + 'm'; + } + + str = GuiText.ToCraft.getLocal() + ": " + str; + final int w = 4 + this.fontRenderer.getStringWidth(str); + this.fontRenderer.drawString(str, (int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2), + (y * offY + yo + 6 - negY + downY) * 2, 4210752); + + if (this.tooltip == z - viewStart) { + lineList.add(GuiText.ToCraft.getLocal() + ": " + pendingStack.getStackSize()); + } + } + + GlStateManager.popMatrix(); + final int posX = x * (1 + sectionLength) + xo + sectionLength - 19; + final int posY = y * offY + yo; + + final ItemStack is = refStack.asItemStackRepresentation(); + + if (this.tooltip == z - viewStart) { + dspToolTip = Platform.getItemDisplayName(refStack); + + if (lineList.size() > 0) { + dspToolTip = dspToolTip + '\n' + Joiner.on("\n").join(lineList); + } + + toolPosX = x * (1 + sectionLength) + xo + sectionLength - 8; + toolPosY = y * offY + yo; + } + + this.drawItem(posX, posY, is); + + if (red) { + final int startX = x * (1 + sectionLength) + xo; + final int startY = posY - 4; + drawRect(startX, startY, startX + sectionLength, startY + offY, 0x1AFF0000); + } + + x++; + + if (x > 2) { + y++; + x = 0; + } + } + } + + if (this.tooltip >= 0 && !dspToolTip.isEmpty()) { + this.drawTooltip(toolPosX, toolPosY + 10, dspToolTip); + } + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.setScrollBar(); + this.bindTexture("guis/craftingreport.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } + + private void setScrollBar() { + final int size = this.visual.size(); + + this.getScrollBar().setTop(19).setLeft(218).setHeight(114); + this.getScrollBar().setRange(0, (size + 2) / 3 - this.rows, 1); + } + + public void postUpdate(final List list, final byte ref) { + switch (ref) { + case 0: + for (final IAEItemStack l : list) { + this.handleInput(this.storage, l); + } + break; + + case 1: + for (final IAEItemStack l : list) { + this.handleInput(this.pending, l); + } + break; + + case 2: + for (final IAEItemStack l : list) { + this.handleInput(this.missing, l); + } + break; + } + + for (final IAEItemStack l : list) { + final long amt = this.getTotal(l); + + if (amt <= 0) { + this.deleteVisualStack(l); + } else { + final IAEItemStack is = this.findVisualStack(l); + is.setStackSize(amt); + } + } + + this.setScrollBar(); + } + + private void handleInput(final IItemList s, final IAEItemStack l) { + IAEItemStack a = s.findPrecise(l); + + if (l.getStackSize() <= 0) { + if (a != null) { + a.reset(); + } + } else { + if (a == null) { + s.add(l.copy()); + a = s.findPrecise(l); + } + + if (a != null) { + a.setStackSize(l.getStackSize()); + } + } + } + + private long getTotal(final IAEItemStack is) { + final IAEItemStack a = this.storage.findPrecise(is); + final IAEItemStack c = this.pending.findPrecise(is); + final IAEItemStack m = this.missing.findPrecise(is); + + long total = 0; + + if (a != null) { + total += a.getStackSize(); + } + + if (c != null) { + total += c.getStackSize(); + } + + if (m != null) { + total += m.getStackSize(); + } + + return total; + } + + private void deleteVisualStack(final IAEItemStack l) { + final Iterator i = this.visual.iterator(); + while (i.hasNext()) { + final IAEItemStack o = i.next(); + if (o.equals(l)) { + i.remove(); + return; + } + } + } + + private IAEItemStack findVisualStack(final IAEItemStack l) { + for (final IAEItemStack o : this.visual) { + if (o.equals(l)) { + return o; + } + } + + final IAEItemStack stack = l.copy(); + this.visual.add(stack); + return stack; + } + + @Override + protected void keyTyped(final char character, final int key) throws IOException { + if (!this.checkHotbarKeys(key)) { + if (key == Keyboard.KEY_RETURN || key == Keyboard.KEY_NUMPADENTER) { + this.actionPerformed(this.start); + } + super.keyTyped(character, key); + } + } + + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); + + final boolean backwards = Mouse.isButtonDown(1); + + if (btn == this.selectCPU) { + try { + NetworkHandler.instance().sendToServer(new PacketValueConfig("Terminal.Cpu", backwards ? "Prev" : "Next")); + } catch (final IOException e) { + AELog.debug(e); + } + } + + if (btn == this.cancel) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(this.OriginalGui)); + } + + if (btn == this.start) { + try { + NetworkHandler.instance().sendToServer(new PacketValueConfig("Terminal.Start", "Start")); + } catch (final Throwable e) { + AELog.debug(e); + } + } + } + + public List getVisual() { + return visual; + } + + public int getDisplayedRows() { + return this.rows; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java b/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java index 6b0ff4bed..0cf30218b 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java @@ -19,21 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import com.google.common.base.Joiner; - -import org.apache.commons.lang3.time.DurationFormatUtils; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.api.config.SortDir; import appeng.api.config.SortOrder; @@ -53,454 +38,400 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; import appeng.util.Platform; import appeng.util.ReadableNumberConverter; - - -public class GuiCraftingCPU extends AEBaseGui implements ISortSource -{ - private static final int GUI_HEIGHT = 184; - private static final int GUI_WIDTH = 238; - - private static final int DISPLAYED_ROWS = 6; - - private static final int TEXT_COLOR = 0x404040; - private static final int BACKGROUND_ALPHA = 0x5A000000; - - private static final int SECTION_LENGTH = 67; - - private static final int SCROLLBAR_TOP = 19; - private static final int SCROLLBAR_LEFT = 218; - private static final int SCROLLBAR_HEIGHT = 137; - - private static final int CANCEL_LEFT_OFFSET = 163; - private static final int CANCEL_TOP_OFFSET = 25; - private static final int CANCEL_HEIGHT = 20; - private static final int CANCEL_WIDTH = 50; - - private static final int TITLE_TOP_OFFSET = 7; - private static final int TITLE_LEFT_OFFSET = 8; - - private static final int ITEMSTACK_LEFT_OFFSET = 9; - private static final int ITEMSTACK_TOP_OFFSET = 22; - - private final ContainerCraftingCPU craftingCpu; - - private IItemList storage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - private IItemList active = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - private IItemList pending = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - - private List visual = new ArrayList<>(); - private GuiButton cancel; - private int tooltip = -1; - - public GuiCraftingCPU( final InventoryPlayer inventoryPlayer, final Object te ) - { - this( new ContainerCraftingCPU( inventoryPlayer, te ) ); - } - - protected GuiCraftingCPU( final ContainerCraftingCPU container ) - { - super( container ); - this.craftingCpu = container; - this.ySize = GUI_HEIGHT; - this.xSize = GUI_WIDTH; - - final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - } - - public void clearItems() - { - this.storage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - this.active = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - this.pending = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - this.visual = new ArrayList<>(); - } - - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); - - if( this.cancel == btn ) - { - try - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "TileCrafting.Cancel", "Cancel" ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - - @Override - public void initGui() - { - super.initGui(); - this.setScrollBar(); - this.cancel = new GuiButton( 0, this.guiLeft + CANCEL_LEFT_OFFSET, this.guiTop + this.ySize - CANCEL_TOP_OFFSET, CANCEL_WIDTH, CANCEL_HEIGHT, GuiText.Cancel - .getLocal() ); - this.buttonList.add( this.cancel ); - } - - private void setScrollBar() - { - final int size = this.visual.size(); - - this.getScrollBar().setTop( SCROLLBAR_TOP ).setLeft( SCROLLBAR_LEFT ).setHeight( SCROLLBAR_HEIGHT ); - this.getScrollBar().setRange( 0, ( size + 2 ) / 3 - DISPLAYED_ROWS, 1 ); - } - - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - this.cancel.enabled = !this.visual.isEmpty(); - - final int gx = ( this.width - this.xSize ) / 2; - final int gy = ( this.height - this.ySize ) / 2; - - this.tooltip = -1; - - final int offY = 23; - int y = 0; - int x = 0; - for( int z = 0; z <= 4 * 5; z++ ) - { - final int minX = gx + 9 + x * 67; - final int minY = gy + 22 + y * offY; - - if( minX < mouseX && minX + 67 > mouseX ) - { - if( minY < mouseY && minY + offY - 2 > mouseY ) - { - this.tooltip = z; - break; - } - } - - x++; - - if( x > 2 ) - { - y++; - x = 0; - } - } - - super.drawScreen( mouseX, mouseY, btn ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - String title = this.getGuiDisplayName( GuiText.CraftingStatus.getLocal() ); - - if( this.craftingCpu.getEstimatedTime() > 0 && !this.visual.isEmpty() ) - { - final long etaInMilliseconds = TimeUnit.MILLISECONDS.convert( this.craftingCpu.getEstimatedTime(), TimeUnit.NANOSECONDS ); - final String etaTimeText = DurationFormatUtils.formatDuration( etaInMilliseconds, GuiText.ETAFormat.getLocal() ); - title += " - " + etaTimeText; - } - - this.fontRenderer.drawString( title, TITLE_LEFT_OFFSET, TITLE_TOP_OFFSET, TEXT_COLOR ); - - int x = 0; - int y = 0; - final int viewStart = this.getScrollBar().getCurrentScroll() * 3; - final int viewEnd = viewStart + 3 * 6; - - String dspToolTip = ""; - final List lineList = new ArrayList<>(); - int toolPosX = 0; - int toolPosY = 0; - - final int offY = 23; - - final ReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; - for( int z = viewStart; z < Math.min( viewEnd, this.visual.size() ); z++ ) - { - final IAEItemStack refStack = this.visual.get( z );// repo.getReferenceItem( z ); - if( refStack != null ) - { - GlStateManager.pushMatrix(); - GlStateManager.scale( 0.5, 0.5, 0.5 ); - - final IAEItemStack stored = this.storage.findPrecise( refStack ); - final IAEItemStack activeStack = this.active.findPrecise( refStack ); - final IAEItemStack pendingStack = this.pending.findPrecise( refStack ); - - int lines = 0; - - if( stored != null && stored.getStackSize() > 0 ) - { - lines++; - } - boolean active = false; - if( activeStack != null && activeStack.getStackSize() > 0 ) - { - lines++; - active = true; - } - boolean scheduled = false; - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - lines++; - scheduled = true; - } - - if( AEConfig.instance().isUseColoredCraftingStatus() && ( active || scheduled ) ) - { - final int bgColor = ( active ? AEColor.GREEN.blackVariant : AEColor.YELLOW.blackVariant ) | BACKGROUND_ALPHA; - final int startX = ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET ) * 2; - final int startY = ( ( y * offY + ITEMSTACK_TOP_OFFSET ) - 3 ) * 2; - drawRect( startX, startY, startX + ( SECTION_LENGTH * 2 ), startY + ( offY * 2 ) - 2, bgColor ); - } - - final int negY = ( ( lines - 1 ) * 5 ) / 2; - int downY = 0; - - if( stored != null && stored.getStackSize() > 0 ) - { - final String str = GuiText.Stored.getLocal() + ": " + converter.toWideReadableForm( stored.getStackSize() ); - final int w = 4 + this.fontRenderer.getStringWidth( str ); - this.fontRenderer.drawString( str, (int) ( ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - ( w * 0.5 ) ) * 2 ), - ( y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY ) * 2, TEXT_COLOR ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.Stored.getLocal() + ": " + Long.toString( stored.getStackSize() ) ); - } - - downY += 5; - } - - if( activeStack != null && activeStack.getStackSize() > 0 ) - { - final String str = GuiText.Crafting.getLocal() + ": " + converter.toWideReadableForm( activeStack.getStackSize() ); - final int w = 4 + this.fontRenderer.getStringWidth( str ); - - this.fontRenderer.drawString( str, (int) ( ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - ( w * 0.5 ) ) * 2 ), - ( y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY ) * 2, TEXT_COLOR ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.Crafting.getLocal() + ": " + Long.toString( activeStack.getStackSize() ) ); - } - - downY += 5; - } - - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - final String str = GuiText.Scheduled.getLocal() + ": " + converter.toWideReadableForm( pendingStack.getStackSize() ); - final int w = 4 + this.fontRenderer.getStringWidth( str ); - - this.fontRenderer.drawString( str, (int) ( ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - ( w * 0.5 ) ) * 2 ), - ( y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY ) * 2, TEXT_COLOR ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.Scheduled.getLocal() + ": " + Long.toString( pendingStack.getStackSize() ) ); - } - } - - GlStateManager.popMatrix(); - final int posX = x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19; - final int posY = y * offY + ITEMSTACK_TOP_OFFSET; - - final ItemStack is = refStack.asItemStackRepresentation(); - - if( this.tooltip == z - viewStart ) - { - dspToolTip = Platform.getItemDisplayName( refStack ); - - if( lineList.size() > 0 ) - { - dspToolTip = dspToolTip + '\n' + Joiner.on( "\n" ).join( lineList ); - } - - toolPosX = x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 8; - toolPosY = y * offY + ITEMSTACK_TOP_OFFSET; - } - - this.drawItem( posX, posY, is ); - - x++; - - if( x > 2 ) - { - y++; - x = 0; - } - } - } - - if( this.tooltip >= 0 && !dspToolTip.isEmpty() ) - { - this.drawTooltip( toolPosX, toolPosY + 10, dspToolTip ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/craftingcpu.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - public void postUpdate( final List list, final byte ref ) - { - switch( ref ) - { - case 0: - for( final IAEItemStack l : list ) - { - this.handleInput( this.storage, l ); - } - break; - - case 1: - for( final IAEItemStack l : list ) - { - this.handleInput( this.active, l ); - } - break; - - case 2: - for( final IAEItemStack l : list ) - { - this.handleInput( this.pending, l ); - } - break; - } - - for( final IAEItemStack l : list ) - { - final long amt = this.getTotal( l ); - - if( amt <= 0 ) - { - this.deleteVisualStack( l ); - } - else - { - final IAEItemStack is = this.findVisualStack( l ); - is.setStackSize( amt ); - } - } - - this.setScrollBar(); - } - - private void handleInput( final IItemList s, final IAEItemStack l ) - { - IAEItemStack a = s.findPrecise( l ); - - if( l.getStackSize() <= 0 ) - { - if( a != null ) - { - a.reset(); - } - } - else - { - if( a == null ) - { - s.add( l.copy() ); - a = s.findPrecise( l ); - } - - if( a != null ) - { - a.setStackSize( l.getStackSize() ); - } - } - } - - private long getTotal( final IAEItemStack is ) - { - final IAEItemStack a = this.storage.findPrecise( is ); - final IAEItemStack b = this.active.findPrecise( is ); - final IAEItemStack c = this.pending.findPrecise( is ); - - long total = 0; - - if( a != null ) - { - total += a.getStackSize(); - } - - if( b != null ) - { - total += b.getStackSize(); - } - - if( c != null ) - { - total += c.getStackSize(); - } - - return total; - } - - private void deleteVisualStack( final IAEItemStack l ) - { - final Iterator i = this.visual.iterator(); - - while( i.hasNext() ) - { - final IAEItemStack o = i.next(); - if( o.equals( l ) ) - { - i.remove(); - return; - } - } - } - - private IAEItemStack findVisualStack( final IAEItemStack l ) - { - for( final IAEItemStack o : this.visual ) - { - if( o.equals( l ) ) - { - return o; - } - } - - final IAEItemStack stack = l.copy(); - this.visual.add( stack ); - - return stack; - } - - @Override - public Enum getSortBy() - { - return SortOrder.NAME; - } - - @Override - public Enum getSortDir() - { - return SortDir.ASCENDING; - } - - @Override - public Enum getSortDisplay() - { - return ViewItems.ALL; - } - - public List getVisual() - { - return visual; - } - - public int getDisplayedRows() - { - return DISPLAYED_ROWS; - } +import com.google.common.base.Joiner; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import org.apache.commons.lang3.time.DurationFormatUtils; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.TimeUnit; + + +public class GuiCraftingCPU extends AEBaseGui implements ISortSource { + private static final int GUI_HEIGHT = 184; + private static final int GUI_WIDTH = 238; + + private static final int DISPLAYED_ROWS = 6; + + private static final int TEXT_COLOR = 0x404040; + private static final int BACKGROUND_ALPHA = 0x5A000000; + + private static final int SECTION_LENGTH = 67; + + private static final int SCROLLBAR_TOP = 19; + private static final int SCROLLBAR_LEFT = 218; + private static final int SCROLLBAR_HEIGHT = 137; + + private static final int CANCEL_LEFT_OFFSET = 163; + private static final int CANCEL_TOP_OFFSET = 25; + private static final int CANCEL_HEIGHT = 20; + private static final int CANCEL_WIDTH = 50; + + private static final int TITLE_TOP_OFFSET = 7; + private static final int TITLE_LEFT_OFFSET = 8; + + private static final int ITEMSTACK_LEFT_OFFSET = 9; + private static final int ITEMSTACK_TOP_OFFSET = 22; + + private final ContainerCraftingCPU craftingCpu; + + private IItemList storage = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + private IItemList active = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + private IItemList pending = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + + private List visual = new ArrayList<>(); + private GuiButton cancel; + private int tooltip = -1; + + public GuiCraftingCPU(final InventoryPlayer inventoryPlayer, final Object te) { + this(new ContainerCraftingCPU(inventoryPlayer, te)); + } + + protected GuiCraftingCPU(final ContainerCraftingCPU container) { + super(container); + this.craftingCpu = container; + this.ySize = GUI_HEIGHT; + this.xSize = GUI_WIDTH; + + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar(scrollbar); + } + + public void clearItems() { + this.storage = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + this.active = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + this.pending = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + this.visual = new ArrayList<>(); + } + + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); + + if (this.cancel == btn) { + try { + NetworkHandler.instance().sendToServer(new PacketValueConfig("TileCrafting.Cancel", "Cancel")); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + + @Override + public void initGui() { + super.initGui(); + this.setScrollBar(); + this.cancel = new GuiButton(0, this.guiLeft + CANCEL_LEFT_OFFSET, this.guiTop + this.ySize - CANCEL_TOP_OFFSET, CANCEL_WIDTH, CANCEL_HEIGHT, GuiText.Cancel + .getLocal()); + this.buttonList.add(this.cancel); + } + + private void setScrollBar() { + final int size = this.visual.size(); + + this.getScrollBar().setTop(SCROLLBAR_TOP).setLeft(SCROLLBAR_LEFT).setHeight(SCROLLBAR_HEIGHT); + this.getScrollBar().setRange(0, (size + 2) / 3 - DISPLAYED_ROWS, 1); + } + + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + this.cancel.enabled = !this.visual.isEmpty(); + + final int gx = (this.width - this.xSize) / 2; + final int gy = (this.height - this.ySize) / 2; + + this.tooltip = -1; + + final int offY = 23; + int y = 0; + int x = 0; + for (int z = 0; z <= 4 * 5; z++) { + final int minX = gx + 9 + x * 67; + final int minY = gy + 22 + y * offY; + + if (minX < mouseX && minX + 67 > mouseX) { + if (minY < mouseY && minY + offY - 2 > mouseY) { + this.tooltip = z; + break; + } + } + + x++; + + if (x > 2) { + y++; + x = 0; + } + } + + super.drawScreen(mouseX, mouseY, btn); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + String title = this.getGuiDisplayName(GuiText.CraftingStatus.getLocal()); + + if (this.craftingCpu.getEstimatedTime() > 0 && !this.visual.isEmpty()) { + final long etaInMilliseconds = TimeUnit.MILLISECONDS.convert(this.craftingCpu.getEstimatedTime(), TimeUnit.NANOSECONDS); + final String etaTimeText = DurationFormatUtils.formatDuration(etaInMilliseconds, GuiText.ETAFormat.getLocal()); + title += " - " + etaTimeText; + } + + this.fontRenderer.drawString(title, TITLE_LEFT_OFFSET, TITLE_TOP_OFFSET, TEXT_COLOR); + + int x = 0; + int y = 0; + final int viewStart = this.getScrollBar().getCurrentScroll() * 3; + final int viewEnd = viewStart + 3 * 6; + + String dspToolTip = ""; + final List lineList = new ArrayList<>(); + int toolPosX = 0; + int toolPosY = 0; + + final int offY = 23; + + final ReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; + for (int z = viewStart; z < Math.min(viewEnd, this.visual.size()); z++) { + final IAEItemStack refStack = this.visual.get(z);// repo.getReferenceItem( z ); + if (refStack != null) { + GlStateManager.pushMatrix(); + GlStateManager.scale(0.5, 0.5, 0.5); + + final IAEItemStack stored = this.storage.findPrecise(refStack); + final IAEItemStack activeStack = this.active.findPrecise(refStack); + final IAEItemStack pendingStack = this.pending.findPrecise(refStack); + + int lines = 0; + + if (stored != null && stored.getStackSize() > 0) { + lines++; + } + boolean active = false; + if (activeStack != null && activeStack.getStackSize() > 0) { + lines++; + active = true; + } + boolean scheduled = false; + if (pendingStack != null && pendingStack.getStackSize() > 0) { + lines++; + scheduled = true; + } + + if (AEConfig.instance().isUseColoredCraftingStatus() && (active || scheduled)) { + final int bgColor = (active ? AEColor.GREEN.blackVariant : AEColor.YELLOW.blackVariant) | BACKGROUND_ALPHA; + final int startX = (x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET) * 2; + final int startY = ((y * offY + ITEMSTACK_TOP_OFFSET) - 3) * 2; + drawRect(startX, startY, startX + (SECTION_LENGTH * 2), startY + (offY * 2) - 2, bgColor); + } + + final int negY = ((lines - 1) * 5) / 2; + int downY = 0; + + if (stored != null && stored.getStackSize() > 0) { + final String str = GuiText.Stored.getLocal() + ": " + converter.toWideReadableForm(stored.getStackSize()); + final int w = 4 + this.fontRenderer.getStringWidth(str); + this.fontRenderer.drawString(str, (int) ((x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - (w * 0.5)) * 2), + (y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY) * 2, TEXT_COLOR); + + if (this.tooltip == z - viewStart) { + lineList.add(GuiText.Stored.getLocal() + ": " + stored.getStackSize()); + } + + downY += 5; + } + + if (activeStack != null && activeStack.getStackSize() > 0) { + final String str = GuiText.Crafting.getLocal() + ": " + converter.toWideReadableForm(activeStack.getStackSize()); + final int w = 4 + this.fontRenderer.getStringWidth(str); + + this.fontRenderer.drawString(str, (int) ((x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - (w * 0.5)) * 2), + (y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY) * 2, TEXT_COLOR); + + if (this.tooltip == z - viewStart) { + lineList.add(GuiText.Crafting.getLocal() + ": " + activeStack.getStackSize()); + } + + downY += 5; + } + + if (pendingStack != null && pendingStack.getStackSize() > 0) { + final String str = GuiText.Scheduled.getLocal() + ": " + converter.toWideReadableForm(pendingStack.getStackSize()); + final int w = 4 + this.fontRenderer.getStringWidth(str); + + this.fontRenderer.drawString(str, (int) ((x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - (w * 0.5)) * 2), + (y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY) * 2, TEXT_COLOR); + + if (this.tooltip == z - viewStart) { + lineList.add(GuiText.Scheduled.getLocal() + ": " + pendingStack.getStackSize()); + } + } + + GlStateManager.popMatrix(); + final int posX = x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19; + final int posY = y * offY + ITEMSTACK_TOP_OFFSET; + + final ItemStack is = refStack.asItemStackRepresentation(); + + if (this.tooltip == z - viewStart) { + dspToolTip = Platform.getItemDisplayName(refStack); + + if (lineList.size() > 0) { + dspToolTip = dspToolTip + '\n' + Joiner.on("\n").join(lineList); + } + + toolPosX = x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 8; + toolPosY = y * offY + ITEMSTACK_TOP_OFFSET; + } + + this.drawItem(posX, posY, is); + + x++; + + if (x > 2) { + y++; + x = 0; + } + } + } + + if (this.tooltip >= 0 && !dspToolTip.isEmpty()) { + this.drawTooltip(toolPosX, toolPosY + 10, dspToolTip); + } + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/craftingcpu.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } + + public void postUpdate(final List list, final byte ref) { + switch (ref) { + case 0: + for (final IAEItemStack l : list) { + this.handleInput(this.storage, l); + } + break; + + case 1: + for (final IAEItemStack l : list) { + this.handleInput(this.active, l); + } + break; + + case 2: + for (final IAEItemStack l : list) { + this.handleInput(this.pending, l); + } + break; + } + + for (final IAEItemStack l : list) { + final long amt = this.getTotal(l); + + if (amt <= 0) { + this.deleteVisualStack(l); + } else { + final IAEItemStack is = this.findVisualStack(l); + is.setStackSize(amt); + } + } + + this.setScrollBar(); + } + + private void handleInput(final IItemList s, final IAEItemStack l) { + IAEItemStack a = s.findPrecise(l); + + if (l.getStackSize() <= 0) { + if (a != null) { + a.reset(); + } + } else { + if (a == null) { + s.add(l.copy()); + a = s.findPrecise(l); + } + + if (a != null) { + a.setStackSize(l.getStackSize()); + } + } + } + + private long getTotal(final IAEItemStack is) { + final IAEItemStack a = this.storage.findPrecise(is); + final IAEItemStack b = this.active.findPrecise(is); + final IAEItemStack c = this.pending.findPrecise(is); + + long total = 0; + + if (a != null) { + total += a.getStackSize(); + } + + if (b != null) { + total += b.getStackSize(); + } + + if (c != null) { + total += c.getStackSize(); + } + + return total; + } + + private void deleteVisualStack(final IAEItemStack l) { + final Iterator i = this.visual.iterator(); + + while (i.hasNext()) { + final IAEItemStack o = i.next(); + if (o.equals(l)) { + i.remove(); + return; + } + } + } + + private IAEItemStack findVisualStack(final IAEItemStack l) { + for (final IAEItemStack o : this.visual) { + if (o.equals(l)) { + return o; + } + } + + final IAEItemStack stack = l.copy(); + this.visual.add(stack); + + return stack; + } + + @Override + public Enum getSortBy() { + return SortOrder.NAME; + } + + @Override + public Enum getSortDir() { + return SortDir.ASCENDING; + } + + @Override + public Enum getSortDisplay() { + return ViewItems.ALL; + } + + public List getVisual() { + return visual; + } + + public int getDisplayedRows() { + return DISPLAYED_ROWS; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java b/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java index d07b3ffae..6e9efecd4 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java @@ -23,29 +23,15 @@ package appeng.client.gui.implementations; -import java.awt.*; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import appeng.api.storage.data.IAEItemStack; -import appeng.client.gui.widgets.GuiScrollbar; -import appeng.container.implementations.CraftingCPUStatus; -import appeng.parts.reporting.PartExpandedProcessingPatternTerminal; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.definitions.IParts; import appeng.api.storage.ITerminalHost; +import appeng.api.storage.data.IAEItemStack; +import appeng.client.gui.widgets.GuiScrollbar; import appeng.client.gui.widgets.GuiTabButton; import appeng.container.implementations.ContainerCraftingStatus; +import appeng.container.implementations.CraftingCPUStatus; import appeng.core.AELog; import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; @@ -54,393 +40,349 @@ import appeng.core.sync.packets.PacketSwitchGuis; import appeng.core.sync.packets.PacketValueConfig; import appeng.helpers.WirelessTerminalGuiObject; import appeng.parts.reporting.PartCraftingTerminal; +import appeng.parts.reporting.PartExpandedProcessingPatternTerminal; import appeng.parts.reporting.PartPatternTerminal; import appeng.parts.reporting.PartTerminal; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; +import java.awt.*; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; -public class GuiCraftingStatus extends GuiCraftingCPU -{ - private static final int CPU_TABLE_WIDTH = 94; - private static final int CPU_TABLE_HEIGHT = 164; - private static final int CPU_TABLE_SLOT_XOFF = 100; - private static final int CPU_TABLE_SLOT_YOFF = 0; - private static final int CPU_TABLE_SLOT_WIDTH = 67; - private static final int CPU_TABLE_SLOT_HEIGHT = 23; +public class GuiCraftingStatus extends GuiCraftingCPU { - private final ContainerCraftingStatus status; - private GuiButton selectCPU; - private GuiScrollbar cpuScrollbar; + private static final int CPU_TABLE_WIDTH = 94; + private static final int CPU_TABLE_HEIGHT = 164; + private static final int CPU_TABLE_SLOT_XOFF = 100; + private static final int CPU_TABLE_SLOT_YOFF = 0; + private static final int CPU_TABLE_SLOT_WIDTH = 67; + private static final int CPU_TABLE_SLOT_HEIGHT = 23; - private GuiTabButton originalGuiBtn; - private GuiBridge originalGui; - private ItemStack myIcon = ItemStack.EMPTY; - private String selectedCPUName = ""; + private final ContainerCraftingStatus status; + private GuiButton selectCPU; + private GuiScrollbar cpuScrollbar; - public GuiCraftingStatus( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( new ContainerCraftingStatus( inventoryPlayer, te ) ); + private GuiTabButton originalGuiBtn; + private GuiBridge originalGui; + private ItemStack myIcon = ItemStack.EMPTY; + private String selectedCPUName = ""; - this.status = (ContainerCraftingStatus) this.inventorySlots; - final Object target = this.status.getTarget(); - final IDefinitions definitions = AEApi.instance().definitions(); - final IParts parts = definitions.parts(); + public GuiCraftingStatus(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(new ContainerCraftingStatus(inventoryPlayer, te)); - if( target instanceof WirelessTerminalGuiObject ) - { - this.myIcon = definitions.items().wirelessTerminal().maybeStack( 1 ).orElse( ItemStack.EMPTY ); + this.status = (ContainerCraftingStatus) this.inventorySlots; + final Object target = this.status.getTarget(); + final IDefinitions definitions = AEApi.instance().definitions(); + final IParts parts = definitions.parts(); - this.originalGui = GuiBridge.GUI_WIRELESS_TERM; - } + if (target instanceof WirelessTerminalGuiObject) { + this.myIcon = definitions.items().wirelessTerminal().maybeStack(1).orElse(ItemStack.EMPTY); - if( target instanceof PartTerminal ) - { - this.myIcon = parts.terminal().maybeStack( 1 ).orElse( ItemStack.EMPTY ); + this.originalGui = GuiBridge.GUI_WIRELESS_TERM; + } - this.originalGui = GuiBridge.GUI_ME; - } + if (target instanceof PartTerminal) { + this.myIcon = parts.terminal().maybeStack(1).orElse(ItemStack.EMPTY); - if( target instanceof PartCraftingTerminal ) - { - this.myIcon = parts.craftingTerminal().maybeStack( 1 ).orElse( ItemStack.EMPTY ); + this.originalGui = GuiBridge.GUI_ME; + } - this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; - } + if (target instanceof PartCraftingTerminal) { + this.myIcon = parts.craftingTerminal().maybeStack(1).orElse(ItemStack.EMPTY); - if( target instanceof PartPatternTerminal ) - { - this.myIcon = parts.patternTerminal().maybeStack( 1 ).orElse( ItemStack.EMPTY ); + this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; + } - this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; - } + if (target instanceof PartPatternTerminal) { + this.myIcon = parts.patternTerminal().maybeStack(1).orElse(ItemStack.EMPTY); - if( target instanceof PartExpandedProcessingPatternTerminal ) - { - myIcon = parts.expandedProcessingPatternTerminal().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - this.originalGui = GuiBridge.GUI_EXPANDED_PROCESSING_PATTERN_TERMINAL; - } - } + this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + if (target instanceof PartExpandedProcessingPatternTerminal) { + myIcon = parts.expandedProcessingPatternTerminal().maybeStack(1).orElse(ItemStack.EMPTY); + this.originalGui = GuiBridge.GUI_EXPANDED_PROCESSING_PATTERN_TERMINAL; + } + } - final boolean backwards = Mouse.isButtonDown( 1 ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - if( btn == this.originalGuiBtn ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( this.originalGui ) ); - } - } + final boolean backwards = Mouse.isButtonDown(1); - @Override - public void initGui() - { - super.initGui(); + if (btn == this.originalGuiBtn) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(this.originalGui)); + } + } - this.selectCPU = new GuiButton( 0, this.guiLeft + 8, this.guiTop + this.ySize - 25, 150, 20, GuiText.CraftingCPU - .getLocal() + ": " + GuiText.NoCraftingCPUs ); - selectCPU.enabled = false; - this.buttonList.add( this.selectCPU ); + @Override + public void initGui() { + super.initGui(); - this.cpuScrollbar = new GuiScrollbar(); - this.cpuScrollbar.setLeft( -16 ); - this.cpuScrollbar.setTop( 19 ); - this.cpuScrollbar.setWidth( 12 ); - this.cpuScrollbar.setHeight( 137 ); + this.selectCPU = new GuiButton(0, this.guiLeft + 8, this.guiTop + this.ySize - 25, 150, 20, GuiText.CraftingCPU + .getLocal() + ": " + GuiText.NoCraftingCPUs); + selectCPU.enabled = false; + this.buttonList.add(this.selectCPU); - if( !this.myIcon.isEmpty() ) - { - this.buttonList.add( - this.originalGuiBtn = new GuiTabButton( this.guiLeft + 213, this.guiTop - 4, this.myIcon, this.myIcon.getDisplayName(), this.itemRender ) ); - this.originalGuiBtn.setHideEdge( 13 ); - } - } + this.cpuScrollbar = new GuiScrollbar(); + this.cpuScrollbar.setLeft(-16); + this.cpuScrollbar.setTop(19); + this.cpuScrollbar.setWidth(12); + this.cpuScrollbar.setHeight(137); - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - List cpus = this.status.getCPUs(); - this.selectedCPUName = null; - this.cpuScrollbar.setRange( 0, Integer.max(0, cpus.size() - 6), 1 ); - for (CraftingCPUStatus cpu : cpus) - { - if (cpu.getSerial() == this.status.selectedCpuSerial) - { - this.selectedCPUName = cpu.getName(); - } - } - this.updateCPUButtonText(); - super.drawScreen( mouseX, mouseY, btn ); - } + if (!this.myIcon.isEmpty()) { + this.buttonList.add( + this.originalGuiBtn = new GuiTabButton(this.guiLeft + 213, this.guiTop - 4, this.myIcon, this.myIcon.getDisplayName(), this.itemRender)); + this.originalGuiBtn.setHideEdge(13); + } + } - @Override - public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - List cpus = this.status.getCPUs(); - final int firstCpu = this.cpuScrollbar.getCurrentScroll(); - CraftingCPUStatus hoveredCpu = hitCpu( mouseX, mouseY ); - { - FontRenderer font = Minecraft.getMinecraft().fontRenderer; - final int TEXT_COLOR = 0x202020; - for( int i = firstCpu; i < firstCpu + 6; i++ ) - { - if( i < 0 || i >= cpus.size() ) - { - continue; - } - CraftingCPUStatus cpu = cpus.get( i ); - if( cpu == null ) - { - continue; - } - int x = -CPU_TABLE_WIDTH + 9; - int y = 19 + ( i - firstCpu ) * CPU_TABLE_SLOT_HEIGHT; - if( cpu.getSerial() == this.status.selectedCpuSerial ) - { - GL11.glColor4f( 0.0F, 0.8352F, 1.0F, 1.0F ); - } - else if( hoveredCpu != null && hoveredCpu.getSerial() == cpu.getSerial() ) - { - GL11.glColor4f( 0.65F, 0.9F, 1.0F, 1.0F ); - } else - { - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - } - this.bindTexture( "guis/cpu_selector.png" ); - this.drawTexturedModalRect( x, y, CPU_TABLE_SLOT_XOFF, CPU_TABLE_SLOT_YOFF, CPU_TABLE_SLOT_WIDTH, CPU_TABLE_SLOT_HEIGHT ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + List cpus = this.status.getCPUs(); + this.selectedCPUName = null; + this.cpuScrollbar.setRange(0, Integer.max(0, cpus.size() - 6), 1); + for (CraftingCPUStatus cpu : cpus) { + if (cpu.getSerial() == this.status.selectedCpuSerial) { + this.selectedCPUName = cpu.getName(); + } + } + this.updateCPUButtonText(); + super.drawScreen(mouseX, mouseY, btn); + } - String name = cpu.getName(); - if( name == null || name.isEmpty() ) - { - name = GuiText.CPUs.getLocal() + " #" + cpu.getSerial(); - } - if( name.length() > 12 ) - { - name = name.substring( 0, 11 ) + ".."; - } - GL11.glPushMatrix(); - GL11.glTranslatef( x + 3, y + 3, 0 ); - GL11.glScalef( 0.8f, 0.8f, 1.0f ); - font.drawString( name, 0, 0, TEXT_COLOR ); - GL11.glPopMatrix(); + @Override + public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) { + List cpus = this.status.getCPUs(); + final int firstCpu = this.cpuScrollbar.getCurrentScroll(); + CraftingCPUStatus hoveredCpu = hitCpu(mouseX, mouseY); + { + FontRenderer font = Minecraft.getMinecraft().fontRenderer; + final int TEXT_COLOR = 0x202020; + for (int i = firstCpu; i < firstCpu + 6; i++) { + if (i < 0 || i >= cpus.size()) { + continue; + } + CraftingCPUStatus cpu = cpus.get(i); + if (cpu == null) { + continue; + } + int x = -CPU_TABLE_WIDTH + 9; + int y = 19 + (i - firstCpu) * CPU_TABLE_SLOT_HEIGHT; + if (cpu.getSerial() == this.status.selectedCpuSerial) { + GL11.glColor4f(0.0F, 0.8352F, 1.0F, 1.0F); + } else if (hoveredCpu != null && hoveredCpu.getSerial() == cpu.getSerial()) { + GL11.glColor4f(0.65F, 0.9F, 1.0F, 1.0F); + } else { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } + this.bindTexture("guis/cpu_selector.png"); + this.drawTexturedModalRect(x, y, CPU_TABLE_SLOT_XOFF, CPU_TABLE_SLOT_YOFF, CPU_TABLE_SLOT_WIDTH, CPU_TABLE_SLOT_HEIGHT); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glPushMatrix(); - GL11.glTranslatef( x + 3, y + 11, 0 ); - final IAEItemStack craftingStack = cpu.getCrafting(); - if( craftingStack != null ) - { - final int iconIndex = 16 * 11 + 2; - this.bindTexture( "guis/states.png" ); - final int uv_y = iconIndex / 16; - final int uv_x = iconIndex - uv_y * 16; + String name = cpu.getName(); + if (name == null || name.isEmpty()) { + name = GuiText.CPUs.getLocal() + " #" + cpu.getSerial(); + } + if (name.length() > 12) { + name = name.substring(0, 11) + ".."; + } + GL11.glPushMatrix(); + GL11.glTranslatef(x + 3, y + 3, 0); + GL11.glScalef(0.8f, 0.8f, 1.0f); + font.drawString(name, 0, 0, TEXT_COLOR); + GL11.glPopMatrix(); - GL11.glScalef( 0.5f, 0.5f, 1.0f ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - this.drawTexturedModalRect( 0, 0, uv_x * 16, uv_y * 16, 16, 16 ); - GL11.glTranslatef( 18.0f, 2.0f, 0.0f ); - String amount = Long.toString( craftingStack.getStackSize() ); - if( amount.length() > 5 ) - { - amount = amount.substring( 0, 5 ) + ".."; - } - GL11.glScalef( 1.5f, 1.5f, 1.0f ); - font.drawString( amount, 0, 0, 0x009000 ); - GL11.glPopMatrix(); - GL11.glPushMatrix(); - GL11.glTranslatef( x + CPU_TABLE_SLOT_WIDTH - 19, y + 3, 0 ); - this.drawItem( 0, 0, craftingStack.createItemStack() ); - } - else - { - final int iconIndex = 16 * 4 + 3; - this.bindTexture( "guis/states.png" ); - final int uv_y = iconIndex / 16; - final int uv_x = iconIndex - uv_y * 16; + GL11.glPushMatrix(); + GL11.glTranslatef(x + 3, y + 11, 0); + final IAEItemStack craftingStack = cpu.getCrafting(); + if (craftingStack != null) { + final int iconIndex = 16 * 11 + 2; + this.bindTexture("guis/states.png"); + final int uv_y = iconIndex / 16; + final int uv_x = iconIndex - uv_y * 16; - GL11.glScalef( 0.5f, 0.5f, 1.0f ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - this.drawTexturedModalRect( 0, 0, uv_x * 16, uv_y * 16, 16, 16 ); - GL11.glTranslatef( 18.0f, 2.0f, 0.0f ); - GL11.glScalef( 1.5f, 1.5f, 1.0f ); - font.drawString( cpu.formatStorage(), 0, 0, TEXT_COLOR ); - } - GL11.glPopMatrix(); - } - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - } - StringBuilder tooltip = new StringBuilder(); - if( hoveredCpu != null ) - { - String name = hoveredCpu.getName(); - if( name != null && !name.isEmpty() ) - { - tooltip.append( name ); - tooltip.append( '\n' ); - } - else - { - tooltip.append ( GuiText.CPUs.getLocal() ); - tooltip.append ( " #" ); - tooltip.append ( hoveredCpu.getSerial() ); - tooltip.append ( '\n' ); - } - IAEItemStack crafting = hoveredCpu.getCrafting(); - if( crafting != null && crafting.getStackSize() > 0 ) - { - tooltip.append( GuiText.Crafting.getLocal() ); - tooltip.append( ": " ); - tooltip.append( crafting.getStackSize() ); - tooltip.append( ' ' ); - tooltip.append( crafting.createItemStack().getDisplayName() ); - tooltip.append( '\n' ); - tooltip.append( hoveredCpu.getRemainingItems() ); - tooltip.append( " / " ); - tooltip.append( hoveredCpu.getTotalItems() ); - tooltip.append( '\n' ); - } - if ( hoveredCpu.getStorage() > 0 ) - { - tooltip.append( GuiText.Bytes.getLocal() ); - tooltip.append( ": " ); - tooltip.append( hoveredCpu.formatStorage() ); - tooltip.append( '\n' ); - } - if ( hoveredCpu.getCoprocessors() > 0 ) - { - tooltip.append( GuiText.CoProcessors.getLocal() ); - tooltip.append( ": " ); - tooltip.append( hoveredCpu.getCoprocessors() ); - tooltip.append( '\n' ); - } - } - if (this.cpuScrollbar != null) - { - this.cpuScrollbar.draw( this ); - } - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - if (tooltip.length() > 0) - { - this.drawTooltip( mouseX - offsetX, mouseY - offsetY, tooltip.toString() ); - } - } + GL11.glScalef(0.5f, 0.5f, 1.0f); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + this.drawTexturedModalRect(0, 0, uv_x * 16, uv_y * 16, 16, 16); + GL11.glTranslatef(18.0f, 2.0f, 0.0f); + String amount = Long.toString(craftingStack.getStackSize()); + if (amount.length() > 5) { + amount = amount.substring(0, 5) + ".."; + } + GL11.glScalef(1.5f, 1.5f, 1.0f); + font.drawString(amount, 0, 0, 0x009000); + GL11.glPopMatrix(); + GL11.glPushMatrix(); + GL11.glTranslatef(x + CPU_TABLE_SLOT_WIDTH - 19, y + 3, 0); + this.drawItem(0, 0, craftingStack.createItemStack()); + } else { + final int iconIndex = 16 * 4 + 3; + this.bindTexture("guis/states.png"); + final int uv_y = iconIndex / 16; + final int uv_x = iconIndex - uv_y * 16; - @Override - public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - super.drawBG( offsetX, offsetY, mouseX, mouseY ); - this.bindTexture( "guis/cpu_selector.png" ); - this.drawTexturedModalRect( offsetX - CPU_TABLE_WIDTH, offsetY, 0, 0, CPU_TABLE_WIDTH, CPU_TABLE_HEIGHT ); - } + GL11.glScalef(0.5f, 0.5f, 1.0f); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + this.drawTexturedModalRect(0, 0, uv_x * 16, uv_y * 16, 16, 16); + GL11.glTranslatef(18.0f, 2.0f, 0.0f); + GL11.glScalef(1.5f, 1.5f, 1.0f); + font.drawString(cpu.formatStorage(), 0, 0, TEXT_COLOR); + } + GL11.glPopMatrix(); + } + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } + StringBuilder tooltip = new StringBuilder(); + if (hoveredCpu != null) { + String name = hoveredCpu.getName(); + if (name != null && !name.isEmpty()) { + tooltip.append(name); + tooltip.append('\n'); + } else { + tooltip.append(GuiText.CPUs.getLocal()); + tooltip.append(" #"); + tooltip.append(hoveredCpu.getSerial()); + tooltip.append('\n'); + } + IAEItemStack crafting = hoveredCpu.getCrafting(); + if (crafting != null && crafting.getStackSize() > 0) { + tooltip.append(GuiText.Crafting.getLocal()); + tooltip.append(": "); + tooltip.append(crafting.getStackSize()); + tooltip.append(' '); + tooltip.append(crafting.createItemStack().getDisplayName()); + tooltip.append('\n'); + tooltip.append(hoveredCpu.getRemainingItems()); + tooltip.append(" / "); + tooltip.append(hoveredCpu.getTotalItems()); + tooltip.append('\n'); + } + if (hoveredCpu.getStorage() > 0) { + tooltip.append(GuiText.Bytes.getLocal()); + tooltip.append(": "); + tooltip.append(hoveredCpu.formatStorage()); + tooltip.append('\n'); + } + if (hoveredCpu.getCoprocessors() > 0) { + tooltip.append(GuiText.CoProcessors.getLocal()); + tooltip.append(": "); + tooltip.append(hoveredCpu.getCoprocessors()); + tooltip.append('\n'); + } + } + if (this.cpuScrollbar != null) { + this.cpuScrollbar.draw(this); + } + super.drawFG(offsetX, offsetY, mouseX, mouseY); + if (tooltip.length() > 0) { + this.drawTooltip(mouseX - offsetX, mouseY - offsetY, tooltip.toString()); + } + } - @Override - public List getJEIExclusionArea() { - Rectangle craftingCPUArea = new Rectangle(this.guiLeft - CPU_TABLE_WIDTH, this.guiTop, CPU_TABLE_WIDTH, CPU_TABLE_HEIGHT); - List area = new ArrayList(); - area.add(craftingCPUArea); - return area; - } + @Override + public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) { + super.drawBG(offsetX, offsetY, mouseX, mouseY); + this.bindTexture("guis/cpu_selector.png"); + this.drawTexturedModalRect(offsetX - CPU_TABLE_WIDTH, offsetY, 0, 0, CPU_TABLE_WIDTH, CPU_TABLE_HEIGHT); + } - @Override - protected void mouseClicked( int xCoord, int yCoord, int btn ) throws IOException { - super.mouseClicked( xCoord, yCoord, btn ); + @Override + public List getJEIExclusionArea() { + Rectangle craftingCPUArea = new Rectangle(this.guiLeft - CPU_TABLE_WIDTH, this.guiTop, CPU_TABLE_WIDTH, CPU_TABLE_HEIGHT); + List area = new ArrayList(); + area.add(craftingCPUArea); + return area; + } - if( cpuScrollbar != null ) - { - cpuScrollbar.click( this, xCoord - this.guiLeft, yCoord - this.guiTop ); - } - CraftingCPUStatus hit = hitCpu( xCoord, yCoord ); - if (hit != null) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "Terminal.Cpu.Set", Integer.toString( hit.getSerial() ) ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } + @Override + protected void mouseClicked(int xCoord, int yCoord, int btn) throws IOException { + super.mouseClicked(xCoord, yCoord, btn); - @Override - protected void mouseClickMove( int x, int y, int c, long d ) - { - super.mouseClickMove( x, y, c, d ); - if( cpuScrollbar != null ) - { - cpuScrollbar.click( this, x - this.guiLeft, y - this.guiTop ); - } - } + if (cpuScrollbar != null) { + cpuScrollbar.click(this, xCoord - this.guiLeft, yCoord - this.guiTop); + } + CraftingCPUStatus hit = hitCpu(xCoord, yCoord); + if (hit != null) { + try { + NetworkHandler.instance.sendToServer(new PacketValueConfig("Terminal.Cpu.Set", Integer.toString(hit.getSerial()))); + } catch (final IOException e) { + AELog.debug(e); + } + } + } - @Override - public void handleMouseInput() throws IOException { - int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; - x -= guiLeft - CPU_TABLE_WIDTH; - y -= guiTop; - int dwheel = Mouse.getEventDWheel(); - if (x >= 9 && x < CPU_TABLE_SLOT_WIDTH + 9 && y >= 19 && y < 19 + 6 * CPU_TABLE_SLOT_HEIGHT) - { - if (this.cpuScrollbar != null && dwheel != 0) - { - this.cpuScrollbar.wheel( dwheel ); - return; - } - } - super.handleMouseInput(); - } + @Override + protected void mouseClickMove(int x, int y, int c, long d) { + super.mouseClickMove(x, y, c, d); + if (cpuScrollbar != null) { + cpuScrollbar.click(this, x - this.guiLeft, y - this.guiTop); + } + } - private CraftingCPUStatus hitCpu( int x, int y ) - { - x -= guiLeft - CPU_TABLE_WIDTH; - y -= guiTop; - if (!(x >= 9 && x < CPU_TABLE_SLOT_WIDTH + 9 && y >= 19 && y < 19 + 6 * CPU_TABLE_SLOT_HEIGHT)) - { - return null; - } - int scrollOffset = this.cpuScrollbar != null ? this.cpuScrollbar.getCurrentScroll() : 0; - int cpuId = scrollOffset + (y - 19) / CPU_TABLE_SLOT_HEIGHT; - List cpus = this.status.getCPUs(); - return (cpuId >= 0 && cpuId < cpus.size()) ? cpus.get(cpuId) : null; - } + @Override + public void handleMouseInput() throws IOException { + int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; + x -= guiLeft - CPU_TABLE_WIDTH; + y -= guiTop; + int dwheel = Mouse.getEventDWheel(); + if (x >= 9 && x < CPU_TABLE_SLOT_WIDTH + 9 && y >= 19 && y < 19 + 6 * CPU_TABLE_SLOT_HEIGHT) { + if (this.cpuScrollbar != null && dwheel != 0) { + this.cpuScrollbar.wheel(dwheel); + return; + } + } + super.handleMouseInput(); + } - private void updateCPUButtonText() - { - String btnTextText = GuiText.NoCraftingJobs.getLocal(); + private CraftingCPUStatus hitCpu(int x, int y) { + x -= guiLeft - CPU_TABLE_WIDTH; + y -= guiTop; + if (!(x >= 9 && x < CPU_TABLE_SLOT_WIDTH + 9 && y >= 19 && y < 19 + 6 * CPU_TABLE_SLOT_HEIGHT)) { + return null; + } + int scrollOffset = this.cpuScrollbar != null ? this.cpuScrollbar.getCurrentScroll() : 0; + int cpuId = scrollOffset + (y - 19) / CPU_TABLE_SLOT_HEIGHT; + List cpus = this.status.getCPUs(); + return (cpuId >= 0 && cpuId < cpus.size()) ? cpus.get(cpuId) : null; + } - if( this.status.selectedCpuSerial >= 0 )// && status.selectedCpu < status.cpus.size() ) - { - if( this.selectedCPUName != null && this.selectedCPUName.length() > 0 ) - { - final String name = this.selectedCPUName.substring( 0, Math.min( 20, this.selectedCPUName.length() ) ); - btnTextText = GuiText.CPUs.getLocal() + ": " + name; - } - else - { - btnTextText = GuiText.CPUs.getLocal() + ": #" + this.status.selectedCpuSerial; - } - } + private void updateCPUButtonText() { + String btnTextText = GuiText.NoCraftingJobs.getLocal(); - if( this.status.getCPUs().isEmpty() ) - { - btnTextText = GuiText.NoCraftingJobs.getLocal(); - } + if (this.status.selectedCpuSerial >= 0)// && status.selectedCpu < status.cpus.size() ) + { + if (this.selectedCPUName != null && this.selectedCPUName.length() > 0) { + final String name = this.selectedCPUName.substring(0, Math.min(20, this.selectedCPUName.length())); + btnTextText = GuiText.CPUs.getLocal() + ": " + name; + } else { + btnTextText = GuiText.CPUs.getLocal() + ": #" + this.status.selectedCpuSerial; + } + } - this.selectCPU.displayString = btnTextText; - } + if (this.status.getCPUs().isEmpty()) { + btnTextText = GuiText.NoCraftingJobs.getLocal(); + } - @Override - protected String getGuiDisplayName( final String in ) - { - return in; // the cup name is on the button - } + this.selectCPU.displayString = btnTextText; + } - public void postCPUUpdate( CraftingCPUStatus[] cpus ) - { - this.status.postCPUUpdate(cpus); - } + @Override + protected String getGuiDisplayName(final String in) { + return in; // the cup name is on the button + } + + public void postCPUUpdate(CraftingCPUStatus[] cpus) { + this.status.postCPUUpdate(cpus); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java b/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java index a609cafe0..4de1c8859 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java @@ -19,11 +19,6 @@ package appeng.client.gui.implementations; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.Slot; - import appeng.api.config.ActionItems; import appeng.api.config.Settings; import appeng.api.storage.ITerminalHost; @@ -34,62 +29,56 @@ import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketInventoryAction; import appeng.helpers.InventoryAction; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; -public class GuiCraftingTerm extends GuiMEMonitorable -{ +public class GuiCraftingTerm extends GuiMEMonitorable { - private GuiImgButton clearBtn; + private GuiImgButton clearBtn; - public GuiCraftingTerm( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( inventoryPlayer, te, new ContainerCraftingTerm( inventoryPlayer, te ) ); - this.setReservedSpace( 73 ); - } + public GuiCraftingTerm(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(inventoryPlayer, te, new ContainerCraftingTerm(inventoryPlayer, te)); + this.setReservedSpace(73); + } - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - if( this.clearBtn == btn ) - { - Slot s = null; - final Container c = this.inventorySlots; - for( final Object j : c.inventorySlots ) - { - if( j instanceof SlotCraftingMatrix ) - { - s = (Slot) j; - } - } + if (this.clearBtn == btn) { + Slot s = null; + final Container c = this.inventorySlots; + for (final Object j : c.inventorySlots) { + if (j instanceof SlotCraftingMatrix) { + s = (Slot) j; + } + } - if( s != null ) - { - final PacketInventoryAction p = new PacketInventoryAction( InventoryAction.MOVE_REGION, s.slotNumber, 0 ); - NetworkHandler.instance().sendToServer( p ); - } - } - } + if (s != null) { + final PacketInventoryAction p = new PacketInventoryAction(InventoryAction.MOVE_REGION, s.slotNumber, 0); + NetworkHandler.instance().sendToServer(p); + } + } + } - @Override - public void initGui() - { - super.initGui(); - this.buttonList.add( this.clearBtn = new GuiImgButton( this.guiLeft + 92, this.guiTop + this.ySize - 156, Settings.ACTIONS, ActionItems.STASH ) ); - this.clearBtn.setHalfSize( true ); - } + @Override + public void initGui() { + super.initGui(); + this.buttonList.add(this.clearBtn = new GuiImgButton(this.guiLeft + 92, this.guiTop + this.ySize - 156, Settings.ACTIONS, ActionItems.STASH)); + this.clearBtn.setHalfSize(true); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.fontRenderer.drawString( GuiText.CraftingTerminal.getLocal(), 8, this.ySize - 96 + 1 - this.getReservedSpace(), 4210752 ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawFG(offsetX, offsetY, mouseX, mouseY); + this.fontRenderer.drawString(GuiText.CraftingTerminal.getLocal(), 8, this.ySize - 96 + 1 - this.getReservedSpace(), 4210752); + } - @Override - protected String getBackground() - { - return "guis/crafting.png"; - } + @Override + protected String getBackground() { + return "guis/crafting.png"; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiDrive.java b/src/main/java/appeng/client/gui/implementations/GuiDrive.java index 6e332e567..fcf274a4d 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiDrive.java +++ b/src/main/java/appeng/client/gui/implementations/GuiDrive.java @@ -19,11 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiTabButton; import appeng.container.implementations.ContainerDrive; @@ -32,49 +27,46 @@ import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketSwitchGuis; import appeng.tile.storage.TileDrive; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; + +import java.io.IOException; -public class GuiDrive extends AEBaseGui -{ +public class GuiDrive extends AEBaseGui { - private GuiTabButton priority; + private GuiTabButton priority; - public GuiDrive( final InventoryPlayer inventoryPlayer, final TileDrive te ) - { - super( new ContainerDrive( inventoryPlayer, te ) ); - this.ySize = 199; - } + public GuiDrive(final InventoryPlayer inventoryPlayer, final TileDrive te) { + super(new ContainerDrive(inventoryPlayer, te)); + this.ySize = 199; + } - @Override - protected void actionPerformed( final GuiButton par1GuiButton ) throws IOException - { - super.actionPerformed( par1GuiButton ); + @Override + protected void actionPerformed(final GuiButton par1GuiButton) throws IOException { + super.actionPerformed(par1GuiButton); - if( par1GuiButton == this.priority ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - } + if (par1GuiButton == this.priority) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender ) ); - } + this.buttonList.add(this.priority = new GuiTabButton(this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender)); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.Drive.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.Drive.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/drive.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/drive.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiExpandedProcessingPatternTerm.java b/src/main/java/appeng/client/gui/implementations/GuiExpandedProcessingPatternTerm.java index 2594b121f..2ea395213 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiExpandedProcessingPatternTerm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiExpandedProcessingPatternTerm.java @@ -24,13 +24,13 @@ import net.minecraft.init.Blocks; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; -import java.awt.Rectangle; +import java.awt.*; import java.io.IOException; +import java.util.List; import java.util.*; -public class GuiExpandedProcessingPatternTerm extends GuiMEMonitorable implements IJEIGhostIngredients -{ +public class GuiExpandedProcessingPatternTerm extends GuiMEMonitorable implements IJEIGhostIngredients { private static final String BACKGROUND_EXPANDED_PROCESSING_MODE = "guis/pattern_processing_expanded.png"; private static final String SUBSITUTION_DISABLE = "0"; @@ -54,146 +54,125 @@ public class GuiExpandedProcessingPatternTerm extends GuiMEMonitorable implement private GuiImgButton maxCountBtn; public Map, Object> mapTargetSlot = new HashMap<>(); - public GuiExpandedProcessingPatternTerm( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( inventoryPlayer, te, new ContainerExpandedProcessingPatternTerm( inventoryPlayer, te ) ); - this.setReservedSpace( 81 ); + public GuiExpandedProcessingPatternTerm(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(inventoryPlayer, te, new ContainerExpandedProcessingPatternTerm(inventoryPlayer, te)); + this.setReservedSpace(81); } @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - try - { + try { - if( this.tabCraftButton == btn || this.tabProcessButton == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.CraftMode", this.tabProcessButton == btn ? CRAFTMODE_CRFTING : CRAFTMODE_PROCESSING ) ); + if (this.tabCraftButton == btn || this.tabProcessButton == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.CraftMode", this.tabProcessButton == btn ? CRAFTMODE_CRFTING : CRAFTMODE_PROCESSING)); } - if( this.encodeBtn == btn ) - { - if( isShiftKeyDown() ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.Encode", "2" ) ); - } - else - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.Encode", "1" ) ); + if (this.encodeBtn == btn) { + if (isShiftKeyDown()) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.Encode", "2")); + } else { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.Encode", "1")); } } - if( this.clearBtn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.Clear", "1" ) ); + if (this.clearBtn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.Clear", "1")); } - if( this.x2Btn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.MultiplyByTwo", "1" ) ); + if (this.x2Btn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.MultiplyByTwo", "1")); } - if( this.x3Btn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.MultiplyByThree", "1" ) ); + if (this.x3Btn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.MultiplyByThree", "1")); } - if( this.divTwoBtn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.DivideByTwo", "1" ) ); + if (this.divTwoBtn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.DivideByTwo", "1")); } - if( this.divThreeBtn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.DivideByThree", "1" ) ); + if (this.divThreeBtn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.DivideByThree", "1")); } - if( this.plusOneBtn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.IncreaseByOne", "1" ) ); + if (this.plusOneBtn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.IncreaseByOne", "1")); } - if( this.minusOneBtn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.DecreaseByOne", "1" ) ); + if (this.minusOneBtn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.DecreaseByOne", "1")); } - if( this.maxCountBtn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.MaximizeCount", "1" ) ); + if (this.maxCountBtn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.MaximizeCount", "1")); } - if( this.substitutionsEnabledBtn == btn || this.substitutionsDisabledBtn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.Substitute", this.substitutionsEnabledBtn == btn ? SUBSITUTION_DISABLE : SUBSITUTION_ENABLE ) ); + if (this.substitutionsEnabledBtn == btn || this.substitutionsDisabledBtn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.Substitute", this.substitutionsEnabledBtn == btn ? SUBSITUTION_DISABLE : SUBSITUTION_ENABLE)); } - } - catch( final IOException e ) - { - AELog.error( e ); + } catch (final IOException e) { + AELog.error(e); } } @Override - public void initGui() - { + public void initGui() { super.initGui(); - this.tabCraftButton = new GuiTabButton( this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack( Blocks.CRAFTING_TABLE ), GuiText.CraftingPattern.getLocal(), this.itemRender ); - this.buttonList.add( this.tabCraftButton ); + this.tabCraftButton = new GuiTabButton(this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack(Blocks.CRAFTING_TABLE), GuiText.CraftingPattern.getLocal(), this.itemRender); + this.buttonList.add(this.tabCraftButton); - this.tabProcessButton = new GuiTabButton( this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack( Blocks.FURNACE ), GuiText.ProcessingPattern.getLocal(), this.itemRender ); - this.buttonList.add( this.tabProcessButton ); + this.tabProcessButton = new GuiTabButton(this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack(Blocks.FURNACE), GuiText.ProcessingPattern.getLocal(), this.itemRender); + this.buttonList.add(this.tabProcessButton); - this.substitutionsEnabledBtn = new GuiImgButton( this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.ENABLED ); - this.substitutionsEnabledBtn.setHalfSize( true ); - this.buttonList.add( this.substitutionsEnabledBtn ); + this.substitutionsEnabledBtn = new GuiImgButton(this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.ENABLED); + this.substitutionsEnabledBtn.setHalfSize(true); + this.buttonList.add(this.substitutionsEnabledBtn); - this.substitutionsDisabledBtn = new GuiImgButton( this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.DISABLED ); - this.substitutionsDisabledBtn.setHalfSize( true ); - this.buttonList.add( this.substitutionsDisabledBtn ); + this.substitutionsDisabledBtn = new GuiImgButton(this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.DISABLED); + this.substitutionsDisabledBtn.setHalfSize(true); + this.buttonList.add(this.substitutionsDisabledBtn); - this.clearBtn = new GuiImgButton( this.guiLeft + 74, this.guiTop + this.ySize - 163, Settings.ACTIONS, ActionItems.CLOSE ); - this.clearBtn.setHalfSize( true ); - this.buttonList.add( this.clearBtn ); + this.clearBtn = new GuiImgButton(this.guiLeft + 74, this.guiTop + this.ySize - 163, Settings.ACTIONS, ActionItems.CLOSE); + this.clearBtn.setHalfSize(true); + this.buttonList.add(this.clearBtn); - this.x3Btn = new GuiImgButton( this.guiLeft + 131, this.guiTop + this.ySize - 158, Settings.ACTIONS, ActionItems.MULTIPLY_BY_THREE ); - this.x3Btn.setHalfSize( true ); - this.buttonList.add( this.x3Btn ); + this.x3Btn = new GuiImgButton(this.guiLeft + 131, this.guiTop + this.ySize - 158, Settings.ACTIONS, ActionItems.MULTIPLY_BY_THREE); + this.x3Btn.setHalfSize(true); + this.buttonList.add(this.x3Btn); - this.x2Btn = new GuiImgButton( this.guiLeft + 131, this.guiTop + this.ySize - 148, Settings.ACTIONS, ActionItems.MULTIPLY_BY_TWO ); - this.x2Btn.setHalfSize( true ); - this.buttonList.add( this.x2Btn ); + this.x2Btn = new GuiImgButton(this.guiLeft + 131, this.guiTop + this.ySize - 148, Settings.ACTIONS, ActionItems.MULTIPLY_BY_TWO); + this.x2Btn.setHalfSize(true); + this.buttonList.add(this.x2Btn); - this.plusOneBtn = new GuiImgButton( this.guiLeft + 131, this.guiTop + this.ySize - 110, Settings.ACTIONS, ActionItems.INCREASE_BY_ONE ); - this.plusOneBtn.setHalfSize( true ); - this.buttonList.add( this.plusOneBtn ); + this.plusOneBtn = new GuiImgButton(this.guiLeft + 131, this.guiTop + this.ySize - 110, Settings.ACTIONS, ActionItems.INCREASE_BY_ONE); + this.plusOneBtn.setHalfSize(true); + this.buttonList.add(this.plusOneBtn); - this.divThreeBtn = new GuiImgButton( this.guiLeft + 87, this.guiTop + this.ySize - 158, Settings.ACTIONS, ActionItems.DIVIDE_BY_THREE ); - this.divThreeBtn.setHalfSize( true ); - this.buttonList.add( this.divThreeBtn ); + this.divThreeBtn = new GuiImgButton(this.guiLeft + 87, this.guiTop + this.ySize - 158, Settings.ACTIONS, ActionItems.DIVIDE_BY_THREE); + this.divThreeBtn.setHalfSize(true); + this.buttonList.add(this.divThreeBtn); - this.divTwoBtn = new GuiImgButton( this.guiLeft + 87, this.guiTop + this.ySize - 148, Settings.ACTIONS, ActionItems.DIVIDE_BY_TWO ); - this.divTwoBtn.setHalfSize( true ); - this.buttonList.add( this.divTwoBtn ); + this.divTwoBtn = new GuiImgButton(this.guiLeft + 87, this.guiTop + this.ySize - 148, Settings.ACTIONS, ActionItems.DIVIDE_BY_TWO); + this.divTwoBtn.setHalfSize(true); + this.buttonList.add(this.divTwoBtn); - this.minusOneBtn = new GuiImgButton( this.guiLeft + 87, this.guiTop + this.ySize - 110, Settings.ACTIONS, ActionItems.DECREASE_BY_ONE ); - this.minusOneBtn.setHalfSize( true ); - this.buttonList.add( this.minusOneBtn ); + this.minusOneBtn = new GuiImgButton(this.guiLeft + 87, this.guiTop + this.ySize - 110, Settings.ACTIONS, ActionItems.DECREASE_BY_ONE); + this.minusOneBtn.setHalfSize(true); + this.buttonList.add(this.minusOneBtn); //this.maxCountBtn = new GuiImgButton( this.guiLeft + 128, this.guiTop + this.ySize - 108, Settings.ACTIONS, ActionItems.MAX_COUNT ); //this.maxCountBtn.setHalfSize( true ); //this.buttonList.add( this.maxCountBtn ); - this.encodeBtn = new GuiImgButton( this.guiLeft + 147, this.guiTop + this.ySize - 142, Settings.ACTIONS, ActionItems.ENCODE ); - this.buttonList.add( this.encodeBtn ); + this.encodeBtn = new GuiImgButton(this.guiLeft + 147, this.guiTop + this.ySize - 142, Settings.ACTIONS, ActionItems.ENCODE); + this.buttonList.add(this.encodeBtn); } @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { this.tabCraftButton.visible = false; this.tabProcessButton.visible = true; this.substitutionsEnabledBtn.visible = false; @@ -206,71 +185,58 @@ public class GuiExpandedProcessingPatternTerm extends GuiMEMonitorable implement this.minusOneBtn.visible = true; //this.maxCountBtn.visible = true; - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.fontRenderer.drawString( GuiText.PatternTerminal.getLocal(), 8, this.ySize - 96 + 2 - this.getReservedSpace(), 4210752 ); + super.drawFG(offsetX, offsetY, mouseX, mouseY); + this.fontRenderer.drawString(GuiText.PatternTerminal.getLocal(), 8, this.ySize - 96 + 2 - this.getReservedSpace(), 4210752); } @Override - protected String getBackground() - { + protected String getBackground() { return BACKGROUND_EXPANDED_PROCESSING_MODE; } @Override - protected void repositionSlot( final AppEngSlot s ) - { + protected void repositionSlot(final AppEngSlot s) { final int offsetPlayerSide = s.isPlayerSide() ? 5 : 3; s.yPos = s.getY() + this.ySize - 78 - offsetPlayerSide; } @Override - public List> getPhantomTargets( Object ingredient ) - { - if( !( ingredient instanceof ItemStack ) ) - { + public List> getPhantomTargets(Object ingredient) { + if (!(ingredient instanceof ItemStack)) { return Collections.emptyList(); } List> targets = new ArrayList<>(); - for( Slot slot : this.inventorySlots.inventorySlots ) - { - if( slot instanceof SlotFake ) - { + for (Slot slot : this.inventorySlots.inventorySlots) { + if (slot instanceof SlotFake) { ItemStack itemStack = (ItemStack) ingredient; - IGhostIngredientHandler.Target target = new IGhostIngredientHandler.Target() - { + IGhostIngredientHandler.Target target = new IGhostIngredientHandler.Target() { @Override - public Rectangle getArea() - { - return new Rectangle( getGuiLeft() + slot.xPos, getGuiTop() + slot.yPos, 16, 16 ); + public Rectangle getArea() { + return new Rectangle(getGuiLeft() + slot.xPos, getGuiTop() + slot.yPos, 16, 16); } @Override - public void accept( Object ingredient ) - { + public void accept(Object ingredient) { final PacketInventoryAction p; - try - { - p = new PacketInventoryAction( InventoryAction.PLACE_JEI_GHOST_ITEM, (SlotFake) slot, AEItemStack.fromItemStack( itemStack ) ); - NetworkHandler.instance().sendToServer( p ); + try { + p = new PacketInventoryAction(InventoryAction.PLACE_JEI_GHOST_ITEM, (SlotFake) slot, AEItemStack.fromItemStack(itemStack)); + NetworkHandler.instance().sendToServer(p); - } - catch( IOException e ) - { + } catch (IOException e) { e.printStackTrace(); } } }; - targets.add( target ); - mapTargetSlot.putIfAbsent( target, slot ); + targets.add(target); + mapTargetSlot.putIfAbsent(target, slot); } } return targets; } @Override - public Map, Object> getFakeSlotTargetMap() - { + public Map, Object> getFakeSlotTargetMap() { return mapTargetSlot; } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java b/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java index 8b8646be3..3f2d205f5 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java +++ b/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java @@ -19,13 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.config.FuzzyMode; import appeng.api.config.Settings; import appeng.api.config.YesNo; @@ -38,69 +31,63 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; import appeng.core.sync.packets.PacketSwitchGuis; import appeng.parts.automation.PartFormationPlane; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import org.lwjgl.input.Mouse; + +import java.io.IOException; -public class GuiFormationPlane extends GuiUpgradeable -{ +public class GuiFormationPlane extends GuiUpgradeable { - private GuiTabButton priority; - private GuiImgButton placeMode; + private GuiTabButton priority; + private GuiImgButton placeMode; - public GuiFormationPlane( final InventoryPlayer inventoryPlayer, final PartFormationPlane te ) - { - super( new ContainerFormationPlane( inventoryPlayer, te ) ); - this.ySize = 251; - } + public GuiFormationPlane(final InventoryPlayer inventoryPlayer, final PartFormationPlane te) { + super(new ContainerFormationPlane(inventoryPlayer, te)); + this.ySize = 251; + } - @Override - protected void addButtons() - { - this.placeMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.PLACE_BLOCK, YesNo.YES ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); + @Override + protected void addButtons() { + this.placeMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.PLACE_BLOCK, YesNo.YES); + this.fuzzyMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 48, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender ) ); + this.buttonList.add(this.priority = new GuiTabButton(this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender)); - this.buttonList.add( this.placeMode ); - this.buttonList.add( this.fuzzyMode ); - } + this.buttonList.add(this.placeMode); + this.buttonList.add(this.fuzzyMode); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.FormationPlane.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.FormationPlane.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); - if( this.fuzzyMode != null ) - { - this.fuzzyMode.set( this.cvb.getFuzzyMode() ); - } + if (this.fuzzyMode != null) { + this.fuzzyMode.set(this.cvb.getFuzzyMode()); + } - if( this.placeMode != null ) - { - this.placeMode.set( ( (ContainerFormationPlane) this.cvb ).getPlaceMode() ); - } - } + if (this.placeMode != null) { + this.placeMode.set(((ContainerFormationPlane) this.cvb).getPlaceMode()); + } + } - @Override - protected String getBackground() - { - return "guis/storagebus.png"; - } + @Override + protected String getBackground() { + return "guis/storagebus.png"; + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - if( btn == this.priority ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - else if( btn == this.placeMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.placeMode.getSetting(), backwards ) ); - } - } + if (btn == this.priority) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } else if (btn == this.placeMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.placeMode.getSetting(), backwards)); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiGrinder.java b/src/main/java/appeng/client/gui/implementations/GuiGrinder.java index 2fc12b54e..8f8ee26e6 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiGrinder.java +++ b/src/main/java/appeng/client/gui/implementations/GuiGrinder.java @@ -19,34 +19,29 @@ package appeng.client.gui.implementations; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.client.gui.AEBaseGui; import appeng.container.implementations.ContainerGrinder; import appeng.core.localization.GuiText; import appeng.tile.grindstone.TileGrinder; +import net.minecraft.entity.player.InventoryPlayer; -public class GuiGrinder extends AEBaseGui -{ +public class GuiGrinder extends AEBaseGui { - public GuiGrinder( final InventoryPlayer inventoryPlayer, final TileGrinder te ) - { - super( new ContainerGrinder( inventoryPlayer, te ) ); - this.ySize = 176; - } + public GuiGrinder(final InventoryPlayer inventoryPlayer, final TileGrinder te) { + super(new ContainerGrinder(inventoryPlayer, te)); + this.ySize = 176; + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.GrindStone.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.GrindStone.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/grinder.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/grinder.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiIOPort.java b/src/main/java/appeng/client/gui/implementations/GuiIOPort.java index fa63b7e54..7f7a01359 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiIOPort.java +++ b/src/main/java/appeng/client/gui/implementations/GuiIOPort.java @@ -19,13 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.AEApi; import appeng.api.config.FullnessMode; import appeng.api.config.OperationMode; @@ -38,87 +31,80 @@ import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; import appeng.tile.storage.TileIOPort; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import org.lwjgl.input.Mouse; + +import java.io.IOException; -public class GuiIOPort extends GuiUpgradeable -{ +public class GuiIOPort extends GuiUpgradeable { - private GuiImgButton fullMode; - private GuiImgButton operationMode; + private GuiImgButton fullMode; + private GuiImgButton operationMode; - public GuiIOPort( final InventoryPlayer inventoryPlayer, final TileIOPort te ) - { - super( new ContainerIOPort( inventoryPlayer, te ) ); - this.ySize = 166; - } + public GuiIOPort(final InventoryPlayer inventoryPlayer, final TileIOPort te) { + super(new ContainerIOPort(inventoryPlayer, te)); + this.ySize = 166; + } - @Override - protected void addButtons() - { - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.fullMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.FULLNESS_MODE, FullnessMode.EMPTY ); - this.operationMode = new GuiImgButton( this.guiLeft + 80, this.guiTop + 17, Settings.OPERATION_MODE, OperationMode.EMPTY ); + @Override + protected void addButtons() { + this.redstoneMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.fullMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.FULLNESS_MODE, FullnessMode.EMPTY); + this.operationMode = new GuiImgButton(this.guiLeft + 80, this.guiTop + 17, Settings.OPERATION_MODE, OperationMode.EMPTY); - this.buttonList.add( this.operationMode ); - this.buttonList.add( this.redstoneMode ); - this.buttonList.add( this.fullMode ); - } + this.buttonList.add(this.operationMode); + this.buttonList.add(this.redstoneMode); + this.buttonList.add(this.fullMode); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.IOPort.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.IOPort.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); - if( this.redstoneMode != null ) - { - this.redstoneMode.set( this.cvb.getRedStoneMode() ); - } + if (this.redstoneMode != null) { + this.redstoneMode.set(this.cvb.getRedStoneMode()); + } - if( this.operationMode != null ) - { - this.operationMode.set( ( (ContainerIOPort) this.cvb ).getOperationMode() ); - } + if (this.operationMode != null) { + this.operationMode.set(((ContainerIOPort) this.cvb).getOperationMode()); + } - if( this.fullMode != null ) - { - this.fullMode.set( ( (ContainerIOPort) this.cvb ).getFullMode() ); - } - } + if (this.fullMode != null) { + this.fullMode.set(((ContainerIOPort) this.cvb).getFullMode()); + } + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawBG( offsetX, offsetY, mouseX, mouseY ); + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawBG(offsetX, offsetY, mouseX, mouseY); - final IDefinitions definitions = AEApi.instance().definitions(); + final IDefinitions definitions = AEApi.instance().definitions(); - definitions.items().cell1k().maybeStack( 1 ).ifPresent( cell1kStack -> this.drawItem( offsetX + 66 - 8, offsetY + 17, cell1kStack ) ); + definitions.items().cell1k().maybeStack(1).ifPresent(cell1kStack -> this.drawItem(offsetX + 66 - 8, offsetY + 17, cell1kStack)); - definitions.blocks().drive().maybeStack( 1 ).ifPresent( driveStack -> this.drawItem( offsetX + 94 + 8, offsetY + 17, driveStack ) ); - } + definitions.blocks().drive().maybeStack(1).ifPresent(driveStack -> this.drawItem(offsetX + 94 + 8, offsetY + 17, driveStack)); + } - @Override - protected String getBackground() - { - return "guis/io_port.png"; - } + @Override + protected String getBackground() { + return "guis/io_port.png"; + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - if( btn == this.fullMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.fullMode.getSetting(), backwards ) ); - } + if (btn == this.fullMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.fullMode.getSetting(), backwards)); + } - if( btn == this.operationMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.operationMode.getSetting(), backwards ) ); - } - } + if (btn == this.operationMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.operationMode.getSetting(), backwards)); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiInscriber.java b/src/main/java/appeng/client/gui/implementations/GuiInscriber.java index 2c6dfc018..0dcf31494 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiInscriber.java +++ b/src/main/java/appeng/client/gui/implementations/GuiInscriber.java @@ -19,8 +19,6 @@ package appeng.client.gui.implementations; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiProgressBar; import appeng.client.gui.widgets.GuiProgressBar.Direction; @@ -28,66 +26,58 @@ import appeng.container.implementations.ContainerInscriber; import appeng.container.implementations.ContainerUpgradeable; import appeng.core.localization.GuiText; import appeng.tile.misc.TileInscriber; +import net.minecraft.entity.player.InventoryPlayer; -public class GuiInscriber extends AEBaseGui -{ +public class GuiInscriber extends AEBaseGui { - private final ContainerInscriber cvc; - private GuiProgressBar pb; + private final ContainerInscriber cvc; + private GuiProgressBar pb; - public GuiInscriber( final InventoryPlayer inventoryPlayer, final TileInscriber te ) - { - super( new ContainerInscriber( inventoryPlayer, te ) ); - this.cvc = (ContainerInscriber) this.inventorySlots; - this.ySize = 176; - this.xSize = this.hasToolbox() ? 246 : 211; - } + public GuiInscriber(final InventoryPlayer inventoryPlayer, final TileInscriber te) { + super(new ContainerInscriber(inventoryPlayer, te)); + this.cvc = (ContainerInscriber) this.inventorySlots; + this.ySize = 176; + this.xSize = this.hasToolbox() ? 246 : 211; + } - private boolean hasToolbox() - { - return ( (ContainerUpgradeable) this.inventorySlots ).hasToolbox(); - } + private boolean hasToolbox() { + return ((ContainerUpgradeable) this.inventorySlots).hasToolbox(); + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.pb = new GuiProgressBar( this.cvc, "guis/inscriber.png", 135, 39, 135, 177, 6, 18, Direction.VERTICAL ); - this.buttonList.add( this.pb ); - } + this.pb = new GuiProgressBar(this.cvc, "guis/inscriber.png", 135, 39, 135, 177, 6, 18, Direction.VERTICAL); + this.buttonList.add(this.pb); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.pb.setFullMsg( this.cvc.getCurrentProgress() * 100 / this.cvc.getMaxProgress() + "%" ); + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.pb.setFullMsg(this.cvc.getCurrentProgress() * 100 / this.cvc.getMaxProgress() + "%"); - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.Inscriber.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - } + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.Inscriber.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/inscriber.png" ); - this.pb.x = 135 + this.guiLeft; - this.pb.y = 39 + this.guiTop; + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/inscriber.png"); + this.pb.x = 135 + this.guiLeft; + this.pb.y = 39 + this.guiTop; - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, 211 - 34, this.ySize ); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, 211 - 34, this.ySize); - if( this.drawUpgrades() ) - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 14 + this.cvc.availableUpgrades() * 18 ); - } - if( this.hasToolbox() ) - { - this.drawTexturedModalRect( offsetX + 178, offsetY + this.ySize - 90, 178, this.ySize - 90, 68, 68 ); - } - } + if (this.drawUpgrades()) { + this.drawTexturedModalRect(offsetX + 177, offsetY, 177, 0, 35, 14 + this.cvc.availableUpgrades() * 18); + } + if (this.hasToolbox()) { + this.drawTexturedModalRect(offsetX + 178, offsetY + this.ySize - 90, 178, this.ySize - 90, 68, 68); + } + } - private boolean drawUpgrades() - { - return true; - } + private boolean drawUpgrades() { + return true; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiInterface.java b/src/main/java/appeng/client/gui/implementations/GuiInterface.java index 94c0a6e68..ee501be3c 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiInterface.java +++ b/src/main/java/appeng/client/gui/implementations/GuiInterface.java @@ -19,13 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.config.Settings; import appeng.api.config.YesNo; import appeng.client.gui.widgets.GuiImgButton; @@ -38,90 +31,81 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; import appeng.core.sync.packets.PacketSwitchGuis; import appeng.helpers.IInterfaceHost; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import org.lwjgl.input.Mouse; + +import java.io.IOException; -public class GuiInterface extends GuiUpgradeable -{ +public class GuiInterface extends GuiUpgradeable { - private GuiTabButton priority; - private GuiImgButton BlockMode; - private GuiToggleButton interfaceMode; + private GuiTabButton priority; + private GuiImgButton BlockMode; + private GuiToggleButton interfaceMode; - public GuiInterface( final InventoryPlayer inventoryPlayer, final IInterfaceHost te ) - { - super( new ContainerInterface( inventoryPlayer, te ) ); - this.ySize = 256; - } + public GuiInterface(final InventoryPlayer inventoryPlayer, final IInterfaceHost te) { + super(new ContainerInterface(inventoryPlayer, te)); + this.ySize = 256; + } - @Override - protected void addButtons() - { - this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender ); - this.buttonList.add( this.priority ); + @Override + protected void addButtons() { + this.priority = new GuiTabButton(this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender); + this.buttonList.add(this.priority); - this.BlockMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.BLOCK, YesNo.NO ); - this.buttonList.add( this.BlockMode ); + this.BlockMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.BLOCK, YesNo.NO); + this.buttonList.add(this.BlockMode); - this.interfaceMode = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 26, 84, 85, GuiText.InterfaceTerminal.getLocal(), GuiText.InterfaceTerminalHint.getLocal() ); - this.buttonList.add( this.interfaceMode ); - } + this.interfaceMode = new GuiToggleButton(this.guiLeft - 18, this.guiTop + 26, 84, 85, GuiText.InterfaceTerminal.getLocal(), GuiText.InterfaceTerminalHint.getLocal()); + this.buttonList.add(this.interfaceMode); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - if( this.BlockMode != null ) - { - this.BlockMode.set( ( (ContainerInterface) this.cvb ).getBlockingMode() ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + if (this.BlockMode != null) { + this.BlockMode.set(((ContainerInterface) this.cvb).getBlockingMode()); + } - if( this.interfaceMode != null ) - { - this.interfaceMode.setState( ( (ContainerInterface) this.cvb ).getInterfaceTerminalMode() == YesNo.YES ); - } + if (this.interfaceMode != null) { + this.interfaceMode.setState(((ContainerInterface) this.cvb).getInterfaceTerminalMode() == YesNo.YES); + } - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.Interface.getLocal() ), 8, 6, 4210752 ); + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.Interface.getLocal()), 8, 6, 4210752); - this.fontRenderer.drawString( GuiText.Config.getLocal(), 8, 6 + 11 + 7, 4210752 ); - this.fontRenderer.drawString( GuiText.StoredItems.getLocal(), 8, 6 + 60 + 7, 4210752 ); - this.fontRenderer.drawString( GuiText.Patterns.getLocal(), 8, 6 + 73 + 7, 4210752 ); + this.fontRenderer.drawString(GuiText.Config.getLocal(), 8, 6 + 11 + 7, 4210752); + this.fontRenderer.drawString(GuiText.StoredItems.getLocal(), 8, 6 + 60 + 7, 4210752); + this.fontRenderer.drawString(GuiText.Patterns.getLocal(), 8, 6 + 73 + 7, 4210752); - } + } - @Override - protected String getBackground() - { - int upgrades = ( (ContainerInterface) this.cvb ).getPatternUpgrades(); - if( upgrades == 0 ) - { - return "guis/newinterface.png"; - } - else - { - return "guis/newinterface" + upgrades + ".png"; - } - } + @Override + protected String getBackground() { + int upgrades = ((ContainerInterface) this.cvb).getPatternUpgrades(); + if (upgrades == 0) { + return "guis/newinterface.png"; + } else { + return "guis/newinterface" + upgrades + ".png"; + } + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - if( btn == this.priority ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } + if (btn == this.priority) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } - if( btn == this.interfaceMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( Settings.INTERFACE_TERMINAL, backwards ) ); - } + if (btn == this.interfaceMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(Settings.INTERFACE_TERMINAL, backwards)); + } - if( btn == this.BlockMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.BlockMode.getSetting(), backwards ) ); - } - } + if (btn == this.BlockMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.BlockMode.getSetting(), backwards)); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiInterfaceConfigurationTerminal.java b/src/main/java/appeng/client/gui/implementations/GuiInterfaceConfigurationTerminal.java index 11386a198..e86b2c404 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiInterfaceConfigurationTerminal.java +++ b/src/main/java/appeng/client/gui/implementations/GuiInterfaceConfigurationTerminal.java @@ -19,25 +19,28 @@ package appeng.client.gui.implementations; -import java.awt.*; -import java.io.IOException; -import java.util.*; -import java.util.List; - +import appeng.api.AEApi; import appeng.api.config.ActionItems; import appeng.api.config.Settings; +import appeng.api.storage.channels.IItemStorageChannel; +import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiImgButton; +import appeng.client.gui.widgets.GuiScrollbar; +import appeng.client.gui.widgets.MEGuiTextField; +import appeng.client.me.ClientDCInternalInv; +import appeng.client.me.SlotDisconnected; import appeng.container.implementations.ContainerInterfaceConfigurationTerminal; import appeng.container.interfaces.IJEIGhostIngredients; +import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketInventoryAction; import appeng.helpers.DualityInterface; import appeng.helpers.InventoryAction; import appeng.parts.reporting.PartInterfaceConfigurationTerminal; import appeng.util.BlockPosUtils; +import appeng.util.Platform; import appeng.util.item.AEItemStack; import com.google.common.collect.HashMultimap; - import mezz.jei.api.gui.IGhostIngredientHandler; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; @@ -45,531 +48,436 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; - -import appeng.api.AEApi; -import appeng.api.storage.channels.IItemStorageChannel; -import appeng.client.gui.AEBaseGui; -import appeng.client.gui.widgets.GuiScrollbar; -import appeng.client.gui.widgets.MEGuiTextField; -import appeng.client.me.ClientDCInternalInv; -import appeng.client.me.SlotDisconnected; -import appeng.core.localization.GuiText; -import appeng.util.Platform; import net.minecraft.nbt.NBTUtil; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.common.DimensionManager; import org.lwjgl.input.Mouse; +import java.awt.*; +import java.io.IOException; +import java.util.List; +import java.util.*; import static appeng.client.render.BlockPosHighlighter.hilightBlock; -public class GuiInterfaceConfigurationTerminal extends AEBaseGui implements IJEIGhostIngredients -{ - - private static final int LINES_ON_PAGE = 6; - - // TODO: copied from GuiMEMonitorable. It looks not changed, maybe unneeded? - private final int offsetX = 21; - - private final HashMap byId = new HashMap<>(); - private final HashMultimap byName = HashMultimap.create(); - private final HashMap blockPosHashMap = new HashMap<>(); - private final HashMap guiButtonHashMap = new HashMap<>(); - private final Map numUpgradesMap = new HashMap<>(); - private final ArrayList names = new ArrayList<>(); - private final ArrayList lines = new ArrayList<>(); - private final Set matchedStacks = new HashSet<>(); - - private final Map> cachedSearches = new WeakHashMap<>(); - - private boolean refreshList = false; - private MEGuiTextField searchFieldInputs; - private PartInterfaceConfigurationTerminal partInterfaceTerminal; - private HashMap dimHashMap = new HashMap<>(); - public Map, Object> mapTargetSlot = new HashMap<>(); - - public GuiInterfaceConfigurationTerminal( final InventoryPlayer inventoryPlayer, final PartInterfaceConfigurationTerminal te ) - { - super( new ContainerInterfaceConfigurationTerminal( inventoryPlayer, te ) ); - - this.partInterfaceTerminal = te; - final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - this.xSize = 208; - this.ySize = 235; - } - - @Override - public void initGui() - { - super.initGui(); - - this.getScrollBar().setLeft( 189 ); - this.getScrollBar().setHeight( 106 ); - this.getScrollBar().setTop( 31 ); - - this.searchFieldInputs = new MEGuiTextField( this.fontRenderer, this.guiLeft + Math.max( 32, this.offsetX ), this.guiTop + 17, 65, 12 ); - this.searchFieldInputs.setEnableBackgroundDrawing( false ); - this.searchFieldInputs.setMaxStringLength( 25 ); - this.searchFieldInputs.setTextColor( 0xFFFFFF ); - this.searchFieldInputs.setVisible( true ); - this.searchFieldInputs.setFocused( false ); - - this.searchFieldInputs.setText( partInterfaceTerminal.in ); - } - - @Override - public void onGuiClosed() - { - partInterfaceTerminal.saveSearchStrings( this.searchFieldInputs.getText().toLowerCase() ); - super.onGuiClosed(); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.buttonList.clear(); - - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.InterfaceConfigurationTerminal.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), this.offsetX + 2, this.ySize - 96 + 3, 4210752 ); - - final int currentScroll = this.getScrollBar().getCurrentScroll(); - - this.inventorySlots.inventorySlots.removeIf( slot -> slot instanceof SlotDisconnected ); - - int offset = 30; - int linesDraw = 0; - for( int x = 0; x < LINES_ON_PAGE && linesDraw < LINES_ON_PAGE && currentScroll + x < this.lines.size(); x++ ) - { - final Object lineObj = this.lines.get( currentScroll + x ); - if( lineObj instanceof ClientDCInternalInv ) - { - final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; - - GuiButton guiButton = new GuiImgButton( guiLeft + 4, guiTop + offset, Settings.ACTIONS, ActionItems.HIGHLIGHT_INTERFACE ); - guiButtonHashMap.put( guiButton, inv ); - this.buttonList.add( guiButton ); - int extraLines = numUpgradesMap.get( inv ); - - for( int row = 0; row < 1 + extraLines && linesDraw < LINES_ON_PAGE; ++row ) - { - for( int z = 0; z < 9; z++ ) - { - this.inventorySlots.inventorySlots.add( new SlotDisconnected( inv, z + ( row * 9 ), ( z * 18 + 22 ), offset ) ); - if( this.matchedStacks.contains( inv.getInventory().getStackInSlot( z + ( row * 9 ) ) ) ) - { - drawRect( z * 18 + 22, offset, z * 18 + 22 + 16, offset + 16, 0x2A00FF00 ); - } - } - linesDraw++; - offset += 18; - } - } - else if( lineObj instanceof String ) - { - String name = (String) lineObj; - final int rows = this.byName.get( name ).size(); - if( rows > 1 ) - { - name = name + " (" + rows + ')'; - } - - while ( name.length() > 2 && this.fontRenderer.getStringWidth( name ) > 155 ) - { - name = name.substring( 0, name.length() - 1 ); - } - this.fontRenderer.drawString( name, this.offsetX + 2, 5 + offset, 4210752 ); - linesDraw++; - offset += 18; - } - } - - if( searchFieldInputs.isMouseIn( mouseX, mouseY ) ) - { - drawTooltip( Mouse.getEventX() * this.width / this.mc.displayWidth - offsetX, mouseY - guiTop, "Inputs OR names" ); - } - } - - @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) throws IOException - { - this.searchFieldInputs.mouseClicked( xCoord, yCoord, btn ); - - if( btn == 1 && this.searchFieldInputs.isMouseIn( xCoord, yCoord ) ) - { - this.searchFieldInputs.setText( "" ); - this.refreshList(); - } - - super.mouseClicked( xCoord, yCoord, btn ); - } - - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - if( guiButtonHashMap.containsKey( btn ) ) - { - BlockPos blockPos = blockPosHashMap.get( guiButtonHashMap.get( this.selectedButton ) ); - BlockPos blockPos2 = mc.player.getPosition(); - int playerDim = mc.world.provider.getDimension(); - int interfaceDim = dimHashMap.get( guiButtonHashMap.get( this.selectedButton ) ); - if( playerDim != interfaceDim ) - { - try - { - mc.player.sendStatusMessage( new TextComponentString( "Interface located at dimension: " + interfaceDim + " [" + DimensionManager.getWorld( interfaceDim ).provider.getDimensionType().getName() + "] and cant be highlighted" ), false ); - } - catch( Exception e ) - { - mc.player.sendStatusMessage( new TextComponentString( "Interface is located in another dimension and cannot be highlighted" ), false ); - } - } - else - { - hilightBlock( blockPos, System.currentTimeMillis() + 500 * BlockPosUtils.getDistance( blockPos, blockPos2 ), playerDim ); - mc.player.sendStatusMessage( new TextComponentString( "The interface is now highlighted at " + "X: " + blockPos.getX() + " Y: " + blockPos.getY() + " Z: " + blockPos.getZ() ), false ); - } - mc.player.closeScreen(); - } - } - - @Override - protected void mouseWheelEvent( final int x, final int y, final int wheel ) - { - final Slot slot = this.getSlot( x, y ); - if( slot instanceof SlotDisconnected ) - { - final ItemStack stack = slot.getStack(); - if( stack != ItemStack.EMPTY ) - { - InventoryAction direction = wheel > 0 ? InventoryAction.PLACE_SINGLE : InventoryAction.PICKUP_SINGLE; - final PacketInventoryAction p = new PacketInventoryAction( direction, slot.getSlotIndex(), ( (SlotDisconnected) slot ).getSlot().getId() ); - NetworkHandler.instance().sendToServer( p ); - } - } - else - { - super.mouseWheelEvent( x, y, wheel ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/interfaceconfigurationterminal.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - - int offset = 29; - final int ex = this.getScrollBar().getCurrentScroll(); - int linesDraw = 0; - for( int x = 0; x < LINES_ON_PAGE && linesDraw < LINES_ON_PAGE && ex + x < this.lines.size(); x++ ) - { - final Object lineObj = this.lines.get( ex + x ); - if( lineObj instanceof ClientDCInternalInv ) - { - GlStateManager.color( 1, 1, 1, 1 ); - final int width = 9 * 18; - - int extraLines = numUpgradesMap.get( lineObj ); - - for( int row = 0; row < 1 + extraLines && linesDraw < LINES_ON_PAGE; ++row ) - { - this.drawTexturedModalRect( offsetX + 20, offsetY + offset, 20, 170, width, 18 ); - offset += 18; - linesDraw++; - } - } - else - { - offset += 18; - linesDraw++; - } - } - - if( this.searchFieldInputs != null ) - { - this.searchFieldInputs.drawTextBox(); - } - } - - @Override - protected void keyTyped( final char character, final int key ) throws IOException - { - if( !this.checkHotbarKeys( key ) ) - { - if( character == ' ' && this.searchFieldInputs.getText().isEmpty() && this.searchFieldInputs.isFocused() ) - { - return; - } - - if( this.searchFieldInputs.textboxKeyTyped( character, key ) ) - { - this.refreshList(); - } - - else - { - super.keyTyped( character, key ); - } - } - } - - public void postUpdate( final NBTTagCompound in ) - { - if( in.getBoolean( "clear" ) ) - { - this.byId.clear(); - this.refreshList = true; - } - - for( final Object oKey : in.getKeySet() ) - { - final String key = (String) oKey; - if( key.startsWith( "=" ) ) - { - try - { - final long id = Long.parseLong( key.substring( 1 ), Character.MAX_RADIX ); - final NBTTagCompound invData = in.getCompoundTag( key ); - final ClientDCInternalInv current = this.getById( id, invData.getLong( "sortBy" ), invData.getString( "un" ) ); - blockPosHashMap.put( current, NBTUtil.getPosFromTag( invData.getCompoundTag( "pos" ) ) ); - dimHashMap.put( current, invData.getInteger( "dim" ) ); - numUpgradesMap.put( current, invData.getInteger( "numUpgrades" ) ); - - for( int x = 0; x < current.getInventory().getSlots(); x++ ) - { - final String which = Integer.toString( x ); - if( invData.hasKey( which ) ) - { - current.getInventory().setStackInSlot( x, new ItemStack( invData.getCompoundTag( which ) ) ); - } - } - } - catch( final NumberFormatException ignored ) - { - } - } - } - - if( this.refreshList ) - { - this.refreshList = false; - // invalid caches on refresh - this.cachedSearches.clear(); - this.refreshList(); - } - } - - /** - * Rebuilds the list of interfaces. - *

- * Respects a search term if present (ignores case) and adding only matching patterns. - */ - private void refreshList() - { - this.byName.clear(); - this.buttonList.clear(); - this.matchedStacks.clear(); - - final String searchFieldInputs = this.searchFieldInputs.getText().toLowerCase(); - - final Set cachedSearch = this.getCacheForSearchTerm( searchFieldInputs ); - final boolean rebuild = cachedSearch.isEmpty(); - - for( final ClientDCInternalInv entry : this.byId.values() ) - { - // ignore inventory if not doing a full rebuild and cache already marks it as miss. - if( !rebuild && !cachedSearch.contains( entry ) ) - { - continue; - } - - // Shortcut to skip any filter if search term is ""/empty - - boolean found = searchFieldInputs.isEmpty(); - - // Search if the current inventory holds a pattern containing the search term. - if( !found ) - { - int slot = 0; - for( final ItemStack itemStack : entry.getInventory() ) - { - if( slot > 8 + numUpgradesMap.get( entry ) * 9 ) - { - break; - } - if( this.itemStackMatchesSearchTerm( itemStack, searchFieldInputs ) ) - { - found = true; - matchedStacks.add( itemStack ); - } - slot++; - } - } - // if found, filter skipped or machine name matching the search term, add it - if( found || entry.getName().toLowerCase().contains( searchFieldInputs ) ) - { - this.byName.put( entry.getName(), entry ); - cachedSearch.add( entry ); - } - else - { - cachedSearch.remove( entry ); - } - } - - this.names.clear(); - this.names.addAll( this.byName.keySet() ); - - Collections.sort( this.names ); - - this.lines.clear(); - this.lines.ensureCapacity( this.getMaxRows() ); - - for( final String n : this.names ) - { - this.lines.add( n ); - - final ArrayList clientInventories = new ArrayList<>(); - clientInventories.addAll( this.byName.get( n ) ); - - Collections.sort( clientInventories ); - this.lines.addAll( clientInventories ); - } - - this.getScrollBar().setRange( 0, this.lines.size() - 1, 1 ); - } - - private boolean itemStackMatchesSearchTerm( final ItemStack itemStack, final String searchTerm ) - { - if( itemStack.isEmpty() ) - { - return false; - } - - boolean foundMatchingItemStack = false; - - final String displayName = Platform - .getItemDisplayName( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( itemStack ) ) - .toLowerCase(); - - for( String term : searchTerm.split( " " ) ) - { - if( term.length() > 1 && ( term.startsWith( "-" ) || term.startsWith( "!" ) ) ) - { - term = term.substring( 1 ); - if( displayName.contains( term ) ) - { - return false; - } - } - else if( displayName.contains( term ) ) - { - foundMatchingItemStack = true; - } - } - return foundMatchingItemStack; - } - - /** - * Tries to retrieve a cache for a with search term as keyword. - *

- * If this cache should be empty, it will populate it with an earlier cache if available or at least the cache for - * the empty string. - * - * @param searchTerm the corresponding search - * @return a Set matching a superset of the search term - */ - private Set getCacheForSearchTerm( final String searchTerm ) - { - if( !this.cachedSearches.containsKey( searchTerm ) ) - { - this.cachedSearches.put( searchTerm, new HashSet<>() ); - } - - final Set cache = this.cachedSearches.get( searchTerm ); - - if( cache.isEmpty() && searchTerm.length() > 1 ) - { - cache.addAll( this.getCacheForSearchTerm( searchTerm.substring( 0, searchTerm.length() - 1 ) ) ); - return cache; - } - - return cache; - } - - /** - * The max amount of unique names and each inv row. Not affected by the filtering. - * - * @return max amount of unique names and each inv row - */ - private int getMaxRows() - { - return this.names.size() + this.byId.size(); - } - - private ClientDCInternalInv getById( final long id, final long sortBy, final String string ) - { - ClientDCInternalInv o = this.byId.get( id ); - - if( o == null ) - { - this.byId.put( id, o = new ClientDCInternalInv( DualityInterface.NUMBER_OF_CONFIG_SLOTS, id, sortBy, string, 64 ) ); - this.refreshList = true; - } - - return o; - } - - @Override - public List> getPhantomTargets( Object ingredient ) - { - if( !( ingredient instanceof ItemStack ) ) - { - return Collections.emptyList(); - } - List> targets = new ArrayList<>(); - for( Slot slot : this.inventorySlots.inventorySlots ) - { - if( slot instanceof SlotDisconnected ) - { - ItemStack itemStack = (ItemStack) ingredient; - IGhostIngredientHandler.Target target = new IGhostIngredientHandler.Target() - { - @Override - public Rectangle getArea() - { - return new Rectangle( getGuiLeft() + slot.xPos, getGuiTop() + slot.yPos, 16, 16 ); - } - - @Override - public void accept( Object ingredient ) - { - final PacketInventoryAction p; - try - { - p = new PacketInventoryAction( InventoryAction.PLACE_JEI_GHOST_ITEM, (SlotDisconnected) slot, AEItemStack.fromItemStack( itemStack ) ); - NetworkHandler.instance().sendToServer( p ); - - } - catch( IOException e ) - { - e.printStackTrace(); - } - } - }; - targets.add( target ); - mapTargetSlot.putIfAbsent( target, slot ); - } - } - return targets; - } - - @Override - public Map, Object> getFakeSlotTargetMap() - { - return IJEIGhostIngredients.super.getFakeSlotTargetMap(); - } +public class GuiInterfaceConfigurationTerminal extends AEBaseGui implements IJEIGhostIngredients { + + private static final int LINES_ON_PAGE = 6; + + // TODO: copied from GuiMEMonitorable. It looks not changed, maybe unneeded? + private final int offsetX = 21; + + private final HashMap byId = new HashMap<>(); + private final HashMultimap byName = HashMultimap.create(); + private final HashMap blockPosHashMap = new HashMap<>(); + private final HashMap guiButtonHashMap = new HashMap<>(); + private final Map numUpgradesMap = new HashMap<>(); + private final ArrayList names = new ArrayList<>(); + private final ArrayList lines = new ArrayList<>(); + private final Set matchedStacks = new HashSet<>(); + + private final Map> cachedSearches = new WeakHashMap<>(); + + private boolean refreshList = false; + private MEGuiTextField searchFieldInputs; + private final PartInterfaceConfigurationTerminal partInterfaceTerminal; + private final HashMap dimHashMap = new HashMap<>(); + public Map, Object> mapTargetSlot = new HashMap<>(); + + public GuiInterfaceConfigurationTerminal(final InventoryPlayer inventoryPlayer, final PartInterfaceConfigurationTerminal te) { + super(new ContainerInterfaceConfigurationTerminal(inventoryPlayer, te)); + + this.partInterfaceTerminal = te; + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar(scrollbar); + this.xSize = 208; + this.ySize = 235; + } + + @Override + public void initGui() { + super.initGui(); + + this.getScrollBar().setLeft(189); + this.getScrollBar().setHeight(106); + this.getScrollBar().setTop(31); + + this.searchFieldInputs = new MEGuiTextField(this.fontRenderer, this.guiLeft + Math.max(32, this.offsetX), this.guiTop + 17, 65, 12); + this.searchFieldInputs.setEnableBackgroundDrawing(false); + this.searchFieldInputs.setMaxStringLength(25); + this.searchFieldInputs.setTextColor(0xFFFFFF); + this.searchFieldInputs.setVisible(true); + this.searchFieldInputs.setFocused(false); + + this.searchFieldInputs.setText(partInterfaceTerminal.in); + } + + @Override + public void onGuiClosed() { + partInterfaceTerminal.saveSearchStrings(this.searchFieldInputs.getText().toLowerCase()); + super.onGuiClosed(); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.buttonList.clear(); + + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.InterfaceConfigurationTerminal.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), this.offsetX + 2, this.ySize - 96 + 3, 4210752); + + final int currentScroll = this.getScrollBar().getCurrentScroll(); + + this.inventorySlots.inventorySlots.removeIf(slot -> slot instanceof SlotDisconnected); + + int offset = 30; + int linesDraw = 0; + for (int x = 0; x < LINES_ON_PAGE && linesDraw < LINES_ON_PAGE && currentScroll + x < this.lines.size(); x++) { + final Object lineObj = this.lines.get(currentScroll + x); + if (lineObj instanceof ClientDCInternalInv) { + final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; + + GuiButton guiButton = new GuiImgButton(guiLeft + 4, guiTop + offset, Settings.ACTIONS, ActionItems.HIGHLIGHT_INTERFACE); + guiButtonHashMap.put(guiButton, inv); + this.buttonList.add(guiButton); + int extraLines = numUpgradesMap.get(inv); + + for (int row = 0; row < 1 + extraLines && linesDraw < LINES_ON_PAGE; ++row) { + for (int z = 0; z < 9; z++) { + this.inventorySlots.inventorySlots.add(new SlotDisconnected(inv, z + (row * 9), (z * 18 + 22), offset)); + if (this.matchedStacks.contains(inv.getInventory().getStackInSlot(z + (row * 9)))) { + drawRect(z * 18 + 22, offset, z * 18 + 22 + 16, offset + 16, 0x2A00FF00); + } + } + linesDraw++; + offset += 18; + } + } else if (lineObj instanceof String) { + String name = (String) lineObj; + final int rows = this.byName.get(name).size(); + if (rows > 1) { + name = name + " (" + rows + ')'; + } + + while (name.length() > 2 && this.fontRenderer.getStringWidth(name) > 155) { + name = name.substring(0, name.length() - 1); + } + this.fontRenderer.drawString(name, this.offsetX + 2, 5 + offset, 4210752); + linesDraw++; + offset += 18; + } + } + + if (searchFieldInputs.isMouseIn(mouseX, mouseY)) { + drawTooltip(Mouse.getEventX() * this.width / this.mc.displayWidth - offsetX, mouseY - guiTop, "Inputs OR names"); + } + } + + @Override + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) throws IOException { + this.searchFieldInputs.mouseClicked(xCoord, yCoord, btn); + + if (btn == 1 && this.searchFieldInputs.isMouseIn(xCoord, yCoord)) { + this.searchFieldInputs.setText(""); + this.refreshList(); + } + + super.mouseClicked(xCoord, yCoord, btn); + } + + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + if (guiButtonHashMap.containsKey(btn)) { + BlockPos blockPos = blockPosHashMap.get(guiButtonHashMap.get(this.selectedButton)); + BlockPos blockPos2 = mc.player.getPosition(); + int playerDim = mc.world.provider.getDimension(); + int interfaceDim = dimHashMap.get(guiButtonHashMap.get(this.selectedButton)); + if (playerDim != interfaceDim) { + try { + mc.player.sendStatusMessage(new TextComponentString("Interface located at dimension: " + interfaceDim + " [" + DimensionManager.getWorld(interfaceDim).provider.getDimensionType().getName() + "] and cant be highlighted"), false); + } catch (Exception e) { + mc.player.sendStatusMessage(new TextComponentString("Interface is located in another dimension and cannot be highlighted"), false); + } + } else { + hilightBlock(blockPos, System.currentTimeMillis() + 500 * BlockPosUtils.getDistance(blockPos, blockPos2), playerDim); + mc.player.sendStatusMessage(new TextComponentString("The interface is now highlighted at " + "X: " + blockPos.getX() + " Y: " + blockPos.getY() + " Z: " + blockPos.getZ()), false); + } + mc.player.closeScreen(); + } + } + + @Override + protected void mouseWheelEvent(final int x, final int y, final int wheel) { + final Slot slot = this.getSlot(x, y); + if (slot instanceof SlotDisconnected) { + final ItemStack stack = slot.getStack(); + if (stack != ItemStack.EMPTY) { + InventoryAction direction = wheel > 0 ? InventoryAction.PLACE_SINGLE : InventoryAction.PICKUP_SINGLE; + final PacketInventoryAction p = new PacketInventoryAction(direction, slot.getSlotIndex(), ((SlotDisconnected) slot).getSlot().getId()); + NetworkHandler.instance().sendToServer(p); + } + } else { + super.mouseWheelEvent(x, y, wheel); + } + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/interfaceconfigurationterminal.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + + int offset = 29; + final int ex = this.getScrollBar().getCurrentScroll(); + int linesDraw = 0; + for (int x = 0; x < LINES_ON_PAGE && linesDraw < LINES_ON_PAGE && ex + x < this.lines.size(); x++) { + final Object lineObj = this.lines.get(ex + x); + if (lineObj instanceof ClientDCInternalInv) { + GlStateManager.color(1, 1, 1, 1); + final int width = 9 * 18; + + int extraLines = numUpgradesMap.get(lineObj); + + for (int row = 0; row < 1 + extraLines && linesDraw < LINES_ON_PAGE; ++row) { + this.drawTexturedModalRect(offsetX + 20, offsetY + offset, 20, 170, width, 18); + offset += 18; + linesDraw++; + } + } else { + offset += 18; + linesDraw++; + } + } + + if (this.searchFieldInputs != null) { + this.searchFieldInputs.drawTextBox(); + } + } + + @Override + protected void keyTyped(final char character, final int key) throws IOException { + if (!this.checkHotbarKeys(key)) { + if (character == ' ' && this.searchFieldInputs.getText().isEmpty() && this.searchFieldInputs.isFocused()) { + return; + } + + if (this.searchFieldInputs.textboxKeyTyped(character, key)) { + this.refreshList(); + } else { + super.keyTyped(character, key); + } + } + } + + public void postUpdate(final NBTTagCompound in) { + if (in.getBoolean("clear")) { + this.byId.clear(); + this.refreshList = true; + } + + for (final Object oKey : in.getKeySet()) { + final String key = (String) oKey; + if (key.startsWith("=")) { + try { + final long id = Long.parseLong(key.substring(1), Character.MAX_RADIX); + final NBTTagCompound invData = in.getCompoundTag(key); + final ClientDCInternalInv current = this.getById(id, invData.getLong("sortBy"), invData.getString("un")); + blockPosHashMap.put(current, NBTUtil.getPosFromTag(invData.getCompoundTag("pos"))); + dimHashMap.put(current, invData.getInteger("dim")); + numUpgradesMap.put(current, invData.getInteger("numUpgrades")); + + for (int x = 0; x < current.getInventory().getSlots(); x++) { + final String which = Integer.toString(x); + if (invData.hasKey(which)) { + current.getInventory().setStackInSlot(x, new ItemStack(invData.getCompoundTag(which))); + } + } + } catch (final NumberFormatException ignored) { + } + } + } + + if (this.refreshList) { + this.refreshList = false; + // invalid caches on refresh + this.cachedSearches.clear(); + this.refreshList(); + } + } + + /** + * Rebuilds the list of interfaces. + *

+ * Respects a search term if present (ignores case) and adding only matching patterns. + */ + private void refreshList() { + this.byName.clear(); + this.buttonList.clear(); + this.matchedStacks.clear(); + + final String searchFieldInputs = this.searchFieldInputs.getText().toLowerCase(); + + final Set cachedSearch = this.getCacheForSearchTerm(searchFieldInputs); + final boolean rebuild = cachedSearch.isEmpty(); + + for (final ClientDCInternalInv entry : this.byId.values()) { + // ignore inventory if not doing a full rebuild and cache already marks it as miss. + if (!rebuild && !cachedSearch.contains(entry)) { + continue; + } + + // Shortcut to skip any filter if search term is ""/empty + + boolean found = searchFieldInputs.isEmpty(); + + // Search if the current inventory holds a pattern containing the search term. + if (!found) { + int slot = 0; + for (final ItemStack itemStack : entry.getInventory()) { + if (slot > 8 + numUpgradesMap.get(entry) * 9) { + break; + } + if (this.itemStackMatchesSearchTerm(itemStack, searchFieldInputs)) { + found = true; + matchedStacks.add(itemStack); + } + slot++; + } + } + // if found, filter skipped or machine name matching the search term, add it + if (found || entry.getName().toLowerCase().contains(searchFieldInputs)) { + this.byName.put(entry.getName(), entry); + cachedSearch.add(entry); + } else { + cachedSearch.remove(entry); + } + } + + this.names.clear(); + this.names.addAll(this.byName.keySet()); + + Collections.sort(this.names); + + this.lines.clear(); + this.lines.ensureCapacity(this.getMaxRows()); + + for (final String n : this.names) { + this.lines.add(n); + + final ArrayList clientInventories = new ArrayList<>(); + clientInventories.addAll(this.byName.get(n)); + + Collections.sort(clientInventories); + this.lines.addAll(clientInventories); + } + + this.getScrollBar().setRange(0, this.lines.size() - 1, 1); + } + + private boolean itemStackMatchesSearchTerm(final ItemStack itemStack, final String searchTerm) { + if (itemStack.isEmpty()) { + return false; + } + + boolean foundMatchingItemStack = false; + + final String displayName = Platform + .getItemDisplayName(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(itemStack)) + .toLowerCase(); + + for (String term : searchTerm.split(" ")) { + if (term.length() > 1 && (term.startsWith("-") || term.startsWith("!"))) { + term = term.substring(1); + if (displayName.contains(term)) { + return false; + } + } else if (displayName.contains(term)) { + foundMatchingItemStack = true; + } + } + return foundMatchingItemStack; + } + + /** + * Tries to retrieve a cache for a with search term as keyword. + *

+ * If this cache should be empty, it will populate it with an earlier cache if available or at least the cache for + * the empty string. + * + * @param searchTerm the corresponding search + * @return a Set matching a superset of the search term + */ + private Set getCacheForSearchTerm(final String searchTerm) { + if (!this.cachedSearches.containsKey(searchTerm)) { + this.cachedSearches.put(searchTerm, new HashSet<>()); + } + + final Set cache = this.cachedSearches.get(searchTerm); + + if (cache.isEmpty() && searchTerm.length() > 1) { + cache.addAll(this.getCacheForSearchTerm(searchTerm.substring(0, searchTerm.length() - 1))); + return cache; + } + + return cache; + } + + /** + * The max amount of unique names and each inv row. Not affected by the filtering. + * + * @return max amount of unique names and each inv row + */ + private int getMaxRows() { + return this.names.size() + this.byId.size(); + } + + private ClientDCInternalInv getById(final long id, final long sortBy, final String string) { + ClientDCInternalInv o = this.byId.get(id); + + if (o == null) { + this.byId.put(id, o = new ClientDCInternalInv(DualityInterface.NUMBER_OF_CONFIG_SLOTS, id, sortBy, string, 64)); + this.refreshList = true; + } + + return o; + } + + @Override + public List> getPhantomTargets(Object ingredient) { + if (!(ingredient instanceof ItemStack)) { + return Collections.emptyList(); + } + List> targets = new ArrayList<>(); + for (Slot slot : this.inventorySlots.inventorySlots) { + if (slot instanceof SlotDisconnected) { + ItemStack itemStack = (ItemStack) ingredient; + IGhostIngredientHandler.Target target = new IGhostIngredientHandler.Target() { + @Override + public Rectangle getArea() { + return new Rectangle(getGuiLeft() + slot.xPos, getGuiTop() + slot.yPos, 16, 16); + } + + @Override + public void accept(Object ingredient) { + final PacketInventoryAction p; + try { + p = new PacketInventoryAction(InventoryAction.PLACE_JEI_GHOST_ITEM, (SlotDisconnected) slot, AEItemStack.fromItemStack(itemStack)); + NetworkHandler.instance().sendToServer(p); + + } catch (IOException e) { + e.printStackTrace(); + } + } + }; + targets.add(target); + mapTargetSlot.putIfAbsent(target, slot); + } + } + return targets; + } + + @Override + public Map, Object> getFakeSlotTargetMap() { + return IJEIGhostIngredients.super.getFakeSlotTargetMap(); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java b/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java index d9f2ad6f5..1ce42d2da 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java +++ b/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java @@ -19,603 +19,498 @@ package appeng.client.gui.implementations; -import java.io.IOException; -import java.util.*; - +import appeng.api.AEApi; import appeng.api.config.ActionItems; import appeng.api.config.Settings; -import appeng.api.config.Upgrades; -import appeng.client.gui.widgets.GuiImgButton; -import appeng.core.worlddata.IWorldPlayerMapping; -import appeng.helpers.DualityInterface; -import appeng.parts.misc.PartInterface; -import appeng.tile.inventory.AppEngInternalInventory; -import appeng.tile.misc.TileInterface; -import appeng.util.BlockPosUtils; -import com.google.common.collect.HashMultimap; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; - -import appeng.api.AEApi; import appeng.api.storage.channels.IItemStorageChannel; import appeng.client.gui.AEBaseGui; +import appeng.client.gui.widgets.GuiImgButton; import appeng.client.gui.widgets.GuiScrollbar; import appeng.client.gui.widgets.MEGuiTextField; import appeng.client.me.ClientDCInternalInv; import appeng.client.me.SlotDisconnected; import appeng.container.implementations.ContainerInterfaceTerminal; import appeng.core.localization.GuiText; +import appeng.helpers.DualityInterface; import appeng.parts.reporting.PartInterfaceTerminal; +import appeng.util.BlockPosUtils; import appeng.util.Platform; +import com.google.common.collect.HashMultimap; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTUtil; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.common.DimensionManager; import org.lwjgl.input.Mouse; +import java.io.IOException; +import java.util.*; import static appeng.client.render.BlockPosHighlighter.hilightBlock; -public class GuiInterfaceTerminal extends AEBaseGui -{ - - private static final int LINES_ON_PAGE = 6; - - // TODO: copied from GuiMEMonitorable. It looks not changed, maybe unneeded? - private final int offsetX = 21; - - private final HashMap byId = new HashMap<>(); - private final HashMultimap byName = HashMultimap.create(); - private final HashMap blockPosHashMap = new HashMap<>(); - private final HashMap guiButtonHashMap = new HashMap<>(); - private final Map numUpgradesMap = new HashMap<>(); - private final ArrayList names = new ArrayList<>(); - private final ArrayList lines = new ArrayList<>(); - private final Set matchedStacks = new HashSet<>(); - - private final Map> cachedSearches = new WeakHashMap<>(); - - private boolean refreshList = false; - private MEGuiTextField searchFieldOutputs; - private MEGuiTextField searchFieldInputs; - private PartInterfaceTerminal partInterfaceTerminal; - private GuiButton guiButtonHide; - private GuiButton guiButtonNextAssembler; - private HashMap dimHashMap = new HashMap<>(); - - public GuiInterfaceTerminal( final InventoryPlayer inventoryPlayer, final PartInterfaceTerminal te ) - { - super( new ContainerInterfaceTerminal( inventoryPlayer, te ) ); - - this.partInterfaceTerminal = te; - final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - this.xSize = 208; - this.ySize = 255; - } - - @Override - public void initGui() - { - super.initGui(); - - this.getScrollBar().setLeft( 189 ); - this.getScrollBar().setHeight( 106 ); - this.getScrollBar().setTop( 51 ); - - this.searchFieldInputs = new MEGuiTextField( this.fontRenderer, this.guiLeft + Math.max( 32, this.offsetX ), this.guiTop + 25, 65, 12 ); - this.searchFieldInputs.setEnableBackgroundDrawing( false ); - this.searchFieldInputs.setMaxStringLength( 25 ); - this.searchFieldInputs.setTextColor( 0xFFFFFF ); - this.searchFieldInputs.setVisible( true ); - this.searchFieldInputs.setFocused( false ); - - this.searchFieldOutputs = new MEGuiTextField( this.fontRenderer, this.guiLeft + Math.max( 32, this.offsetX ), this.guiTop + 38, 65, 12 ); - this.searchFieldOutputs.setEnableBackgroundDrawing( false ); - this.searchFieldOutputs.setMaxStringLength( 25 ); - this.searchFieldOutputs.setTextColor( 0xFFFFFF ); - this.searchFieldOutputs.setVisible( true ); - this.searchFieldOutputs.setFocused( true ); - - this.searchFieldInputs.setText( partInterfaceTerminal.in ); - this.searchFieldOutputs.setText( partInterfaceTerminal.out ); - } - - @Override - public void onGuiClosed() - { - partInterfaceTerminal.saveSearchStrings( this.searchFieldInputs.getText().toLowerCase(), this.searchFieldOutputs.getText().toLowerCase() ); - super.onGuiClosed(); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.buttonList.clear(); - - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.InterfaceTerminal.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), this.offsetX + 2, this.ySize - 96 + 3, 4210752 ); - - final int currentScroll = this.getScrollBar().getCurrentScroll(); - - this.guiButtonNextAssembler = new GuiImgButton( guiLeft + 123, guiTop + 25, Settings.ACTIONS, ActionItems.FREE_MOLECULAR_SLOT_SHORTCUT ); - this.buttonList.add( guiButtonNextAssembler ); - - guiButtonHide = new GuiImgButton( guiLeft + 141, guiTop + 25, Settings.ACTIONS, this.partInterfaceTerminal.onlyInterfacesWithFreeSlots ? ActionItems.TOGGLE_SHOW_FULL_INTERFACES_OFF : ActionItems.TOGGLE_SHOW_FULL_INTERFACES_ON ); - this.buttonList.add( guiButtonHide ); - - this.inventorySlots.inventorySlots.removeIf( slot -> slot instanceof SlotDisconnected ); - - int offset = 52; - int linesDraw = 0; - for( int x = 0; x < LINES_ON_PAGE && linesDraw < LINES_ON_PAGE && currentScroll + x < this.lines.size(); x++ ) - { - final Object lineObj = this.lines.get( currentScroll + x ); - if( lineObj instanceof ClientDCInternalInv ) - { - final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; - - GuiButton guiButton = new GuiImgButton( guiLeft + 4, guiTop + offset, Settings.ACTIONS, ActionItems.HIGHLIGHT_INTERFACE ); - guiButtonHashMap.put( guiButton, inv ); - this.buttonList.add( guiButton ); - int extraLines = numUpgradesMap.get( inv ); - - for( int row = 0; row < 1 + extraLines && linesDraw < LINES_ON_PAGE; ++row ) - { - for( int z = 0; z < 9; z++ ) - { - this.inventorySlots.inventorySlots.add( new SlotDisconnected( inv, z + ( row * 9 ), ( z * 18 + 22 ), offset ) ); - if( this.matchedStacks.contains( inv.getInventory().getStackInSlot( z + ( row * 9 ) ) ) ) - { - drawRect( z * 18 + 22, offset, z * 18 + 22 + 16, offset + 16, 0x2A00FF00 ); - } - } - linesDraw++; - offset += 18; - } - } - else if( lineObj instanceof String ) - { - String name = (String) lineObj; - final int rows = this.byName.get( name ).size(); - if( rows > 1 ) - { - name = name + " (" + rows + ')'; - } - - while ( name.length() > 2 && this.fontRenderer.getStringWidth( name ) > 155 ) - { - name = name.substring( 0, name.length() - 1 ); - } - this.fontRenderer.drawString( name, this.offsetX + 2, 5 + offset, 4210752 ); - linesDraw++; - offset += 18; - } - } - - if( searchFieldInputs.isMouseIn( mouseX, mouseY ) ) - { - drawTooltip( Mouse.getEventX() * this.width / this.mc.displayWidth - offsetX, mouseY - guiTop, "Inputs OR names" ); - } - else if( searchFieldOutputs.isMouseIn( mouseX, mouseY ) ) - { - drawTooltip( Mouse.getEventX() * this.width / this.mc.displayWidth - offsetX, mouseY - guiTop, "Outputs OR names" ); - } - - } - - @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) throws IOException - { - this.searchFieldInputs.mouseClicked( xCoord, yCoord, btn ); - - if( btn == 1 && this.searchFieldInputs.isMouseIn( xCoord, yCoord ) ) - { - this.searchFieldInputs.setText( "" ); - this.refreshList(); - } - - this.searchFieldOutputs.mouseClicked( xCoord, yCoord, btn ); - - if( btn == 1 && this.searchFieldOutputs.isMouseIn( xCoord, yCoord ) ) - { - this.searchFieldOutputs.setText( "" ); - this.refreshList(); - } - - super.mouseClicked( xCoord, yCoord, btn ); - } - - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - if( guiButtonHashMap.containsKey( btn ) ) - { - BlockPos blockPos = blockPosHashMap.get( guiButtonHashMap.get( this.selectedButton ) ); - BlockPos blockPos2 = mc.player.getPosition(); - int playerDim = mc.world.provider.getDimension(); - int interfaceDim = dimHashMap.get( guiButtonHashMap.get( this.selectedButton ) ); - if( playerDim != interfaceDim ) - { - try - { - mc.player.sendStatusMessage( new TextComponentString( "Interface located at dimension: " + interfaceDim + " [" + DimensionManager.getWorld( interfaceDim ).provider.getDimensionType().getName() + "] and cant be highlighted" ), false ); - } - catch( Exception e ) - { - mc.player.sendStatusMessage( new TextComponentString( "Interface is located in another dimension and cannot be highlighted" ), false ); - } - } - else - { - hilightBlock( blockPos, System.currentTimeMillis() + 500 * BlockPosUtils.getDistance( blockPos, blockPos2 ), playerDim ); - mc.player.sendStatusMessage( new TextComponentString( "The interface is now highlighted at " + "X: " + blockPos.getX() + " Y: " + blockPos.getY() + " Z: " + blockPos.getZ() ), false ); - } - mc.player.closeScreen(); - } - - if( btn == guiButtonHide ) - { - partInterfaceTerminal.onlyInterfacesWithFreeSlots = !partInterfaceTerminal.onlyInterfacesWithFreeSlots; - this.refreshList(); - } - - if( btn == guiButtonNextAssembler ) - { - // Set Search to "Molecular Assembler" and set "Only Free Interface" - boolean currentOnlyInterfacesWithFreeSlots = this.partInterfaceTerminal.onlyInterfacesWithFreeSlots; - String currentSearchText = this.searchFieldOutputs.getText(); - - this.partInterfaceTerminal.onlyInterfacesWithFreeSlots = true; - this.searchFieldOutputs.setText( "Molecular Assembler" ); - - this.refreshList(); - - this.partInterfaceTerminal.onlyInterfacesWithFreeSlots = currentOnlyInterfacesWithFreeSlots; - this.searchFieldOutputs.setText( currentSearchText ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/newinterfaceterminal.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - - int offset = 51; - final int ex = this.getScrollBar().getCurrentScroll(); - int linesDraw = 0; - for( int x = 0; x < LINES_ON_PAGE && linesDraw < LINES_ON_PAGE && ex + x < this.lines.size(); x++ ) - { - final Object lineObj = this.lines.get( ex + x ); - if( lineObj instanceof ClientDCInternalInv ) - { - GlStateManager.color( 1, 1, 1, 1 ); - final int width = 9 * 18; - - int extraLines = numUpgradesMap.get( lineObj ); - - for( int row = 0; row < 1 + extraLines && linesDraw < LINES_ON_PAGE; ++row ) - { - this.drawTexturedModalRect( offsetX + 20, offsetY + offset, 20, 173, width, 18 ); - offset += 18; - linesDraw++; - } - } - else - { - offset += 18; - linesDraw++; - } - } - - if( this.searchFieldInputs != null ) - { - this.searchFieldInputs.drawTextBox(); - } - - if( this.searchFieldOutputs != null ) - { - this.searchFieldOutputs.drawTextBox(); - } - } - - @Override - protected void keyTyped( final char character, final int key ) throws IOException - { - if( !this.checkHotbarKeys( key ) ) - { - if( character == ' ' && this.searchFieldInputs.getText().isEmpty() && this.searchFieldInputs.isFocused() ) - { - return; - } - - if( character == ' ' && this.searchFieldOutputs.getText().isEmpty() && this.searchFieldOutputs.isFocused() ) - { - return; - } - - if( this.searchFieldInputs.textboxKeyTyped( character, key ) || this.searchFieldOutputs.textboxKeyTyped( character, key ) ) - { - this.refreshList(); - } - - else - { - super.keyTyped( character, key ); - } - } - } - - public void postUpdate( final NBTTagCompound in ) - { - if( in.getBoolean( "clear" ) ) - { - this.byId.clear(); - this.refreshList = true; - } - - for( final Object oKey : in.getKeySet() ) - { - final String key = (String) oKey; - if( key.startsWith( "=" ) ) - { - try - { - final long id = Long.parseLong( key.substring( 1 ), Character.MAX_RADIX ); - final NBTTagCompound invData = in.getCompoundTag( key ); - final ClientDCInternalInv current = this.getById( id, invData.getLong( "sortBy" ), invData.getString( "un" ) ); - blockPosHashMap.put( current, NBTUtil.getPosFromTag( invData.getCompoundTag( "pos" ) ) ); - dimHashMap.put( current, invData.getInteger( "dim" ) ); - numUpgradesMap.put( current, invData.getInteger( "numUpgrades" ) ); - - for( int x = 0; x < current.getInventory().getSlots(); x++ ) - { - final String which = Integer.toString( x ); - if( invData.hasKey( which ) ) - { - current.getInventory().setStackInSlot( x, new ItemStack( invData.getCompoundTag( which ) ) ); - } - } - } - catch( final NumberFormatException ignored ) - { - } - } - } - - if( this.refreshList ) - { - this.refreshList = false; - // invalid caches on refresh - this.cachedSearches.clear(); - this.refreshList(); - } - } - - /** - * Rebuilds the list of interfaces. - *

- * Respects a search term if present (ignores case) and adding only matching patterns. - */ - private void refreshList() - { - this.byName.clear(); - this.buttonList.clear(); - this.matchedStacks.clear(); - - final String searchFieldInputs = this.searchFieldInputs.getText().toLowerCase(); - final String searchFieldOutputs = this.searchFieldOutputs.getText().toLowerCase(); - - final Set cachedSearch = this.getCacheForSearchTerm( "IN:" + searchFieldInputs + " OUT:" + searchFieldOutputs + partInterfaceTerminal.onlyInterfacesWithFreeSlots ); - final boolean rebuild = cachedSearch.isEmpty(); - - for( final ClientDCInternalInv entry : this.byId.values() ) - { - // ignore inventory if not doing a full rebuild and cache already marks it as miss. - if( !rebuild && !cachedSearch.contains( entry ) ) - { - continue; - } - - // Shortcut to skip any filter if search term is ""/empty - - boolean found = ( searchFieldInputs.isEmpty() && searchFieldOutputs.isEmpty() && !partInterfaceTerminal.onlyInterfacesWithFreeSlots ); - boolean interfaceHasFreeSlots = false; - - // Search if the current inventory holds a pattern containing the search term. - if( !found ) - { - int slot = 0; - for( final ItemStack itemStack : entry.getInventory() ) - { - if( slot > 8 + numUpgradesMap.get( entry ) * 9 ) - { - break; - } - if( !searchFieldInputs.isEmpty() && !searchFieldOutputs.isEmpty() ) - { - if( this.itemStackMatchesSearchTerm( itemStack, searchFieldInputs, 0 ) || this.itemStackMatchesSearchTerm( itemStack, searchFieldOutputs, 1 ) ) - { - found = true; - matchedStacks.add( itemStack ); - } - } - else if( !searchFieldInputs.isEmpty() ) - { - if( this.itemStackMatchesSearchTerm( itemStack, searchFieldInputs, 0 ) ) - { - found = true; - matchedStacks.add( itemStack ); - } - } - else if( !searchFieldOutputs.isEmpty() ) - { - if( this.itemStackMatchesSearchTerm( itemStack, searchFieldOutputs, 1 ) ) - { - found = true; - matchedStacks.add( itemStack ); - } - } - // If only Interfaces with empty slots should be shown, check that here - if( itemStack.isEmpty() ) - { - interfaceHasFreeSlots = true; - } - slot++; - } - } - // if found, filter skipped or machine name matching the search term, add it - if( found || ( entry.getName().toLowerCase().contains( searchFieldInputs ) && entry.getName().toLowerCase().contains( searchFieldOutputs ) ) ) - { - if( !partInterfaceTerminal.onlyInterfacesWithFreeSlots ) - { - this.byName.put( entry.getName(), entry ); - cachedSearch.add( entry ); - } - else if( interfaceHasFreeSlots ) - { - this.byName.put( entry.getName(), entry ); - cachedSearch.add( entry ); - } - } - else - { - cachedSearch.remove( entry ); - } - } - - this.names.clear(); - this.names.addAll( this.byName.keySet() ); - - Collections.sort( this.names ); - - this.lines.clear(); - this.lines.ensureCapacity( this.getMaxRows() ); - - for( final String n : this.names ) - { - this.lines.add( n ); - - final ArrayList clientInventories = new ArrayList<>(); - clientInventories.addAll( this.byName.get( n ) ); - - Collections.sort( clientInventories ); - this.lines.addAll( clientInventories ); - } - - this.getScrollBar().setRange( 0, this.lines.size() - 1, 1 ); - } - - private boolean itemStackMatchesSearchTerm( final ItemStack itemStack, final String searchTerm, int pass ) - { - if( itemStack.isEmpty() ) - { - return false; - } - - final NBTTagCompound encodedValue = itemStack.getTagCompound(); - - if( encodedValue == null ) - { - return false; - } - - NBTTagList tag = new NBTTagList(); - - if( pass == 0 ) - { - tag = encodedValue.getTagList( "in", 10 ); - } - else - { - tag = encodedValue.getTagList( "out", 10 ); - } - - boolean foundMatchingItemStack = false; - - for( int i = 0; i < tag.tagCount(); i++ ) - { - final ItemStack parsedItemStack = new ItemStack( tag.getCompoundTagAt( i ) ); - if( !parsedItemStack.isEmpty() ) - { - final String displayName = Platform - .getItemDisplayName( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( parsedItemStack ) ) - .toLowerCase(); - - for( String term : searchTerm.split( " " ) ) - { - if( term.length() > 1 && ( term.startsWith( "-" ) || term.startsWith( "!" ) ) ) - { - term = term.substring( 1 ); - if( displayName.contains( term ) ) - { - return false; - } - } - else if( displayName.contains( term ) ) - { - foundMatchingItemStack = true; - } - } - } - } - return foundMatchingItemStack; - } - - /** - * Tries to retrieve a cache for a with search term as keyword. - *

- * If this cache should be empty, it will populate it with an earlier cache if available or at least the cache for - * the empty string. - * - * @param searchTerm the corresponding search - * @return a Set matching a superset of the search term - */ - private Set getCacheForSearchTerm( final String searchTerm ) - { - if( !this.cachedSearches.containsKey( searchTerm ) ) - { - this.cachedSearches.put( searchTerm, new HashSet<>() ); - } - - final Set cache = this.cachedSearches.get( searchTerm ); - - if( cache.isEmpty() && searchTerm.length() > 1 ) - { - cache.addAll( this.getCacheForSearchTerm( searchTerm.substring( 0, searchTerm.length() - 1 ) ) ); - return cache; - } - - return cache; - } - - /** - * The max amount of unique names and each inv row. Not affected by the filtering. - * - * @return max amount of unique names and each inv row - */ - private int getMaxRows() - { - return this.names.size() + this.byId.size(); - } - - private ClientDCInternalInv getById( final long id, final long sortBy, final String string ) - { - ClientDCInternalInv o = this.byId.get( id ); - - if( o == null ) - { - this.byId.put( id, o = new ClientDCInternalInv( DualityInterface.NUMBER_OF_PATTERN_SLOTS, id, sortBy, string ) ); - this.refreshList = true; - } - - return o; - } +public class GuiInterfaceTerminal extends AEBaseGui { + + private static final int LINES_ON_PAGE = 6; + + // TODO: copied from GuiMEMonitorable. It looks not changed, maybe unneeded? + private final int offsetX = 21; + + private final HashMap byId = new HashMap<>(); + private final HashMultimap byName = HashMultimap.create(); + private final HashMap blockPosHashMap = new HashMap<>(); + private final HashMap guiButtonHashMap = new HashMap<>(); + private final Map numUpgradesMap = new HashMap<>(); + private final ArrayList names = new ArrayList<>(); + private final ArrayList lines = new ArrayList<>(); + private final Set matchedStacks = new HashSet<>(); + + private final Map> cachedSearches = new WeakHashMap<>(); + + private boolean refreshList = false; + private MEGuiTextField searchFieldOutputs; + private MEGuiTextField searchFieldInputs; + private final PartInterfaceTerminal partInterfaceTerminal; + private GuiButton guiButtonHide; + private GuiButton guiButtonNextAssembler; + private final HashMap dimHashMap = new HashMap<>(); + + public GuiInterfaceTerminal(final InventoryPlayer inventoryPlayer, final PartInterfaceTerminal te) { + super(new ContainerInterfaceTerminal(inventoryPlayer, te)); + + this.partInterfaceTerminal = te; + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar(scrollbar); + this.xSize = 208; + this.ySize = 255; + } + + @Override + public void initGui() { + super.initGui(); + + this.getScrollBar().setLeft(189); + this.getScrollBar().setHeight(106); + this.getScrollBar().setTop(51); + + this.searchFieldInputs = new MEGuiTextField(this.fontRenderer, this.guiLeft + Math.max(32, this.offsetX), this.guiTop + 25, 65, 12); + this.searchFieldInputs.setEnableBackgroundDrawing(false); + this.searchFieldInputs.setMaxStringLength(25); + this.searchFieldInputs.setTextColor(0xFFFFFF); + this.searchFieldInputs.setVisible(true); + this.searchFieldInputs.setFocused(false); + + this.searchFieldOutputs = new MEGuiTextField(this.fontRenderer, this.guiLeft + Math.max(32, this.offsetX), this.guiTop + 38, 65, 12); + this.searchFieldOutputs.setEnableBackgroundDrawing(false); + this.searchFieldOutputs.setMaxStringLength(25); + this.searchFieldOutputs.setTextColor(0xFFFFFF); + this.searchFieldOutputs.setVisible(true); + this.searchFieldOutputs.setFocused(true); + + this.searchFieldInputs.setText(partInterfaceTerminal.in); + this.searchFieldOutputs.setText(partInterfaceTerminal.out); + } + + @Override + public void onGuiClosed() { + partInterfaceTerminal.saveSearchStrings(this.searchFieldInputs.getText().toLowerCase(), this.searchFieldOutputs.getText().toLowerCase()); + super.onGuiClosed(); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.buttonList.clear(); + + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.InterfaceTerminal.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), this.offsetX + 2, this.ySize - 96 + 3, 4210752); + + final int currentScroll = this.getScrollBar().getCurrentScroll(); + + this.guiButtonNextAssembler = new GuiImgButton(guiLeft + 123, guiTop + 25, Settings.ACTIONS, ActionItems.FREE_MOLECULAR_SLOT_SHORTCUT); + this.buttonList.add(guiButtonNextAssembler); + + guiButtonHide = new GuiImgButton(guiLeft + 141, guiTop + 25, Settings.ACTIONS, this.partInterfaceTerminal.onlyInterfacesWithFreeSlots ? ActionItems.TOGGLE_SHOW_FULL_INTERFACES_OFF : ActionItems.TOGGLE_SHOW_FULL_INTERFACES_ON); + this.buttonList.add(guiButtonHide); + + this.inventorySlots.inventorySlots.removeIf(slot -> slot instanceof SlotDisconnected); + + int offset = 52; + int linesDraw = 0; + for (int x = 0; x < LINES_ON_PAGE && linesDraw < LINES_ON_PAGE && currentScroll + x < this.lines.size(); x++) { + final Object lineObj = this.lines.get(currentScroll + x); + if (lineObj instanceof ClientDCInternalInv) { + final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; + + GuiButton guiButton = new GuiImgButton(guiLeft + 4, guiTop + offset, Settings.ACTIONS, ActionItems.HIGHLIGHT_INTERFACE); + guiButtonHashMap.put(guiButton, inv); + this.buttonList.add(guiButton); + int extraLines = numUpgradesMap.get(inv); + + for (int row = 0; row < 1 + extraLines && linesDraw < LINES_ON_PAGE; ++row) { + for (int z = 0; z < 9; z++) { + this.inventorySlots.inventorySlots.add(new SlotDisconnected(inv, z + (row * 9), (z * 18 + 22), offset)); + if (this.matchedStacks.contains(inv.getInventory().getStackInSlot(z + (row * 9)))) { + drawRect(z * 18 + 22, offset, z * 18 + 22 + 16, offset + 16, 0x2A00FF00); + } + } + linesDraw++; + offset += 18; + } + } else if (lineObj instanceof String) { + String name = (String) lineObj; + final int rows = this.byName.get(name).size(); + if (rows > 1) { + name = name + " (" + rows + ')'; + } + + while (name.length() > 2 && this.fontRenderer.getStringWidth(name) > 155) { + name = name.substring(0, name.length() - 1); + } + this.fontRenderer.drawString(name, this.offsetX + 2, 5 + offset, 4210752); + linesDraw++; + offset += 18; + } + } + + if (searchFieldInputs.isMouseIn(mouseX, mouseY)) { + drawTooltip(Mouse.getEventX() * this.width / this.mc.displayWidth - offsetX, mouseY - guiTop, "Inputs OR names"); + } else if (searchFieldOutputs.isMouseIn(mouseX, mouseY)) { + drawTooltip(Mouse.getEventX() * this.width / this.mc.displayWidth - offsetX, mouseY - guiTop, "Outputs OR names"); + } + + } + + @Override + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) throws IOException { + this.searchFieldInputs.mouseClicked(xCoord, yCoord, btn); + + if (btn == 1 && this.searchFieldInputs.isMouseIn(xCoord, yCoord)) { + this.searchFieldInputs.setText(""); + this.refreshList(); + } + + this.searchFieldOutputs.mouseClicked(xCoord, yCoord, btn); + + if (btn == 1 && this.searchFieldOutputs.isMouseIn(xCoord, yCoord)) { + this.searchFieldOutputs.setText(""); + this.refreshList(); + } + + super.mouseClicked(xCoord, yCoord, btn); + } + + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + if (guiButtonHashMap.containsKey(btn)) { + BlockPos blockPos = blockPosHashMap.get(guiButtonHashMap.get(this.selectedButton)); + BlockPos blockPos2 = mc.player.getPosition(); + int playerDim = mc.world.provider.getDimension(); + int interfaceDim = dimHashMap.get(guiButtonHashMap.get(this.selectedButton)); + if (playerDim != interfaceDim) { + try { + mc.player.sendStatusMessage(new TextComponentString("Interface located at dimension: " + interfaceDim + " [" + DimensionManager.getWorld(interfaceDim).provider.getDimensionType().getName() + "] and cant be highlighted"), false); + } catch (Exception e) { + mc.player.sendStatusMessage(new TextComponentString("Interface is located in another dimension and cannot be highlighted"), false); + } + } else { + hilightBlock(blockPos, System.currentTimeMillis() + 500 * BlockPosUtils.getDistance(blockPos, blockPos2), playerDim); + mc.player.sendStatusMessage(new TextComponentString("The interface is now highlighted at " + "X: " + blockPos.getX() + " Y: " + blockPos.getY() + " Z: " + blockPos.getZ()), false); + } + mc.player.closeScreen(); + } + + if (btn == guiButtonHide) { + partInterfaceTerminal.onlyInterfacesWithFreeSlots = !partInterfaceTerminal.onlyInterfacesWithFreeSlots; + this.refreshList(); + } + + if (btn == guiButtonNextAssembler) { + // Set Search to "Molecular Assembler" and set "Only Free Interface" + boolean currentOnlyInterfacesWithFreeSlots = this.partInterfaceTerminal.onlyInterfacesWithFreeSlots; + String currentSearchText = this.searchFieldOutputs.getText(); + + this.partInterfaceTerminal.onlyInterfacesWithFreeSlots = true; + this.searchFieldOutputs.setText("Molecular Assembler"); + + this.refreshList(); + + this.partInterfaceTerminal.onlyInterfacesWithFreeSlots = currentOnlyInterfacesWithFreeSlots; + this.searchFieldOutputs.setText(currentSearchText); + } + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/newinterfaceterminal.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + + int offset = 51; + final int ex = this.getScrollBar().getCurrentScroll(); + int linesDraw = 0; + for (int x = 0; x < LINES_ON_PAGE && linesDraw < LINES_ON_PAGE && ex + x < this.lines.size(); x++) { + final Object lineObj = this.lines.get(ex + x); + if (lineObj instanceof ClientDCInternalInv) { + GlStateManager.color(1, 1, 1, 1); + final int width = 9 * 18; + + int extraLines = numUpgradesMap.get(lineObj); + + for (int row = 0; row < 1 + extraLines && linesDraw < LINES_ON_PAGE; ++row) { + this.drawTexturedModalRect(offsetX + 20, offsetY + offset, 20, 173, width, 18); + offset += 18; + linesDraw++; + } + } else { + offset += 18; + linesDraw++; + } + } + + if (this.searchFieldInputs != null) { + this.searchFieldInputs.drawTextBox(); + } + + if (this.searchFieldOutputs != null) { + this.searchFieldOutputs.drawTextBox(); + } + } + + @Override + protected void keyTyped(final char character, final int key) throws IOException { + if (!this.checkHotbarKeys(key)) { + if (character == ' ' && this.searchFieldInputs.getText().isEmpty() && this.searchFieldInputs.isFocused()) { + return; + } + + if (character == ' ' && this.searchFieldOutputs.getText().isEmpty() && this.searchFieldOutputs.isFocused()) { + return; + } + + if (this.searchFieldInputs.textboxKeyTyped(character, key) || this.searchFieldOutputs.textboxKeyTyped(character, key)) { + this.refreshList(); + } else { + super.keyTyped(character, key); + } + } + } + + public void postUpdate(final NBTTagCompound in) { + if (in.getBoolean("clear")) { + this.byId.clear(); + this.refreshList = true; + } + + for (final Object oKey : in.getKeySet()) { + final String key = (String) oKey; + if (key.startsWith("=")) { + try { + final long id = Long.parseLong(key.substring(1), Character.MAX_RADIX); + final NBTTagCompound invData = in.getCompoundTag(key); + final ClientDCInternalInv current = this.getById(id, invData.getLong("sortBy"), invData.getString("un")); + blockPosHashMap.put(current, NBTUtil.getPosFromTag(invData.getCompoundTag("pos"))); + dimHashMap.put(current, invData.getInteger("dim")); + numUpgradesMap.put(current, invData.getInteger("numUpgrades")); + + for (int x = 0; x < current.getInventory().getSlots(); x++) { + final String which = Integer.toString(x); + if (invData.hasKey(which)) { + current.getInventory().setStackInSlot(x, new ItemStack(invData.getCompoundTag(which))); + } + } + } catch (final NumberFormatException ignored) { + } + } + } + + if (this.refreshList) { + this.refreshList = false; + // invalid caches on refresh + this.cachedSearches.clear(); + this.refreshList(); + } + } + + /** + * Rebuilds the list of interfaces. + *

+ * Respects a search term if present (ignores case) and adding only matching patterns. + */ + private void refreshList() { + this.byName.clear(); + this.buttonList.clear(); + this.matchedStacks.clear(); + + final String searchFieldInputs = this.searchFieldInputs.getText().toLowerCase(); + final String searchFieldOutputs = this.searchFieldOutputs.getText().toLowerCase(); + + final Set cachedSearch = this.getCacheForSearchTerm("IN:" + searchFieldInputs + " OUT:" + searchFieldOutputs + partInterfaceTerminal.onlyInterfacesWithFreeSlots); + final boolean rebuild = cachedSearch.isEmpty(); + + for (final ClientDCInternalInv entry : this.byId.values()) { + // ignore inventory if not doing a full rebuild and cache already marks it as miss. + if (!rebuild && !cachedSearch.contains(entry)) { + continue; + } + + // Shortcut to skip any filter if search term is ""/empty + + boolean found = (searchFieldInputs.isEmpty() && searchFieldOutputs.isEmpty() && !partInterfaceTerminal.onlyInterfacesWithFreeSlots); + boolean interfaceHasFreeSlots = false; + + // Search if the current inventory holds a pattern containing the search term. + if (!found) { + int slot = 0; + for (final ItemStack itemStack : entry.getInventory()) { + if (slot > 8 + numUpgradesMap.get(entry) * 9) { + break; + } + if (!searchFieldInputs.isEmpty() && !searchFieldOutputs.isEmpty()) { + if (this.itemStackMatchesSearchTerm(itemStack, searchFieldInputs, 0) || this.itemStackMatchesSearchTerm(itemStack, searchFieldOutputs, 1)) { + found = true; + matchedStacks.add(itemStack); + } + } else if (!searchFieldInputs.isEmpty()) { + if (this.itemStackMatchesSearchTerm(itemStack, searchFieldInputs, 0)) { + found = true; + matchedStacks.add(itemStack); + } + } else if (!searchFieldOutputs.isEmpty()) { + if (this.itemStackMatchesSearchTerm(itemStack, searchFieldOutputs, 1)) { + found = true; + matchedStacks.add(itemStack); + } + } + // If only Interfaces with empty slots should be shown, check that here + if (itemStack.isEmpty()) { + interfaceHasFreeSlots = true; + } + slot++; + } + } + // if found, filter skipped or machine name matching the search term, add it + if (found || (entry.getName().toLowerCase().contains(searchFieldInputs) && entry.getName().toLowerCase().contains(searchFieldOutputs))) { + if (!partInterfaceTerminal.onlyInterfacesWithFreeSlots) { + this.byName.put(entry.getName(), entry); + cachedSearch.add(entry); + } else if (interfaceHasFreeSlots) { + this.byName.put(entry.getName(), entry); + cachedSearch.add(entry); + } + } else { + cachedSearch.remove(entry); + } + } + + this.names.clear(); + this.names.addAll(this.byName.keySet()); + + Collections.sort(this.names); + + this.lines.clear(); + this.lines.ensureCapacity(this.getMaxRows()); + + for (final String n : this.names) { + this.lines.add(n); + + final ArrayList clientInventories = new ArrayList<>(); + clientInventories.addAll(this.byName.get(n)); + + Collections.sort(clientInventories); + this.lines.addAll(clientInventories); + } + + this.getScrollBar().setRange(0, this.lines.size() - 1, 1); + } + + private boolean itemStackMatchesSearchTerm(final ItemStack itemStack, final String searchTerm, int pass) { + if (itemStack.isEmpty()) { + return false; + } + + final NBTTagCompound encodedValue = itemStack.getTagCompound(); + + if (encodedValue == null) { + return false; + } + + NBTTagList tag = new NBTTagList(); + + if (pass == 0) { + tag = encodedValue.getTagList("in", 10); + } else { + tag = encodedValue.getTagList("out", 10); + } + + boolean foundMatchingItemStack = false; + + for (int i = 0; i < tag.tagCount(); i++) { + final ItemStack parsedItemStack = new ItemStack(tag.getCompoundTagAt(i)); + if (!parsedItemStack.isEmpty()) { + final String displayName = Platform + .getItemDisplayName(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(parsedItemStack)) + .toLowerCase(); + + for (String term : searchTerm.split(" ")) { + if (term.length() > 1 && (term.startsWith("-") || term.startsWith("!"))) { + term = term.substring(1); + if (displayName.contains(term)) { + return false; + } + } else if (displayName.contains(term)) { + foundMatchingItemStack = true; + } + } + } + } + return foundMatchingItemStack; + } + + /** + * Tries to retrieve a cache for a with search term as keyword. + *

+ * If this cache should be empty, it will populate it with an earlier cache if available or at least the cache for + * the empty string. + * + * @param searchTerm the corresponding search + * @return a Set matching a superset of the search term + */ + private Set getCacheForSearchTerm(final String searchTerm) { + if (!this.cachedSearches.containsKey(searchTerm)) { + this.cachedSearches.put(searchTerm, new HashSet<>()); + } + + final Set cache = this.cachedSearches.get(searchTerm); + + if (cache.isEmpty() && searchTerm.length() > 1) { + cache.addAll(this.getCacheForSearchTerm(searchTerm.substring(0, searchTerm.length() - 1))); + return cache; + } + + return cache; + } + + /** + * The max amount of unique names and each inv row. Not affected by the filtering. + * + * @return max amount of unique names and each inv row + */ + private int getMaxRows() { + return this.names.size() + this.byId.size(); + } + + private ClientDCInternalInv getById(final long id, final long sortBy, final String string) { + ClientDCInternalInv o = this.byId.get(id); + + if (o == null) { + this.byId.put(id, o = new ClientDCInternalInv(DualityInterface.NUMBER_OF_PATTERN_SLOTS, id, sortBy, string)); + this.refreshList = true; + } + + return o; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java b/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java index cdd60a4a6..ce90ae295 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java +++ b/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java @@ -19,19 +19,7 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - -import appeng.api.config.FuzzyMode; -import appeng.api.config.LevelType; -import appeng.api.config.RedstoneMode; -import appeng.api.config.Settings; -import appeng.api.config.Upgrades; -import appeng.api.config.YesNo; +import appeng.api.config.*; import appeng.client.gui.widgets.GuiImgButton; import appeng.client.gui.widgets.GuiNumberBox; import appeng.container.implementations.ContainerLevelEmitter; @@ -42,240 +30,209 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; import appeng.core.sync.packets.PacketValueConfig; import appeng.parts.automation.PartLevelEmitter; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import org.lwjgl.input.Mouse; + +import java.io.IOException; -public class GuiLevelEmitter extends GuiUpgradeable -{ +public class GuiLevelEmitter extends GuiUpgradeable { - private GuiNumberBox level; + private GuiNumberBox level; - private GuiButton plus1; - private GuiButton plus10; - private GuiButton plus100; - private GuiButton plus1000; - private GuiButton minus1; - private GuiButton minus10; - private GuiButton minus100; - private GuiButton minus1000; + private GuiButton plus1; + private GuiButton plus10; + private GuiButton plus100; + private GuiButton plus1000; + private GuiButton minus1; + private GuiButton minus10; + private GuiButton minus100; + private GuiButton minus1000; - private GuiImgButton levelMode; - private GuiImgButton craftingMode; + private GuiImgButton levelMode; + private GuiImgButton craftingMode; - public GuiLevelEmitter( final InventoryPlayer inventoryPlayer, final PartLevelEmitter te ) - { - super( new ContainerLevelEmitter( inventoryPlayer, te ) ); - } + public GuiLevelEmitter(final InventoryPlayer inventoryPlayer, final PartLevelEmitter te) { + super(new ContainerLevelEmitter(inventoryPlayer, te)); + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.level = new GuiNumberBox( this.fontRenderer, this.guiLeft + 24, this.guiTop + 43, 79, this.fontRenderer.FONT_HEIGHT, Long.class ); - this.level.setEnableBackgroundDrawing( false ); - this.level.setMaxStringLength( 16 ); - this.level.setTextColor( 0xFFFFFF ); - this.level.setVisible( true ); - this.level.setFocused( true ); - ( (ContainerLevelEmitter) this.inventorySlots ).setTextField( this.level ); - } + this.level = new GuiNumberBox(this.fontRenderer, this.guiLeft + 24, this.guiTop + 43, 79, this.fontRenderer.FONT_HEIGHT, Long.class); + this.level.setEnableBackgroundDrawing(false); + this.level.setMaxStringLength(16); + this.level.setTextColor(0xFFFFFF); + this.level.setVisible(true); + this.level.setFocused(true); + ((ContainerLevelEmitter) this.inventorySlots).setTextField(this.level); + } - @Override - protected void addButtons() - { - this.levelMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL ); - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.REDSTONE_EMITTER, RedstoneMode.LOW_SIGNAL ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.craftingMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.CRAFT_VIA_REDSTONE, YesNo.NO ); + @Override + protected void addButtons() { + this.levelMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL); + this.redstoneMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.REDSTONE_EMITTER, RedstoneMode.LOW_SIGNAL); + this.fuzzyMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 48, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.craftingMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 48, Settings.CRAFT_VIA_REDSTONE, YesNo.NO); - final int a = AEConfig.instance().levelByStackAmounts( 0 ); - final int b = AEConfig.instance().levelByStackAmounts( 1 ); - final int c = AEConfig.instance().levelByStackAmounts( 2 ); - final int d = AEConfig.instance().levelByStackAmounts( 3 ); + final int a = AEConfig.instance().levelByStackAmounts(0); + final int b = AEConfig.instance().levelByStackAmounts(1); + final int c = AEConfig.instance().levelByStackAmounts(2); + final int d = AEConfig.instance().levelByStackAmounts(3); - this.buttonList.add( this.plus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 17, 22, 20, "+" + a ) ); - this.buttonList.add( this.plus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 17, 28, 20, "+" + b ) ); - this.buttonList.add( this.plus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 17, 32, 20, "+" + c ) ); - this.buttonList.add( this.plus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 17, 38, 20, "+" + d ) ); + this.buttonList.add(this.plus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 17, 22, 20, "+" + a)); + this.buttonList.add(this.plus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 17, 28, 20, "+" + b)); + this.buttonList.add(this.plus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 17, 32, 20, "+" + c)); + this.buttonList.add(this.plus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 17, 38, 20, "+" + d)); - this.buttonList.add( this.minus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 59, 22, 20, "-" + a ) ); - this.buttonList.add( this.minus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 59, 28, 20, "-" + b ) ); - this.buttonList.add( this.minus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 59, 32, 20, "-" + c ) ); - this.buttonList.add( this.minus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 59, 38, 20, "-" + d ) ); + this.buttonList.add(this.minus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 59, 22, 20, "-" + a)); + this.buttonList.add(this.minus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 59, 28, 20, "-" + b)); + this.buttonList.add(this.minus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 59, 32, 20, "-" + c)); + this.buttonList.add(this.minus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 59, 38, 20, "-" + d)); - this.buttonList.add( this.levelMode ); - this.buttonList.add( this.redstoneMode ); - this.buttonList.add( this.fuzzyMode ); - this.buttonList.add( this.craftingMode ); - } + this.buttonList.add(this.levelMode); + this.buttonList.add(this.redstoneMode); + this.buttonList.add(this.fuzzyMode); + this.buttonList.add(this.craftingMode); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - final boolean notCraftingMode = this.bc.getInstalledUpgrades( Upgrades.CRAFTING ) == 0; + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + final boolean notCraftingMode = this.bc.getInstalledUpgrades(Upgrades.CRAFTING) == 0; - // configure enabled status... - this.level.setEnabled( notCraftingMode ); - this.plus1.enabled = notCraftingMode; - this.plus10.enabled = notCraftingMode; - this.plus100.enabled = notCraftingMode; - this.plus1000.enabled = notCraftingMode; - this.minus1.enabled = notCraftingMode; - this.minus10.enabled = notCraftingMode; - this.minus100.enabled = notCraftingMode; - this.minus1000.enabled = notCraftingMode; - this.levelMode.enabled = notCraftingMode; - this.redstoneMode.enabled = notCraftingMode; + // configure enabled status... + this.level.setEnabled(notCraftingMode); + this.plus1.enabled = notCraftingMode; + this.plus10.enabled = notCraftingMode; + this.plus100.enabled = notCraftingMode; + this.plus1000.enabled = notCraftingMode; + this.minus1.enabled = notCraftingMode; + this.minus10.enabled = notCraftingMode; + this.minus100.enabled = notCraftingMode; + this.minus1000.enabled = notCraftingMode; + this.levelMode.enabled = notCraftingMode; + this.redstoneMode.enabled = notCraftingMode; - super.drawFG( offsetX, offsetY, mouseX, mouseY ); + super.drawFG(offsetX, offsetY, mouseX, mouseY); - if( this.craftingMode != null ) - { - this.craftingMode.set( ( (ContainerLevelEmitter) this.cvb ).getCraftingMode() ); - } + if (this.craftingMode != null) { + this.craftingMode.set(this.cvb.getCraftingMode()); + } - if( this.levelMode != null ) - { - this.levelMode.set( ( (ContainerLevelEmitter) this.cvb ).getLevelMode() ); - } - } + if (this.levelMode != null) { + this.levelMode.set(((ContainerLevelEmitter) this.cvb).getLevelMode()); + } + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawBG( offsetX, offsetY, mouseX, mouseY ); - this.level.drawTextBox(); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawBG(offsetX, offsetY, mouseX, mouseY); + this.level.drawTextBox(); + } - @Override - protected void handleButtonVisibility() - { - this.craftingMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ); - this.fuzzyMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ); - } + @Override + protected void handleButtonVisibility() { + this.craftingMode.setVisibility(this.bc.getInstalledUpgrades(Upgrades.CRAFTING) > 0); + this.fuzzyMode.setVisibility(this.bc.getInstalledUpgrades(Upgrades.FUZZY) > 0); + } - @Override - protected String getBackground() - { - return "guis/lvlemitter.png"; - } + @Override + protected String getBackground() { + return "guis/lvlemitter.png"; + } - @Override - protected GuiText getName() - { - return GuiText.LevelEmitter; - } + @Override + protected GuiText getName() { + return GuiText.LevelEmitter; + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - if( btn == this.craftingMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.craftingMode.getSetting(), backwards ) ); - } + if (btn == this.craftingMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.craftingMode.getSetting(), backwards)); + } - if( btn == this.levelMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.levelMode.getSetting(), backwards ) ); - } + if (btn == this.levelMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.levelMode.getSetting(), backwards)); + } - final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; - final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; + final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; - if( isPlus || isMinus ) - { - this.addQty( this.getQty( btn ) ); - } - } + if (isPlus || isMinus) { + this.addQty(this.getQty(btn)); + } + } - private void addQty( final long i ) - { - try - { - String Out = this.level.getText(); + private void addQty(final long i) { + try { + String Out = this.level.getText(); - boolean Fixed = false; - while( Out.startsWith( "0" ) && Out.length() > 1 ) - { - Out = Out.substring( 1 ); - Fixed = true; - } + boolean Fixed = false; + while (Out.startsWith("0") && Out.length() > 1) { + Out = Out.substring(1); + Fixed = true; + } - if( Fixed ) - { - this.level.setText( Out ); - } + if (Fixed) { + this.level.setText(Out); + } - if( Out.isEmpty() ) - { - Out = "0"; - } + if (Out.isEmpty()) { + Out = "0"; + } - long result = Long.parseLong( Out ); - result += i; - if( result < 0 ) - { - result = 0; - } + long result = Long.parseLong(Out); + result += i; + if (result < 0) { + result = 0; + } - this.level.setText( Out = Long.toString( result ) ); + this.level.setText(Out = Long.toString(result)); - NetworkHandler.instance().sendToServer( new PacketValueConfig( "LevelEmitter.Value", Out ) ); - } - catch( final NumberFormatException e ) - { - // nope.. - this.level.setText( "0" ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + NetworkHandler.instance().sendToServer(new PacketValueConfig("LevelEmitter.Value", Out)); + } catch (final NumberFormatException e) { + // nope.. + this.level.setText("0"); + } catch (final IOException e) { + AELog.debug(e); + } + } - @Override - protected void keyTyped( final char character, final int key ) throws IOException - { - if( !this.checkHotbarKeys( key ) ) - { - if( ( key == 211 || key == 205 || key == 203 || key == 14 || Character.isDigit( character ) ) && this.level.textboxKeyTyped( character, key ) ) - { - try - { - String Out = this.level.getText(); + @Override + protected void keyTyped(final char character, final int key) throws IOException { + if (!this.checkHotbarKeys(key)) { + if ((key == 211 || key == 205 || key == 203 || key == 14 || Character.isDigit(character)) && this.level.textboxKeyTyped(character, key)) { + try { + String Out = this.level.getText(); - boolean Fixed = false; - while( Out.startsWith( "0" ) && Out.length() > 1 ) - { - Out = Out.substring( 1 ); - Fixed = true; - } + boolean Fixed = false; + while (Out.startsWith("0") && Out.length() > 1) { + Out = Out.substring(1); + Fixed = true; + } - if( Fixed ) - { - this.level.setText( Out ); - } + if (Fixed) { + this.level.setText(Out); + } - if( Out.isEmpty() ) - { - Out = "0"; - } + if (Out.isEmpty()) { + Out = "0"; + } - NetworkHandler.instance().sendToServer( new PacketValueConfig( "LevelEmitter.Value", Out ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - else - { - super.keyTyped( character, key ); - } - } - } + NetworkHandler.instance().sendToServer(new PacketValueConfig("LevelEmitter.Value", Out)); + } catch (final IOException e) { + AELog.debug(e); + } + } else { + super.keyTyped(character, key); + } + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiMAC.java b/src/main/java/appeng/client/gui/implementations/GuiMAC.java index 3e58982d8..1ec3dc37b 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiMAC.java +++ b/src/main/java/appeng/client/gui/implementations/GuiMAC.java @@ -19,8 +19,6 @@ package appeng.client.gui.implementations; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.config.RedstoneMode; import appeng.api.config.Settings; import appeng.client.gui.widgets.GuiImgButton; @@ -29,61 +27,54 @@ import appeng.client.gui.widgets.GuiProgressBar.Direction; import appeng.container.implementations.ContainerMAC; import appeng.core.localization.GuiText; import appeng.tile.crafting.TileMolecularAssembler; +import net.minecraft.entity.player.InventoryPlayer; -public class GuiMAC extends GuiUpgradeable -{ +public class GuiMAC extends GuiUpgradeable { - private final ContainerMAC container; - private GuiProgressBar pb; + private final ContainerMAC container; + private GuiProgressBar pb; - public GuiMAC( final InventoryPlayer inventoryPlayer, final TileMolecularAssembler te ) - { - super( new ContainerMAC( inventoryPlayer, te ) ); - this.ySize = 197; - this.container = (ContainerMAC) this.inventorySlots; - } + public GuiMAC(final InventoryPlayer inventoryPlayer, final TileMolecularAssembler te) { + super(new ContainerMAC(inventoryPlayer, te)); + this.ySize = 197; + this.container = (ContainerMAC) this.inventorySlots; + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.pb = new GuiProgressBar( this.container, "guis/mac.png", 139, 36, 148, 201, 6, 18, Direction.VERTICAL ); - this.buttonList.add( this.pb ); - } + this.pb = new GuiProgressBar(this.container, "guis/mac.png", 139, 36, 148, 201, 6, 18, Direction.VERTICAL); + this.buttonList.add(this.pb); + } - @Override - protected void addButtons() - { - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.buttonList.add( this.redstoneMode ); - } + @Override + protected void addButtons() { + this.redstoneMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.buttonList.add(this.redstoneMode); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.pb.setFullMsg( this.container.getCurrentProgress() + "%" ); - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.pb.setFullMsg(this.container.getCurrentProgress() + "%"); + super.drawFG(offsetX, offsetY, mouseX, mouseY); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.pb.x = 148 + this.guiLeft; - this.pb.y = 48 + this.guiTop; - super.drawBG( offsetX, offsetY, mouseX, mouseY ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.pb.x = 148 + this.guiLeft; + this.pb.y = 48 + this.guiTop; + super.drawBG(offsetX, offsetY, mouseX, mouseY); + } - @Override - protected String getBackground() - { - return "guis/mac.png"; - } + @Override + protected String getBackground() { + return "guis/mac.png"; + } - @Override - protected GuiText getName() - { - return GuiText.MolecularAssembler; - } + @Override + protected GuiText getName() { + return GuiText.MolecularAssembler; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java b/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java index 894b58909..0a00855e1 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java +++ b/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java @@ -19,21 +19,6 @@ package appeng.client.gui.implementations; -import java.awt.*; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import appeng.client.me.SlotME; -import net.minecraftforge.fml.common.Loader; -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; - import appeng.api.config.SearchBoxMode; import appeng.api.config.Settings; import appeng.api.config.TerminalStyle; @@ -46,13 +31,10 @@ import appeng.api.util.IConfigManager; import appeng.api.util.IConfigurableObject; import appeng.client.ActionKey; import appeng.client.gui.AEBaseMEGui; -import appeng.client.gui.widgets.GuiImgButton; -import appeng.client.gui.widgets.GuiScrollbar; -import appeng.client.gui.widgets.GuiTabButton; -import appeng.client.gui.widgets.ISortSource; -import appeng.client.gui.widgets.MEGuiTextField; +import appeng.client.gui.widgets.*; import appeng.client.me.InternalSlotME; import appeng.client.me.ItemRepo; +import appeng.client.me.SlotME; import appeng.container.implementations.ContainerMEMonitorable; import appeng.container.slot.AppEngSlot; import appeng.container.slot.SlotCraftingMatrix; @@ -71,604 +53,513 @@ import appeng.parts.reporting.AbstractPartTerminal; import appeng.tile.misc.TileSecurityStation; import appeng.util.IConfigManagerHost; import appeng.util.Platform; - - -public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfigManagerHost -{ - - private static int craftingGridOffsetX; - private static int craftingGridOffsetY; - - private static String memoryText = ""; - private final ItemRepo repo; - private final int offsetX = 9; - private final int lowerTextureOffset = 0; - private final IConfigManager configSrc; - private final boolean viewCell; - private final ItemStack[] myCurrentViewCells = new ItemStack[5]; - private final ContainerMEMonitorable monitorableContainer; - private GuiTabButton craftingStatusBtn; - private MEGuiTextField searchField; - private GuiText myName; - private int perRow = 9; - private int reservedSpace = 0; - private boolean customSortOrder = true; - private int rows = 0; - private int maxRows = Integer.MAX_VALUE; - private int standardSize; - private GuiImgButton ViewBox; - private GuiImgButton SortByBox; - private GuiImgButton SortDirBox; - private GuiImgButton searchBoxSettings; - private GuiImgButton terminalStyleBox; - private boolean isAutoFocus = false; - private int currentMouseX = 0; - private int currentMouseY = 0; - private boolean delayedUpdate; - - protected int jeiOffset = Loader.isModLoaded( "jei" ) ? 24 : 0; - - public GuiMEMonitorable( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - this( inventoryPlayer, te, new ContainerMEMonitorable( inventoryPlayer, te ) ); - } - - public GuiMEMonitorable( final InventoryPlayer inventoryPlayer, final ITerminalHost te, final ContainerMEMonitorable c ) - { - - super( c ); - - final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - this.repo = new ItemRepo( scrollbar, this ); - - this.xSize = 185; - this.ySize = 204; - - if( te instanceof IViewCellStorage ) - { - this.xSize += 33; - } - - this.standardSize = this.xSize; - - this.configSrc = ( (IConfigurableObject) this.inventorySlots ).getConfigManager(); - ( this.monitorableContainer = (ContainerMEMonitorable) this.inventorySlots ).setGui( this ); - - this.viewCell = te instanceof IViewCellStorage; - - if( te instanceof TileSecurityStation ) - { - this.myName = GuiText.Security; - } - else if( te instanceof WirelessTerminalGuiObject ) - { - this.myName = GuiText.WirelessTerminal; - } - else if( te instanceof IPortableCell ) - { - this.myName = GuiText.PortableCell; - } - else if( te instanceof IMEChest ) - { - this.myName = GuiText.Chest; - } - else if( te instanceof AbstractPartTerminal ) - { - this.myName = GuiText.Terminal; - } - } - - public void postUpdate( final List list ) - { - for( final IAEItemStack is : list ) - { - this.repo.postUpdate( is ); - } - - if( isShiftKeyDown() ) - { - for( Slot slot : this.inventorySlots.inventorySlots ) - { - if( slot instanceof SlotME ) - { - if( this.isPointInRegion( slot.xPos, slot.yPos, 18, 18, currentMouseX, currentMouseY ) ) - { - this.delayedUpdate = true; - break; - } - } - } - } - - if( !this.delayedUpdate ) - { - this.repo.updateView(); - this.setScrollBar(); - } - } - - private void setScrollBar() - { - this.getScrollBar().setTop( 18 ).setLeft( 175 ).setHeight( this.rows * 18 - 2 ); - this.getScrollBar().setRange( 0, ( this.repo.size() + this.perRow - 1 ) / this.perRow - this.rows, Math.max( 1, this.rows / 6 ) ); - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - if( btn == this.craftingStatusBtn ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( GuiBridge.GUI_CRAFTING_STATUS ) ); - } - - if( btn instanceof GuiImgButton ) - { - final boolean backwards = Mouse.isButtonDown( 1 ); - - final GuiImgButton iBtn = (GuiImgButton) btn; - if( iBtn.getSetting() != Settings.ACTIONS ) - { - final Enum cv = iBtn.getCurrentValue(); - final Enum next = Platform.rotateEnum( cv, backwards, iBtn.getSetting().getPossibleValues() ); - - if( btn == this.terminalStyleBox ) - { - AEConfig.instance().getConfigManager().putSetting( iBtn.getSetting(), next ); - } - else if( btn == this.searchBoxSettings ) - { - AEConfig.instance().getConfigManager().putSetting( iBtn.getSetting(), next ); - } - else - { - try - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( iBtn.getSetting().name(), next.name() ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - - iBtn.set( next ); - - if( next.getClass() == SearchBoxMode.class || next.getClass() == TerminalStyle.class ) - { - this.reinitalize(); - } - } - } - } - - private void reinitalize() - { - this.buttonList.clear(); - this.initGui(); - } - - @Override - public void initGui() - { - Keyboard.enableRepeatEvents( true ); - - this.maxRows = this.getMaxRows(); - this.perRow = AEConfig.instance() - .getConfigManager() - .getSetting( - Settings.TERMINAL_STYLE ) != TerminalStyle.FULL ? 9 : 9 + ( ( this.width - this.standardSize ) / 18 ); - - final int magicNumber = 114 + 1; - final int extraSpace = this.height - magicNumber - this.reservedSpace; - - this.rows = (int) Math.floor( extraSpace / 18 ); - if( this.rows > this.maxRows ) - { - this.rows = this.maxRows; - } - - if( this.rows < 3 ) - { - this.rows = 3; - } - - this.getMeSlots().clear(); - for( int y = 0; y < this.rows; y++ ) - { - for( int x = 0; x < this.perRow; x++ ) - { - this.getMeSlots().add( new InternalSlotME( this.repo, x + y * this.perRow, this.offsetX + x * 18, 18 + y * 18 ) ); - } - } - - if( AEConfig.instance().getConfigManager().getSetting( Settings.TERMINAL_STYLE ) != TerminalStyle.FULL ) - { - this.xSize = this.standardSize + ( ( this.perRow - 9 ) * 18 ); - } - else - { - this.xSize = this.standardSize; - } - - super.initGui(); - // full size : 204 - // extra slots : 72 - // slot 18 - - this.ySize = magicNumber + this.rows * 18 + this.reservedSpace; - // this.guiTop = top; - final int unusedSpace = this.height - this.ySize; - this.guiTop = (int) Math.floor( unusedSpace / ( unusedSpace < 0 ? 3.8f : 2.0f ) ); - - int offset = this.guiTop + 8 + jeiOffset; - - { - if( this.customSortOrder ) - { - this.buttonList - .add( this.SortByBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.SORT_BY, this.configSrc.getSetting( Settings.SORT_BY ) ) ); - offset += 20; - } - } - - if( this.viewCell || this instanceof GuiWirelessTerm ) - { - this.buttonList - .add( this.ViewBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.VIEW_MODE, this.configSrc.getSetting( Settings.VIEW_MODE ) ) ); - offset += 20; - } - - this.buttonList.add( this.SortDirBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.SORT_DIRECTION, this.configSrc - .getSetting( Settings.SORT_DIRECTION ) ) ); - offset += 20; - - this.buttonList.add( - this.searchBoxSettings = new GuiImgButton( this.guiLeft - 18, offset, Settings.SEARCH_MODE, AEConfig.instance() - .getConfigManager() - .getSetting( - Settings.SEARCH_MODE ) ) ); - - offset += 20; - - if( !( this instanceof GuiMEPortableCell ) || this instanceof GuiWirelessTerm ) - { - this.buttonList.add( this.terminalStyleBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.TERMINAL_STYLE, AEConfig.instance() - .getConfigManager() - .getSetting( Settings.TERMINAL_STYLE ) ) ); - } - - this.searchField = new MEGuiTextField( this.fontRenderer, this.guiLeft + Math.max( 80, this.offsetX ), this.guiTop + 4, 90, 12 ); - this.searchField.setEnableBackgroundDrawing( false ); - this.searchField.setMaxStringLength( 25 ); - this.searchField.setTextColor( 0xFFFFFF ); - this.searchField.setSelectionColor( 0xFF008000 ); - this.searchField.setVisible( true ); - - if( this.viewCell || this instanceof GuiWirelessTerm ) - { - this.buttonList.add( this.craftingStatusBtn = new GuiTabButton( this.guiLeft + 170, this.guiTop - 4, 2 + 11 * 16, GuiText.CraftingStatus - .getLocal(), this.itemRender ) ); - this.craftingStatusBtn.setHideEdge( 13 ); - } - - final Enum searchModeSetting = AEConfig.instance().getConfigManager().getSetting( Settings.SEARCH_MODE ); - - this.isAutoFocus = SearchBoxMode.AUTOSEARCH == searchModeSetting || SearchBoxMode.JEI_AUTOSEARCH == searchModeSetting || SearchBoxMode.AUTOSEARCH_KEEP == searchModeSetting || SearchBoxMode.JEI_AUTOSEARCH_KEEP == searchModeSetting; - final boolean isKeepFilter = SearchBoxMode.AUTOSEARCH_KEEP == searchModeSetting || SearchBoxMode.JEI_AUTOSEARCH_KEEP == searchModeSetting || SearchBoxMode.MANUAL_SEARCH_KEEP == searchModeSetting || SearchBoxMode.JEI_MANUAL_SEARCH_KEEP == searchModeSetting; - final boolean isJEIEnabled = SearchBoxMode.JEI_AUTOSEARCH == searchModeSetting || SearchBoxMode.JEI_MANUAL_SEARCH == searchModeSetting; - - this.searchField.setFocused( this.isAutoFocus ); - - if( isJEIEnabled ) - { - memoryText = Integrations.jei().getSearchText(); - } - - if( isKeepFilter && memoryText != null && !memoryText.isEmpty() ) - { - this.searchField.setText( memoryText ); - this.searchField.selectAll(); - this.repo.setSearchString( memoryText ); - this.repo.updateView(); - this.setScrollBar(); - } - - craftingGridOffsetX = Integer.MAX_VALUE; - craftingGridOffsetY = Integer.MAX_VALUE; - - for( final Object s : this.inventorySlots.inventorySlots ) - { - if( s instanceof AppEngSlot ) - { - if( ( (Slot) s ).xPos < 197 ) - { - this.repositionSlot( (AppEngSlot) s ); - } - } - - if( s instanceof SlotCraftingMatrix || s instanceof SlotFakeCraftingMatrix ) - { - final Slot g = (Slot) s; - if( g.xPos > 0 && g.yPos > 0 ) - { - craftingGridOffsetX = Math.min( craftingGridOffsetX, g.xPos ); - craftingGridOffsetY = Math.min( craftingGridOffsetY, g.yPos ); - } - } - } - - craftingGridOffsetX -= 25; - craftingGridOffsetY -= 6; - - } - - @Override - public List getJEIExclusionArea() - { - List exclusionArea = new ArrayList<>(); - - int yOffset = guiTop + 8 + jeiOffset; - - int visibleButtons = (int) this.buttonList.stream().filter( v -> v.enabled && v.x < guiLeft ).count(); - Rectangle sortDir = new Rectangle( guiLeft - 18, yOffset, 20, visibleButtons * 20 + visibleButtons - 2 ); - exclusionArea.add( sortDir ); - - if( this.viewCell ) - { - Rectangle viewMode = new Rectangle( guiLeft + 205, yOffset - 4, 24, 19 * monitorableContainer.getViewCells().length ); - exclusionArea.add( viewMode ); - } - - return exclusionArea; - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( this.myName.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - - this.currentMouseX = mouseX; - this.currentMouseY = mouseY; - } - - @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) throws IOException - { - this.searchField.mouseClicked( xCoord, yCoord, btn ); - - if( btn == 1 && this.searchField.isMouseIn( xCoord, yCoord ) ) - { - this.searchField.setText( "" ); - this.repo.setSearchString( "" ); - this.repo.updateView(); - this.setScrollBar(); - } - - super.mouseClicked( xCoord, yCoord, btn ); - } - - @Override - public void onGuiClosed() - { - super.onGuiClosed(); - Keyboard.enableRepeatEvents( false ); - memoryText = this.searchField.getText(); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - - this.bindTexture( this.getBackground() ); - final int x_width = 197; - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, x_width, 18 ); - - if( this.viewCell || ( this instanceof GuiSecurityStation ) ) - { - this.drawTexturedModalRect( offsetX + x_width, offsetY + jeiOffset, x_width, 0, 46, 128 ); - } - - for( int x = 0; x < this.rows; x++ ) - { - this.drawTexturedModalRect( offsetX, offsetY + 18 + x * 18, 0, 18, x_width, 18 ); - } - - this.drawTexturedModalRect( offsetX, offsetY + 16 + this.rows * 18 + this.lowerTextureOffset, 0, 106 - 18 - 18, x_width, - 99 + this.reservedSpace - this.lowerTextureOffset ); - - if( this.viewCell ) - { - boolean update = false; - - for( int i = 0; i < 5; i++ ) - { - if( this.myCurrentViewCells[i] != this.monitorableContainer.getCellViewSlot( i ).getStack() ) - { - update = true; - this.myCurrentViewCells[i] = this.monitorableContainer.getCellViewSlot( i ).getStack(); - } - } - - if( update ) - { - this.repo.setViewCell( this.myCurrentViewCells ); - } - } - - if( this.searchField != null ) - { - this.searchField.drawTextBox(); - } - } - - protected String getBackground() - { - return "guis/terminal.png"; - } - - @Override - protected boolean isPowered() - { - return this.repo.hasPower(); - } - - int getMaxRows() - { - return AEConfig.instance().getConfigManager().getSetting( Settings.TERMINAL_STYLE ) == TerminalStyle.SMALL ? 6 : Integer.MAX_VALUE; - } - - protected void repositionSlot( final AppEngSlot s ) - { - s.yPos = s.getY() + this.ySize - 78 - 5; - } - - @Override - protected void keyTyped( final char character, final int key ) throws IOException - { - - if( !this.checkHotbarKeys( key ) ) - { - if( AppEng.proxy.isActionKey( ActionKey.TOGGLE_FOCUS, key ) ) - { - this.searchField.setFocused( !this.searchField.isFocused() ); - return; - } - - if( this.searchField.isFocused() && key == Keyboard.KEY_RETURN ) - { - this.searchField.setFocused( false ); - return; - } - - if( character == ' ' && this.searchField.getText().isEmpty() ) - { - return; - } - - final boolean mouseInGui = this.isPointInRegion( 0, 0, this.xSize, this.ySize, this.currentMouseX, this.currentMouseY ); - - if( this.isAutoFocus && !this.searchField.isFocused() && mouseInGui ) - { - this.searchField.setFocused( true ); - } - - if( this.searchField.textboxKeyTyped( character, key ) ) - { - this.repo.setSearchString( this.searchField.getText() ); - this.repo.updateView(); - this.setScrollBar(); - // tell forge the key event is handled and should not be sent out - this.keyHandled = mouseInGui; - } - else - { - super.keyTyped( character, key ); - } - } - } - - @Override - public void updateScreen() - { - this.repo.setPower( this.monitorableContainer.isPowered() ); - if( this.delayedUpdate ) - { - if( isShiftKeyDown() ) - { - this.delayedUpdate = false; - for( Slot slot : this.inventorySlots.inventorySlots ) - { - if( slot instanceof SlotME ) - { - if( this.isPointInRegion( slot.xPos, slot.yPos, 18, 18, currentMouseX, currentMouseY ) ) - { - this.delayedUpdate = true; - break; - } - } - } - } - else - { - this.delayedUpdate = false; - } - } - if( !this.delayedUpdate ) - { - this.repo.updateView(); - this.setScrollBar(); - } - super.updateScreen(); - } - - @Override - public Enum getSortBy() - { - return this.configSrc.getSetting( Settings.SORT_BY ); - } - - @Override - public Enum getSortDir() - { - return this.configSrc.getSetting( Settings.SORT_DIRECTION ); - } - - @Override - public Enum getSortDisplay() - { - return this.configSrc.getSetting( Settings.VIEW_MODE ); - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - if( this.SortByBox != null ) - { - this.SortByBox.set( this.configSrc.getSetting( Settings.SORT_BY ) ); - } - - if( this.SortDirBox != null ) - { - this.SortDirBox.set( this.configSrc.getSetting( Settings.SORT_DIRECTION ) ); - } - - if( this.ViewBox != null ) - { - this.ViewBox.set( this.configSrc.getSetting( Settings.VIEW_MODE ) ); - } - - this.repo.updateView(); - } - - int getReservedSpace() - { - return this.reservedSpace; - } - - void setReservedSpace( final int reservedSpace ) - { - this.reservedSpace = reservedSpace; - } - - public boolean isCustomSortOrder() - { - return this.customSortOrder; - } - - void setCustomSortOrder( final boolean customSortOrder ) - { - this.customSortOrder = customSortOrder; - } - - public int getStandardSize() - { - return this.standardSize; - } - - void setStandardSize( final int standardSize ) - { - this.standardSize = standardSize; - } +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fml.common.Loader; +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; + +import java.awt.*; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + + +public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfigManagerHost { + + private static int craftingGridOffsetX; + private static int craftingGridOffsetY; + + private static String memoryText = ""; + private final ItemRepo repo; + private final int offsetX = 9; + private final int lowerTextureOffset = 0; + private final IConfigManager configSrc; + private final boolean viewCell; + private final ItemStack[] myCurrentViewCells = new ItemStack[5]; + private final ContainerMEMonitorable monitorableContainer; + private GuiTabButton craftingStatusBtn; + private MEGuiTextField searchField; + private GuiText myName; + private int perRow = 9; + private int reservedSpace = 0; + private boolean customSortOrder = true; + private int rows = 0; + private int maxRows = Integer.MAX_VALUE; + private int standardSize; + private GuiImgButton ViewBox; + private GuiImgButton SortByBox; + private GuiImgButton SortDirBox; + private GuiImgButton searchBoxSettings; + private GuiImgButton terminalStyleBox; + private boolean isAutoFocus = false; + private int currentMouseX = 0; + private int currentMouseY = 0; + private boolean delayedUpdate; + + protected int jeiOffset = Loader.isModLoaded("jei") ? 24 : 0; + + public GuiMEMonitorable(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + this(inventoryPlayer, te, new ContainerMEMonitorable(inventoryPlayer, te)); + } + + public GuiMEMonitorable(final InventoryPlayer inventoryPlayer, final ITerminalHost te, final ContainerMEMonitorable c) { + + super(c); + + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar(scrollbar); + this.repo = new ItemRepo(scrollbar, this); + + this.xSize = 185; + this.ySize = 204; + + if (te instanceof IViewCellStorage) { + this.xSize += 33; + } + + this.standardSize = this.xSize; + + this.configSrc = ((IConfigurableObject) this.inventorySlots).getConfigManager(); + (this.monitorableContainer = (ContainerMEMonitorable) this.inventorySlots).setGui(this); + + this.viewCell = te instanceof IViewCellStorage; + + if (te instanceof TileSecurityStation) { + this.myName = GuiText.Security; + } else if (te instanceof WirelessTerminalGuiObject) { + this.myName = GuiText.WirelessTerminal; + } else if (te instanceof IPortableCell) { + this.myName = GuiText.PortableCell; + } else if (te instanceof IMEChest) { + this.myName = GuiText.Chest; + } else if (te instanceof AbstractPartTerminal) { + this.myName = GuiText.Terminal; + } + } + + public void postUpdate(final List list) { + for (final IAEItemStack is : list) { + this.repo.postUpdate(is); + } + + if (isShiftKeyDown()) { + for (Slot slot : this.inventorySlots.inventorySlots) { + if (slot instanceof SlotME) { + if (this.isPointInRegion(slot.xPos, slot.yPos, 18, 18, currentMouseX, currentMouseY)) { + this.delayedUpdate = true; + break; + } + } + } + } + + if (!this.delayedUpdate) { + this.repo.updateView(); + this.setScrollBar(); + } + } + + private void setScrollBar() { + this.getScrollBar().setTop(18).setLeft(175).setHeight(this.rows * 18 - 2); + this.getScrollBar().setRange(0, (this.repo.size() + this.perRow - 1) / this.perRow - this.rows, Math.max(1, this.rows / 6)); + } + + @Override + protected void actionPerformed(final GuiButton btn) { + if (btn == this.craftingStatusBtn) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(GuiBridge.GUI_CRAFTING_STATUS)); + } + + if (btn instanceof GuiImgButton) { + final boolean backwards = Mouse.isButtonDown(1); + + final GuiImgButton iBtn = (GuiImgButton) btn; + if (iBtn.getSetting() != Settings.ACTIONS) { + final Enum cv = iBtn.getCurrentValue(); + final Enum next = Platform.rotateEnum(cv, backwards, iBtn.getSetting().getPossibleValues()); + + if (btn == this.terminalStyleBox) { + AEConfig.instance().getConfigManager().putSetting(iBtn.getSetting(), next); + } else if (btn == this.searchBoxSettings) { + AEConfig.instance().getConfigManager().putSetting(iBtn.getSetting(), next); + } else { + try { + NetworkHandler.instance().sendToServer(new PacketValueConfig(iBtn.getSetting().name(), next.name())); + } catch (final IOException e) { + AELog.debug(e); + } + } + + iBtn.set(next); + + if (next.getClass() == SearchBoxMode.class || next.getClass() == TerminalStyle.class) { + this.reinitalize(); + } + } + } + } + + private void reinitalize() { + this.buttonList.clear(); + this.initGui(); + } + + @Override + public void initGui() { + Keyboard.enableRepeatEvents(true); + + this.maxRows = this.getMaxRows(); + this.perRow = AEConfig.instance() + .getConfigManager() + .getSetting( + Settings.TERMINAL_STYLE) != TerminalStyle.FULL ? 9 : 9 + ((this.width - this.standardSize) / 18); + + final int magicNumber = 114 + 1; + final int extraSpace = this.height - magicNumber - this.reservedSpace; + + this.rows = (int) Math.floor(extraSpace / 18); + if (this.rows > this.maxRows) { + this.rows = this.maxRows; + } + + if (this.rows < 3) { + this.rows = 3; + } + + this.getMeSlots().clear(); + for (int y = 0; y < this.rows; y++) { + for (int x = 0; x < this.perRow; x++) { + this.getMeSlots().add(new InternalSlotME(this.repo, x + y * this.perRow, this.offsetX + x * 18, 18 + y * 18)); + } + } + + if (AEConfig.instance().getConfigManager().getSetting(Settings.TERMINAL_STYLE) != TerminalStyle.FULL) { + this.xSize = this.standardSize + ((this.perRow - 9) * 18); + } else { + this.xSize = this.standardSize; + } + + super.initGui(); + // full size : 204 + // extra slots : 72 + // slot 18 + + this.ySize = magicNumber + this.rows * 18 + this.reservedSpace; + // this.guiTop = top; + final int unusedSpace = this.height - this.ySize; + this.guiTop = (int) Math.floor(unusedSpace / (unusedSpace < 0 ? 3.8f : 2.0f)); + + int offset = this.guiTop + 8 + jeiOffset; + + { + if (this.customSortOrder) { + this.buttonList + .add(this.SortByBox = new GuiImgButton(this.guiLeft - 18, offset, Settings.SORT_BY, this.configSrc.getSetting(Settings.SORT_BY))); + offset += 20; + } + } + + if (this.viewCell || this instanceof GuiWirelessTerm) { + this.buttonList + .add(this.ViewBox = new GuiImgButton(this.guiLeft - 18, offset, Settings.VIEW_MODE, this.configSrc.getSetting(Settings.VIEW_MODE))); + offset += 20; + } + + this.buttonList.add(this.SortDirBox = new GuiImgButton(this.guiLeft - 18, offset, Settings.SORT_DIRECTION, this.configSrc + .getSetting(Settings.SORT_DIRECTION))); + offset += 20; + + this.buttonList.add( + this.searchBoxSettings = new GuiImgButton(this.guiLeft - 18, offset, Settings.SEARCH_MODE, AEConfig.instance() + .getConfigManager() + .getSetting( + Settings.SEARCH_MODE))); + + offset += 20; + + if (!(this instanceof GuiMEPortableCell) || this instanceof GuiWirelessTerm) { + this.buttonList.add(this.terminalStyleBox = new GuiImgButton(this.guiLeft - 18, offset, Settings.TERMINAL_STYLE, AEConfig.instance() + .getConfigManager() + .getSetting(Settings.TERMINAL_STYLE))); + } + + this.searchField = new MEGuiTextField(this.fontRenderer, this.guiLeft + Math.max(80, this.offsetX), this.guiTop + 4, 90, 12); + this.searchField.setEnableBackgroundDrawing(false); + this.searchField.setMaxStringLength(25); + this.searchField.setTextColor(0xFFFFFF); + this.searchField.setSelectionColor(0xFF008000); + this.searchField.setVisible(true); + + if (this.viewCell || this instanceof GuiWirelessTerm) { + this.buttonList.add(this.craftingStatusBtn = new GuiTabButton(this.guiLeft + 170, this.guiTop - 4, 2 + 11 * 16, GuiText.CraftingStatus + .getLocal(), this.itemRender)); + this.craftingStatusBtn.setHideEdge(13); + } + + final Enum searchModeSetting = AEConfig.instance().getConfigManager().getSetting(Settings.SEARCH_MODE); + + this.isAutoFocus = SearchBoxMode.AUTOSEARCH == searchModeSetting || SearchBoxMode.JEI_AUTOSEARCH == searchModeSetting || SearchBoxMode.AUTOSEARCH_KEEP == searchModeSetting || SearchBoxMode.JEI_AUTOSEARCH_KEEP == searchModeSetting; + final boolean isKeepFilter = SearchBoxMode.AUTOSEARCH_KEEP == searchModeSetting || SearchBoxMode.JEI_AUTOSEARCH_KEEP == searchModeSetting || SearchBoxMode.MANUAL_SEARCH_KEEP == searchModeSetting || SearchBoxMode.JEI_MANUAL_SEARCH_KEEP == searchModeSetting; + final boolean isJEIEnabled = SearchBoxMode.JEI_AUTOSEARCH == searchModeSetting || SearchBoxMode.JEI_MANUAL_SEARCH == searchModeSetting; + + this.searchField.setFocused(this.isAutoFocus); + + if (isJEIEnabled) { + memoryText = Integrations.jei().getSearchText(); + } + + if (isKeepFilter && memoryText != null && !memoryText.isEmpty()) { + this.searchField.setText(memoryText); + this.searchField.selectAll(); + this.repo.setSearchString(memoryText); + this.repo.updateView(); + this.setScrollBar(); + } + + craftingGridOffsetX = Integer.MAX_VALUE; + craftingGridOffsetY = Integer.MAX_VALUE; + + for (final Object s : this.inventorySlots.inventorySlots) { + if (s instanceof AppEngSlot) { + if (((Slot) s).xPos < 197) { + this.repositionSlot((AppEngSlot) s); + } + } + + if (s instanceof SlotCraftingMatrix || s instanceof SlotFakeCraftingMatrix) { + final Slot g = (Slot) s; + if (g.xPos > 0 && g.yPos > 0) { + craftingGridOffsetX = Math.min(craftingGridOffsetX, g.xPos); + craftingGridOffsetY = Math.min(craftingGridOffsetY, g.yPos); + } + } + } + + craftingGridOffsetX -= 25; + craftingGridOffsetY -= 6; + + } + + @Override + public List getJEIExclusionArea() { + List exclusionArea = new ArrayList<>(); + + int yOffset = guiTop + 8 + jeiOffset; + + int visibleButtons = (int) this.buttonList.stream().filter(v -> v.enabled && v.x < guiLeft).count(); + Rectangle sortDir = new Rectangle(guiLeft - 18, yOffset, 20, visibleButtons * 20 + visibleButtons - 2); + exclusionArea.add(sortDir); + + if (this.viewCell) { + Rectangle viewMode = new Rectangle(guiLeft + 205, yOffset - 4, 24, 19 * monitorableContainer.getViewCells().length); + exclusionArea.add(viewMode); + } + + return exclusionArea; + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(this.myName.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); + + this.currentMouseX = mouseX; + this.currentMouseY = mouseY; + } + + @Override + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) throws IOException { + this.searchField.mouseClicked(xCoord, yCoord, btn); + + if (btn == 1 && this.searchField.isMouseIn(xCoord, yCoord)) { + this.searchField.setText(""); + this.repo.setSearchString(""); + this.repo.updateView(); + this.setScrollBar(); + } + + super.mouseClicked(xCoord, yCoord, btn); + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + Keyboard.enableRepeatEvents(false); + memoryText = this.searchField.getText(); + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + + this.bindTexture(this.getBackground()); + final int x_width = 197; + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, x_width, 18); + + if (this.viewCell || (this instanceof GuiSecurityStation)) { + this.drawTexturedModalRect(offsetX + x_width, offsetY + jeiOffset, x_width, 0, 46, 128); + } + + for (int x = 0; x < this.rows; x++) { + this.drawTexturedModalRect(offsetX, offsetY + 18 + x * 18, 0, 18, x_width, 18); + } + + this.drawTexturedModalRect(offsetX, offsetY + 16 + this.rows * 18 + this.lowerTextureOffset, 0, 106 - 18 - 18, x_width, + 99 + this.reservedSpace - this.lowerTextureOffset); + + if (this.viewCell) { + boolean update = false; + + for (int i = 0; i < 5; i++) { + if (this.myCurrentViewCells[i] != this.monitorableContainer.getCellViewSlot(i).getStack()) { + update = true; + this.myCurrentViewCells[i] = this.monitorableContainer.getCellViewSlot(i).getStack(); + } + } + + if (update) { + this.repo.setViewCell(this.myCurrentViewCells); + } + } + + if (this.searchField != null) { + this.searchField.drawTextBox(); + } + } + + protected String getBackground() { + return "guis/terminal.png"; + } + + @Override + protected boolean isPowered() { + return this.repo.hasPower(); + } + + int getMaxRows() { + return AEConfig.instance().getConfigManager().getSetting(Settings.TERMINAL_STYLE) == TerminalStyle.SMALL ? 6 : Integer.MAX_VALUE; + } + + protected void repositionSlot(final AppEngSlot s) { + s.yPos = s.getY() + this.ySize - 78 - 5; + } + + @Override + protected void keyTyped(final char character, final int key) throws IOException { + + if (!this.checkHotbarKeys(key)) { + if (AppEng.proxy.isActionKey(ActionKey.TOGGLE_FOCUS, key)) { + this.searchField.setFocused(!this.searchField.isFocused()); + return; + } + + if (this.searchField.isFocused() && key == Keyboard.KEY_RETURN) { + this.searchField.setFocused(false); + return; + } + + if (character == ' ' && this.searchField.getText().isEmpty()) { + return; + } + + final boolean mouseInGui = this.isPointInRegion(0, 0, this.xSize, this.ySize, this.currentMouseX, this.currentMouseY); + + if (this.isAutoFocus && !this.searchField.isFocused() && mouseInGui) { + this.searchField.setFocused(true); + } + + if (this.searchField.textboxKeyTyped(character, key)) { + this.repo.setSearchString(this.searchField.getText()); + this.repo.updateView(); + this.setScrollBar(); + // tell forge the key event is handled and should not be sent out + this.keyHandled = mouseInGui; + } else { + super.keyTyped(character, key); + } + } + } + + @Override + public void updateScreen() { + this.repo.setPower(this.monitorableContainer.isPowered()); + if (this.delayedUpdate) { + if (isShiftKeyDown()) { + this.delayedUpdate = false; + for (Slot slot : this.inventorySlots.inventorySlots) { + if (slot instanceof SlotME) { + if (this.isPointInRegion(slot.xPos, slot.yPos, 18, 18, currentMouseX, currentMouseY)) { + this.delayedUpdate = true; + break; + } + } + } + } else { + this.delayedUpdate = false; + } + } + if (!this.delayedUpdate) { + this.repo.updateView(); + this.setScrollBar(); + } + super.updateScreen(); + } + + @Override + public Enum getSortBy() { + return this.configSrc.getSetting(Settings.SORT_BY); + } + + @Override + public Enum getSortDir() { + return this.configSrc.getSetting(Settings.SORT_DIRECTION); + } + + @Override + public Enum getSortDisplay() { + return this.configSrc.getSetting(Settings.VIEW_MODE); + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + if (this.SortByBox != null) { + this.SortByBox.set(this.configSrc.getSetting(Settings.SORT_BY)); + } + + if (this.SortDirBox != null) { + this.SortDirBox.set(this.configSrc.getSetting(Settings.SORT_DIRECTION)); + } + + if (this.ViewBox != null) { + this.ViewBox.set(this.configSrc.getSetting(Settings.VIEW_MODE)); + } + + this.repo.updateView(); + } + + int getReservedSpace() { + return this.reservedSpace; + } + + void setReservedSpace(final int reservedSpace) { + this.reservedSpace = reservedSpace; + } + + public boolean isCustomSortOrder() { + return this.customSortOrder; + } + + void setCustomSortOrder(final boolean customSortOrder) { + this.customSortOrder = customSortOrder; + } + + public int getStandardSize() { + return this.standardSize; + } + + void setStandardSize(final int standardSize) { + this.standardSize = standardSize; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java b/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java index b43afef93..697a7e80b 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java +++ b/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java @@ -19,28 +19,23 @@ package appeng.client.gui.implementations; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.implementations.guiobjects.IPortableCell; import appeng.container.implementations.ContainerMEPortableCell; +import net.minecraft.entity.player.InventoryPlayer; -public class GuiMEPortableCell extends GuiMEMonitorable -{ +public class GuiMEPortableCell extends GuiMEMonitorable { - public GuiMEPortableCell( final InventoryPlayer inventoryPlayer, final IPortableCell te ) - { - super( inventoryPlayer, te, new ContainerMEPortableCell( inventoryPlayer, te ) ); - } + public GuiMEPortableCell(final InventoryPlayer inventoryPlayer, final IPortableCell te) { + super(inventoryPlayer, te, new ContainerMEPortableCell(inventoryPlayer, te)); + } - int defaultGetMaxRows() - { - return super.getMaxRows(); - } + int defaultGetMaxRows() { + return super.getMaxRows(); + } - @Override - int getMaxRows() - { - return 3; - } + @Override + int getMaxRows() { + return 3; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java b/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java index 809870f32..b14a455b8 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java +++ b/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java @@ -19,18 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; -import java.util.List; - -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; - import appeng.api.config.Settings; import appeng.api.config.SortDir; import appeng.api.config.SortOrder; @@ -47,249 +35,227 @@ import appeng.container.implementations.ContainerNetworkStatus; import appeng.core.AEConfig; import appeng.core.localization.GuiText; import appeng.util.Platform; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import org.lwjgl.input.Mouse; + +import java.io.IOException; +import java.util.List; -public class GuiNetworkStatus extends AEBaseGui implements ISortSource -{ +public class GuiNetworkStatus extends AEBaseGui implements ISortSource { - private final ItemRepo repo; - private final int rows = 4; - private GuiImgButton units; - private int tooltip = -1; + private final ItemRepo repo; + private final int rows = 4; + private GuiImgButton units; + private int tooltip = -1; - public GuiNetworkStatus( final InventoryPlayer inventoryPlayer, final INetworkTool te ) - { - super( new ContainerNetworkStatus( inventoryPlayer, te ) ); - final GuiScrollbar scrollbar = new GuiScrollbar(); + public GuiNetworkStatus(final InventoryPlayer inventoryPlayer, final INetworkTool te) { + super(new ContainerNetworkStatus(inventoryPlayer, te)); + final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - this.repo = new ItemRepo( scrollbar, this ); - this.ySize = 153; - this.xSize = 195; - this.repo.setRowSize( 5 ); - } + this.setScrollBar(scrollbar); + this.repo = new ItemRepo(scrollbar, this); + this.ySize = 153; + this.xSize = 195; + this.repo.setRowSize(5); + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - if( btn == this.units ) - { - AEConfig.instance().nextPowerUnit( backwards ); - this.units.set( AEConfig.instance().selectedPowerUnit() ); - } - } + if (btn == this.units) { + AEConfig.instance().nextPowerUnit(backwards); + this.units.set(AEConfig.instance().selectedPowerUnit()); + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.units = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance().selectedPowerUnit() ); - this.buttonList.add( this.units ); - } + this.units = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance().selectedPowerUnit()); + this.buttonList.add(this.units); + } - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { - final int gx = ( this.width - this.xSize ) / 2; - final int gy = ( this.height - this.ySize ) / 2; + final int gx = (this.width - this.xSize) / 2; + final int gy = (this.height - this.ySize) / 2; - this.tooltip = -1; + this.tooltip = -1; - int y = 0; - int x = 0; - for( int z = 0; z <= 4 * 5; z++ ) - { - final int minX = gx + 14 + x * 31; - final int minY = gy + 41 + y * 18; + int y = 0; + int x = 0; + for (int z = 0; z <= 4 * 5; z++) { + final int minX = gx + 14 + x * 31; + final int minY = gy + 41 + y * 18; - if( minX < mouseX && minX + 28 > mouseX ) - { - if( minY < mouseY && minY + 20 > mouseY ) - { - this.tooltip = z; - break; - } - } + if (minX < mouseX && minX + 28 > mouseX) { + if (minY < mouseY && minY + 20 > mouseY) { + this.tooltip = z; + break; + } + } - x++; + x++; - if( x > 4 ) - { - y++; - x = 0; - } - } + if (x > 4) { + y++; + x = 0; + } + } - super.drawScreen( mouseX, mouseY, btn ); - } + super.drawScreen(mouseX, mouseY, btn); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - final ContainerNetworkStatus ns = (ContainerNetworkStatus) this.inventorySlots; + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + final ContainerNetworkStatus ns = (ContainerNetworkStatus) this.inventorySlots; - this.fontRenderer.drawString( GuiText.NetworkDetails.getLocal(), 8, 6, 4210752 ); + this.fontRenderer.drawString(GuiText.NetworkDetails.getLocal(), 8, 6, 4210752); - this.fontRenderer.drawString( GuiText.StoredPower.getLocal() + ": " + Platform.formatPowerLong( ns.getCurrentPower(), false ), 13, 16, 4210752 ); - this.fontRenderer.drawString( GuiText.MaxPower.getLocal() + ": " + Platform.formatPowerLong( ns.getMaxPower(), false ), 13, 26, 4210752 ); + this.fontRenderer.drawString(GuiText.StoredPower.getLocal() + ": " + Platform.formatPowerLong(ns.getCurrentPower(), false), 13, 16, 4210752); + this.fontRenderer.drawString(GuiText.MaxPower.getLocal() + ": " + Platform.formatPowerLong(ns.getMaxPower(), false), 13, 26, 4210752); - this.fontRenderer.drawString( GuiText.PowerInputRate.getLocal() + ": " + Platform.formatPowerLong( ns.getAverageAddition(), true ), 13, 143 - 10, - 4210752 ); - this.fontRenderer.drawString( GuiText.PowerUsageRate.getLocal() + ": " + Platform.formatPowerLong( ns.getPowerUsage(), true ), 13, 143 - 20, 4210752 ); + this.fontRenderer.drawString(GuiText.PowerInputRate.getLocal() + ": " + Platform.formatPowerLong(ns.getAverageAddition(), true), 13, 143 - 10, + 4210752); + this.fontRenderer.drawString(GuiText.PowerUsageRate.getLocal() + ": " + Platform.formatPowerLong(ns.getPowerUsage(), true), 13, 143 - 20, 4210752); - final int sectionLength = 30; + final int sectionLength = 30; - int x = 0; - int y = 0; - final int xo = 12; - final int yo = 42; - final int viewStart = 0;// myScrollBar.getCurrentScroll() * 5; - final int viewEnd = viewStart + 5 * 4; + int x = 0; + int y = 0; + final int xo = 12; + final int yo = 42; + final int viewStart = 0;// myScrollBar.getCurrentScroll() * 5; + final int viewEnd = viewStart + 5 * 4; - String toolTip = ""; - int toolPosX = 0; - int toolPosY = 0; + String toolTip = ""; + int toolPosX = 0; + int toolPosY = 0; - for( int z = viewStart; z < Math.min( viewEnd, this.repo.size() ); z++ ) - { - final IAEItemStack refStack = this.repo.getReferenceItem( z ); - if( refStack != null ) - { - GlStateManager.pushMatrix(); - GlStateManager.scale( 0.5, 0.5, 0.5 ); + for (int z = viewStart; z < Math.min(viewEnd, this.repo.size()); z++) { + final IAEItemStack refStack = this.repo.getReferenceItem(z); + if (refStack != null) { + GlStateManager.pushMatrix(); + GlStateManager.scale(0.5, 0.5, 0.5); - String str = Long.toString( refStack.getStackSize() ); - if( refStack.getStackSize() >= 10000 ) - { - str = Long.toString( refStack.getStackSize() / 1000 ) + 'k'; - } + String str = Long.toString(refStack.getStackSize()); + if (refStack.getStackSize() >= 10000) { + str = Long.toString(refStack.getStackSize() / 1000) + 'k'; + } - final int w = this.fontRenderer.getStringWidth( str ); - this.fontRenderer.drawString( str, (int) ( ( x * sectionLength + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * 18 + yo + 6 ) * 2, - 4210752 ); + final int w = this.fontRenderer.getStringWidth(str); + this.fontRenderer.drawString(str, (int) ((x * sectionLength + xo + sectionLength - 19 - (w * 0.5)) * 2), (y * 18 + yo + 6) * 2, + 4210752); - GlStateManager.popMatrix(); - final int posX = x * sectionLength + xo + sectionLength - 18; - final int posY = y * 18 + yo; + GlStateManager.popMatrix(); + final int posX = x * sectionLength + xo + sectionLength - 18; + final int posY = y * 18 + yo; - if( this.tooltip == z - viewStart ) - { - toolTip = Platform.getItemDisplayName( refStack ); + if (this.tooltip == z - viewStart) { + toolTip = Platform.getItemDisplayName(refStack); - toolTip += ( '\n' + GuiText.Installed.getLocal() + ": " + ( refStack.getStackSize() ) ); - if( refStack.getCountRequestable() > 0 ) - { - toolTip += ( '\n' + GuiText.EnergyDrain.getLocal() + ": " + Platform.formatPowerLong( refStack.getCountRequestable(), true ) ); - } + toolTip += ('\n' + GuiText.Installed.getLocal() + ": " + (refStack.getStackSize())); + if (refStack.getCountRequestable() > 0) { + toolTip += ('\n' + GuiText.EnergyDrain.getLocal() + ": " + Platform.formatPowerLong(refStack.getCountRequestable(), true)); + } - toolPosX = x * sectionLength + xo + sectionLength - 8; - toolPosY = y * 18 + yo; - } + toolPosX = x * sectionLength + xo + sectionLength - 8; + toolPosY = y * 18 + yo; + } - this.drawItem( posX, posY, refStack.asItemStackRepresentation() ); + this.drawItem(posX, posY, refStack.asItemStackRepresentation()); - x++; + x++; - if( x > 4 ) - { - y++; - x = 0; - } - } - } + if (x > 4) { + y++; + x = 0; + } + } + } - if( this.tooltip >= 0 && toolTip.length() > 0 ) - { - this.drawTooltip( toolPosX, toolPosY + 10, toolTip ); - } - } + if (this.tooltip >= 0 && toolTip.length() > 0) { + this.drawTooltip(toolPosX, toolPosY + 10, toolTip); + } + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/networkstatus.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/networkstatus.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } - public void postUpdate( final List list ) - { - this.repo.clear(); + public void postUpdate(final List list) { + this.repo.clear(); - for( final IAEItemStack is : list ) - { - this.repo.postUpdate( is ); - } + for (final IAEItemStack is : list) { + this.repo.postUpdate(is); + } - this.repo.updateView(); - this.setScrollBar(); - } + this.repo.updateView(); + this.setScrollBar(); + } - private void setScrollBar() - { - final int size = this.repo.size(); - this.getScrollBar().setTop( 39 ).setLeft( 175 ).setHeight( 78 ); - this.getScrollBar().setRange( 0, ( size + 4 ) / 5 - this.rows, 1 ); - } + private void setScrollBar() { + final int size = this.repo.size(); + this.getScrollBar().setTop(39).setLeft(175).setHeight(78); + this.getScrollBar().setRange(0, (size + 4) / 5 - this.rows, 1); + } - @Override - protected void renderToolTip( final ItemStack stack, final int x, final int y ) - { - final Slot s = this.getSlot( x, y ); + @Override + protected void renderToolTip(final ItemStack stack, final int x, final int y) { + final Slot s = this.getSlot(x, y); - if( s instanceof SlotME && stack != null ) - { - IAEItemStack myStack = null; + if (s instanceof SlotME && stack != null) { + IAEItemStack myStack = null; - try - { - final SlotME theSlotField = (SlotME) s; - myStack = theSlotField.getAEStack(); - } - catch( final Throwable ignore ) - { - } + try { + final SlotME theSlotField = (SlotME) s; + myStack = theSlotField.getAEStack(); + } catch (final Throwable ignore) { + } - if( myStack != null ) - { - ITooltipFlag.TooltipFlags tooltipFlag = this.mc.gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL; - List currentToolTip = stack.getTooltip( this.mc.player, tooltipFlag ); + if (myStack != null) { + ITooltipFlag.TooltipFlags tooltipFlag = this.mc.gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL; + List currentToolTip = stack.getTooltip(this.mc.player, tooltipFlag); - while( currentToolTip.size() > 1 ) - { - currentToolTip.remove( 1 ); - } + while (currentToolTip.size() > 1) { + currentToolTip.remove(1); + } - currentToolTip.add( GuiText.Installed.getLocal() + ": " + ( myStack.getStackSize() ) ); - currentToolTip.add( GuiText.EnergyDrain.getLocal() + ": " + Platform.formatPowerLong( myStack.getCountRequestable(), true ) ); + currentToolTip.add(GuiText.Installed.getLocal() + ": " + (myStack.getStackSize())); + currentToolTip.add(GuiText.EnergyDrain.getLocal() + ": " + Platform.formatPowerLong(myStack.getCountRequestable(), true)); - this.drawTooltip( x, y, currentToolTip ); - } - } + this.drawTooltip(x, y, currentToolTip); + } + } - super.renderToolTip( stack, x, y ); - } + super.renderToolTip(stack, x, y); + } - @Override - public Enum getSortBy() - { - return SortOrder.NAME; - } + @Override + public Enum getSortBy() { + return SortOrder.NAME; + } - @Override - public Enum getSortDir() - { - return SortDir.ASCENDING; - } + @Override + public Enum getSortDir() { + return SortDir.ASCENDING; + } - @Override - public Enum getSortDisplay() - { - return ViewItems.ALL; - } + @Override + public Enum getSortDisplay() { + return ViewItems.ALL; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java b/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java index 9c3d726a0..e38dc8047 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java +++ b/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java @@ -19,11 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.implementations.guiobjects.INetworkTool; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiToggleButton; @@ -32,64 +27,57 @@ import appeng.core.AELog; import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; + +import java.io.IOException; -public class GuiNetworkTool extends AEBaseGui -{ +public class GuiNetworkTool extends AEBaseGui { - private GuiToggleButton tFacades; + private GuiToggleButton tFacades; - public GuiNetworkTool( final InventoryPlayer inventoryPlayer, final INetworkTool te ) - { - super( new ContainerNetworkTool( inventoryPlayer, te ) ); - this.ySize = 166; - } + public GuiNetworkTool(final InventoryPlayer inventoryPlayer, final INetworkTool te) { + super(new ContainerNetworkTool(inventoryPlayer, te)); + this.ySize = 166; + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - try - { - if( btn == this.tFacades ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "NetworkTool", "Toggle" ) ); - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + try { + if (btn == this.tFacades) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("NetworkTool", "Toggle")); + } + } catch (final IOException e) { + AELog.debug(e); + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.tFacades = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 8, 23, 22, GuiText.TransparentFacades.getLocal(), GuiText.TransparentFacadesHint - .getLocal() ); + this.tFacades = new GuiToggleButton(this.guiLeft - 18, this.guiTop + 8, 23, 22, GuiText.TransparentFacades.getLocal(), GuiText.TransparentFacadesHint + .getLocal()); - this.buttonList.add( this.tFacades ); - } + this.buttonList.add(this.tFacades); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - if( this.tFacades != null ) - { - this.tFacades.setState( ( (ContainerNetworkTool) this.inventorySlots ).isFacadeMode() ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + if (this.tFacades != null) { + this.tFacades.setState(((ContainerNetworkTool) this.inventorySlots).isFacadeMode()); + } - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.NetworkTool.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - } + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.NetworkTool.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/toolbox.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/toolbox.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiOreDictStorageBus.java b/src/main/java/appeng/client/gui/implementations/GuiOreDictStorageBus.java index 22fc0ae9c..22d2301bf 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiOreDictStorageBus.java +++ b/src/main/java/appeng/client/gui/implementations/GuiOreDictStorageBus.java @@ -26,152 +26,123 @@ import java.io.IOException; import java.util.regex.Pattern; -public class GuiOreDictStorageBus extends AEBaseGui -{ +public class GuiOreDictStorageBus extends AEBaseGui { private final ContainerOreDictStorageBus container; PartOreDicStorageBus part; private GuiTabButton priority; private GuiImgButton partition; private GuiImgButton storageFilter; private GuiImgButton rwMode; - private static final Pattern ORE_DICTIONARY_FILTER = Pattern.compile( "[(!]* *[0-9a-zA-Z*]* *\\)*( *[&|^]? *[(!]* *[0-9a-zA-Z*]* *\\)*)*" ); + private static final Pattern ORE_DICTIONARY_FILTER = Pattern.compile("[(!]* *[0-9a-zA-Z*]* *\\)*( *[&|^]? *[(!]* *[0-9a-zA-Z*]* *\\)*)*"); private MEGuiTextField searchFieldInputs; - public GuiOreDictStorageBus( final InventoryPlayer inventoryPlayer, final PartOreDicStorageBus te ) - { - super( new ContainerOreDictStorageBus( inventoryPlayer, te ) ); + public GuiOreDictStorageBus(final InventoryPlayer inventoryPlayer, final PartOreDicStorageBus te) { + super(new ContainerOreDictStorageBus(inventoryPlayer, te)); this.container = (ContainerOreDictStorageBus) super.inventorySlots; part = te; this.ySize = 84; } @Override - public void initGui() - { + public void initGui() { super.initGui(); - this.searchFieldInputs = new MEGuiTextField( this.fontRenderer, this.guiLeft + 3, this.guiTop + 22, 170, 12 ); - this.searchFieldInputs.setEnableBackgroundDrawing( false ); - this.searchFieldInputs.setMaxStringLength( 512 ); - this.searchFieldInputs.setTextColor( 0xFFFFFF ); - this.searchFieldInputs.setVisible( true ); - this.searchFieldInputs.setFocused( false ); - this.searchFieldInputs.setValidator( str -> ORE_DICTIONARY_FILTER.matcher( str ).matches() ); + this.searchFieldInputs = new MEGuiTextField(this.fontRenderer, this.guiLeft + 3, this.guiTop + 22, 170, 12); + this.searchFieldInputs.setEnableBackgroundDrawing(false); + this.searchFieldInputs.setMaxStringLength(512); + this.searchFieldInputs.setTextColor(0xFFFFFF); + this.searchFieldInputs.setVisible(true); + this.searchFieldInputs.setFocused(false); + this.searchFieldInputs.setValidator(str -> ORE_DICTIONARY_FILTER.matcher(str).matches()); - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender ) ); - this.buttonList.add( this.partition = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH ) ); - this.buttonList.add( this.rwMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.ACCESS, AccessRestriction.READ_WRITE ) ); - this.buttonList.add( this.storageFilter = new GuiImgButton( this.guiLeft - 18, this.guiTop + 68, Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY ) ); + this.buttonList.add(this.priority = new GuiTabButton(this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender)); + this.buttonList.add(this.partition = new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH)); + this.buttonList.add(this.rwMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 48, Settings.ACCESS, AccessRestriction.READ_WRITE)); + this.buttonList.add(this.storageFilter = new GuiImgButton(this.guiLeft - 18, this.guiTop + 68, Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY)); - try - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "OreDictStorageBus.getRegex", "1" ) ); - } - catch( IOException e ) - { + try { + NetworkHandler.instance().sendToServer(new PacketValueConfig("OreDictStorageBus.getRegex", "1")); + } catch (IOException e) { e.printStackTrace(); } } - public void fillRegex( String regex ) - { - this.searchFieldInputs.setText( regex ); + public void fillRegex(String regex) { + this.searchFieldInputs.setText(regex); } @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - try - { - if( btn == this.priority ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); + try { + if (btn == this.priority) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } else if (btn == this.partition) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("StorageBus.Action", "Partition")); + } else if (btn == this.rwMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.rwMode.getSetting(), backwards)); + } else if (btn == this.storageFilter) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.storageFilter.getSetting(), backwards)); } - else if( btn == this.partition ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "StorageBus.Action", "Partition" ) ); - } - else if( btn == this.rwMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.rwMode.getSetting(), backwards ) ); - } - else if( btn == this.storageFilter ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.storageFilter.getSetting(), backwards ) ); - } - } - catch( final IOException e ) - { - AELog.debug( e ); + } catch (final IOException e) { + AELog.debug(e); } } @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) throws IOException - { + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) throws IOException { boolean wasFocused = this.searchFieldInputs.isFocused(); - this.searchFieldInputs.mouseClicked( xCoord, yCoord, btn ); + this.searchFieldInputs.mouseClicked(xCoord, yCoord, btn); - if( btn == 1 && this.searchFieldInputs.isMouseIn( xCoord, yCoord ) ) - { - this.searchFieldInputs.setText( "" ); + if (btn == 1 && this.searchFieldInputs.isMouseIn(xCoord, yCoord)) { + this.searchFieldInputs.setText(""); } - if( !searchFieldInputs.isFocused() && wasFocused ) - { - searchFieldInputs.setText( OreDictFilterMatcher.validateExp( searchFieldInputs.getText() ) ); - NetworkHandler.instance().sendToServer( new PacketValueConfig( "OreDictStorageBus.save", searchFieldInputs.getText() ) ); + if (!searchFieldInputs.isFocused() && wasFocused) { + searchFieldInputs.setText(OreDictFilterMatcher.validateExp(searchFieldInputs.getText())); + NetworkHandler.instance().sendToServer(new PacketValueConfig("OreDictStorageBus.save", searchFieldInputs.getText())); } - super.mouseClicked( xCoord, yCoord, btn ); + super.mouseClicked(xCoord, yCoord, btn); } @Override - protected void keyTyped( final char character, final int key ) throws IOException - { - if( !this.checkHotbarKeys( key ) ) - { - if( !this.searchFieldInputs.textboxKeyTyped( character, key ) ) - { - super.keyTyped( character, key ); + protected void keyTyped(final char character, final int key) throws IOException { + if (!this.checkHotbarKeys(key)) { + if (!this.searchFieldInputs.textboxKeyTyped(character, key)) { + super.keyTyped(character, key); } } } @Override - public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.OreDictStorageBus.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( this.searchFieldInputs.getText().length() + " / " + this.searchFieldInputs.getMaxStringLength(), 120, 36, 4210752 ); - this.fontRenderer.drawString( "& = AND " + "| = OR", 8, 36, 4210752 ); - this.fontRenderer.drawString( "^ = XOR " + "! = NOT", 8, 48, 4210752 ); - this.fontRenderer.drawString( "() for priority " + "* for wildcard", 8, 60, 4210752 ); - this.fontRenderer.drawString( "Ex.: *Redstone*&!dustRedstone", 8, 72, 4210752 ); + public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.OreDictStorageBus.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(this.searchFieldInputs.getText().length() + " / " + this.searchFieldInputs.getMaxStringLength(), 120, 36, 4210752); + this.fontRenderer.drawString("& = AND " + "| = OR", 8, 36, 4210752); + this.fontRenderer.drawString("^ = XOR " + "! = NOT", 8, 48, 4210752); + this.fontRenderer.drawString("() for priority " + "* for wildcard", 8, 60, 4210752); + this.fontRenderer.drawString("Ex.: *Redstone*&!dustRedstone", 8, 72, 4210752); - if( this.storageFilter != null ) - { - this.storageFilter.set( container.getStorageFilter() ); + if (this.storageFilter != null) { + this.storageFilter.set(container.getStorageFilter()); } - if( this.rwMode != null ) - { - this.rwMode.set( container.getReadWriteMode() ); + if (this.rwMode != null) { + this.rwMode.set(container.getReadWriteMode()); } } @Override - public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - this.bindTexture( "guis/oredictstoragebus.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, 175, 85 ); + public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) { + this.bindTexture("guis/oredictstoragebus.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, 175, 85); - if( this.searchFieldInputs != null ) - { + if (this.searchFieldInputs != null) { this.searchFieldInputs.drawTextBox(); } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiPatternTerm.java b/src/main/java/appeng/client/gui/implementations/GuiPatternTerm.java index b61cee120..f7d8cd248 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiPatternTerm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiPatternTerm.java @@ -19,14 +19,21 @@ package appeng.client.gui.implementations; -import java.awt.*; -import java.io.IOException; -import java.util.*; -import java.util.List; - +import appeng.api.config.ActionItems; +import appeng.api.config.ItemSubstitution; +import appeng.api.config.Settings; +import appeng.api.storage.ITerminalHost; +import appeng.client.gui.widgets.GuiImgButton; +import appeng.client.gui.widgets.GuiTabButton; +import appeng.container.implementations.ContainerPatternTerm; import appeng.container.interfaces.IJEIGhostIngredients; +import appeng.container.slot.AppEngSlot; import appeng.container.slot.SlotFake; +import appeng.core.AELog; +import appeng.core.localization.GuiText; +import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketInventoryAction; +import appeng.core.sync.packets.PacketValueConfig; import appeng.helpers.InventoryAction; import appeng.util.item.AEItemStack; import mezz.jei.api.gui.IGhostIngredientHandler.Target; @@ -36,301 +43,254 @@ import net.minecraft.init.Blocks; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; -import appeng.api.config.ActionItems; -import appeng.api.config.ItemSubstitution; -import appeng.api.config.Settings; -import appeng.api.storage.ITerminalHost; -import appeng.client.gui.widgets.GuiImgButton; -import appeng.client.gui.widgets.GuiTabButton; -import appeng.container.implementations.ContainerPatternTerm; -import appeng.container.slot.AppEngSlot; -import appeng.core.AELog; -import appeng.core.localization.GuiText; -import appeng.core.sync.network.NetworkHandler; -import appeng.core.sync.packets.PacketValueConfig; +import java.awt.*; +import java.io.IOException; +import java.util.List; +import java.util.*; -public class GuiPatternTerm extends GuiMEMonitorable implements IJEIGhostIngredients -{ +public class GuiPatternTerm extends GuiMEMonitorable implements IJEIGhostIngredients { - private static final String BACKGROUND_CRAFTING_MODE = "guis/pattern.png"; - private static final String BACKGROUND_PROCESSING_MODE = "guis/pattern2.png"; + private static final String BACKGROUND_CRAFTING_MODE = "guis/pattern.png"; + private static final String BACKGROUND_PROCESSING_MODE = "guis/pattern2.png"; - private static final String SUBSITUTION_DISABLE = "0"; - private static final String SUBSITUTION_ENABLE = "1"; + private static final String SUBSITUTION_DISABLE = "0"; + private static final String SUBSITUTION_ENABLE = "1"; - private static final String CRAFTMODE_CRFTING = "1"; - private static final String CRAFTMODE_PROCESSING = "0"; + private static final String CRAFTMODE_CRFTING = "1"; + private static final String CRAFTMODE_PROCESSING = "0"; - private final ContainerPatternTerm container; + private final ContainerPatternTerm container; - private GuiTabButton tabCraftButton; - private GuiTabButton tabProcessButton; - private GuiImgButton substitutionsEnabledBtn; - private GuiImgButton substitutionsDisabledBtn; - private GuiImgButton encodeBtn; - private GuiImgButton clearBtn; - private GuiImgButton x2Btn; - private GuiImgButton x3Btn; - private GuiImgButton plusOneBtn; - private GuiImgButton divTwoBtn; - private GuiImgButton divThreeBtn; - private GuiImgButton minusOneBtn; - private GuiImgButton maxCountBtn; - public Map,Object> mapTargetSlot = new HashMap<>(); + private GuiTabButton tabCraftButton; + private GuiTabButton tabProcessButton; + private GuiImgButton substitutionsEnabledBtn; + private GuiImgButton substitutionsDisabledBtn; + private GuiImgButton encodeBtn; + private GuiImgButton clearBtn; + private GuiImgButton x2Btn; + private GuiImgButton x3Btn; + private GuiImgButton plusOneBtn; + private GuiImgButton divTwoBtn; + private GuiImgButton divThreeBtn; + private GuiImgButton minusOneBtn; + private GuiImgButton maxCountBtn; + public Map, Object> mapTargetSlot = new HashMap<>(); - public GuiPatternTerm( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( inventoryPlayer, te, new ContainerPatternTerm( inventoryPlayer, te ) ); - this.container = (ContainerPatternTerm) this.inventorySlots; - this.setReservedSpace( 81 ); - } + public GuiPatternTerm(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(inventoryPlayer, te, new ContainerPatternTerm(inventoryPlayer, te)); + this.container = (ContainerPatternTerm) this.inventorySlots; + this.setReservedSpace(81); + } - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - try - { + try { - if( this.tabCraftButton == btn || this.tabProcessButton == btn ) - { - NetworkHandler.instance() - .sendToServer( - new PacketValueConfig( "PatternTerminal.CraftMode", this.tabProcessButton == btn ? CRAFTMODE_CRFTING : CRAFTMODE_PROCESSING ) ); - } + if (this.tabCraftButton == btn || this.tabProcessButton == btn) { + NetworkHandler.instance() + .sendToServer( + new PacketValueConfig("PatternTerminal.CraftMode", this.tabProcessButton == btn ? CRAFTMODE_CRFTING : CRAFTMODE_PROCESSING)); + } - if( this.encodeBtn == btn ) - { - if ( isShiftKeyDown() ){ - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.Encode", "2" ) ); - } - else - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.Encode", "1" ) ); - } - } + if (this.encodeBtn == btn) { + if (isShiftKeyDown()) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.Encode", "2")); + } else { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.Encode", "1")); + } + } - if( this.clearBtn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.Clear", "1" ) ); - } + if (this.clearBtn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.Clear", "1")); + } - if( this.x2Btn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.MultiplyByTwo", "1" ) ); - } + if (this.x2Btn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.MultiplyByTwo", "1")); + } - if( this.x3Btn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.MultiplyByThree", "1" ) ); - } + if (this.x3Btn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.MultiplyByThree", "1")); + } - if( this.divTwoBtn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.DivideByTwo", "1" ) ); - } + if (this.divTwoBtn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.DivideByTwo", "1")); + } - if( this.divThreeBtn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.DivideByThree", "1" ) ); - } + if (this.divThreeBtn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.DivideByThree", "1")); + } - if( this.plusOneBtn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.IncreaseByOne", "1" ) ); - } + if (this.plusOneBtn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.IncreaseByOne", "1")); + } - if( this.minusOneBtn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.DecreaseByOne", "1" ) ); - } + if (this.minusOneBtn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.DecreaseByOne", "1")); + } - if( this.maxCountBtn == btn ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.MaximizeCount", "1" ) ); - } + if (this.maxCountBtn == btn) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.MaximizeCount", "1")); + } - if( this.substitutionsEnabledBtn == btn || this.substitutionsDisabledBtn == btn ) - { - NetworkHandler.instance() - .sendToServer( - new PacketValueConfig( "PatternTerminal.Substitute", this.substitutionsEnabledBtn == btn ? SUBSITUTION_DISABLE : SUBSITUTION_ENABLE ) ); - } - } - catch( final IOException e ) - { - AELog.error( e ); - } - } + if (this.substitutionsEnabledBtn == btn || this.substitutionsDisabledBtn == btn) { + NetworkHandler.instance() + .sendToServer( + new PacketValueConfig("PatternTerminal.Substitute", this.substitutionsEnabledBtn == btn ? SUBSITUTION_DISABLE : SUBSITUTION_ENABLE)); + } + } catch (final IOException e) { + AELog.error(e); + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.tabCraftButton = new GuiTabButton( this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack( Blocks.CRAFTING_TABLE ), GuiText.CraftingPattern - .getLocal(), this.itemRender ); - this.buttonList.add( this.tabCraftButton ); + this.tabCraftButton = new GuiTabButton(this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack(Blocks.CRAFTING_TABLE), GuiText.CraftingPattern + .getLocal(), this.itemRender); + this.buttonList.add(this.tabCraftButton); - this.tabProcessButton = new GuiTabButton( this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack( Blocks.FURNACE ), GuiText.ProcessingPattern - .getLocal(), this.itemRender ); - this.buttonList.add( this.tabProcessButton ); + this.tabProcessButton = new GuiTabButton(this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack(Blocks.FURNACE), GuiText.ProcessingPattern + .getLocal(), this.itemRender); + this.buttonList.add(this.tabProcessButton); - this.substitutionsEnabledBtn = new GuiImgButton( this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.ENABLED ); - this.substitutionsEnabledBtn.setHalfSize( true ); - this.buttonList.add( this.substitutionsEnabledBtn ); + this.substitutionsEnabledBtn = new GuiImgButton(this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.ENABLED); + this.substitutionsEnabledBtn.setHalfSize(true); + this.buttonList.add(this.substitutionsEnabledBtn); - this.substitutionsDisabledBtn = new GuiImgButton( this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.DISABLED ); - this.substitutionsDisabledBtn.setHalfSize( true ); - this.buttonList.add( this.substitutionsDisabledBtn ); + this.substitutionsDisabledBtn = new GuiImgButton(this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.DISABLED); + this.substitutionsDisabledBtn.setHalfSize(true); + this.buttonList.add(this.substitutionsDisabledBtn); - this.clearBtn = new GuiImgButton( this.guiLeft + 74, this.guiTop + this.ySize - 163, Settings.ACTIONS, ActionItems.CLOSE ); - this.clearBtn.setHalfSize( true ); - this.buttonList.add( this.clearBtn ); + this.clearBtn = new GuiImgButton(this.guiLeft + 74, this.guiTop + this.ySize - 163, Settings.ACTIONS, ActionItems.CLOSE); + this.clearBtn.setHalfSize(true); + this.buttonList.add(this.clearBtn); - this.x3Btn = new GuiImgButton( this.guiLeft + 128, this.guiTop + this.ySize - 158, Settings.ACTIONS, ActionItems.MULTIPLY_BY_THREE ); - this.x3Btn.setHalfSize( true ); - this.buttonList.add( this.x3Btn ); + this.x3Btn = new GuiImgButton(this.guiLeft + 128, this.guiTop + this.ySize - 158, Settings.ACTIONS, ActionItems.MULTIPLY_BY_THREE); + this.x3Btn.setHalfSize(true); + this.buttonList.add(this.x3Btn); - this.x2Btn = new GuiImgButton( this.guiLeft + 128, this.guiTop + this.ySize - 148, Settings.ACTIONS, ActionItems.MULTIPLY_BY_TWO ); - this.x2Btn.setHalfSize( true ); - this.buttonList.add( this.x2Btn ); + this.x2Btn = new GuiImgButton(this.guiLeft + 128, this.guiTop + this.ySize - 148, Settings.ACTIONS, ActionItems.MULTIPLY_BY_TWO); + this.x2Btn.setHalfSize(true); + this.buttonList.add(this.x2Btn); - this.plusOneBtn = new GuiImgButton( this.guiLeft + 128, this.guiTop + this.ySize - 138, Settings.ACTIONS, ActionItems.INCREASE_BY_ONE ); - this.plusOneBtn.setHalfSize( true ); - this.buttonList.add( this.plusOneBtn ); + this.plusOneBtn = new GuiImgButton(this.guiLeft + 128, this.guiTop + this.ySize - 138, Settings.ACTIONS, ActionItems.INCREASE_BY_ONE); + this.plusOneBtn.setHalfSize(true); + this.buttonList.add(this.plusOneBtn); - this.divThreeBtn = new GuiImgButton( this.guiLeft + 100, this.guiTop + this.ySize - 158, Settings.ACTIONS, ActionItems.DIVIDE_BY_THREE ); - this.divThreeBtn.setHalfSize( true ); - this.buttonList.add( this.divThreeBtn ); + this.divThreeBtn = new GuiImgButton(this.guiLeft + 100, this.guiTop + this.ySize - 158, Settings.ACTIONS, ActionItems.DIVIDE_BY_THREE); + this.divThreeBtn.setHalfSize(true); + this.buttonList.add(this.divThreeBtn); - this.divTwoBtn = new GuiImgButton( this.guiLeft + 100, this.guiTop + this.ySize - 148, Settings.ACTIONS, ActionItems.DIVIDE_BY_TWO ); - this.divTwoBtn.setHalfSize( true ); - this.buttonList.add( this.divTwoBtn ); + this.divTwoBtn = new GuiImgButton(this.guiLeft + 100, this.guiTop + this.ySize - 148, Settings.ACTIONS, ActionItems.DIVIDE_BY_TWO); + this.divTwoBtn.setHalfSize(true); + this.buttonList.add(this.divTwoBtn); - this.minusOneBtn = new GuiImgButton( this.guiLeft + 100, this.guiTop + this.ySize - 138, Settings.ACTIONS, ActionItems.DECREASE_BY_ONE ); - this.minusOneBtn.setHalfSize( true ); - this.buttonList.add( this.minusOneBtn ); + this.minusOneBtn = new GuiImgButton(this.guiLeft + 100, this.guiTop + this.ySize - 138, Settings.ACTIONS, ActionItems.DECREASE_BY_ONE); + this.minusOneBtn.setHalfSize(true); + this.buttonList.add(this.minusOneBtn); - //this.maxCountBtn = new GuiImgButton( this.guiLeft + 128, this.guiTop + this.ySize - 108, Settings.ACTIONS, ActionItems.MAX_COUNT ); - //this.maxCountBtn.setHalfSize( true ); - //this.buttonList.add( this.maxCountBtn ); + //this.maxCountBtn = new GuiImgButton( this.guiLeft + 128, this.guiTop + this.ySize - 108, Settings.ACTIONS, ActionItems.MAX_COUNT ); + //this.maxCountBtn.setHalfSize( true ); + //this.buttonList.add( this.maxCountBtn ); - this.encodeBtn = new GuiImgButton( this.guiLeft + 147, this.guiTop + this.ySize - 142, Settings.ACTIONS, ActionItems.ENCODE ); - this.buttonList.add( this.encodeBtn ); - } + this.encodeBtn = new GuiImgButton(this.guiLeft + 147, this.guiTop + this.ySize - 142, Settings.ACTIONS, ActionItems.ENCODE); + this.buttonList.add(this.encodeBtn); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - if( this.container.isCraftingMode() ) - { - this.tabCraftButton.visible = true; - this.tabProcessButton.visible = false; - this.x2Btn.visible = false; - this.x3Btn.visible = false; - this.divTwoBtn.visible = false; - this.divThreeBtn.visible = false; - this.plusOneBtn.visible = false; - this.minusOneBtn.visible = false; - //this.maxCountBtn.visible = false; + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + if (this.container.isCraftingMode()) { + this.tabCraftButton.visible = true; + this.tabProcessButton.visible = false; + this.x2Btn.visible = false; + this.x3Btn.visible = false; + this.divTwoBtn.visible = false; + this.divThreeBtn.visible = false; + this.plusOneBtn.visible = false; + this.minusOneBtn.visible = false; + //this.maxCountBtn.visible = false; - if( this.container.substitute ) - { - this.substitutionsEnabledBtn.visible = true; - this.substitutionsDisabledBtn.visible = false; - } - else - { - this.substitutionsEnabledBtn.visible = false; - this.substitutionsDisabledBtn.visible = true; - } - } - else - { - this.tabCraftButton.visible = false; - this.tabProcessButton.visible = true; - this.substitutionsEnabledBtn.visible = false; - this.substitutionsDisabledBtn.visible = false; - this.x2Btn.visible = true; - this.x3Btn.visible = true; - this.divTwoBtn.visible = true; - this.divThreeBtn.visible = true; - this.plusOneBtn.visible = true; - this.minusOneBtn.visible = true; - //this.maxCountBtn.visible = true; - } + if (this.container.substitute) { + this.substitutionsEnabledBtn.visible = true; + this.substitutionsDisabledBtn.visible = false; + } else { + this.substitutionsEnabledBtn.visible = false; + this.substitutionsDisabledBtn.visible = true; + } + } else { + this.tabCraftButton.visible = false; + this.tabProcessButton.visible = true; + this.substitutionsEnabledBtn.visible = false; + this.substitutionsDisabledBtn.visible = false; + this.x2Btn.visible = true; + this.x3Btn.visible = true; + this.divTwoBtn.visible = true; + this.divThreeBtn.visible = true; + this.plusOneBtn.visible = true; + this.minusOneBtn.visible = true; + //this.maxCountBtn.visible = true; + } - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.fontRenderer.drawString( GuiText.PatternTerminal.getLocal(), 8, this.ySize - 96 + 2 - this.getReservedSpace(), 4210752 ); - } + super.drawFG(offsetX, offsetY, mouseX, mouseY); + this.fontRenderer.drawString(GuiText.PatternTerminal.getLocal(), 8, this.ySize - 96 + 2 - this.getReservedSpace(), 4210752); + } - @Override - protected String getBackground() - { - if( this.container.isCraftingMode() ) - { - return BACKGROUND_CRAFTING_MODE; - } + @Override + protected String getBackground() { + if (this.container.isCraftingMode()) { + return BACKGROUND_CRAFTING_MODE; + } - return BACKGROUND_PROCESSING_MODE; - } + return BACKGROUND_PROCESSING_MODE; + } - @Override - protected void repositionSlot( final AppEngSlot s ) - { - final int offsetPlayerSide = s.isPlayerSide() ? 5 : 3; + @Override + protected void repositionSlot(final AppEngSlot s) { + final int offsetPlayerSide = s.isPlayerSide() ? 5 : 3; - s.yPos = s.getY() + this.ySize - 78 - offsetPlayerSide; - } + s.yPos = s.getY() + this.ySize - 78 - offsetPlayerSide; + } - @Override - public List> getPhantomTargets(Object ingredient) { - if (!(ingredient instanceof ItemStack )) { - return Collections.emptyList(); - } - List> targets = new ArrayList<>(); - for( Slot slot : this.inventorySlots.inventorySlots ) - { - if( slot instanceof SlotFake ) - { - ItemStack itemStack = (ItemStack) ingredient; - Target target = new Target() - { - @Override - public Rectangle getArea() - { - return new Rectangle( getGuiLeft() + slot.xPos, getGuiTop() + slot.yPos, 16, 16 ); - } + @Override + public List> getPhantomTargets(Object ingredient) { + if (!(ingredient instanceof ItemStack)) { + return Collections.emptyList(); + } + List> targets = new ArrayList<>(); + for (Slot slot : this.inventorySlots.inventorySlots) { + if (slot instanceof SlotFake) { + ItemStack itemStack = (ItemStack) ingredient; + Target target = new Target() { + @Override + public Rectangle getArea() { + return new Rectangle(getGuiLeft() + slot.xPos, getGuiTop() + slot.yPos, 16, 16); + } - @Override - public void accept( Object ingredient ) - { - final PacketInventoryAction p; - try - { - p = new PacketInventoryAction( InventoryAction.PLACE_JEI_GHOST_ITEM, (SlotFake) slot, AEItemStack.fromItemStack( itemStack ) ); - NetworkHandler.instance().sendToServer( p ); + @Override + public void accept(Object ingredient) { + final PacketInventoryAction p; + try { + p = new PacketInventoryAction(InventoryAction.PLACE_JEI_GHOST_ITEM, (SlotFake) slot, AEItemStack.fromItemStack(itemStack)); + NetworkHandler.instance().sendToServer(p); - } - catch( IOException e ) - { - e.printStackTrace(); - } - } - }; - targets.add( target ); - mapTargetSlot.putIfAbsent( target, slot ); - } - } - return targets; - } + } catch (IOException e) { + e.printStackTrace(); + } + } + }; + targets.add(target); + mapTargetSlot.putIfAbsent(target, slot); + } + } + return targets; + } - @Override - public Map, Object> getFakeSlotTargetMap() - { - return mapTargetSlot; - } + @Override + public Map, Object> getFakeSlotTargetMap() { + return mapTargetSlot; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiPriority.java b/src/main/java/appeng/client/gui/implementations/GuiPriority.java index 801069240..1d62b0031 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiPriority.java +++ b/src/main/java/appeng/client/gui/implementations/GuiPriority.java @@ -19,12 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiNumberBox; import appeng.client.gui.widgets.GuiTabButton; @@ -37,188 +31,163 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketSwitchGuis; import appeng.core.sync.packets.PacketValueConfig; import appeng.helpers.IPriorityHost; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; + +import java.io.IOException; -public class GuiPriority extends AEBaseGui -{ +public class GuiPriority extends AEBaseGui { - private GuiNumberBox priority; - private GuiTabButton originalGuiBtn; + private GuiNumberBox priority; + private GuiTabButton originalGuiBtn; - private GuiButton plus1; - private GuiButton plus10; - private GuiButton plus100; - private GuiButton plus1000; - private GuiButton minus1; - private GuiButton minus10; - private GuiButton minus100; - private GuiButton minus1000; + private GuiButton plus1; + private GuiButton plus10; + private GuiButton plus100; + private GuiButton plus1000; + private GuiButton minus1; + private GuiButton minus10; + private GuiButton minus100; + private GuiButton minus1000; - private GuiBridge OriginalGui; + private GuiBridge OriginalGui; - public GuiPriority( final InventoryPlayer inventoryPlayer, final IPriorityHost te ) - { - super( new ContainerPriority( inventoryPlayer, te ) ); - } + public GuiPriority(final InventoryPlayer inventoryPlayer, final IPriorityHost te) { + super(new ContainerPriority(inventoryPlayer, te)); + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - final int a = AEConfig.instance().priorityByStacksAmounts( 0 ); - final int b = AEConfig.instance().priorityByStacksAmounts( 1 ); - final int c = AEConfig.instance().priorityByStacksAmounts( 2 ); - final int d = AEConfig.instance().priorityByStacksAmounts( 3 ); + final int a = AEConfig.instance().priorityByStacksAmounts(0); + final int b = AEConfig.instance().priorityByStacksAmounts(1); + final int c = AEConfig.instance().priorityByStacksAmounts(2); + final int d = AEConfig.instance().priorityByStacksAmounts(3); - this.buttonList.add( this.plus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 32, 22, 20, "+" + a ) ); - this.buttonList.add( this.plus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 32, 28, 20, "+" + b ) ); - this.buttonList.add( this.plus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 32, 32, 20, "+" + c ) ); - this.buttonList.add( this.plus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 32, 38, 20, "+" + d ) ); + this.buttonList.add(this.plus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 32, 22, 20, "+" + a)); + this.buttonList.add(this.plus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 32, 28, 20, "+" + b)); + this.buttonList.add(this.plus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 32, 32, 20, "+" + c)); + this.buttonList.add(this.plus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 32, 38, 20, "+" + d)); - this.buttonList.add( this.minus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 69, 22, 20, "-" + a ) ); - this.buttonList.add( this.minus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 69, 28, 20, "-" + b ) ); - this.buttonList.add( this.minus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 69, 32, 20, "-" + c ) ); - this.buttonList.add( this.minus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 69, 38, 20, "-" + d ) ); + this.buttonList.add(this.minus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 69, 22, 20, "-" + a)); + this.buttonList.add(this.minus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 69, 28, 20, "-" + b)); + this.buttonList.add(this.minus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 69, 32, 20, "-" + c)); + this.buttonList.add(this.minus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 69, 38, 20, "-" + d)); - final ContainerPriority con = ( (ContainerPriority) this.inventorySlots ); - final ItemStack myIcon = con.getPriorityHost().getItemStackRepresentation(); - this.OriginalGui = con.getPriorityHost().getGuiBridge(); + final ContainerPriority con = ((ContainerPriority) this.inventorySlots); + final ItemStack myIcon = con.getPriorityHost().getItemStackRepresentation(); + this.OriginalGui = con.getPriorityHost().getGuiBridge(); - if( this.OriginalGui != null && !myIcon.isEmpty() ) - { - this.buttonList.add( this.originalGuiBtn = new GuiTabButton( this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), this.itemRender ) ); - } + if (this.OriginalGui != null && !myIcon.isEmpty()) { + this.buttonList.add(this.originalGuiBtn = new GuiTabButton(this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), this.itemRender)); + } - this.priority = new GuiNumberBox( this.fontRenderer, this.guiLeft + 62, this.guiTop + 57, 59, this.fontRenderer.FONT_HEIGHT, Long.class ); - this.priority.setEnableBackgroundDrawing( false ); - this.priority.setMaxStringLength( 16 ); - this.priority.setTextColor( 0xFFFFFF ); - this.priority.setVisible( true ); - this.priority.setFocused( true ); - ( (ContainerPriority) this.inventorySlots ).setTextField( this.priority ); - } + this.priority = new GuiNumberBox(this.fontRenderer, this.guiLeft + 62, this.guiTop + 57, 59, this.fontRenderer.FONT_HEIGHT, Long.class); + this.priority.setEnableBackgroundDrawing(false); + this.priority.setMaxStringLength(16); + this.priority.setTextColor(0xFFFFFF); + this.priority.setVisible(true); + this.priority.setFocused(true); + ((ContainerPriority) this.inventorySlots).setTextField(this.priority); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( GuiText.Priority.getLocal(), 8, 6, 4210752 ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(GuiText.Priority.getLocal(), 8, 6, 4210752); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/priority.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/priority.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); - this.priority.drawTextBox(); - } + this.priority.drawTextBox(); + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - if( btn == this.originalGuiBtn ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( this.OriginalGui ) ); - } + if (btn == this.originalGuiBtn) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(this.OriginalGui)); + } - final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; - final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; + final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; - if( isPlus || isMinus ) - { - this.addQty( this.getQty( btn ) ); - } - } + if (isPlus || isMinus) { + this.addQty(this.getQty(btn)); + } + } - private void addQty( final int i ) - { - try - { - String out = this.priority.getText(); + private void addQty(final int i) { + try { + String out = this.priority.getText(); - boolean fixed = false; - while( out.startsWith( "0" ) && out.length() > 1 ) - { - out = out.substring( 1 ); - fixed = true; - } + boolean fixed = false; + while (out.startsWith("0") && out.length() > 1) { + out = out.substring(1); + fixed = true; + } - if( fixed ) - { - this.priority.setText( out ); - } + if (fixed) { + this.priority.setText(out); + } - if( out.isEmpty() ) - { - out = "0"; - } + if (out.isEmpty()) { + out = "0"; + } - long result = Long.parseLong( out ); - result += i; + long result = Long.parseLong(out); + result += i; - this.priority.setText( out = Long.toString( result ) ); + this.priority.setText(out = Long.toString(result)); - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PriorityHost.Priority", out ) ); - } - catch( final NumberFormatException e ) - { - // nope.. - this.priority.setText( "0" ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + NetworkHandler.instance().sendToServer(new PacketValueConfig("PriorityHost.Priority", out)); + } catch (final NumberFormatException e) { + // nope.. + this.priority.setText("0"); + } catch (final IOException e) { + AELog.debug(e); + } + } - @Override - protected void keyTyped( final char character, final int key ) throws IOException - { - if( !this.checkHotbarKeys( key ) ) - { - if( ( key == 211 || key == 205 || key == 203 || key == 14 || character == '-' || Character.isDigit( character ) ) && this.priority - .textboxKeyTyped( character, key ) ) - { - try - { - String out = this.priority.getText(); + @Override + protected void keyTyped(final char character, final int key) throws IOException { + if (!this.checkHotbarKeys(key)) { + if ((key == 211 || key == 205 || key == 203 || key == 14 || character == '-' || Character.isDigit(character)) && this.priority + .textboxKeyTyped(character, key)) { + try { + String out = this.priority.getText(); - boolean fixed = false; - while( out.startsWith( "0" ) && out.length() > 1 ) - { - out = out.substring( 1 ); - fixed = true; - } + boolean fixed = false; + while (out.startsWith("0") && out.length() > 1) { + out = out.substring(1); + fixed = true; + } - if( fixed ) - { - this.priority.setText( out ); - } + if (fixed) { + this.priority.setText(out); + } - if( out.isEmpty() ) - { - out = "0"; - } + if (out.isEmpty()) { + out = "0"; + } - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PriorityHost.Priority", out ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - else - { - super.keyTyped( character, key ); - } - } - } + NetworkHandler.instance().sendToServer(new PacketValueConfig("PriorityHost.Priority", out)); + } catch (final IOException e) { + AELog.debug(e); + } + } else { + super.keyTyped(character, key); + } + } + } - protected String getBackground() - { - return "guis/priority.png"; - } + protected String getBackground() { + return "guis/priority.png"; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiQNB.java b/src/main/java/appeng/client/gui/implementations/GuiQNB.java index d029c16a7..fe2fdb40a 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiQNB.java +++ b/src/main/java/appeng/client/gui/implementations/GuiQNB.java @@ -19,34 +19,29 @@ package appeng.client.gui.implementations; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.client.gui.AEBaseGui; import appeng.container.implementations.ContainerQNB; import appeng.core.localization.GuiText; import appeng.tile.qnb.TileQuantumBridge; +import net.minecraft.entity.player.InventoryPlayer; -public class GuiQNB extends AEBaseGui -{ +public class GuiQNB extends AEBaseGui { - public GuiQNB( final InventoryPlayer inventoryPlayer, final TileQuantumBridge te ) - { - super( new ContainerQNB( inventoryPlayer, te ) ); - this.ySize = 166; - } + public GuiQNB(final InventoryPlayer inventoryPlayer, final TileQuantumBridge te) { + super(new ContainerQNB(inventoryPlayer, te)); + this.ySize = 166; + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.QuantumLinkChamber.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.QuantumLinkChamber.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/chest.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/chest.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiQuartzKnife.java b/src/main/java/appeng/client/gui/implementations/GuiQuartzKnife.java index 6a0324c95..33dc4982c 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiQuartzKnife.java +++ b/src/main/java/appeng/client/gui/implementations/GuiQuartzKnife.java @@ -19,78 +19,65 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import appeng.items.contents.QuartzKnifeObj; -import net.minecraft.client.gui.GuiTextField; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.client.gui.AEBaseGui; import appeng.container.implementations.ContainerQuartzKnife; import appeng.core.AELog; import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; +import appeng.items.contents.QuartzKnifeObj; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.entity.player.InventoryPlayer; + +import java.io.IOException; -public class GuiQuartzKnife extends AEBaseGui -{ +public class GuiQuartzKnife extends AEBaseGui { - private GuiTextField name; + private GuiTextField name; - public GuiQuartzKnife( final InventoryPlayer inventoryPlayer, final QuartzKnifeObj te ) - { - super( new ContainerQuartzKnife( inventoryPlayer, te ) ); - this.ySize = 184; - } + public GuiQuartzKnife(final InventoryPlayer inventoryPlayer, final QuartzKnifeObj te) { + super(new ContainerQuartzKnife(inventoryPlayer, te)); + this.ySize = 184; + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.name = new GuiTextField( 0, this.fontRenderer, this.guiLeft + 24, this.guiTop + 32, 79, this.fontRenderer.FONT_HEIGHT ); - this.name.setEnableBackgroundDrawing( false ); - this.name.setMaxStringLength( 32 ); - this.name.setTextColor( 0xFFFFFF ); - this.name.setVisible( true ); - this.name.setFocused( true ); - } + this.name = new GuiTextField(0, this.fontRenderer, this.guiLeft + 24, this.guiTop + 32, 79, this.fontRenderer.FONT_HEIGHT); + this.name.setEnableBackgroundDrawing(false); + this.name.setMaxStringLength(32); + this.name.setTextColor(0xFFFFFF); + this.name.setVisible(true); + this.name.setFocused(true); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.QuartzCuttingKnife.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.QuartzCuttingKnife.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/quartzknife.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - this.name.drawTextBox(); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/quartzknife.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + this.name.drawTextBox(); + } - @Override - protected void keyTyped( final char character, final int key ) throws IOException - { - if( this.name.textboxKeyTyped( character, key ) ) - { - try - { - final String Out = this.name.getText(); - ( (ContainerQuartzKnife) this.inventorySlots ).setName( Out ); - NetworkHandler.instance().sendToServer( new PacketValueConfig( "QuartzKnife.Name", Out ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - else - { - super.keyTyped( character, key ); - } - } + @Override + protected void keyTyped(final char character, final int key) throws IOException { + if (this.name.textboxKeyTyped(character, key)) { + try { + final String Out = this.name.getText(); + ((ContainerQuartzKnife) this.inventorySlots).setName(Out); + NetworkHandler.instance().sendToServer(new PacketValueConfig("QuartzKnife.Name", Out)); + } catch (final IOException e) { + AELog.debug(e); + } + } else { + super.keyTyped(character, key); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiRenamer.java b/src/main/java/appeng/client/gui/implementations/GuiRenamer.java index b9efc1adb..f4dcff1eb 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiRenamer.java +++ b/src/main/java/appeng/client/gui/implementations/GuiRenamer.java @@ -14,101 +14,81 @@ import org.lwjgl.input.Keyboard; import java.io.IOException; -public class GuiRenamer extends AEBaseGui -{ - private MEGuiTextField textField; - private GuiButton confirmButton; +public class GuiRenamer extends AEBaseGui { + private MEGuiTextField textField; + private GuiButton confirmButton; - public GuiRenamer( InventoryPlayer ip, ICustomNameObject obj ) - { - super( new ContainerRenamer( ip, obj ) ); - this.xSize = 256; - } + public GuiRenamer(InventoryPlayer ip, ICustomNameObject obj) { + super(new ContainerRenamer(ip, obj)); + this.xSize = 256; + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.textField = new MEGuiTextField( this.fontRenderer, this.guiLeft + 9, this.guiTop + 33, 229, 12 ); + this.textField = new MEGuiTextField(this.fontRenderer, this.guiLeft + 9, this.guiTop + 33, 229, 12); - this.textField.setEnableBackgroundDrawing( false ); - this.textField.setMaxStringLength( 32 ); + this.textField.setEnableBackgroundDrawing(false); + this.textField.setMaxStringLength(32); - this.textField.setFocused( true ); + this.textField.setFocused(true); - this.buttonList.add( this.confirmButton = new GuiButton( 0, this.guiLeft + 238, this.guiTop + 33, 12, 12, "↵" ) ); + this.buttonList.add(this.confirmButton = new GuiButton(0, this.guiLeft + 238, this.guiTop + 33, 12, 12, "↵")); - ( (ContainerRenamer) this.inventorySlots ).setTextField( this.textField ); - } + ((ContainerRenamer) this.inventorySlots).setTextField(this.textField); + } - @Override - public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.Renamer.getLocal() ), 12, 8, 4210752 ); - } + @Override + public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.Renamer.getLocal()), 12, 8, 4210752); + } - @Override - public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - this.bindTexture( "guis/renamer.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - this.textField.drawTextBox(); - } + @Override + public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) { + this.bindTexture("guis/renamer.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + this.textField.drawTextBox(); + } - @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) throws IOException - { - if( this.textField.isMouseIn( xCoord, yCoord ) ) - { - if( btn == 1 ) - { - this.textField.setText( "" ); - } - this.textField.mouseClicked( xCoord, yCoord, btn ); - } - super.mouseClicked( xCoord, yCoord, btn ); - } + @Override + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) throws IOException { + if (this.textField.isMouseIn(xCoord, yCoord)) { + if (btn == 1) { + this.textField.setText(""); + } + this.textField.mouseClicked(xCoord, yCoord, btn); + } + super.mouseClicked(xCoord, yCoord, btn); + } - @Override - protected void keyTyped( final char character, final int key ) throws IOException - { - if( key == Keyboard.KEY_RETURN || key == Keyboard.KEY_NUMPADENTER ) - { // Enter - try - { - NetworkHandler.instance().sendToServer( - new PacketValueConfig( "QuartzKnife.ReName", this.textField.getText() ) ); - } - catch( IOException e ) - { - AELog.debug( e ); - } - this.mc.player.closeScreen(); - } - else if( !this.textField.textboxKeyTyped( character, key ) ) - { - super.keyTyped( character, key ); - } - } + @Override + protected void keyTyped(final char character, final int key) throws IOException { + if (key == Keyboard.KEY_RETURN || key == Keyboard.KEY_NUMPADENTER) { // Enter + try { + NetworkHandler.instance().sendToServer( + new PacketValueConfig("QuartzKnife.ReName", this.textField.getText())); + } catch (IOException e) { + AELog.debug(e); + } + this.mc.player.closeScreen(); + } else if (!this.textField.textboxKeyTyped(character, key)) { + super.keyTyped(character, key); + } + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - if( btn == this.confirmButton ) - { - try - { - NetworkHandler.instance().sendToServer( - new PacketValueConfig( "QuartzKnife.ReName", this.textField.getText() ) ); - this.mc.player.closeScreen(); - } - catch( IOException e ) - { - AELog.debug( e ); - } - } - } + if (btn == this.confirmButton) { + try { + NetworkHandler.instance().sendToServer( + new PacketValueConfig("QuartzKnife.ReName", this.textField.getText())); + this.mc.player.closeScreen(); + } catch (IOException e) { + AELog.debug(e); + } + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiSecurityStation.java b/src/main/java/appeng/client/gui/implementations/GuiSecurityStation.java index b2b2904a4..f8f607d04 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiSecurityStation.java +++ b/src/main/java/appeng/client/gui/implementations/GuiSecurityStation.java @@ -19,10 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.config.SecurityPermissions; import appeng.api.config.SortOrder; import appeng.api.storage.ITerminalHost; @@ -32,115 +28,102 @@ import appeng.core.AELog; import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; +import net.minecraft.entity.player.InventoryPlayer; + +import java.io.IOException; -public class GuiSecurityStation extends GuiMEMonitorable -{ +public class GuiSecurityStation extends GuiMEMonitorable { - private GuiToggleButton inject; - private GuiToggleButton extract; - private GuiToggleButton craft; - private GuiToggleButton build; - private GuiToggleButton security; + private GuiToggleButton inject; + private GuiToggleButton extract; + private GuiToggleButton craft; + private GuiToggleButton build; + private GuiToggleButton security; - public GuiSecurityStation( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( inventoryPlayer, te, new ContainerSecurityStation( inventoryPlayer, te ) ); - this.setCustomSortOrder( false ); - this.setReservedSpace( 33 ); + public GuiSecurityStation(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(inventoryPlayer, te, new ContainerSecurityStation(inventoryPlayer, te)); + this.setCustomSortOrder(false); + this.setReservedSpace(33); - // increase size so that the slot is over the gui. - this.xSize += 56; - this.setStandardSize( this.xSize ); - } + // increase size so that the slot is over the gui. + this.xSize += 56; + this.setStandardSize(this.xSize); + } - @Override - protected void actionPerformed( final net.minecraft.client.gui.GuiButton btn ) - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final net.minecraft.client.gui.GuiButton btn) { + super.actionPerformed(btn); - SecurityPermissions toggleSetting = null; + SecurityPermissions toggleSetting = null; - if( btn == this.inject ) - { - toggleSetting = SecurityPermissions.INJECT; - } - if( btn == this.extract ) - { - toggleSetting = SecurityPermissions.EXTRACT; - } - if( btn == this.craft ) - { - toggleSetting = SecurityPermissions.CRAFT; - } - if( btn == this.build ) - { - toggleSetting = SecurityPermissions.BUILD; - } - if( btn == this.security ) - { - toggleSetting = SecurityPermissions.SECURITY; - } + if (btn == this.inject) { + toggleSetting = SecurityPermissions.INJECT; + } + if (btn == this.extract) { + toggleSetting = SecurityPermissions.EXTRACT; + } + if (btn == this.craft) { + toggleSetting = SecurityPermissions.CRAFT; + } + if (btn == this.build) { + toggleSetting = SecurityPermissions.BUILD; + } + if (btn == this.security) { + toggleSetting = SecurityPermissions.SECURITY; + } - if( toggleSetting != null ) - { - try - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "TileSecurityStation.ToggleOption", toggleSetting.name() ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } + if (toggleSetting != null) { + try { + NetworkHandler.instance().sendToServer(new PacketValueConfig("TileSecurityStation.ToggleOption", toggleSetting.name())); + } catch (final IOException e) { + AELog.debug(e); + } + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - final int top = this.guiTop + this.ySize - 116; - this.buttonList.add( this.inject = new GuiToggleButton( this.guiLeft + 56, top, 11 * 16, 12 * 16, SecurityPermissions.INJECT - .getUnlocalizedName(), SecurityPermissions.INJECT.getUnlocalizedTip() ) ); + final int top = this.guiTop + this.ySize - 116; + this.buttonList.add(this.inject = new GuiToggleButton(this.guiLeft + 56, top, 11 * 16, 12 * 16, SecurityPermissions.INJECT + .getUnlocalizedName(), SecurityPermissions.INJECT.getUnlocalizedTip())); - this.buttonList.add( this.extract = new GuiToggleButton( this.guiLeft + 56 + 18, top, 11 * 16 + 1, 12 * 16 + 1, SecurityPermissions.EXTRACT - .getUnlocalizedName(), SecurityPermissions.EXTRACT.getUnlocalizedTip() ) ); + this.buttonList.add(this.extract = new GuiToggleButton(this.guiLeft + 56 + 18, top, 11 * 16 + 1, 12 * 16 + 1, SecurityPermissions.EXTRACT + .getUnlocalizedName(), SecurityPermissions.EXTRACT.getUnlocalizedTip())); - this.buttonList.add( this.craft = new GuiToggleButton( this.guiLeft + 56 + 18 * 2, top, 11 * 16 + 2, 12 * 16 + 2, SecurityPermissions.CRAFT - .getUnlocalizedName(), SecurityPermissions.CRAFT.getUnlocalizedTip() ) ); + this.buttonList.add(this.craft = new GuiToggleButton(this.guiLeft + 56 + 18 * 2, top, 11 * 16 + 2, 12 * 16 + 2, SecurityPermissions.CRAFT + .getUnlocalizedName(), SecurityPermissions.CRAFT.getUnlocalizedTip())); - this.buttonList.add( this.build = new GuiToggleButton( this.guiLeft + 56 + 18 * 3, top, 11 * 16 + 3, 12 * 16 + 3, SecurityPermissions.BUILD - .getUnlocalizedName(), SecurityPermissions.BUILD.getUnlocalizedTip() ) ); + this.buttonList.add(this.build = new GuiToggleButton(this.guiLeft + 56 + 18 * 3, top, 11 * 16 + 3, 12 * 16 + 3, SecurityPermissions.BUILD + .getUnlocalizedName(), SecurityPermissions.BUILD.getUnlocalizedTip())); - this.buttonList.add( this.security = new GuiToggleButton( this.guiLeft + 56 + 18 * 4, top, 11 * 16 + 4, 12 * 16 + 4, SecurityPermissions.SECURITY - .getUnlocalizedName(), SecurityPermissions.SECURITY.getUnlocalizedTip() ) ); - } + this.buttonList.add(this.security = new GuiToggleButton(this.guiLeft + 56 + 18 * 4, top, 11 * 16 + 4, 12 * 16 + 4, SecurityPermissions.SECURITY + .getUnlocalizedName(), SecurityPermissions.SECURITY.getUnlocalizedTip())); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.fontRenderer.drawString( GuiText.SecurityCardEditor.getLocal(), 8, this.ySize - 96 + 1 - this.getReservedSpace(), 4210752 ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawFG(offsetX, offsetY, mouseX, mouseY); + this.fontRenderer.drawString(GuiText.SecurityCardEditor.getLocal(), 8, this.ySize - 96 + 1 - this.getReservedSpace(), 4210752); + } - @Override - protected String getBackground() - { - final ContainerSecurityStation cs = (ContainerSecurityStation) this.inventorySlots; + @Override + protected String getBackground() { + final ContainerSecurityStation cs = (ContainerSecurityStation) this.inventorySlots; - this.inject.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.INJECT.ordinal() ) ) > 0 ); - this.extract.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.EXTRACT.ordinal() ) ) > 0 ); - this.craft.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.CRAFT.ordinal() ) ) > 0 ); - this.build.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.BUILD.ordinal() ) ) > 0 ); - this.security.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.SECURITY.ordinal() ) ) > 0 ); + this.inject.setState((cs.getPermissionMode() & (1 << SecurityPermissions.INJECT.ordinal())) > 0); + this.extract.setState((cs.getPermissionMode() & (1 << SecurityPermissions.EXTRACT.ordinal())) > 0); + this.craft.setState((cs.getPermissionMode() & (1 << SecurityPermissions.CRAFT.ordinal())) > 0); + this.build.setState((cs.getPermissionMode() & (1 << SecurityPermissions.BUILD.ordinal())) > 0); + this.security.setState((cs.getPermissionMode() & (1 << SecurityPermissions.SECURITY.ordinal())) > 0); - return "guis/security_station.png"; - } + return "guis/security_station.png"; + } - @Override - public Enum getSortBy() - { - return SortOrder.NAME; - } + @Override + public Enum getSortBy() { + return SortOrder.NAME; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java b/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java index 9ef1dccd7..18ac25b8a 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java +++ b/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java @@ -19,41 +19,35 @@ package appeng.client.gui.implementations; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.client.gui.AEBaseGui; import appeng.container.implementations.ContainerSkyChest; import appeng.core.localization.GuiText; import appeng.integration.Integrations; import appeng.tile.storage.TileSkyChest; +import net.minecraft.entity.player.InventoryPlayer; -public class GuiSkyChest extends AEBaseGui -{ +public class GuiSkyChest extends AEBaseGui { - public GuiSkyChest( final InventoryPlayer inventoryPlayer, final TileSkyChest te ) - { - super( new ContainerSkyChest( inventoryPlayer, te ) ); - this.ySize = 195; - } + public GuiSkyChest(final InventoryPlayer inventoryPlayer, final TileSkyChest te) { + super(new ContainerSkyChest(inventoryPlayer, te)); + this.ySize = 195; + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.SkyChest.getLocal() ), 8, 8, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 2, 4210752 ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.SkyChest.getLocal()), 8, 8, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 2, 4210752); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/skychest.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/skychest.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } - @Override - protected boolean enableSpaceClicking() - { - return !Integrations.invTweaks().isEnabled(); - } + @Override + protected boolean enableSpaceClicking() { + return !Integrations.invTweaks().isEnabled(); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java b/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java index 7aadaae46..fbf2f5ce6 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java +++ b/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java @@ -19,13 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.config.Settings; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiImgButton; @@ -34,73 +27,68 @@ import appeng.core.AEConfig; import appeng.core.localization.GuiText; import appeng.tile.spatial.TileSpatialIOPort; import appeng.util.Platform; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import org.lwjgl.input.Mouse; + +import java.io.IOException; -public class GuiSpatialIOPort extends AEBaseGui -{ +public class GuiSpatialIOPort extends AEBaseGui { - private final ContainerSpatialIOPort container; - private GuiImgButton units; + private final ContainerSpatialIOPort container; + private GuiImgButton units; - public GuiSpatialIOPort( final InventoryPlayer inventoryPlayer, final TileSpatialIOPort te ) - { - super( new ContainerSpatialIOPort( inventoryPlayer, te ) ); - this.ySize = 199; - this.container = (ContainerSpatialIOPort) this.inventorySlots; - } + public GuiSpatialIOPort(final InventoryPlayer inventoryPlayer, final TileSpatialIOPort te) { + super(new ContainerSpatialIOPort(inventoryPlayer, te)); + this.ySize = 199; + this.container = (ContainerSpatialIOPort) this.inventorySlots; + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - if( btn == this.units ) - { - AEConfig.instance().nextPowerUnit( backwards ); - this.units.set( AEConfig.instance().selectedPowerUnit() ); - } - } + if (btn == this.units) { + AEConfig.instance().nextPowerUnit(backwards); + this.units.set(AEConfig.instance().selectedPowerUnit()); + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.units = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance().selectedPowerUnit() ); - this.buttonList.add( this.units ); - } + this.units = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance().selectedPowerUnit()); + this.buttonList.add(this.units); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( GuiText.StoredPower.getLocal() + ": " + Platform.formatPowerLong( this.container.getCurrentPower(), false ), 13, 21, - 4210752 ); - this.fontRenderer.drawString( GuiText.MaxPower.getLocal() + ": " + Platform.formatPowerLong( this.container.getMaxPower(), false ), 13, 31, 4210752 ); - this.fontRenderer.drawString( GuiText.RequiredPower.getLocal() + ": " + Platform.formatPowerLong( this.container.getRequiredPower(), false ), 13, 73, - 4210752 ); - this.fontRenderer.drawString( GuiText.Efficiency.getLocal() + ": " + ( ( (float) this.container.getEfficency() ) / 100 ) + '%', 13, 83, 4210752 ); + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(GuiText.StoredPower.getLocal() + ": " + Platform.formatPowerLong(this.container.getCurrentPower(), false), 13, 21, + 4210752); + this.fontRenderer.drawString(GuiText.MaxPower.getLocal() + ": " + Platform.formatPowerLong(this.container.getMaxPower(), false), 13, 31, 4210752); + this.fontRenderer.drawString(GuiText.RequiredPower.getLocal() + ": " + Platform.formatPowerLong(this.container.getRequiredPower(), false), 13, 73, + 4210752); + this.fontRenderer.drawString(GuiText.Efficiency.getLocal() + ": " + (((float) this.container.getEfficency()) / 100) + '%', 13, 83, 4210752); - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.SpatialIOPort.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96, 4210752 ); + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.SpatialIOPort.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96, 4210752); - if( this.container.xSize != 0 && this.container.ySize != 0 && this.container.zSize != 0 ) - { - final String text = GuiText.SCSSize.getLocal() + ": " + this.container.xSize + "x" + this.container.ySize + "x" + this.container.zSize; - this.fontRenderer.drawString( text, 13, 93, 4210752 ); - } - else - { - this.fontRenderer.drawString( GuiText.SCSSize.getLocal() + ": " + GuiText.SCSInvalid.getLocal(), 13, 93, 4210752 ); - } + if (this.container.xSize != 0 && this.container.ySize != 0 && this.container.zSize != 0) { + final String text = GuiText.SCSSize.getLocal() + ": " + this.container.xSize + "x" + this.container.ySize + "x" + this.container.zSize; + this.fontRenderer.drawString(text, 13, 93, 4210752); + } else { + this.fontRenderer.drawString(GuiText.SCSSize.getLocal() + ": " + GuiText.SCSInvalid.getLocal(), 13, 93, 4210752); + } - } + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/spatialio.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/spatialio.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiStorageBus.java b/src/main/java/appeng/client/gui/implementations/GuiStorageBus.java index 1b64e5c44..02b5516cb 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiStorageBus.java +++ b/src/main/java/appeng/client/gui/implementations/GuiStorageBus.java @@ -19,18 +19,7 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - -import appeng.api.config.AccessRestriction; -import appeng.api.config.ActionItems; -import appeng.api.config.FuzzyMode; -import appeng.api.config.Settings; -import appeng.api.config.StorageFilter; +import appeng.api.config.*; import appeng.client.gui.widgets.GuiImgButton; import appeng.client.gui.widgets.GuiTabButton; import appeng.container.implementations.ContainerStorageBus; @@ -42,102 +31,86 @@ import appeng.core.sync.packets.PacketConfigButton; import appeng.core.sync.packets.PacketSwitchGuis; import appeng.core.sync.packets.PacketValueConfig; import appeng.parts.misc.PartStorageBus; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import org.lwjgl.input.Mouse; + +import java.io.IOException; -public class GuiStorageBus extends GuiUpgradeable -{ +public class GuiStorageBus extends GuiUpgradeable { - private GuiImgButton rwMode; - private GuiImgButton storageFilter; - private GuiTabButton priority; - private GuiImgButton partition; - private GuiImgButton clear; + private GuiImgButton rwMode; + private GuiImgButton storageFilter; + private GuiTabButton priority; + private GuiImgButton partition; + private GuiImgButton clear; - public GuiStorageBus( final InventoryPlayer inventoryPlayer, final PartStorageBus te ) - { - super( new ContainerStorageBus( inventoryPlayer, te ) ); - this.ySize = 251; - } + public GuiStorageBus(final InventoryPlayer inventoryPlayer, final PartStorageBus te) { + super(new ContainerStorageBus(inventoryPlayer, te)); + this.ySize = 251; + } - @Override - protected void addButtons() - { - this.clear = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE ); - this.partition = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH ); - this.rwMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.ACCESS, AccessRestriction.READ_WRITE ); - this.storageFilter = new GuiImgButton( this.guiLeft - 18, this.guiTop + 68, Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 88, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); + @Override + protected void addButtons() { + this.clear = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE); + this.partition = new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH); + this.rwMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 48, Settings.ACCESS, AccessRestriction.READ_WRITE); + this.storageFilter = new GuiImgButton(this.guiLeft - 18, this.guiTop + 68, Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY); + this.fuzzyMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 88, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender ) ); + this.buttonList.add(this.priority = new GuiTabButton(this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender)); - this.buttonList.add( this.storageFilter ); - this.buttonList.add( this.fuzzyMode ); - this.buttonList.add( this.rwMode ); - this.buttonList.add( this.partition ); - this.buttonList.add( this.clear ); - } + this.buttonList.add(this.storageFilter); + this.buttonList.add(this.fuzzyMode); + this.buttonList.add(this.rwMode); + this.buttonList.add(this.partition); + this.buttonList.add(this.clear); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.StorageBus.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.StorageBus.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); - if( this.fuzzyMode != null ) - { - this.fuzzyMode.set( this.cvb.getFuzzyMode() ); - } + if (this.fuzzyMode != null) { + this.fuzzyMode.set(this.cvb.getFuzzyMode()); + } - if( this.storageFilter != null ) - { - this.storageFilter.set( ( (ContainerStorageBus) this.cvb ).getStorageFilter() ); - } + if (this.storageFilter != null) { + this.storageFilter.set(((ContainerStorageBus) this.cvb).getStorageFilter()); + } - if( this.rwMode != null ) - { - this.rwMode.set( ( (ContainerStorageBus) this.cvb ).getReadWriteMode() ); - } - } + if (this.rwMode != null) { + this.rwMode.set(((ContainerStorageBus) this.cvb).getReadWriteMode()); + } + } - @Override - protected String getBackground() - { - return "guis/storagebus.png"; - } + @Override + protected String getBackground() { + return "guis/storagebus.png"; + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - try - { - if( btn == this.partition ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "StorageBus.Action", "Partition" ) ); - } - else if( btn == this.clear ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "StorageBus.Action", "Clear" ) ); - } - else if( btn == this.priority ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - else if( btn == this.rwMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.rwMode.getSetting(), backwards ) ); - } - else if( btn == this.storageFilter ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.storageFilter.getSetting(), backwards ) ); - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + try { + if (btn == this.partition) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("StorageBus.Action", "Partition")); + } else if (btn == this.clear) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("StorageBus.Action", "Clear")); + } else if (btn == this.priority) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } else if (btn == this.rwMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.rwMode.getSetting(), backwards)); + } else if (btn == this.storageFilter) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.storageFilter.getSetting(), backwards)); + } + } catch (final IOException e) { + AELog.debug(e); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java b/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java index 053650fbf..b7efac632 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java +++ b/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java @@ -19,327 +19,264 @@ package appeng.client.gui.implementations; -import java.awt.*; -import java.io.IOException; -import java.util.*; -import java.util.List; - +import appeng.api.config.*; +import appeng.api.implementations.IUpgradeableHost; +import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiCustomSlot; +import appeng.client.gui.widgets.GuiImgButton; +import appeng.container.implementations.ContainerUpgradeable; import appeng.container.interfaces.IJEIGhostIngredients; import appeng.container.slot.IJEITargetSlot; import appeng.container.slot.SlotFake; +import appeng.core.localization.GuiText; +import appeng.core.sync.network.NetworkHandler; +import appeng.core.sync.packets.PacketConfigButton; import appeng.core.sync.packets.PacketInventoryAction; import appeng.fluids.client.gui.widgets.GuiFluidSlot; import appeng.fluids.util.AEFluidStack; import appeng.helpers.InventoryAction; -import appeng.util.item.AEItemStack; -import mezz.jei.api.gui.IGhostIngredientHandler.Target; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.*; -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - -import appeng.api.config.FuzzyMode; -import appeng.api.config.RedstoneMode; -import appeng.api.config.SchedulingMode; -import appeng.api.config.Settings; -import appeng.api.config.Upgrades; -import appeng.api.config.YesNo; -import appeng.api.implementations.IUpgradeableHost; -import appeng.client.gui.AEBaseGui; -import appeng.client.gui.widgets.GuiImgButton; -import appeng.container.implementations.ContainerUpgradeable; -import appeng.core.localization.GuiText; -import appeng.core.sync.network.NetworkHandler; -import appeng.core.sync.packets.PacketConfigButton; import appeng.parts.automation.PartExportBus; import appeng.parts.automation.PartImportBus; +import appeng.util.item.AEItemStack; +import mezz.jei.api.gui.IGhostIngredientHandler.Target; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; +import org.lwjgl.input.Mouse; + +import java.awt.*; +import java.io.IOException; +import java.util.List; +import java.util.*; -public class GuiUpgradeable extends AEBaseGui implements IJEIGhostIngredients -{ - private final Map, Object> mapTargetSlot = new HashMap<>(); - protected final ContainerUpgradeable cvb; - protected final IUpgradeableHost bc; +public class GuiUpgradeable extends AEBaseGui implements IJEIGhostIngredients { + private final Map, Object> mapTargetSlot = new HashMap<>(); + protected final ContainerUpgradeable cvb; + protected final IUpgradeableHost bc; - protected GuiImgButton redstoneMode; - protected GuiImgButton fuzzyMode; - protected GuiImgButton craftMode; - protected GuiImgButton schedulingMode; + protected GuiImgButton redstoneMode; + protected GuiImgButton fuzzyMode; + protected GuiImgButton craftMode; + protected GuiImgButton schedulingMode; - public GuiUpgradeable( final InventoryPlayer inventoryPlayer, final IUpgradeableHost te ) - { - this( new ContainerUpgradeable( inventoryPlayer, te ) ); - } + public GuiUpgradeable(final InventoryPlayer inventoryPlayer, final IUpgradeableHost te) { + this(new ContainerUpgradeable(inventoryPlayer, te)); + } - public GuiUpgradeable( final ContainerUpgradeable te ) - { - super( te ); - this.cvb = te; + public GuiUpgradeable(final ContainerUpgradeable te) { + super(te); + this.cvb = te; - this.bc = (IUpgradeableHost) te.getTarget(); - this.xSize = this.hasToolbox() ? 246 : 211; - this.ySize = 184; - } + this.bc = (IUpgradeableHost) te.getTarget(); + this.xSize = this.hasToolbox() ? 246 : 211; + this.ySize = 184; + } - protected boolean hasToolbox() - { - return ( (ContainerUpgradeable) this.inventorySlots ).hasToolbox(); - } + protected boolean hasToolbox() { + return ((ContainerUpgradeable) this.inventorySlots).hasToolbox(); + } - @Override - public void initGui() - { - super.initGui(); - this.addButtons(); - } + @Override + public void initGui() { + super.initGui(); + this.addButtons(); + } - @Override - public List getJEIExclusionArea() - { - List exclusionArea = new ArrayList<>(); + @Override + public List getJEIExclusionArea() { + List exclusionArea = new ArrayList<>(); - int yOffset = guiTop + 8; + int yOffset = guiTop + 8; - int visibleButtons = (int) this.buttonList.stream().filter( v -> v.enabled && v.x < guiLeft ).count(); - Rectangle sortDir = new Rectangle( guiLeft - 18, yOffset, 18, visibleButtons * 18 + visibleButtons - 2 ); - exclusionArea.add( sortDir ); + int visibleButtons = (int) this.buttonList.stream().filter(v -> v.enabled && v.x < guiLeft).count(); + Rectangle sortDir = new Rectangle(guiLeft - 18, yOffset, 18, visibleButtons * 18 + visibleButtons - 2); + exclusionArea.add(sortDir); - return exclusionArea; - } + return exclusionArea; + } - protected void addButtons() - { - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.craftMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.CRAFT_ONLY, YesNo.NO ); - this.schedulingMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 68, Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT ); + protected void addButtons() { + this.redstoneMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.fuzzyMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.craftMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 48, Settings.CRAFT_ONLY, YesNo.NO); + this.schedulingMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 68, Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT); - this.buttonList.add( this.craftMode ); - this.buttonList.add( this.redstoneMode ); - this.buttonList.add( this.fuzzyMode ); - this.buttonList.add( this.schedulingMode ); - } + this.buttonList.add(this.craftMode); + this.buttonList.add(this.redstoneMode); + this.buttonList.add(this.fuzzyMode); + this.buttonList.add(this.schedulingMode); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( this.getName().getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(this.getName().getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); - if( this.redstoneMode != null ) - { - this.redstoneMode.set( this.cvb.getRedStoneMode() ); - } + if (this.redstoneMode != null) { + this.redstoneMode.set(this.cvb.getRedStoneMode()); + } - if( this.fuzzyMode != null ) - { - this.fuzzyMode.set( this.cvb.getFuzzyMode() ); - } + if (this.fuzzyMode != null) { + this.fuzzyMode.set(this.cvb.getFuzzyMode()); + } - if( this.craftMode != null ) - { - this.craftMode.set( this.cvb.getCraftingMode() ); - } + if (this.craftMode != null) { + this.craftMode.set(this.cvb.getCraftingMode()); + } - if( this.schedulingMode != null ) - { - this.schedulingMode.set( this.cvb.getSchedulingMode() ); - } - } + if (this.schedulingMode != null) { + this.schedulingMode.set(this.cvb.getSchedulingMode()); + } + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.handleButtonVisibility(); + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.handleButtonVisibility(); - this.bindTexture( this.getBackground() ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, 211 - 34, this.ySize ); - if( this.drawUpgrades() ) - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 14 + this.cvb.availableUpgrades() * 18 ); - } - if( this.hasToolbox() ) - { - this.drawTexturedModalRect( offsetX + 178, offsetY + this.ySize - 90, 178, this.ySize - 90, 68, 68 ); - } - } + this.bindTexture(this.getBackground()); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, 211 - 34, this.ySize); + if (this.drawUpgrades()) { + this.drawTexturedModalRect(offsetX + 177, offsetY, 177, 0, 35, 14 + this.cvb.availableUpgrades() * 18); + } + if (this.hasToolbox()) { + this.drawTexturedModalRect(offsetX + 178, offsetY + this.ySize - 90, 178, this.ySize - 90, 68, 68); + } + } - protected void handleButtonVisibility() - { - if( this.redstoneMode != null ) - { - this.redstoneMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.REDSTONE ) > 0 ); - } - if( this.fuzzyMode != null ) - { - this.fuzzyMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ); - } - if( this.craftMode != null ) - { - this.craftMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ); - } - if( this.schedulingMode != null ) - { - this.schedulingMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.CAPACITY ) > 0 && this.bc instanceof PartExportBus ); - } - } + protected void handleButtonVisibility() { + if (this.redstoneMode != null) { + this.redstoneMode.setVisibility(this.bc.getInstalledUpgrades(Upgrades.REDSTONE) > 0); + } + if (this.fuzzyMode != null) { + this.fuzzyMode.setVisibility(this.bc.getInstalledUpgrades(Upgrades.FUZZY) > 0); + } + if (this.craftMode != null) { + this.craftMode.setVisibility(this.bc.getInstalledUpgrades(Upgrades.CRAFTING) > 0); + } + if (this.schedulingMode != null) { + this.schedulingMode.setVisibility(this.bc.getInstalledUpgrades(Upgrades.CAPACITY) > 0 && this.bc instanceof PartExportBus); + } + } - protected String getBackground() - { - return "guis/bus.png"; - } + protected String getBackground() { + return "guis/bus.png"; + } - protected boolean drawUpgrades() - { - return true; - } + protected boolean drawUpgrades() { + return true; + } - protected GuiText getName() - { - return this.bc instanceof PartImportBus ? GuiText.ImportBus : GuiText.ExportBus; - } + protected GuiText getName() { + return this.bc instanceof PartImportBus ? GuiText.ImportBus : GuiText.ExportBus; + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - if( btn == this.redstoneMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.redstoneMode.getSetting(), backwards ) ); - } + if (btn == this.redstoneMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.redstoneMode.getSetting(), backwards)); + } - if( btn == this.craftMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.craftMode.getSetting(), backwards ) ); - } + if (btn == this.craftMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.craftMode.getSetting(), backwards)); + } - if( btn == this.fuzzyMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.fuzzyMode.getSetting(), backwards ) ); - } + if (btn == this.fuzzyMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.fuzzyMode.getSetting(), backwards)); + } - if( btn == this.schedulingMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.schedulingMode.getSetting(), backwards ) ); - } - } + if (btn == this.schedulingMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.schedulingMode.getSetting(), backwards)); + } + } - @Override - public List> getPhantomTargets( Object ingredient ) - { - mapTargetSlot.clear(); + @Override + public List> getPhantomTargets(Object ingredient) { + mapTargetSlot.clear(); - FluidStack fluidStack = null; - ItemStack itemStack = ItemStack.EMPTY; + FluidStack fluidStack = null; + ItemStack itemStack = ItemStack.EMPTY; - if( ingredient instanceof ItemStack ) - { - itemStack = (ItemStack) ingredient; - fluidStack = FluidUtil.getFluidContained( itemStack ); - } - else if( ingredient instanceof FluidStack ) - { - fluidStack = (FluidStack) ingredient; - } + if (ingredient instanceof ItemStack) { + itemStack = (ItemStack) ingredient; + fluidStack = FluidUtil.getFluidContained(itemStack); + } else if (ingredient instanceof FluidStack) { + fluidStack = (FluidStack) ingredient; + } - if( !( ingredient instanceof ItemStack ) && !( ingredient instanceof FluidStack ) ) - { - return Collections.emptyList(); - } + if (!(ingredient instanceof ItemStack) && !(ingredient instanceof FluidStack)) { + return Collections.emptyList(); + } - List> targets = new ArrayList<>(); + List> targets = new ArrayList<>(); - List slots = new ArrayList<>(); - if( this.inventorySlots.inventorySlots.size() > 0 ) - { - for( Slot slot : this.inventorySlots.inventorySlots ) - { - if( slot instanceof SlotFake && ( !itemStack.isEmpty() || this instanceof GuiCellWorkbench && fluidStack != null ) ) - { - slots.add( (IJEITargetSlot) slot ); - } - } - } - if( this.getGuiSlots().size() > 0 ) - { - for( GuiCustomSlot slot : this.getGuiSlots() ) - { - if( slot instanceof GuiFluidSlot && fluidStack != null ) - { - slots.add( (IJEITargetSlot) slot ); - } - } - } - for( Object slot : slots ) - { - ItemStack finalItemStack = itemStack; - FluidStack finalFluidStack = fluidStack; - Target targetItem = new Target() - { - @Override - public Rectangle getArea() - { - if( slot instanceof SlotFake && ( (SlotFake) slot ).isSlotEnabled() ) - { - return new Rectangle( getGuiLeft() + ( (SlotFake) slot ).xPos, getGuiTop() + ( (SlotFake) slot ).yPos, 16, 16 ); - } - else if( slot instanceof GuiFluidSlot && ( (GuiFluidSlot) slot ).isSlotEnabled() ) - { - return new Rectangle( getGuiLeft() + ( (GuiFluidSlot) slot ).xPos(), getGuiTop() + ( (GuiFluidSlot) slot ).yPos(), 16, 16 ); - } - return new Rectangle(); - } + List slots = new ArrayList<>(); + if (this.inventorySlots.inventorySlots.size() > 0) { + for (Slot slot : this.inventorySlots.inventorySlots) { + if (slot instanceof SlotFake && (!itemStack.isEmpty() || this instanceof GuiCellWorkbench && fluidStack != null)) { + slots.add((IJEITargetSlot) slot); + } + } + } + if (this.getGuiSlots().size() > 0) { + for (GuiCustomSlot slot : this.getGuiSlots()) { + if (slot instanceof GuiFluidSlot && fluidStack != null) { + slots.add((IJEITargetSlot) slot); + } + } + } + for (Object slot : slots) { + ItemStack finalItemStack = itemStack; + FluidStack finalFluidStack = fluidStack; + Target targetItem = new Target() { + @Override + public Rectangle getArea() { + if (slot instanceof SlotFake && ((SlotFake) slot).isSlotEnabled()) { + return new Rectangle(getGuiLeft() + ((SlotFake) slot).xPos, getGuiTop() + ((SlotFake) slot).yPos, 16, 16); + } else if (slot instanceof GuiFluidSlot && ((GuiFluidSlot) slot).isSlotEnabled()) { + return new Rectangle(getGuiLeft() + ((GuiFluidSlot) slot).xPos(), getGuiTop() + ((GuiFluidSlot) slot).yPos(), 16, 16); + } + return new Rectangle(); + } - @Override - public void accept( Object ingredient ) - { - PacketInventoryAction p = null; - try - { - if( slot instanceof SlotFake && ( (SlotFake) slot ).isSlotEnabled() ) - { - if( finalItemStack.isEmpty() && finalFluidStack != null ) - { - p = new PacketInventoryAction( InventoryAction.PLACE_JEI_GHOST_ITEM, (IJEITargetSlot) slot, AEItemStack.fromItemStack( FluidUtil.getFilledBucket( finalFluidStack ) ) ); - } - else if( !finalItemStack.isEmpty() ) - { - p = new PacketInventoryAction( InventoryAction.PLACE_JEI_GHOST_ITEM, (IJEITargetSlot) slot, AEItemStack.fromItemStack( finalItemStack ) ); - } - } - else - { - if( finalFluidStack == null ) - { - return; - } - p = new PacketInventoryAction( InventoryAction.PLACE_JEI_GHOST_ITEM, (IJEITargetSlot) slot, AEItemStack.fromItemStack( AEFluidStack.fromFluidStack( finalFluidStack ).asItemStackRepresentation() ) ); - } - NetworkHandler.instance().sendToServer( p ); + @Override + public void accept(Object ingredient) { + PacketInventoryAction p = null; + try { + if (slot instanceof SlotFake && ((SlotFake) slot).isSlotEnabled()) { + if (finalItemStack.isEmpty() && finalFluidStack != null) { + p = new PacketInventoryAction(InventoryAction.PLACE_JEI_GHOST_ITEM, (IJEITargetSlot) slot, AEItemStack.fromItemStack(FluidUtil.getFilledBucket(finalFluidStack))); + } else if (!finalItemStack.isEmpty()) { + p = new PacketInventoryAction(InventoryAction.PLACE_JEI_GHOST_ITEM, (IJEITargetSlot) slot, AEItemStack.fromItemStack(finalItemStack)); + } + } else { + if (finalFluidStack == null) { + return; + } + p = new PacketInventoryAction(InventoryAction.PLACE_JEI_GHOST_ITEM, (IJEITargetSlot) slot, AEItemStack.fromItemStack(AEFluidStack.fromFluidStack(finalFluidStack).asItemStackRepresentation())); + } + NetworkHandler.instance().sendToServer(p); - } - catch( IOException e ) - { - e.printStackTrace(); - } - } - }; - targets.add( targetItem ); - mapTargetSlot.putIfAbsent( targetItem, slot ); - } - return targets; - } + } catch (IOException e) { + e.printStackTrace(); + } + } + }; + targets.add(targetItem); + mapTargetSlot.putIfAbsent(targetItem, slot); + } + return targets; + } - @Override - public Map, Object> getFakeSlotTargetMap() - { - return mapTargetSlot; - } + @Override + public Map, Object> getFakeSlotTargetMap() { + return mapTargetSlot; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java b/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java index d2ff0b793..a5206b48a 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java +++ b/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java @@ -19,64 +19,57 @@ package appeng.client.gui.implementations; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiProgressBar; import appeng.client.gui.widgets.GuiProgressBar.Direction; import appeng.container.implementations.ContainerVibrationChamber; import appeng.core.localization.GuiText; import appeng.tile.misc.TileVibrationChamber; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.entity.player.InventoryPlayer; -public class GuiVibrationChamber extends AEBaseGui -{ +public class GuiVibrationChamber extends AEBaseGui { - private final ContainerVibrationChamber cvc; - private GuiProgressBar pb; + private final ContainerVibrationChamber cvc; + private GuiProgressBar pb; - public GuiVibrationChamber( final InventoryPlayer inventoryPlayer, final TileVibrationChamber te ) - { - super( new ContainerVibrationChamber( inventoryPlayer, te ) ); - this.cvc = (ContainerVibrationChamber) this.inventorySlots; - this.ySize = 166; - } + public GuiVibrationChamber(final InventoryPlayer inventoryPlayer, final TileVibrationChamber te) { + super(new ContainerVibrationChamber(inventoryPlayer, te)); + this.cvc = (ContainerVibrationChamber) this.inventorySlots; + this.ySize = 166; + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.pb = new GuiProgressBar( this.cvc, "guis/vibchamber.png", 99, 36, 176, 14, 6, 18, Direction.VERTICAL ); - this.buttonList.add( this.pb ); - } + this.pb = new GuiProgressBar(this.cvc, "guis/vibchamber.png", 99, 36, 176, 14, 6, 18, Direction.VERTICAL); + this.buttonList.add(this.pb); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.VibrationChamber.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.VibrationChamber.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); - this.pb.setFullMsg( TileVibrationChamber.POWER_PER_TICK * this.cvc.getCurrentProgress() / TileVibrationChamber.DILATION_SCALING + " AE/t" ); + this.pb.setFullMsg(TileVibrationChamber.POWER_PER_TICK * this.cvc.getCurrentProgress() / TileVibrationChamber.DILATION_SCALING + " AE/t"); - if( this.cvc.getRemainingBurnTime() > 0 ) - { - final int i1 = this.cvc.getRemainingBurnTime() * 12 / 100; - this.bindTexture( "guis/vibchamber.png" ); - GlStateManager.color( 1, 1, 1 ); - final int l = -15; - final int k = 25; - this.drawTexturedModalRect( k + 56, l + 36 + 12 - i1, 176, 12 - i1, 14, i1 + 2 ); - } - } + if (this.cvc.getRemainingBurnTime() > 0) { + final int i1 = this.cvc.getRemainingBurnTime() * 12 / 100; + this.bindTexture("guis/vibchamber.png"); + GlStateManager.color(1, 1, 1); + final int l = -15; + final int k = 25; + this.drawTexturedModalRect(k + 56, l + 36 + 12 - i1, 176, 12 - i1, 14, i1 + 2); + } + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/vibchamber.png" ); - this.pb.x = 99 + this.guiLeft; - this.pb.y = 36 + this.guiTop; - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/vibchamber.png"); + this.pb.x = 99 + this.guiLeft; + this.pb.y = 36 + this.guiTop; + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiWireless.java b/src/main/java/appeng/client/gui/implementations/GuiWireless.java index 3af6043ba..919f2243c 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiWireless.java +++ b/src/main/java/appeng/client/gui/implementations/GuiWireless.java @@ -19,13 +19,6 @@ package appeng.client.gui.implementations; -import java.io.IOException; - -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.config.Settings; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiImgButton; @@ -34,66 +27,63 @@ import appeng.core.AEConfig; import appeng.core.localization.GuiText; import appeng.tile.networking.TileWireless; import appeng.util.Platform; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import org.lwjgl.input.Mouse; + +import java.io.IOException; -public class GuiWireless extends AEBaseGui -{ +public class GuiWireless extends AEBaseGui { - private GuiImgButton units; + private GuiImgButton units; - public GuiWireless( final InventoryPlayer inventoryPlayer, final TileWireless te ) - { - super( new ContainerWireless( inventoryPlayer, te ) ); - this.ySize = 166; - } + public GuiWireless(final InventoryPlayer inventoryPlayer, final TileWireless te) { + super(new ContainerWireless(inventoryPlayer, te)); + this.ySize = 166; + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - if( btn == this.units ) - { - AEConfig.instance().nextPowerUnit( backwards ); - this.units.set( AEConfig.instance().selectedPowerUnit() ); - } - } + if (btn == this.units) { + AEConfig.instance().nextPowerUnit(backwards); + this.units.set(AEConfig.instance().selectedPowerUnit()); + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.units = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance().selectedPowerUnit() ); - this.buttonList.add( this.units ); - } + this.units = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance().selectedPowerUnit()); + this.buttonList.add(this.units); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.Wireless.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.Wireless.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); - final ContainerWireless cw = (ContainerWireless) this.inventorySlots; + final ContainerWireless cw = (ContainerWireless) this.inventorySlots; - if( cw.getRange() > 0 ) - { - final String firstMessage = GuiText.Range.getLocal() + ": " + ( cw.getRange() / 10.0 ) + " m"; - final String secondMessage = GuiText.PowerUsageRate.getLocal() + ": " + Platform.formatPowerLong( cw.getDrain(), true ); + if (cw.getRange() > 0) { + final String firstMessage = GuiText.Range.getLocal() + ": " + (cw.getRange() / 10.0) + " m"; + final String secondMessage = GuiText.PowerUsageRate.getLocal() + ": " + Platform.formatPowerLong(cw.getDrain(), true); - final int strWidth = Math.max( this.fontRenderer.getStringWidth( firstMessage ), this.fontRenderer.getStringWidth( secondMessage ) ); - final int cOffset = ( this.xSize / 2 ) - ( strWidth / 2 ); - this.fontRenderer.drawString( firstMessage, cOffset, 20, 4210752 ); - this.fontRenderer.drawString( secondMessage, cOffset, 20 + 12, 4210752 ); - } - } + final int strWidth = Math.max(this.fontRenderer.getStringWidth(firstMessage), this.fontRenderer.getStringWidth(secondMessage)); + final int cOffset = (this.xSize / 2) - (strWidth / 2); + this.fontRenderer.drawString(firstMessage, cOffset, 20, 4210752); + this.fontRenderer.drawString(secondMessage, cOffset, 20 + 12, 4210752); + } + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/wireless.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/wireless.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java b/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java index f5dba6c05..c9a9b968b 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java @@ -19,22 +19,18 @@ package appeng.client.gui.implementations; +import appeng.api.implementations.guiobjects.IPortableCell; import net.minecraft.entity.player.InventoryPlayer; -import appeng.api.implementations.guiobjects.IPortableCell; +public class GuiWirelessTerm extends GuiMEPortableCell { -public class GuiWirelessTerm extends GuiMEPortableCell -{ + public GuiWirelessTerm(final InventoryPlayer inventoryPlayer, final IPortableCell te) { + super(inventoryPlayer, te); + } - public GuiWirelessTerm( final InventoryPlayer inventoryPlayer, final IPortableCell te ) - { - super( inventoryPlayer, te ); - } - - @Override - int getMaxRows() - { - return this.defaultGetMaxRows(); - } + @Override + int getMaxRows() { + return this.defaultGetMaxRows(); + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiCustomSlot.java b/src/main/java/appeng/client/gui/widgets/GuiCustomSlot.java index 5c24b5c6b..a3e2c3f3c 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiCustomSlot.java +++ b/src/main/java/appeng/client/gui/widgets/GuiCustomSlot.java @@ -1,4 +1,3 @@ - package appeng.client.gui.widgets; @@ -8,78 +7,65 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -public abstract class GuiCustomSlot extends Gui implements ITooltip -{ - protected final int x; - protected final int y; - protected final int id; +public abstract class GuiCustomSlot extends Gui implements ITooltip { + protected final int x; + protected final int y; + protected final int id; - public GuiCustomSlot( final int id, final int x, final int y ) - { - this.x = x; - this.y = y; - this.id = id; - } + public GuiCustomSlot(final int id, final int x, final int y) { + this.x = x; + this.y = y; + this.id = id; + } - public int getId() - { - return this.id; - } + public int getId() { + return this.id; + } - public boolean canClick( final EntityPlayer player ) - { - return true; - } + public boolean canClick(final EntityPlayer player) { + return true; + } - public void slotClicked( final ItemStack clickStack, final int mouseButton ) - { - } + public void slotClicked(final ItemStack clickStack, final int mouseButton) { + } - public abstract void drawContent( final Minecraft mc, final int mouseX, final int mouseY, final float partialTicks ); + public abstract void drawContent(final Minecraft mc, final int mouseX, final int mouseY, final float partialTicks); - public void drawBackground( int guileft, int guitop ) - { - } + public void drawBackground(int guileft, int guitop) { + } - @Override - public String getMessage() - { - return null; - } + @Override + public String getMessage() { + return null; + } - @Override - public int xPos() - { - return this.x; - } + @Override + public int xPos() { + return this.x; + } - @Override - public int yPos() - { - return this.y; - } + @Override + public int yPos() { + return this.y; + } - @Override - public int getWidth() - { - return 16; - } + @Override + public int getWidth() { + return 16; + } - @Override - public int getHeight() - { - return 16; - } + @Override + public int getHeight() { + return 16; + } - @Override - public boolean isVisible() - { - return false; - } + @Override + public boolean isVisible() { + return false; + } - public boolean isSlotEnabled() - { - return true; - } + public boolean isSlotEnabled() { + return true; + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiImgButton.java b/src/main/java/appeng/client/gui/widgets/GuiImgButton.java index 17b1bdddc..a72ac2e9b 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiImgButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiImgButton.java @@ -19,422 +19,354 @@ package appeng.client.gui.widgets; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Pattern; - +import appeng.api.config.*; +import appeng.core.localization.ButtonToolTips; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.translation.I18n; -import appeng.api.config.AccessRestriction; -import appeng.api.config.ActionItems; -import appeng.api.config.CondenserOutput; -import appeng.api.config.FullnessMode; -import appeng.api.config.FuzzyMode; -import appeng.api.config.ItemSubstitution; -import appeng.api.config.LevelType; -import appeng.api.config.OperationMode; -import appeng.api.config.PowerUnits; -import appeng.api.config.RedstoneMode; -import appeng.api.config.RelativeDirection; -import appeng.api.config.SchedulingMode; -import appeng.api.config.SearchBoxMode; -import appeng.api.config.Settings; -import appeng.api.config.SortDir; -import appeng.api.config.SortOrder; -import appeng.api.config.StorageFilter; -import appeng.api.config.TerminalStyle; -import appeng.api.config.ViewItems; -import appeng.api.config.YesNo; -import appeng.core.localization.ButtonToolTips; - - -public class GuiImgButton extends GuiButton implements ITooltip -{ - private static final Pattern COMPILE = Pattern.compile( "%s" ); - private static final Pattern PATTERN_NEW_LINE = Pattern.compile( "\\n", Pattern.LITERAL ); - private static Map appearances; - private final Enum buttonSetting; - private boolean halfSize = false; - private String fillVar; - private Enum currentValue; - - public GuiImgButton( final int x, final int y, final Enum idx, final Enum val ) - { - super( 0, 0, 16, "" ); - - this.buttonSetting = idx; - this.currentValue = val; - this.x = x; - this.y = y; - this.width = 16; - this.height = 16; - - if( appearances == null ) - { - appearances = new HashMap<>(); - this.registerApp( 16 * 7, Settings.CONDENSER_OUTPUT, CondenserOutput.TRASH, ButtonToolTips.CondenserOutput, ButtonToolTips.Trash ); - this.registerApp( 16 * 7 + 1, Settings.CONDENSER_OUTPUT, CondenserOutput.MATTER_BALLS, ButtonToolTips.CondenserOutput, ButtonToolTips.MatterBalls ); - this.registerApp( 16 * 7 + 2, Settings.CONDENSER_OUTPUT, CondenserOutput.SINGULARITY, ButtonToolTips.CondenserOutput, ButtonToolTips.Singularity ); - - this.registerApp( 16 * 9 + 1, Settings.ACCESS, AccessRestriction.READ, ButtonToolTips.IOMode, ButtonToolTips.Read ); - this.registerApp( 16 * 9, Settings.ACCESS, AccessRestriction.WRITE, ButtonToolTips.IOMode, ButtonToolTips.Write ); - this.registerApp( 16 * 9 + 2, Settings.ACCESS, AccessRestriction.READ_WRITE, ButtonToolTips.IOMode, ButtonToolTips.ReadWrite ); - - this.registerApp( 16 * 10, Settings.POWER_UNITS, PowerUnits.AE, ButtonToolTips.PowerUnits, PowerUnits.AE.unlocalizedName ); - this.registerApp( 16 * 10 + 1, Settings.POWER_UNITS, PowerUnits.EU, ButtonToolTips.PowerUnits, PowerUnits.EU.unlocalizedName ); - this.registerApp( 16 * 10 + 4, Settings.POWER_UNITS, PowerUnits.RF, ButtonToolTips.PowerUnits, PowerUnits.RF.unlocalizedName ); - this.registerApp( 16 * 10 + 1, Settings.POWER_UNITS, PowerUnits.GTEU, ButtonToolTips.PowerUnits, PowerUnits.EU.unlocalizedName ); - - this.registerApp( 3, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE, ButtonToolTips.RedstoneMode, ButtonToolTips.AlwaysActive ); - this.registerApp( 0, Settings.REDSTONE_CONTROLLED, RedstoneMode.LOW_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.ActiveWithoutSignal ); - this.registerApp( 1, Settings.REDSTONE_CONTROLLED, RedstoneMode.HIGH_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.ActiveWithSignal ); - this.registerApp( 2, Settings.REDSTONE_CONTROLLED, RedstoneMode.SIGNAL_PULSE, ButtonToolTips.RedstoneMode, ButtonToolTips.ActiveOnPulse ); - - this.registerApp( 0, Settings.REDSTONE_EMITTER, RedstoneMode.LOW_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.EmitLevelsBelow ); - this.registerApp( 1, Settings.REDSTONE_EMITTER, RedstoneMode.HIGH_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.EmitLevelAbove ); - - this.registerApp( 51, Settings.OPERATION_MODE, OperationMode.FILL, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToStorageCell ); - this.registerApp( 50, Settings.OPERATION_MODE, OperationMode.EMPTY, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToNetwork ); - - this.registerApp( 51, Settings.IO_DIRECTION, RelativeDirection.LEFT, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToStorageCell ); - this.registerApp( 50, Settings.IO_DIRECTION, RelativeDirection.RIGHT, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToNetwork ); - - this.registerApp( 48, Settings.SORT_DIRECTION, SortDir.ASCENDING, ButtonToolTips.SortOrder, ButtonToolTips.ToggleSortDirection ); - this.registerApp( 49, Settings.SORT_DIRECTION, SortDir.DESCENDING, ButtonToolTips.SortOrder, ButtonToolTips.ToggleSortDirection ); - - this.registerApp( 16 * 2 + 3, Settings.SEARCH_MODE, SearchBoxMode.AUTOSEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_Auto ); - this.registerApp( 16 * 2 + 4, Settings.SEARCH_MODE, SearchBoxMode.MANUAL_SEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_Standard ); - this.registerApp( 16 * 2 + 5, Settings.SEARCH_MODE, SearchBoxMode.JEI_AUTOSEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_JEIAuto ); - this.registerApp( 16 * 2 + 6, Settings.SEARCH_MODE, SearchBoxMode.JEI_MANUAL_SEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_JEIStandard ); - this.registerApp( 16 * 2 + 7, Settings.SEARCH_MODE, SearchBoxMode.AUTOSEARCH_KEEP, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_AutoKeep ); - this.registerApp( 16 * 2 + 8, Settings.SEARCH_MODE, SearchBoxMode.MANUAL_SEARCH_KEEP, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_StandardKeep ); - this.registerApp( 16 * 2 + 9, Settings.SEARCH_MODE, SearchBoxMode.JEI_AUTOSEARCH_KEEP, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_JEIAutoKeep ); - this.registerApp( 16 * 2 + 10, Settings.SEARCH_MODE, SearchBoxMode.JEI_MANUAL_SEARCH_KEEP, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_JEIStandardKeep ); - - this.registerApp( 16 * 5 + 3, Settings.LEVEL_TYPE, LevelType.ENERGY_LEVEL, ButtonToolTips.LevelType, ButtonToolTips.LevelType_Energy ); - this.registerApp( 16 * 4 + 3, Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL, ButtonToolTips.LevelType, ButtonToolTips.LevelType_Item ); - - this.registerApp( 16 * 13, Settings.TERMINAL_STYLE, TerminalStyle.TALL, ButtonToolTips.TerminalStyle, ButtonToolTips.TerminalStyle_Tall ); - this.registerApp( 16 * 13 + 1, Settings.TERMINAL_STYLE, TerminalStyle.SMALL, ButtonToolTips.TerminalStyle, ButtonToolTips.TerminalStyle_Small ); - this.registerApp( 16 * 13 + 2, Settings.TERMINAL_STYLE, TerminalStyle.FULL, ButtonToolTips.TerminalStyle, ButtonToolTips.TerminalStyle_Full ); - - this.registerApp( 64, Settings.SORT_BY, SortOrder.NAME, ButtonToolTips.SortBy, ButtonToolTips.ItemName ); - this.registerApp( 65, Settings.SORT_BY, SortOrder.AMOUNT, ButtonToolTips.SortBy, ButtonToolTips.NumberOfItems ); - this.registerApp( 68, Settings.SORT_BY, SortOrder.INVTWEAKS, ButtonToolTips.SortBy, ButtonToolTips.InventoryTweaks ); - this.registerApp( 69, Settings.SORT_BY, SortOrder.MOD, ButtonToolTips.SortBy, ButtonToolTips.Mod ); - - this.registerApp( 66, Settings.ACTIONS, ActionItems.WRENCH, ButtonToolTips.PartitionStorage, ButtonToolTips.PartitionStorageHint ); - this.registerApp( 6, Settings.ACTIONS, ActionItems.CLOSE, ButtonToolTips.Clear, ButtonToolTips.ClearSettings ); - this.registerApp( 6, Settings.ACTIONS, ActionItems.STASH, ButtonToolTips.Stash, ButtonToolTips.StashDesc ); - - this.registerApp( 6 + 4 * 16, Settings.ACTIONS, ActionItems.MULTIPLY_BY_TWO, ButtonToolTips.MultiplyByTwo, ButtonToolTips.MultiplyByTwoDesc ); - this.registerApp( 7 + 4 * 16, Settings.ACTIONS, ActionItems.MULTIPLY_BY_THREE, ButtonToolTips.MultiplyByThree, ButtonToolTips.MultiplyByThreeDesc ); - this.registerApp( 8 + 4 * 16, Settings.ACTIONS, ActionItems.INCREASE_BY_ONE, ButtonToolTips.IncreaseByOne, ButtonToolTips.IncreaseByOneDesc ); - this.registerApp( 9 + 4 * 16, Settings.ACTIONS, ActionItems.DIVIDE_BY_TWO, ButtonToolTips.DivideByTwo, ButtonToolTips.DivideByTwoDesc ); - this.registerApp( 10 + 4 * 16, Settings.ACTIONS, ActionItems.DIVIDE_BY_THREE, ButtonToolTips.DivideByThree, ButtonToolTips.DivideByThreeDesc ); - this.registerApp( 11 + 4 * 16, Settings.ACTIONS, ActionItems.DECREASE_BY_ONE, ButtonToolTips.DecreaseByOne, ButtonToolTips.DecreaseByOneDesc ); - this.registerApp( 12 + 4 * 16, Settings.ACTIONS, ActionItems.MAX_COUNT, ButtonToolTips.MaxCount, ButtonToolTips.MaxCountDesc ); - - this.registerApp( 6 + 5 * 16, Settings.ACTIONS, ActionItems.FREE_MOLECULAR_SLOT_SHORTCUT, ButtonToolTips.FreeMolecularSlotShortcut, ButtonToolTips.FreeMolecularSlotShortcutDesc ); - this.registerApp( 7 + 5 * 16, Settings.ACTIONS, ActionItems.TOGGLE_SHOW_FULL_INTERFACES_ON, ButtonToolTips.ToggleShowFullInterfaces, ButtonToolTips.ToggleShowFullInterfacesOnDesc ); - this.registerApp( 8 + 5 * 16, Settings.ACTIONS, ActionItems.TOGGLE_SHOW_FULL_INTERFACES_OFF, ButtonToolTips.ToggleShowFullInterfaces, ButtonToolTips.ToggleShowFullInterfacesOffDesc ); - this.registerApp( 6 + 6 * 16, Settings.ACTIONS, ActionItems.HIGHLIGHT_INTERFACE, ButtonToolTips.HighlightInterface, "" ); - - this.registerApp( 8, Settings.ACTIONS, ActionItems.ENCODE, ButtonToolTips.Encode, ButtonToolTips.EncodeDescription ); - this.registerApp( 4 + 3 * 16, Settings.ACTIONS, ItemSubstitution.ENABLED, ButtonToolTips.Substitutions, ButtonToolTips.SubstitutionsDescEnabled ); - this.registerApp( 7 + 3 * 16, Settings.ACTIONS, ItemSubstitution.DISABLED, ButtonToolTips.Substitutions, ButtonToolTips.SubstitutionsDescDisabled ); - - this.registerApp( 16, Settings.VIEW_MODE, ViewItems.STORED, ButtonToolTips.View, ButtonToolTips.StoredItems ); - this.registerApp( 18, Settings.VIEW_MODE, ViewItems.ALL, ButtonToolTips.View, ButtonToolTips.StoredCraftable ); - this.registerApp( 19, Settings.VIEW_MODE, ViewItems.CRAFTABLE, ButtonToolTips.View, ButtonToolTips.Craftable ); - - this.registerApp( 16 * 6, Settings.FUZZY_MODE, FuzzyMode.PERCENT_25, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_25 ); - this.registerApp( 16 * 6 + 1, Settings.FUZZY_MODE, FuzzyMode.PERCENT_50, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_50 ); - this.registerApp( 16 * 6 + 2, Settings.FUZZY_MODE, FuzzyMode.PERCENT_75, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_75 ); - this.registerApp( 16 * 6 + 3, Settings.FUZZY_MODE, FuzzyMode.PERCENT_99, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_99 ); - this.registerApp( 16 * 6 + 4, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL, ButtonToolTips.FuzzyMode, ButtonToolTips.FZIgnoreAll ); - - this.registerApp( 80, Settings.FULLNESS_MODE, FullnessMode.EMPTY, ButtonToolTips.OperationMode, ButtonToolTips.MoveWhenEmpty ); - this.registerApp( 81, Settings.FULLNESS_MODE, FullnessMode.HALF, ButtonToolTips.OperationMode, ButtonToolTips.MoveWhenWorkIsDone ); - this.registerApp( 82, Settings.FULLNESS_MODE, FullnessMode.FULL, ButtonToolTips.OperationMode, ButtonToolTips.MoveWhenFull ); - - this.registerApp( 16 + 5, Settings.BLOCK, YesNo.YES, ButtonToolTips.InterfaceBlockingMode, ButtonToolTips.Blocking ); - this.registerApp( 16 + 4, Settings.BLOCK, YesNo.NO, ButtonToolTips.InterfaceBlockingMode, ButtonToolTips.NonBlocking ); - - this.registerApp( 16 + 3, Settings.CRAFT_ONLY, YesNo.YES, ButtonToolTips.Craft, ButtonToolTips.CraftOnly ); - this.registerApp( 16 + 2, Settings.CRAFT_ONLY, YesNo.NO, ButtonToolTips.Craft, ButtonToolTips.CraftEither ); - - this.registerApp( 16 * 11 + 2, Settings.CRAFT_VIA_REDSTONE, YesNo.YES, ButtonToolTips.EmitterMode, ButtonToolTips.CraftViaRedstone ); - this.registerApp( 16 * 11 + 1, Settings.CRAFT_VIA_REDSTONE, YesNo.NO, ButtonToolTips.EmitterMode, ButtonToolTips.EmitWhenCrafting ); - - this.registerApp( 16 * 3 + 5, Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY, ButtonToolTips.ReportInaccessibleItems, ButtonToolTips.ReportInaccessibleItemsNo ); - this.registerApp( 16 * 3 + 6, Settings.STORAGE_FILTER, StorageFilter.NONE, ButtonToolTips.ReportInaccessibleItems, ButtonToolTips.ReportInaccessibleItemsYes ); - - this.registerApp( 16 * 14, Settings.PLACE_BLOCK, YesNo.YES, ButtonToolTips.BlockPlacement, ButtonToolTips.BlockPlacementYes ); - this.registerApp( 16 * 14 + 1, Settings.PLACE_BLOCK, YesNo.NO, ButtonToolTips.BlockPlacement, ButtonToolTips.BlockPlacementNo ); - - this.registerApp( 16 * 15, Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT, ButtonToolTips.SchedulingMode, ButtonToolTips.SchedulingModeDefault ); - this.registerApp( 16 * 15 + 1, Settings.SCHEDULING_MODE, SchedulingMode.ROUNDROBIN, ButtonToolTips.SchedulingMode, ButtonToolTips.SchedulingModeRoundRobin ); - this.registerApp( 16 * 15 + 2, Settings.SCHEDULING_MODE, SchedulingMode.RANDOM, ButtonToolTips.SchedulingMode, ButtonToolTips.SchedulingModeRandom ); - } - } - - private void registerApp( final int iconIndex, final Settings setting, final Enum val, final ButtonToolTips title, final Object hint ) - { - final ButtonAppearance a = new ButtonAppearance(); - a.displayName = title.getUnlocalized(); - a.displayValue = (String) ( hint instanceof String ? hint : ( (ButtonToolTips) hint ).getUnlocalized() ); - a.index = iconIndex; - appearances.put( new EnumPair( setting, val ), a ); - } - - public void setVisibility( final boolean vis ) - { - this.visible = vis; - this.enabled = vis; - } - - @Override - public void drawButton( final Minecraft par1Minecraft, final int par2, final int par3, float partial ) - { - if( this.visible ) - { - final int iconIndex = this.getIconIndex(); - - if( this.halfSize ) - { - this.width = 8; - this.height = 8; - - GlStateManager.pushMatrix(); - GlStateManager.translate( this.x, this.y, 0.0F ); - GlStateManager.scale( 0.5f, 0.5f, 0.5f ); - - if( this.enabled ) - { - GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f ); - } - else - { - GlStateManager.color( 0.5f, 0.5f, 0.5f, 1.0f ); - } - - par1Minecraft.renderEngine.bindTexture( new ResourceLocation( "appliedenergistics2", "textures/guis/states.png" ) ); - this.hovered = par2 >= this.x && par3 >= this.y && par2 < this.x + this.width && par3 < this.y + this.height; - - final int uv_y = (int) Math.floor( iconIndex / 16 ); - final int uv_x = iconIndex - uv_y * 16; - - this.drawTexturedModalRect( 0, 0, 256 - 16, 256 - 16, 16, 16 ); - this.drawTexturedModalRect( 0, 0, uv_x * 16, uv_y * 16, 16, 16 ); - this.mouseDragged( par1Minecraft, par2, par3 ); - - GlStateManager.popMatrix(); - } - else - { - if( this.enabled ) - { - GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f ); - } - else - { - GlStateManager.color( 0.5f, 0.5f, 0.5f, 1.0f ); - } - - par1Minecraft.renderEngine.bindTexture( new ResourceLocation( "appliedenergistics2", "textures/guis/states.png" ) ); - this.hovered = par2 >= this.x && par3 >= this.y && par2 < this.x + this.width && par3 < this.y + this.height; - - final int uv_y = (int) Math.floor( iconIndex / 16 ); - final int uv_x = iconIndex - uv_y * 16; - - this.drawTexturedModalRect( this.x, this.y, 256 - 16, 256 - 16, 16, 16 ); - this.drawTexturedModalRect( this.x, this.y, uv_x * 16, uv_y * 16, 16, 16 ); - this.mouseDragged( par1Minecraft, par2, par3 ); - } - } - GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f ); - } - - private int getIconIndex() - { - if( this.buttonSetting != null && this.currentValue != null ) - { - final ButtonAppearance app = appearances.get( new EnumPair( this.buttonSetting, this.currentValue ) ); - if( app == null ) - { - return 256 - 1; - } - return app.index; - } - return 256 - 1; - } - - public Settings getSetting() - { - return (Settings) this.buttonSetting; - } - - public Enum getCurrentValue() - { - return this.currentValue; - } - - @Override - public String getMessage() - { - String displayName = null; - String displayValue = null; - - if( this.buttonSetting != null && this.currentValue != null ) - { - final ButtonAppearance buttonAppearance = appearances.get( new EnumPair( this.buttonSetting, this.currentValue ) ); - if( buttonAppearance == null ) - { - return "No Such Message"; - } - - displayName = buttonAppearance.displayName; - displayValue = buttonAppearance.displayValue; - } - - if( displayName != null ) - { - String name = I18n.translateToLocal( displayName ); - String value = I18n.translateToLocal( displayValue ); - - if( name == null || name.isEmpty() ) - { - name = displayName; - } - if( value == null || value.isEmpty() ) - { - value = displayValue; - } - - if( this.fillVar != null ) - { - value = COMPILE.matcher( value ).replaceFirst( this.fillVar ); - } - - value = PATTERN_NEW_LINE.matcher( value ).replaceAll( "\n" ); - final StringBuilder sb = new StringBuilder( value ); - - int i = sb.lastIndexOf( "\n" ); - if( i <= 0 ) - { - i = 0; - } - while ( i + 30 < sb.length() && ( i = sb.lastIndexOf( " ", i + 30 ) ) != -1 ) - { - sb.replace( i, i + 1, "\n" ); - } - - return name + '\n' + sb; - } - return null; - } - - @Override - public int xPos() - { - return this.x; - } - - @Override - public int yPos() - { - return this.y; - } - - @Override - public int getWidth() - { - return this.halfSize ? 8 : 16; - } - - @Override - public int getHeight() - { - return this.halfSize ? 8 : 16; - } - - @Override - public boolean isVisible() - { - return this.visible; - } - - public void set( final Enum e ) - { - if( this.currentValue != e ) - { - this.currentValue = e; - } - } - - public boolean isHalfSize() - { - return this.halfSize; - } - - public void setHalfSize( final boolean halfSize ) - { - this.halfSize = halfSize; - } - - public String getFillVar() - { - return this.fillVar; - } - - public void setFillVar( final String fillVar ) - { - this.fillVar = fillVar; - } - - private static final class EnumPair - { - - final Enum setting; - final Enum value; - - EnumPair( final Enum a, final Enum b ) - { - this.setting = a; - this.value = b; - } - - @Override - public int hashCode() - { - return this.setting.hashCode() ^ this.value.hashCode(); - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final EnumPair other = (EnumPair) obj; - return other.setting == this.setting && other.value == this.value; - } - } - - private static class ButtonAppearance - { - public int index; - public String displayName; - public String displayValue; - } +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; + + +public class GuiImgButton extends GuiButton implements ITooltip { + private static final Pattern COMPILE = Pattern.compile("%s"); + private static final Pattern PATTERN_NEW_LINE = Pattern.compile("\\n", Pattern.LITERAL); + private static Map appearances; + private final Enum buttonSetting; + private boolean halfSize = false; + private String fillVar; + private Enum currentValue; + + public GuiImgButton(final int x, final int y, final Enum idx, final Enum val) { + super(0, 0, 16, ""); + + this.buttonSetting = idx; + this.currentValue = val; + this.x = x; + this.y = y; + this.width = 16; + this.height = 16; + + if (appearances == null) { + appearances = new HashMap<>(); + this.registerApp(16 * 7, Settings.CONDENSER_OUTPUT, CondenserOutput.TRASH, ButtonToolTips.CondenserOutput, ButtonToolTips.Trash); + this.registerApp(16 * 7 + 1, Settings.CONDENSER_OUTPUT, CondenserOutput.MATTER_BALLS, ButtonToolTips.CondenserOutput, ButtonToolTips.MatterBalls); + this.registerApp(16 * 7 + 2, Settings.CONDENSER_OUTPUT, CondenserOutput.SINGULARITY, ButtonToolTips.CondenserOutput, ButtonToolTips.Singularity); + + this.registerApp(16 * 9 + 1, Settings.ACCESS, AccessRestriction.READ, ButtonToolTips.IOMode, ButtonToolTips.Read); + this.registerApp(16 * 9, Settings.ACCESS, AccessRestriction.WRITE, ButtonToolTips.IOMode, ButtonToolTips.Write); + this.registerApp(16 * 9 + 2, Settings.ACCESS, AccessRestriction.READ_WRITE, ButtonToolTips.IOMode, ButtonToolTips.ReadWrite); + + this.registerApp(16 * 10, Settings.POWER_UNITS, PowerUnits.AE, ButtonToolTips.PowerUnits, PowerUnits.AE.unlocalizedName); + this.registerApp(16 * 10 + 1, Settings.POWER_UNITS, PowerUnits.EU, ButtonToolTips.PowerUnits, PowerUnits.EU.unlocalizedName); + this.registerApp(16 * 10 + 4, Settings.POWER_UNITS, PowerUnits.RF, ButtonToolTips.PowerUnits, PowerUnits.RF.unlocalizedName); + this.registerApp(16 * 10 + 1, Settings.POWER_UNITS, PowerUnits.GTEU, ButtonToolTips.PowerUnits, PowerUnits.EU.unlocalizedName); + + this.registerApp(3, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE, ButtonToolTips.RedstoneMode, ButtonToolTips.AlwaysActive); + this.registerApp(0, Settings.REDSTONE_CONTROLLED, RedstoneMode.LOW_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.ActiveWithoutSignal); + this.registerApp(1, Settings.REDSTONE_CONTROLLED, RedstoneMode.HIGH_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.ActiveWithSignal); + this.registerApp(2, Settings.REDSTONE_CONTROLLED, RedstoneMode.SIGNAL_PULSE, ButtonToolTips.RedstoneMode, ButtonToolTips.ActiveOnPulse); + + this.registerApp(0, Settings.REDSTONE_EMITTER, RedstoneMode.LOW_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.EmitLevelsBelow); + this.registerApp(1, Settings.REDSTONE_EMITTER, RedstoneMode.HIGH_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.EmitLevelAbove); + + this.registerApp(51, Settings.OPERATION_MODE, OperationMode.FILL, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToStorageCell); + this.registerApp(50, Settings.OPERATION_MODE, OperationMode.EMPTY, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToNetwork); + + this.registerApp(51, Settings.IO_DIRECTION, RelativeDirection.LEFT, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToStorageCell); + this.registerApp(50, Settings.IO_DIRECTION, RelativeDirection.RIGHT, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToNetwork); + + this.registerApp(48, Settings.SORT_DIRECTION, SortDir.ASCENDING, ButtonToolTips.SortOrder, ButtonToolTips.ToggleSortDirection); + this.registerApp(49, Settings.SORT_DIRECTION, SortDir.DESCENDING, ButtonToolTips.SortOrder, ButtonToolTips.ToggleSortDirection); + + this.registerApp(16 * 2 + 3, Settings.SEARCH_MODE, SearchBoxMode.AUTOSEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_Auto); + this.registerApp(16 * 2 + 4, Settings.SEARCH_MODE, SearchBoxMode.MANUAL_SEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_Standard); + this.registerApp(16 * 2 + 5, Settings.SEARCH_MODE, SearchBoxMode.JEI_AUTOSEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_JEIAuto); + this.registerApp(16 * 2 + 6, Settings.SEARCH_MODE, SearchBoxMode.JEI_MANUAL_SEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_JEIStandard); + this.registerApp(16 * 2 + 7, Settings.SEARCH_MODE, SearchBoxMode.AUTOSEARCH_KEEP, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_AutoKeep); + this.registerApp(16 * 2 + 8, Settings.SEARCH_MODE, SearchBoxMode.MANUAL_SEARCH_KEEP, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_StandardKeep); + this.registerApp(16 * 2 + 9, Settings.SEARCH_MODE, SearchBoxMode.JEI_AUTOSEARCH_KEEP, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_JEIAutoKeep); + this.registerApp(16 * 2 + 10, Settings.SEARCH_MODE, SearchBoxMode.JEI_MANUAL_SEARCH_KEEP, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_JEIStandardKeep); + + this.registerApp(16 * 5 + 3, Settings.LEVEL_TYPE, LevelType.ENERGY_LEVEL, ButtonToolTips.LevelType, ButtonToolTips.LevelType_Energy); + this.registerApp(16 * 4 + 3, Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL, ButtonToolTips.LevelType, ButtonToolTips.LevelType_Item); + + this.registerApp(16 * 13, Settings.TERMINAL_STYLE, TerminalStyle.TALL, ButtonToolTips.TerminalStyle, ButtonToolTips.TerminalStyle_Tall); + this.registerApp(16 * 13 + 1, Settings.TERMINAL_STYLE, TerminalStyle.SMALL, ButtonToolTips.TerminalStyle, ButtonToolTips.TerminalStyle_Small); + this.registerApp(16 * 13 + 2, Settings.TERMINAL_STYLE, TerminalStyle.FULL, ButtonToolTips.TerminalStyle, ButtonToolTips.TerminalStyle_Full); + + this.registerApp(64, Settings.SORT_BY, SortOrder.NAME, ButtonToolTips.SortBy, ButtonToolTips.ItemName); + this.registerApp(65, Settings.SORT_BY, SortOrder.AMOUNT, ButtonToolTips.SortBy, ButtonToolTips.NumberOfItems); + this.registerApp(68, Settings.SORT_BY, SortOrder.INVTWEAKS, ButtonToolTips.SortBy, ButtonToolTips.InventoryTweaks); + this.registerApp(69, Settings.SORT_BY, SortOrder.MOD, ButtonToolTips.SortBy, ButtonToolTips.Mod); + + this.registerApp(66, Settings.ACTIONS, ActionItems.WRENCH, ButtonToolTips.PartitionStorage, ButtonToolTips.PartitionStorageHint); + this.registerApp(6, Settings.ACTIONS, ActionItems.CLOSE, ButtonToolTips.Clear, ButtonToolTips.ClearSettings); + this.registerApp(6, Settings.ACTIONS, ActionItems.STASH, ButtonToolTips.Stash, ButtonToolTips.StashDesc); + + this.registerApp(6 + 4 * 16, Settings.ACTIONS, ActionItems.MULTIPLY_BY_TWO, ButtonToolTips.MultiplyByTwo, ButtonToolTips.MultiplyByTwoDesc); + this.registerApp(7 + 4 * 16, Settings.ACTIONS, ActionItems.MULTIPLY_BY_THREE, ButtonToolTips.MultiplyByThree, ButtonToolTips.MultiplyByThreeDesc); + this.registerApp(8 + 4 * 16, Settings.ACTIONS, ActionItems.INCREASE_BY_ONE, ButtonToolTips.IncreaseByOne, ButtonToolTips.IncreaseByOneDesc); + this.registerApp(9 + 4 * 16, Settings.ACTIONS, ActionItems.DIVIDE_BY_TWO, ButtonToolTips.DivideByTwo, ButtonToolTips.DivideByTwoDesc); + this.registerApp(10 + 4 * 16, Settings.ACTIONS, ActionItems.DIVIDE_BY_THREE, ButtonToolTips.DivideByThree, ButtonToolTips.DivideByThreeDesc); + this.registerApp(11 + 4 * 16, Settings.ACTIONS, ActionItems.DECREASE_BY_ONE, ButtonToolTips.DecreaseByOne, ButtonToolTips.DecreaseByOneDesc); + this.registerApp(12 + 4 * 16, Settings.ACTIONS, ActionItems.MAX_COUNT, ButtonToolTips.MaxCount, ButtonToolTips.MaxCountDesc); + + this.registerApp(6 + 5 * 16, Settings.ACTIONS, ActionItems.FREE_MOLECULAR_SLOT_SHORTCUT, ButtonToolTips.FreeMolecularSlotShortcut, ButtonToolTips.FreeMolecularSlotShortcutDesc); + this.registerApp(7 + 5 * 16, Settings.ACTIONS, ActionItems.TOGGLE_SHOW_FULL_INTERFACES_ON, ButtonToolTips.ToggleShowFullInterfaces, ButtonToolTips.ToggleShowFullInterfacesOnDesc); + this.registerApp(8 + 5 * 16, Settings.ACTIONS, ActionItems.TOGGLE_SHOW_FULL_INTERFACES_OFF, ButtonToolTips.ToggleShowFullInterfaces, ButtonToolTips.ToggleShowFullInterfacesOffDesc); + this.registerApp(6 + 6 * 16, Settings.ACTIONS, ActionItems.HIGHLIGHT_INTERFACE, ButtonToolTips.HighlightInterface, ""); + + this.registerApp(8, Settings.ACTIONS, ActionItems.ENCODE, ButtonToolTips.Encode, ButtonToolTips.EncodeDescription); + this.registerApp(4 + 3 * 16, Settings.ACTIONS, ItemSubstitution.ENABLED, ButtonToolTips.Substitutions, ButtonToolTips.SubstitutionsDescEnabled); + this.registerApp(7 + 3 * 16, Settings.ACTIONS, ItemSubstitution.DISABLED, ButtonToolTips.Substitutions, ButtonToolTips.SubstitutionsDescDisabled); + + this.registerApp(16, Settings.VIEW_MODE, ViewItems.STORED, ButtonToolTips.View, ButtonToolTips.StoredItems); + this.registerApp(18, Settings.VIEW_MODE, ViewItems.ALL, ButtonToolTips.View, ButtonToolTips.StoredCraftable); + this.registerApp(19, Settings.VIEW_MODE, ViewItems.CRAFTABLE, ButtonToolTips.View, ButtonToolTips.Craftable); + + this.registerApp(16 * 6, Settings.FUZZY_MODE, FuzzyMode.PERCENT_25, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_25); + this.registerApp(16 * 6 + 1, Settings.FUZZY_MODE, FuzzyMode.PERCENT_50, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_50); + this.registerApp(16 * 6 + 2, Settings.FUZZY_MODE, FuzzyMode.PERCENT_75, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_75); + this.registerApp(16 * 6 + 3, Settings.FUZZY_MODE, FuzzyMode.PERCENT_99, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_99); + this.registerApp(16 * 6 + 4, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL, ButtonToolTips.FuzzyMode, ButtonToolTips.FZIgnoreAll); + + this.registerApp(80, Settings.FULLNESS_MODE, FullnessMode.EMPTY, ButtonToolTips.OperationMode, ButtonToolTips.MoveWhenEmpty); + this.registerApp(81, Settings.FULLNESS_MODE, FullnessMode.HALF, ButtonToolTips.OperationMode, ButtonToolTips.MoveWhenWorkIsDone); + this.registerApp(82, Settings.FULLNESS_MODE, FullnessMode.FULL, ButtonToolTips.OperationMode, ButtonToolTips.MoveWhenFull); + + this.registerApp(16 + 5, Settings.BLOCK, YesNo.YES, ButtonToolTips.InterfaceBlockingMode, ButtonToolTips.Blocking); + this.registerApp(16 + 4, Settings.BLOCK, YesNo.NO, ButtonToolTips.InterfaceBlockingMode, ButtonToolTips.NonBlocking); + + this.registerApp(16 + 3, Settings.CRAFT_ONLY, YesNo.YES, ButtonToolTips.Craft, ButtonToolTips.CraftOnly); + this.registerApp(16 + 2, Settings.CRAFT_ONLY, YesNo.NO, ButtonToolTips.Craft, ButtonToolTips.CraftEither); + + this.registerApp(16 * 11 + 2, Settings.CRAFT_VIA_REDSTONE, YesNo.YES, ButtonToolTips.EmitterMode, ButtonToolTips.CraftViaRedstone); + this.registerApp(16 * 11 + 1, Settings.CRAFT_VIA_REDSTONE, YesNo.NO, ButtonToolTips.EmitterMode, ButtonToolTips.EmitWhenCrafting); + + this.registerApp(16 * 3 + 5, Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY, ButtonToolTips.ReportInaccessibleItems, ButtonToolTips.ReportInaccessibleItemsNo); + this.registerApp(16 * 3 + 6, Settings.STORAGE_FILTER, StorageFilter.NONE, ButtonToolTips.ReportInaccessibleItems, ButtonToolTips.ReportInaccessibleItemsYes); + + this.registerApp(16 * 14, Settings.PLACE_BLOCK, YesNo.YES, ButtonToolTips.BlockPlacement, ButtonToolTips.BlockPlacementYes); + this.registerApp(16 * 14 + 1, Settings.PLACE_BLOCK, YesNo.NO, ButtonToolTips.BlockPlacement, ButtonToolTips.BlockPlacementNo); + + this.registerApp(16 * 15, Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT, ButtonToolTips.SchedulingMode, ButtonToolTips.SchedulingModeDefault); + this.registerApp(16 * 15 + 1, Settings.SCHEDULING_MODE, SchedulingMode.ROUNDROBIN, ButtonToolTips.SchedulingMode, ButtonToolTips.SchedulingModeRoundRobin); + this.registerApp(16 * 15 + 2, Settings.SCHEDULING_MODE, SchedulingMode.RANDOM, ButtonToolTips.SchedulingMode, ButtonToolTips.SchedulingModeRandom); + } + } + + private void registerApp(final int iconIndex, final Settings setting, final Enum val, final ButtonToolTips title, final Object hint) { + final ButtonAppearance a = new ButtonAppearance(); + a.displayName = title.getUnlocalized(); + a.displayValue = (String) (hint instanceof String ? hint : ((ButtonToolTips) hint).getUnlocalized()); + a.index = iconIndex; + appearances.put(new EnumPair(setting, val), a); + } + + public void setVisibility(final boolean vis) { + this.visible = vis; + this.enabled = vis; + } + + @Override + public void drawButton(final Minecraft par1Minecraft, final int par2, final int par3, float partial) { + if (this.visible) { + final int iconIndex = this.getIconIndex(); + + if (this.halfSize) { + this.width = 8; + this.height = 8; + + GlStateManager.pushMatrix(); + GlStateManager.translate(this.x, this.y, 0.0F); + GlStateManager.scale(0.5f, 0.5f, 0.5f); + + if (this.enabled) { + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + } else { + GlStateManager.color(0.5f, 0.5f, 0.5f, 1.0f); + } + + par1Minecraft.renderEngine.bindTexture(new ResourceLocation("appliedenergistics2", "textures/guis/states.png")); + this.hovered = par2 >= this.x && par3 >= this.y && par2 < this.x + this.width && par3 < this.y + this.height; + + final int uv_y = (int) Math.floor(iconIndex / 16); + final int uv_x = iconIndex - uv_y * 16; + + this.drawTexturedModalRect(0, 0, 256 - 16, 256 - 16, 16, 16); + this.drawTexturedModalRect(0, 0, uv_x * 16, uv_y * 16, 16, 16); + this.mouseDragged(par1Minecraft, par2, par3); + + GlStateManager.popMatrix(); + } else { + if (this.enabled) { + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + } else { + GlStateManager.color(0.5f, 0.5f, 0.5f, 1.0f); + } + + par1Minecraft.renderEngine.bindTexture(new ResourceLocation("appliedenergistics2", "textures/guis/states.png")); + this.hovered = par2 >= this.x && par3 >= this.y && par2 < this.x + this.width && par3 < this.y + this.height; + + final int uv_y = (int) Math.floor(iconIndex / 16); + final int uv_x = iconIndex - uv_y * 16; + + this.drawTexturedModalRect(this.x, this.y, 256 - 16, 256 - 16, 16, 16); + this.drawTexturedModalRect(this.x, this.y, uv_x * 16, uv_y * 16, 16, 16); + this.mouseDragged(par1Minecraft, par2, par3); + } + } + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + } + + private int getIconIndex() { + if (this.buttonSetting != null && this.currentValue != null) { + final ButtonAppearance app = appearances.get(new EnumPair(this.buttonSetting, this.currentValue)); + if (app == null) { + return 256 - 1; + } + return app.index; + } + return 256 - 1; + } + + public Settings getSetting() { + return (Settings) this.buttonSetting; + } + + public Enum getCurrentValue() { + return this.currentValue; + } + + @Override + public String getMessage() { + String displayName = null; + String displayValue = null; + + if (this.buttonSetting != null && this.currentValue != null) { + final ButtonAppearance buttonAppearance = appearances.get(new EnumPair(this.buttonSetting, this.currentValue)); + if (buttonAppearance == null) { + return "No Such Message"; + } + + displayName = buttonAppearance.displayName; + displayValue = buttonAppearance.displayValue; + } + + if (displayName != null) { + String name = I18n.translateToLocal(displayName); + String value = I18n.translateToLocal(displayValue); + + if (name == null || name.isEmpty()) { + name = displayName; + } + if (value == null || value.isEmpty()) { + value = displayValue; + } + + if (this.fillVar != null) { + value = COMPILE.matcher(value).replaceFirst(this.fillVar); + } + + value = PATTERN_NEW_LINE.matcher(value).replaceAll("\n"); + final StringBuilder sb = new StringBuilder(value); + + int i = sb.lastIndexOf("\n"); + if (i <= 0) { + i = 0; + } + while (i + 30 < sb.length() && (i = sb.lastIndexOf(" ", i + 30)) != -1) { + sb.replace(i, i + 1, "\n"); + } + + return name + '\n' + sb; + } + return null; + } + + @Override + public int xPos() { + return this.x; + } + + @Override + public int yPos() { + return this.y; + } + + @Override + public int getWidth() { + return this.halfSize ? 8 : 16; + } + + @Override + public int getHeight() { + return this.halfSize ? 8 : 16; + } + + @Override + public boolean isVisible() { + return this.visible; + } + + public void set(final Enum e) { + if (this.currentValue != e) { + this.currentValue = e; + } + } + + public boolean isHalfSize() { + return this.halfSize; + } + + public void setHalfSize(final boolean halfSize) { + this.halfSize = halfSize; + } + + public String getFillVar() { + return this.fillVar; + } + + public void setFillVar(final String fillVar) { + this.fillVar = fillVar; + } + + private static final class EnumPair { + + final Enum setting; + final Enum value; + + EnumPair(final Enum a, final Enum b) { + this.setting = a; + this.value = b; + } + + @Override + public int hashCode() { + return this.setting.hashCode() ^ this.value.hashCode(); + } + + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final EnumPair other = (EnumPair) obj; + return other.setting == this.setting && other.value == this.value; + } + } + + private static class ButtonAppearance { + public int index; + public String displayName; + public String displayValue; + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java b/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java index 1443b15ae..bab4aa079 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java +++ b/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java @@ -23,41 +23,30 @@ import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiTextField; -public class GuiNumberBox extends GuiTextField -{ +public class GuiNumberBox extends GuiTextField { - private final Class type; + private final Class type; - public GuiNumberBox( final FontRenderer fontRenderer, final int x, final int y, final int width, final int height, final Class type ) - { - super( 0, fontRenderer, x, y, width, height ); - this.type = type; - } + public GuiNumberBox(final FontRenderer fontRenderer, final int x, final int y, final int width, final int height, final Class type) { + super(0, fontRenderer, x, y, width, height); + this.type = type; + } - @Override - public void writeText( final String selectedText ) - { - final String original = this.getText(); - super.writeText( selectedText ); + @Override + public void writeText(final String selectedText) { + final String original = this.getText(); + super.writeText(selectedText); - try - { - if( this.type == int.class || this.type == Integer.class ) - { - Integer.parseInt( this.getText() ); - } - else if( this.type == long.class || this.type == Long.class ) - { - Long.parseLong( this.getText() ); - } - else if( this.type == double.class || this.type == Double.class ) - { - Double.parseDouble( this.getText() ); - } - } - catch( final NumberFormatException e ) - { - this.setText( original ); - } - } + try { + if (this.type == int.class || this.type == Integer.class) { + Integer.parseInt(this.getText()); + } else if (this.type == long.class || this.type == Long.class) { + Long.parseLong(this.getText()); + } else if (this.type == double.class || this.type == Double.class) { + Double.parseDouble(this.getText()); + } + } catch (final NumberFormatException e) { + this.setText(original); + } + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java b/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java index 0108e0add..a13c85e42 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java +++ b/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java @@ -19,118 +19,100 @@ package appeng.client.gui.widgets; +import appeng.container.interfaces.IProgressProvider; +import appeng.core.localization.GuiText; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.util.ResourceLocation; -import appeng.container.interfaces.IProgressProvider; -import appeng.core.localization.GuiText; +public class GuiProgressBar extends GuiButton implements ITooltip { -public class GuiProgressBar extends GuiButton implements ITooltip -{ + private final IProgressProvider source; + private final ResourceLocation texture; + private final int fill_u; + private final int fill_v; + private final Direction layout; + private final String titleName; + private String fullMsg; - private final IProgressProvider source; - private final ResourceLocation texture; - private final int fill_u; - private final int fill_v; - private final Direction layout; - private final String titleName; - private String fullMsg; + public GuiProgressBar(final IProgressProvider source, final String texture, final int posX, final int posY, final int u, final int y, final int width, final int height, final Direction dir) { + this(source, texture, posX, posY, u, y, width, height, dir, null); + } - public GuiProgressBar( final IProgressProvider source, final String texture, final int posX, final int posY, final int u, final int y, final int width, final int height, final Direction dir ) - { - this( source, texture, posX, posY, u, y, width, height, dir, null ); - } + public GuiProgressBar(final IProgressProvider source, final String texture, final int posX, final int posY, final int u, final int y, final int width, final int height, final Direction dir, final String title) { + super(posX, posY, width, ""); + this.source = source; + this.x = posX; + this.y = posY; + this.texture = new ResourceLocation("appliedenergistics2", "textures/" + texture); + this.width = width; + this.height = height; + this.fill_u = u; + this.fill_v = y; + this.layout = dir; + this.titleName = title; + } - public GuiProgressBar( final IProgressProvider source, final String texture, final int posX, final int posY, final int u, final int y, final int width, final int height, final Direction dir, final String title ) - { - super( posX, posY, width, "" ); - this.source = source; - this.x = posX; - this.y = posY; - this.texture = new ResourceLocation( "appliedenergistics2", "textures/" + texture ); - this.width = width; - this.height = height; - this.fill_u = u; - this.fill_v = y; - this.layout = dir; - this.titleName = title; - } + @Override + public void drawButton(final Minecraft par1Minecraft, final int par2, final int par3, final float partial) { + if (this.visible) { + par1Minecraft.getTextureManager().bindTexture(this.texture); + final int max = this.source.getMaxProgress(); + final int current = this.source.getCurrentProgress(); - @Override - public void drawButton( final Minecraft par1Minecraft, final int par2, final int par3, final float partial ) - { - if( this.visible ) - { - par1Minecraft.getTextureManager().bindTexture( this.texture ); - final int max = this.source.getMaxProgress(); - final int current = this.source.getCurrentProgress(); + if (this.layout == Direction.VERTICAL) { + final int diff = this.height - (max > 0 ? (this.height * current) / max : 0); + this.drawTexturedModalRect(this.x, this.y + diff, this.fill_u, this.fill_v + diff, this.width, this.height - diff); + } else { + final int diff = this.width - (max > 0 ? (this.width * current) / max : 0); + this.drawTexturedModalRect(this.x, this.y, this.fill_u + diff, this.fill_v, this.width - diff, this.height); + } - if( this.layout == Direction.VERTICAL ) - { - final int diff = this.height - ( max > 0 ? ( this.height * current ) / max : 0 ); - this.drawTexturedModalRect( this.x, this.y + diff, this.fill_u, this.fill_v + diff, this.width, this.height - diff ); - } - else - { - final int diff = this.width - ( max > 0 ? ( this.width * current ) / max : 0 ); - this.drawTexturedModalRect( this.x, this.y, this.fill_u + diff, this.fill_v, this.width - diff, this.height ); - } + this.mouseDragged(par1Minecraft, par2, par3); + } + } - this.mouseDragged( par1Minecraft, par2, par3 ); - } - } + public void setFullMsg(final String msg) { + this.fullMsg = msg; + } - public void setFullMsg( final String msg ) - { - this.fullMsg = msg; - } + @Override + public String getMessage() { + if (this.fullMsg != null) { + return this.fullMsg; + } - @Override - public String getMessage() - { - if( this.fullMsg != null ) - { - return this.fullMsg; - } + return (this.titleName != null ? this.titleName : "") + '\n' + this.source.getCurrentProgress() + ' ' + GuiText.Of.getLocal() + ' ' + this.source + .getMaxProgress(); + } - return ( this.titleName != null ? this.titleName : "" ) + '\n' + this.source.getCurrentProgress() + ' ' + GuiText.Of.getLocal() + ' ' + this.source - .getMaxProgress(); - } + @Override + public int xPos() { + return this.x - 2; + } - @Override - public int xPos() - { - return this.x - 2; - } + @Override + public int yPos() { + return this.y - 2; + } - @Override - public int yPos() - { - return this.y - 2; - } + @Override + public int getWidth() { + return this.width + 4; + } - @Override - public int getWidth() - { - return this.width + 4; - } + @Override + public int getHeight() { + return this.height + 4; + } - @Override - public int getHeight() - { - return this.height + 4; - } + @Override + public boolean isVisible() { + return true; + } - @Override - public boolean isVisible() - { - return true; - } - - public enum Direction - { - HORIZONTAL, VERTICAL - } + public enum Direction { + HORIZONTAL, VERTICAL + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java b/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java index 9f71d92fc..dd25530c5 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java +++ b/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java @@ -19,137 +19,113 @@ package appeng.client.gui.widgets; +import appeng.client.gui.AEBaseGui; import net.minecraft.client.renderer.GlStateManager; -import appeng.client.gui.AEBaseGui; +public class GuiScrollbar implements IScrollSource { -public class GuiScrollbar implements IScrollSource -{ + private int displayX = 0; + private int displayY = 0; + private int width = 12; + private int height = 16; + private int pageSize = 1; - private int displayX = 0; - private int displayY = 0; - private int width = 12; - private int height = 16; - private int pageSize = 1; + private int maxScroll = 0; + private int minScroll = 0; + private int currentScroll = 0; - private int maxScroll = 0; - private int minScroll = 0; - private int currentScroll = 0; + public void draw(final AEBaseGui g) { + g.bindTexture("minecraft", "gui/container/creative_inventory/tabs.png"); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - public void draw( final AEBaseGui g ) - { - g.bindTexture( "minecraft", "gui/container/creative_inventory/tabs.png" ); - GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f ); + if (this.getRange() == 0) { + g.drawTexturedModalRect(this.displayX, this.displayY, 232 + this.width, 0, this.width, 15); + } else { + final int offset = (this.currentScroll - this.minScroll) * (this.height - 15) / this.getRange(); + g.drawTexturedModalRect(this.displayX, offset + this.displayY, 232, 0, this.width, 15); + } + } - if( this.getRange() == 0 ) - { - g.drawTexturedModalRect( this.displayX, this.displayY, 232 + this.width, 0, this.width, 15 ); - } - else - { - final int offset = ( this.currentScroll - this.minScroll ) * ( this.height - 15 ) / this.getRange(); - g.drawTexturedModalRect( this.displayX, offset + this.displayY, 232, 0, this.width, 15 ); - } - } + private int getRange() { + return this.maxScroll - this.minScroll; + } - private int getRange() - { - return this.maxScroll - this.minScroll; - } + public int getLeft() { + return this.displayX; + } - public int getLeft() - { - return this.displayX; - } + public GuiScrollbar setLeft(final int v) { + this.displayX = v; + return this; + } - public GuiScrollbar setLeft( final int v ) - { - this.displayX = v; - return this; - } + public int getTop() { + return this.displayY; + } - public int getTop() - { - return this.displayY; - } + public GuiScrollbar setTop(final int v) { + this.displayY = v; + return this; + } - public GuiScrollbar setTop( final int v ) - { - this.displayY = v; - return this; - } + public int getWidth() { + return this.width; + } - public int getWidth() - { - return this.width; - } + public GuiScrollbar setWidth(final int v) { + this.width = v; + return this; + } - public GuiScrollbar setWidth( final int v ) - { - this.width = v; - return this; - } + public int getHeight() { + return this.height; + } - public int getHeight() - { - return this.height; - } + public GuiScrollbar setHeight(final int v) { + this.height = v; + return this; + } - public GuiScrollbar setHeight( final int v ) - { - this.height = v; - return this; - } + public void setRange(final int min, final int max, final int pageSize) { + this.minScroll = min; + this.maxScroll = max; + this.pageSize = pageSize; - public void setRange( final int min, final int max, final int pageSize ) - { - this.minScroll = min; - this.maxScroll = max; - this.pageSize = pageSize; + if (this.minScroll > this.maxScroll) { + this.maxScroll = this.minScroll; + } - if( this.minScroll > this.maxScroll ) - { - this.maxScroll = this.minScroll; - } + this.applyRange(); + } - this.applyRange(); - } + private void applyRange() { + this.currentScroll = Math.max(Math.min(this.currentScroll, this.maxScroll), this.minScroll); + } - private void applyRange() - { - this.currentScroll = Math.max( Math.min( this.currentScroll, this.maxScroll ), this.minScroll ); - } + @Override + public int getCurrentScroll() { + return this.currentScroll; + } - @Override - public int getCurrentScroll() - { - return this.currentScroll; - } + public void click(final AEBaseGui aeBaseGui, final int x, final int y) { + if (this.getRange() == 0) { + return; + } - public void click( final AEBaseGui aeBaseGui, final int x, final int y ) - { - if( this.getRange() == 0 ) - { - return; - } + if (x > this.displayX && x <= this.displayX + this.width) { + if (y > this.displayY && y <= this.displayY + this.height) { + this.currentScroll = (y - this.displayY); + this.currentScroll = this.minScroll + ((this.currentScroll * 2 * this.getRange() / this.height)); + this.currentScroll = (this.currentScroll + 1) >> 1; + this.applyRange(); + } + } + } - if( x > this.displayX && x <= this.displayX + this.width ) - { - if( y > this.displayY && y <= this.displayY + this.height ) - { - this.currentScroll = ( y - this.displayY ); - this.currentScroll = this.minScroll + ( ( this.currentScroll * 2 * this.getRange() / this.height ) ); - this.currentScroll = ( this.currentScroll + 1 ) >> 1; - this.applyRange(); - } - } - } - - public void wheel( int delta ) - { - delta = Math.max( Math.min( -delta, 1 ), -1 ); - this.currentScroll += delta * this.pageSize; - this.applyRange(); - } + public void wheel(int delta) { + delta = Math.max(Math.min(-delta, 1), -1); + this.currentScroll += delta * this.pageSize; + this.applyRange(); + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiTabButton.java b/src/main/java/appeng/client/gui/widgets/GuiTabButton.java index 5ccc035e6..f01bd127e 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiTabButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiTabButton.java @@ -28,132 +28,117 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; -public class GuiTabButton extends GuiButton implements ITooltip -{ - private final RenderItem itemRenderer; - private final String message; - private int hideEdge = 0; - private int myIcon = -1; - private ItemStack myItem; +public class GuiTabButton extends GuiButton implements ITooltip { + private final RenderItem itemRenderer; + private final String message; + private int hideEdge = 0; + private int myIcon = -1; + private ItemStack myItem; - public GuiTabButton( final int x, final int y, final int ico, final String message, final RenderItem ir ) - { - super( 0, 0, 16, "" ); + public GuiTabButton(final int x, final int y, final int ico, final String message, final RenderItem ir) { + super(0, 0, 16, ""); - this.x = x; - this.y = y; - this.width = 22; - this.height = 22; - this.myIcon = ico; - this.message = message; - this.itemRenderer = ir; - } + this.x = x; + this.y = y; + this.width = 22; + this.height = 22; + this.myIcon = ico; + this.message = message; + this.itemRenderer = ir; + } - /** - * Using itemstack as an icon - * - * @param x x pos of button - * @param y y pos of button - * @param ico used icon - * @param message mouse over message - * @param ir renderer - */ - public GuiTabButton( final int x, final int y, final ItemStack ico, final String message, final RenderItem ir ) - { - super( 0, 0, 16, "" ); - this.x = x; - this.y = y; - this.width = 22; - this.height = 22; - this.myItem = ico; - this.message = message; - this.itemRenderer = ir; - } + /** + * Using itemstack as an icon + * + * @param x x pos of button + * @param y y pos of button + * @param ico used icon + * @param message mouse over message + * @param ir renderer + */ + public GuiTabButton(final int x, final int y, final ItemStack ico, final String message, final RenderItem ir) { + super(0, 0, 16, ""); + this.x = x; + this.y = y; + this.width = 22; + this.height = 22; + this.myItem = ico; + this.message = message; + this.itemRenderer = ir; + } - @Override - public void drawButton( final Minecraft minecraft, final int x, final int y, float partial ) - { - if( this.visible ) - { - GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f ); - minecraft.renderEngine.bindTexture( new ResourceLocation( "appliedenergistics2", "textures/guis/states.png" ) ); - this.hovered = x >= this.x && y >= this.y && x < this.x + this.width && y < this.y + this.height; + @Override + public void drawButton(final Minecraft minecraft, final int x, final int y, float partial) { + if (this.visible) { + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + minecraft.renderEngine.bindTexture(new ResourceLocation("appliedenergistics2", "textures/guis/states.png")); + this.hovered = x >= this.x && y >= this.y && x < this.x + this.width && y < this.y + this.height; - int uv_x = ( this.hideEdge > 0 ? 11 : 13 ); + int uv_x = (this.hideEdge > 0 ? 11 : 13); - final int offsetX = this.hideEdge > 0 ? 1 : 0; + final int offsetX = this.hideEdge > 0 ? 1 : 0; - this.drawTexturedModalRect( this.x, this.y, uv_x * 16, 0, 25, 22 ); + this.drawTexturedModalRect(this.x, this.y, uv_x * 16, 0, 25, 22); - if( this.myIcon >= 0 ) - { - final int uv_y = (int) Math.floor( this.myIcon / 16 ); - uv_x = this.myIcon - uv_y * 16; + if (this.myIcon >= 0) { + final int uv_y = (int) Math.floor(this.myIcon / 16); + uv_x = this.myIcon - uv_y * 16; - this.drawTexturedModalRect( offsetX + this.x + 3, this.y + 3, uv_x * 16, uv_y * 16, 16, 16 ); - } + this.drawTexturedModalRect(offsetX + this.x + 3, this.y + 3, uv_x * 16, uv_y * 16, 16, 16); + } - this.mouseDragged( minecraft, x, y ); + this.mouseDragged(minecraft, x, y); - if( this.myItem != null ) - { - this.zLevel = 100.0F; - this.itemRenderer.zLevel = 100.0F; + if (this.myItem != null) { + this.zLevel = 100.0F; + this.itemRenderer.zLevel = 100.0F; - GlStateManager.enableDepth(); - RenderHelper.enableGUIStandardItemLighting(); - this.itemRenderer.renderItemAndEffectIntoGUI( this.myItem, offsetX + this.x + 3, this.y + 3 ); - GlStateManager.disableDepth(); + GlStateManager.enableDepth(); + RenderHelper.enableGUIStandardItemLighting(); + this.itemRenderer.renderItemAndEffectIntoGUI(this.myItem, offsetX + this.x + 3, this.y + 3); + GlStateManager.disableDepth(); - this.itemRenderer.zLevel = 0.0F; - this.zLevel = 0.0F; - } - } - } + this.itemRenderer.zLevel = 0.0F; + this.zLevel = 0.0F; + } + } + } - @Override - public String getMessage() - { - return this.message; - } + @Override + public String getMessage() { + return this.message; + } - @Override - public int xPos() - { - return this.x; - } + @Override + public int xPos() { + return this.x; + } - @Override - public int yPos() - { - return this.y; - } + @Override + public int yPos() { + return this.y; + } - @Override - public int getWidth() - { - return 22; - } + @Override + public int getWidth() { + return 22; + } - @Override - public int getHeight() - { - return 22; - } + @Override + public int getHeight() { + return 22; + } - @Override - public boolean isVisible() - { - return this.visible; - } + @Override + public boolean isVisible() { + return this.visible; + } - public int getHideEdge() - { - return this.hideEdge; - } + public int getHideEdge() { + return this.hideEdge; + } - public void setHideEdge( final int hideEdge ) - { - this.hideEdge = hideEdge; - } + public void setHideEdge(final int hideEdge) { + this.hideEdge = hideEdge; + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java b/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java index 59894da65..6b48abf09 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java @@ -19,131 +19,114 @@ package appeng.client.gui.widgets; -import java.util.regex.Pattern; - import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.translation.I18n; +import java.util.regex.Pattern; -public class GuiToggleButton extends GuiButton implements ITooltip -{ - private static final Pattern PATTERN_NEW_LINE = Pattern.compile( "\\n", Pattern.LITERAL ); - private final int iconIdxOn; - private final int iconIdxOff; - private final String displayName; - private final String displayHint; +public class GuiToggleButton extends GuiButton implements ITooltip { + private static final Pattern PATTERN_NEW_LINE = Pattern.compile("\\n", Pattern.LITERAL); + private final int iconIdxOn; + private final int iconIdxOff; - private boolean isActive; + private final String displayName; + private final String displayHint; - public GuiToggleButton( final int x, final int y, final int on, final int off, final String displayName, final String displayHint ) - { - super( 0, 0, 16, "" ); - this.iconIdxOn = on; - this.iconIdxOff = off; - this.displayName = displayName; - this.displayHint = displayHint; - this.x = x; - this.y = y; - this.width = 16; - this.height = 16; - } + private boolean isActive; - public void setState( final boolean isOn ) - { - this.isActive = isOn; - } + public GuiToggleButton(final int x, final int y, final int on, final int off, final String displayName, final String displayHint) { + super(0, 0, 16, ""); + this.iconIdxOn = on; + this.iconIdxOff = off; + this.displayName = displayName; + this.displayHint = displayHint; + this.x = x; + this.y = y; + this.width = 16; + this.height = 16; + } - @Override - public void drawButton( final Minecraft par1Minecraft, final int par2, final int par3, final float partial ) - { - if( this.visible ) - { - final int iconIndex = this.getIconIndex(); + public void setState(final boolean isOn) { + this.isActive = isOn; + } - GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f ); - par1Minecraft.renderEngine.bindTexture( new ResourceLocation( "appliedenergistics2", "textures/guis/states.png" ) ); - this.hovered = par2 >= this.x && par3 >= this.y && par2 < this.x + this.width && par3 < this.y + this.height; + @Override + public void drawButton(final Minecraft par1Minecraft, final int par2, final int par3, final float partial) { + if (this.visible) { + final int iconIndex = this.getIconIndex(); - final int uv_y = (int) Math.floor( iconIndex / 16 ); - final int uv_x = iconIndex - uv_y * 16; + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + par1Minecraft.renderEngine.bindTexture(new ResourceLocation("appliedenergistics2", "textures/guis/states.png")); + this.hovered = par2 >= this.x && par3 >= this.y && par2 < this.x + this.width && par3 < this.y + this.height; - this.drawTexturedModalRect( this.x, this.y, 256 - 16, 256 - 16, 16, 16 ); - this.drawTexturedModalRect( this.x, this.y, uv_x * 16, uv_y * 16, 16, 16 ); - this.mouseDragged( par1Minecraft, par2, par3 ); - } - } + final int uv_y = (int) Math.floor(iconIndex / 16); + final int uv_x = iconIndex - uv_y * 16; - private int getIconIndex() - { - return this.isActive ? this.iconIdxOn : this.iconIdxOff; - } + this.drawTexturedModalRect(this.x, this.y, 256 - 16, 256 - 16, 16, 16); + this.drawTexturedModalRect(this.x, this.y, uv_x * 16, uv_y * 16, 16, 16); + this.mouseDragged(par1Minecraft, par2, par3); + } + } - @Override - public String getMessage() - { - if( this.displayName != null ) - { - String name = I18n.translateToLocal( this.displayName ); - String value = I18n.translateToLocal( this.displayHint ); + private int getIconIndex() { + return this.isActive ? this.iconIdxOn : this.iconIdxOff; + } - if( name == null || name.isEmpty() ) - { - name = this.displayName; - } - if( value == null || value.isEmpty() ) - { - value = this.displayHint; - } + @Override + public String getMessage() { + if (this.displayName != null) { + String name = I18n.translateToLocal(this.displayName); + String value = I18n.translateToLocal(this.displayHint); - value = PATTERN_NEW_LINE.matcher( value ).replaceAll( "\n" ); - final StringBuilder sb = new StringBuilder( value ); + if (name == null || name.isEmpty()) { + name = this.displayName; + } + if (value == null || value.isEmpty()) { + value = this.displayHint; + } - int i = sb.lastIndexOf( "\n" ); - if( i <= 0 ) - { - i = 0; - } - while( i + 30 < sb.length() && ( i = sb.lastIndexOf( " ", i + 30 ) ) != -1 ) - { - sb.replace( i, i + 1, "\n" ); - } + value = PATTERN_NEW_LINE.matcher(value).replaceAll("\n"); + final StringBuilder sb = new StringBuilder(value); - return name + '\n' + sb; - } - return null; - } + int i = sb.lastIndexOf("\n"); + if (i <= 0) { + i = 0; + } + while (i + 30 < sb.length() && (i = sb.lastIndexOf(" ", i + 30)) != -1) { + sb.replace(i, i + 1, "\n"); + } - @Override - public int xPos() - { - return this.x; - } + return name + '\n' + sb; + } + return null; + } - @Override - public int yPos() - { - return this.y; - } + @Override + public int xPos() { + return this.x; + } - @Override - public int getWidth() - { - return 16; - } + @Override + public int yPos() { + return this.y; + } - @Override - public int getHeight() - { - return 16; - } + @Override + public int getWidth() { + return 16; + } - @Override - public boolean isVisible() - { - return this.visible; - } + @Override + public int getHeight() { + return 16; + } + + @Override + public boolean isVisible() { + return this.visible; + } } diff --git a/src/main/java/appeng/client/gui/widgets/IScrollSource.java b/src/main/java/appeng/client/gui/widgets/IScrollSource.java index 10829091b..247e94c8b 100644 --- a/src/main/java/appeng/client/gui/widgets/IScrollSource.java +++ b/src/main/java/appeng/client/gui/widgets/IScrollSource.java @@ -19,8 +19,7 @@ package appeng.client.gui.widgets; -public interface IScrollSource -{ +public interface IScrollSource { - int getCurrentScroll(); + int getCurrentScroll(); } diff --git a/src/main/java/appeng/client/gui/widgets/ISortSource.java b/src/main/java/appeng/client/gui/widgets/ISortSource.java index 534dcb0dc..281363cb5 100644 --- a/src/main/java/appeng/client/gui/widgets/ISortSource.java +++ b/src/main/java/appeng/client/gui/widgets/ISortSource.java @@ -23,21 +23,20 @@ import appeng.api.config.SortDir; import appeng.api.config.ViewItems; -public interface ISortSource -{ +public interface ISortSource { - /** - * @return Sor - */ - Enum getSortBy(); + /** + * @return Sor + */ + Enum getSortBy(); - /** - * @return {@link SortDir} - */ - Enum getSortDir(); + /** + * @return {@link SortDir} + */ + Enum getSortDir(); - /** - * @return {@link ViewItems} - */ - Enum getSortDisplay(); + /** + * @return {@link ViewItems} + */ + Enum getSortDisplay(); } diff --git a/src/main/java/appeng/client/gui/widgets/ITooltip.java b/src/main/java/appeng/client/gui/widgets/ITooltip.java index 232992ac6..4bcc8a148 100644 --- a/src/main/java/appeng/client/gui/widgets/ITooltip.java +++ b/src/main/java/appeng/client/gui/widgets/ITooltip.java @@ -22,46 +22,45 @@ package appeng.client.gui.widgets; /** * AEBaseGui controlled Tooltip Interface. */ -public interface ITooltip -{ +public interface ITooltip { - /** - * returns the tooltip message. - * - * @return tooltip message - */ - String getMessage(); + /** + * returns the tooltip message. + * + * @return tooltip message + */ + String getMessage(); - /** - * x Location for the object that triggers the tooltip. - * - * @return xPosition - */ - int xPos(); + /** + * x Location for the object that triggers the tooltip. + * + * @return xPosition + */ + int xPos(); - /** - * y Location for the object that triggers the tooltip. - * - * @return yPosition - */ - int yPos(); + /** + * y Location for the object that triggers the tooltip. + * + * @return yPosition + */ + int yPos(); - /** - * Width of the object that triggers the tooltip. - * - * @return width - */ - int getWidth(); + /** + * Width of the object that triggers the tooltip. + * + * @return width + */ + int getWidth(); - /** - * Height for the object that triggers the tooltip. - * - * @return height - */ - int getHeight(); + /** + * Height for the object that triggers the tooltip. + * + * @return height + */ + int getHeight(); - /** - * @return true if button being drawn - */ - boolean isVisible(); + /** + * @return true if button being drawn + */ + boolean isVisible(); } diff --git a/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java b/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java index 330f811a1..06d9d1cd2 100644 --- a/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java +++ b/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java @@ -33,197 +33,179 @@ import org.lwjgl.input.Keyboard; * You can initialize it over the full element span. * The mouse click area is increased to the full element * subtracted with the defined padding. - * + *

* The rendering does pay attention to the size of the '_' caret. */ -public class MEGuiTextField extends GuiTextField -{ - private static final int PADDING = 2; +public class MEGuiTextField extends GuiTextField { + private static final int PADDING = 2; - private final int _xPos; - private final int _yPos; - private final int _width; - private final int _height; - private final int _fontPad; - private int selectionColor = 0xFF00FF00; + private final int _xPos; + private final int _yPos; + private final int _width; + private final int _height; + private final int _fontPad; + private int selectionColor = 0xFF00FF00; - /** - * Uses the values to instantiate a padded version of a text field. - * Pays attention to the '_' caret. - * - * @param fontRenderer renderer for the strings - * @param xPos absolute left position - * @param yPos absolute top position - * @param width absolute width - * @param height absolute height - */ - public MEGuiTextField( final FontRenderer fontRenderer, final int xPos, final int yPos, final int width, final int height ) - { - super( 0, fontRenderer, xPos + PADDING, yPos + PADDING, width - 2 * PADDING - fontRenderer.getCharWidth( '_' ), height - 2 * PADDING ); + /** + * Uses the values to instantiate a padded version of a text field. + * Pays attention to the '_' caret. + * + * @param fontRenderer renderer for the strings + * @param xPos absolute left position + * @param yPos absolute top position + * @param width absolute width + * @param height absolute height + */ + public MEGuiTextField(final FontRenderer fontRenderer, final int xPos, final int yPos, final int width, final int height) { + super(0, fontRenderer, xPos + PADDING, yPos + PADDING, width - 2 * PADDING - fontRenderer.getCharWidth('_'), height - 2 * PADDING); - this._fontPad = fontRenderer.getCharWidth( '_' ); - this._xPos = xPos; - this._yPos = yPos; - this._width = width; - this._height = height; - } + this._fontPad = fontRenderer.getCharWidth('_'); + this._xPos = xPos; + this._yPos = yPos; + this._width = width; + this._height = height; + } - public void onTextChange(final String oldText) {} + public void onTextChange(final String oldText) { + } - @Override - public boolean mouseClicked( final int xPos, final int yPos, final int button ) - { - super.mouseClicked( xPos, yPos, button ); + @Override + public boolean mouseClicked(final int xPos, final int yPos, final int button) { + super.mouseClicked(xPos, yPos, button); - final boolean requiresFocus = this.isMouseIn( xPos, yPos ); - if( !this.isFocused() ) - { - this.setFocused( requiresFocus ); - } + final boolean requiresFocus = this.isMouseIn(xPos, yPos); + if (!this.isFocused()) { + this.setFocused(requiresFocus); + } - return true; - } + return true; + } - /** - * Checks if the mouse is within the element - * - * @param xCoord current x coord of the mouse - * @param yCoord current y coord of the mouse - * - * @return true if mouse position is within the text field area - */ - public boolean isMouseIn( final int xCoord, final int yCoord ) - { - final boolean withinXRange = this._xPos <= xCoord && xCoord < this._xPos + this._width; - final boolean withinYRange = this._yPos <= yCoord && yCoord < this._yPos + this._height; + /** + * Checks if the mouse is within the element + * + * @param xCoord current x coord of the mouse + * @param yCoord current y coord of the mouse + * @return true if mouse position is within the text field area + */ + public boolean isMouseIn(final int xCoord, final int yCoord) { + final boolean withinXRange = this._xPos <= xCoord && xCoord < this._xPos + this._width; + final boolean withinYRange = this._yPos <= yCoord && yCoord < this._yPos + this._height; - return withinXRange && withinYRange; - } + return withinXRange && withinYRange; + } - public boolean textboxKeyTyped(final char keyChar, final int keyID) { - if (!isFocused()) { - return false; - } + public boolean textboxKeyTyped(final char keyChar, final int keyID) { + if (!isFocused()) { + return false; + } - final String oldText = getText(); - boolean handled = super.textboxKeyTyped(keyChar, keyID); + final String oldText = getText(); + boolean handled = super.textboxKeyTyped(keyChar, keyID); - if (!handled - && (keyID == Keyboard.KEY_RETURN - || keyID == Keyboard.KEY_NUMPADENTER - || keyID == Keyboard.KEY_ESCAPE)) { - setFocused(false); - } + if (!handled + && (keyID == Keyboard.KEY_RETURN + || keyID == Keyboard.KEY_NUMPADENTER + || keyID == Keyboard.KEY_ESCAPE)) { + setFocused(false); + } - if (handled) { - onTextChange(oldText); - } + if (handled) { + onTextChange(oldText); + } - return handled; - } + return handled; + } - public void selectAll() - { - this.setCursorPosition( 0 ); - this.setSelectionPos( this.getMaxStringLength() ); - } + public void selectAll() { + this.setCursorPosition(0); + this.setSelectionPos(this.getMaxStringLength()); + } - public void setSelectionColor( int color ) - { - this.selectionColor = color; - } + public void setSelectionColor(int color) { + this.selectionColor = color; + } - @Override - public void drawTextBox() - { - if( this.getVisible() ) - { - if( this.isFocused() ) - { - drawRect( this.x - PADDING + 1, this.y - PADDING + 1, this.x + this.width + this._fontPad + PADDING - 1, this.y + this.height + PADDING - 1, - 0xFF606060 ); - } - else - { - drawRect( this.x - PADDING + 1, this.y - PADDING + 1, this.x + this.width + this._fontPad + PADDING - 1, this.y + this.height + PADDING - 1, - 0xFFA8A8A8 ); - } - super.drawTextBox(); - } - } + @Override + public void drawTextBox() { + if (this.getVisible()) { + if (this.isFocused()) { + drawRect(this.x - PADDING + 1, this.y - PADDING + 1, this.x + this.width + this._fontPad + PADDING - 1, this.y + this.height + PADDING - 1, + 0xFF606060); + } else { + drawRect(this.x - PADDING + 1, this.y - PADDING + 1, this.x + this.width + this._fontPad + PADDING - 1, this.y + this.height + PADDING - 1, + 0xFFA8A8A8); + } + super.drawTextBox(); + } + } - public void setText(String text, boolean ignoreTrigger) { - final String oldText = getText(); + public void setText(String text, boolean ignoreTrigger) { + final String oldText = getText(); - super.setText(text); - super.setCursorPositionEnd(); + super.setText(text); + super.setCursorPositionEnd(); - if (!ignoreTrigger) { - onTextChange(oldText); - } - } + if (!ignoreTrigger) { + onTextChange(oldText); + } + } - public void setText(String text) { - setText(text, false); - } + public void setText(String text) { + setText(text, false); + } - @Override - public void drawSelectionBox( int startX, int startY, int endX, int endY ) - { - if( !this.isFocused() ) - { - return; - } + @Override + public void drawSelectionBox(int startX, int startY, int endX, int endY) { + if (!this.isFocused()) { + return; + } - if( startX < endX ) - { - int i = startX; - startX = endX; - endX = i; - } + if (startX < endX) { + int i = startX; + startX = endX; + endX = i; + } - startX += 1; - endX -= 1; + startX += 1; + endX -= 1; - if( startY < endY ) - { - int j = startY; - startY = endY; - endY = j; - } + if (startY < endY) { + int j = startY; + startY = endY; + endY = j; + } - startY -= PADDING; + startY -= PADDING; - if( endX > this.x + this.width ) - { - endX = this.x + this.width; - } + if (endX > this.x + this.width) { + endX = this.x + this.width; + } - if( startX > this.x + this.width ) - { - startX = this.x + this.width; - } + if (startX > this.x + this.width) { + startX = this.x + this.width; + } - Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder bufferbuilder = tessellator.getBuffer(); + Tessellator tessellator = Tessellator.getInstance(); + BufferBuilder bufferbuilder = tessellator.getBuffer(); - float red = ( this.selectionColor >> 16 & 255 ) / 255.0F; - float blue = ( this.selectionColor >> 8 & 255 ) / 255.0F; - float green = ( this.selectionColor & 255 ) / 255.0F; - float alpha = ( this.selectionColor >> 24 & 255 ) / 255.0F; + float red = (this.selectionColor >> 16 & 255) / 255.0F; + float blue = (this.selectionColor >> 8 & 255) / 255.0F; + float green = (this.selectionColor & 255) / 255.0F; + float alpha = (this.selectionColor >> 24 & 255) / 255.0F; - GlStateManager.color( red, green, blue, alpha ); - GlStateManager.disableTexture2D(); - GlStateManager.enableColorLogic(); - GlStateManager.colorLogicOp( GlStateManager.LogicOp.OR_REVERSE ); - bufferbuilder.begin( 7, DefaultVertexFormats.POSITION ); - bufferbuilder.pos( startX, endY, 0.0D ).endVertex(); - bufferbuilder.pos( endX, endY, 0.0D ).endVertex(); - bufferbuilder.pos( endX, startY, 0.0D ).endVertex(); - bufferbuilder.pos( startX, startY, 0.0D ).endVertex(); - tessellator.draw(); - GlStateManager.disableColorLogic(); - GlStateManager.enableTexture2D(); - } + GlStateManager.color(red, green, blue, alpha); + GlStateManager.disableTexture2D(); + GlStateManager.enableColorLogic(); + GlStateManager.colorLogicOp(GlStateManager.LogicOp.OR_REVERSE); + bufferbuilder.begin(7, DefaultVertexFormats.POSITION); + bufferbuilder.pos(startX, endY, 0.0D).endVertex(); + bufferbuilder.pos(endX, endY, 0.0D).endVertex(); + bufferbuilder.pos(endX, startY, 0.0D).endVertex(); + bufferbuilder.pos(startX, startY, 0.0D).endVertex(); + tessellator.draw(); + GlStateManager.disableColorLogic(); + GlStateManager.enableTexture2D(); + } } diff --git a/src/main/java/appeng/client/me/ClientDCInternalInv.java b/src/main/java/appeng/client/me/ClientDCInternalInv.java index 61aab235b..d3bac675f 100644 --- a/src/main/java/appeng/client/me/ClientDCInternalInv.java +++ b/src/main/java/appeng/client/me/ClientDCInternalInv.java @@ -19,61 +19,52 @@ package appeng.client.me; -import javax.annotation.Nonnull; - +import appeng.tile.inventory.AppEngInternalInventory; import net.minecraft.util.text.translation.I18n; -import appeng.tile.inventory.AppEngInternalInventory; +import javax.annotation.Nonnull; -public class ClientDCInternalInv implements Comparable -{ +public class ClientDCInternalInv implements Comparable { - private final String unlocalizedName; - private final AppEngInternalInventory inventory; + private final String unlocalizedName; + private final AppEngInternalInventory inventory; - private final long id; - private final long sortBy; + private final long id; + private final long sortBy; - public ClientDCInternalInv( final int size, final long id, final long sortBy, final String unlocalizedName ) - { - this.inventory = new AppEngInternalInventory( null, size, 1 ); - this.unlocalizedName = unlocalizedName; - this.id = id; - this.sortBy = sortBy; - } + public ClientDCInternalInv(final int size, final long id, final long sortBy, final String unlocalizedName) { + this.inventory = new AppEngInternalInventory(null, size, 1); + this.unlocalizedName = unlocalizedName; + this.id = id; + this.sortBy = sortBy; + } - public ClientDCInternalInv( final int size, final long id, final long sortBy, final String unlocalizedName, int stackSize ) - { - this.inventory = new AppEngInternalInventory( null, size, stackSize ); - this.unlocalizedName = unlocalizedName; - this.id = id; - this.sortBy = sortBy; - } + public ClientDCInternalInv(final int size, final long id, final long sortBy, final String unlocalizedName, int stackSize) { + this.inventory = new AppEngInternalInventory(null, size, stackSize); + this.unlocalizedName = unlocalizedName; + this.id = id; + this.sortBy = sortBy; + } - public String getName() - { - final String s = I18n.translateToLocal( this.unlocalizedName + ".name" ); - if( s.equals( this.unlocalizedName + ".name" ) ) - { - return I18n.translateToLocal( this.unlocalizedName ); - } - return s; - } + public String getName() { + final String s = I18n.translateToLocal(this.unlocalizedName + ".name"); + if (s.equals(this.unlocalizedName + ".name")) { + return I18n.translateToLocal(this.unlocalizedName); + } + return s; + } - @Override - public int compareTo( @Nonnull final ClientDCInternalInv o ) - { - return Long.compare( this.sortBy, o.sortBy ); - } + @Override + public int compareTo(@Nonnull final ClientDCInternalInv o) { + return Long.compare(this.sortBy, o.sortBy); + } - public AppEngInternalInventory getInventory() - { - return this.inventory; - } + public AppEngInternalInventory getInventory() { + return this.inventory; + } - public long getId() - { - return this.id; - } + public long getId() { + return this.id; + } } diff --git a/src/main/java/appeng/client/me/FluidRepo.java b/src/main/java/appeng/client/me/FluidRepo.java index f8b72779a..c85d45c1d 100644 --- a/src/main/java/appeng/client/me/FluidRepo.java +++ b/src/main/java/appeng/client/me/FluidRepo.java @@ -19,13 +19,6 @@ package appeng.client.me; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.regex.Pattern; - -import javax.annotation.Nonnull; - import appeng.api.AEApi; import appeng.api.config.Settings; import appeng.api.config.SortOrder; @@ -41,203 +34,170 @@ import appeng.fluids.util.FluidSorters; import appeng.util.Platform; import appeng.util.prioritylist.IPartitionList; +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.regex.Pattern; + /** * @author BrockWS * @version rv6 - 22/05/2018 * @since rv6 22/05/2018 */ -public class FluidRepo -{ - private final IItemList list = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList(); - private final ArrayList view = new ArrayList<>(); - private final IScrollSource src; - private final ISortSource sortSrc; +public class FluidRepo { + private final IItemList list = AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class).createList(); + private final ArrayList view = new ArrayList<>(); + private final IScrollSource src; + private final ISortSource sortSrc; - private int rowSize = 9; + private int rowSize = 9; - private String searchString = ""; - private IPartitionList myPartitionList; - private boolean hasPower; + private String searchString = ""; + private IPartitionList myPartitionList; + private boolean hasPower; - public FluidRepo( final IScrollSource src, final ISortSource sortSrc ) - { - this.src = src; - this.sortSrc = sortSrc; - } + public FluidRepo(final IScrollSource src, final ISortSource sortSrc) { + this.src = src; + this.sortSrc = sortSrc; + } - public void updateView() - { - this.view.clear(); + public void updateView() { + this.view.clear(); - this.view.ensureCapacity( this.list.size() ); + this.view.ensureCapacity(this.list.size()); - String innerSearch = this.searchString; + String innerSearch = this.searchString; - boolean searchMod = false; - if( innerSearch.startsWith( "@" ) ) - { - searchMod = true; - innerSearch = innerSearch.substring( 1 ); - } + boolean searchMod = false; + if (innerSearch.startsWith("@")) { + searchMod = true; + innerSearch = innerSearch.substring(1); + } - Pattern m; - try - { - m = Pattern.compile( innerSearch.toLowerCase(), Pattern.CASE_INSENSITIVE ); - } - catch( final Exception ignore1 ) - { - try - { - m = Pattern.compile( Pattern.quote( innerSearch.toLowerCase() ), Pattern.CASE_INSENSITIVE ); - } - catch( final Exception ignore2 ) - { - return; - } - } + Pattern m; + try { + m = Pattern.compile(innerSearch.toLowerCase(), Pattern.CASE_INSENSITIVE); + } catch (final Exception ignore1) { + try { + m = Pattern.compile(Pattern.quote(innerSearch.toLowerCase()), Pattern.CASE_INSENSITIVE); + } catch (final Exception ignore2) { + return; + } + } - final Enum viewMode = this.sortSrc.getSortDisplay(); - final boolean needsZeroCopy = viewMode == ViewItems.CRAFTABLE; - final boolean terminalSearchToolTips = AEConfig.instance().getConfigManager().getSetting( Settings.SEARCH_TOOLTIPS ) != YesNo.NO; + final Enum viewMode = this.sortSrc.getSortDisplay(); + final boolean needsZeroCopy = viewMode == ViewItems.CRAFTABLE; + final boolean terminalSearchToolTips = AEConfig.instance().getConfigManager().getSetting(Settings.SEARCH_TOOLTIPS) != YesNo.NO; - boolean notDone = false; - for( IAEFluidStack fs : this.list ) - { - if( this.myPartitionList != null && !this.myPartitionList.isListed( fs ) ) - { - continue; - } + boolean notDone = false; + for (IAEFluidStack fs : this.list) { + if (this.myPartitionList != null && !this.myPartitionList.isListed(fs)) { + continue; + } - if( viewMode == ViewItems.CRAFTABLE && !fs.isCraftable() ) - { - continue; - } + if (viewMode == ViewItems.CRAFTABLE && !fs.isCraftable()) { + continue; + } - if( viewMode == ViewItems.STORED && fs.getStackSize() == 0 ) - { - continue; - } + if (viewMode == ViewItems.STORED && fs.getStackSize() == 0) { + continue; + } - final String dspName = searchMod ? Platform.getModId( fs ) : Platform.getFluidDisplayName( fs ); - boolean foundMatchingFluidStack = false; - notDone = true; + final String dspName = searchMod ? Platform.getModId(fs) : Platform.getFluidDisplayName(fs); + boolean foundMatchingFluidStack = false; + notDone = true; - if( m.matcher( dspName.toLowerCase() ).find() ) - { - notDone = false; - foundMatchingFluidStack = true; - } + if (m.matcher(dspName.toLowerCase()).find()) { + notDone = false; + foundMatchingFluidStack = true; + } - if( terminalSearchToolTips && notDone && !searchMod ) - { - final List tooltip = Platform.getTooltip( fs ); + if (terminalSearchToolTips && notDone && !searchMod) { + final List tooltip = Platform.getTooltip(fs); - for( final String line : tooltip ) - { - if( m.matcher( line ).find() ) - { - foundMatchingFluidStack = true; - break; - } - } - } + for (final String line : tooltip) { + if (m.matcher(line).find()) { + foundMatchingFluidStack = true; + break; + } + } + } - if( foundMatchingFluidStack ) - { - if( needsZeroCopy ) - { - fs = fs.copy(); - fs.setStackSize( 0 ); - } + if (foundMatchingFluidStack) { + if (needsZeroCopy) { + fs = fs.copy(); + fs.setStackSize(0); + } - this.view.add( fs ); - } - } + this.view.add(fs); + } + } - final Enum sortBy = this.sortSrc.getSortBy(); - final Enum sortDir = this.sortSrc.getSortDir(); + final Enum sortBy = this.sortSrc.getSortBy(); + final Enum sortDir = this.sortSrc.getSortDir(); - FluidSorters.setDirection( (appeng.api.config.SortDir) sortDir ); + FluidSorters.setDirection((appeng.api.config.SortDir) sortDir); - if( sortBy == SortOrder.MOD ) - { - Collections.sort( this.view, FluidSorters.CONFIG_BASED_SORT_BY_MOD ); - } - else if( sortBy == SortOrder.AMOUNT ) - { - Collections.sort( this.view, FluidSorters.CONFIG_BASED_SORT_BY_SIZE ); - } - else - { - Collections.sort( this.view, FluidSorters.CONFIG_BASED_SORT_BY_NAME ); - } - } + if (sortBy == SortOrder.MOD) { + Collections.sort(this.view, FluidSorters.CONFIG_BASED_SORT_BY_MOD); + } else if (sortBy == SortOrder.AMOUNT) { + Collections.sort(this.view, FluidSorters.CONFIG_BASED_SORT_BY_SIZE); + } else { + Collections.sort(this.view, FluidSorters.CONFIG_BASED_SORT_BY_NAME); + } + } - public void postUpdate( final IAEFluidStack is ) - { - final IAEFluidStack st = this.list.findPrecise( is ); + public void postUpdate(final IAEFluidStack is) { + final IAEFluidStack st = this.list.findPrecise(is); - if( st != null ) - { - st.reset(); - st.add( is ); - } - else - { - this.list.add( is ); - } - } + if (st != null) { + st.reset(); + st.add(is); + } else { + this.list.add(is); + } + } - public IAEFluidStack getReferenceFluid( int idx ) - { - idx += this.src.getCurrentScroll() * this.rowSize; + public IAEFluidStack getReferenceFluid(int idx) { + idx += this.src.getCurrentScroll() * this.rowSize; - if( idx >= this.view.size() ) - { - return null; - } - return this.view.get( idx ); - } + if (idx >= this.view.size()) { + return null; + } + return this.view.get(idx); + } - public int size() - { - return this.view.size(); - } + public int size() { + return this.view.size(); + } - public void clear() - { - this.list.resetStatus(); - } + public void clear() { + this.list.resetStatus(); + } - public boolean hasPower() - { - return this.hasPower; - } + public boolean hasPower() { + return this.hasPower; + } - public void setPower( final boolean hasPower ) - { - this.hasPower = hasPower; - } + public void setPower(final boolean hasPower) { + this.hasPower = hasPower; + } - public int getRowSize() - { - return this.rowSize; - } + public int getRowSize() { + return this.rowSize; + } - public void setRowSize( final int rowSize ) - { - this.rowSize = rowSize; - } + public void setRowSize(final int rowSize) { + this.rowSize = rowSize; + } - public String getSearchString() - { - return this.searchString; - } + public String getSearchString() { + return this.searchString; + } - public void setSearchString( @Nonnull final String searchString ) - { - this.searchString = searchString; - } + public void setSearchString(@Nonnull final String searchString) { + this.searchString = searchString; + } } diff --git a/src/main/java/appeng/client/me/InternalFluidSlotME.java b/src/main/java/appeng/client/me/InternalFluidSlotME.java index eeec2b53a..eeebd9ef4 100644 --- a/src/main/java/appeng/client/me/InternalFluidSlotME.java +++ b/src/main/java/appeng/client/me/InternalFluidSlotME.java @@ -27,39 +27,33 @@ import appeng.api.storage.data.IAEFluidStack; * @version rv6 - 22/05/2018 * @since rv6 22/05/2018 */ -public class InternalFluidSlotME -{ +public class InternalFluidSlotME { - private final int offset; - private final int xPos; - private final int yPos; - private final FluidRepo repo; + private final int offset; + private final int xPos; + private final int yPos; + private final FluidRepo repo; - public InternalFluidSlotME( final FluidRepo def, final int offset, final int displayX, final int displayY ) - { - this.repo = def; - this.offset = offset; - this.xPos = displayX; - this.yPos = displayY; - } + public InternalFluidSlotME(final FluidRepo def, final int offset, final int displayX, final int displayY) { + this.repo = def; + this.offset = offset; + this.xPos = displayX; + this.yPos = displayY; + } - IAEFluidStack getAEStack() - { - return this.repo.getReferenceFluid( this.offset ); - } + IAEFluidStack getAEStack() { + return this.repo.getReferenceFluid(this.offset); + } - boolean hasPower() - { - return this.repo.hasPower(); - } + boolean hasPower() { + return this.repo.hasPower(); + } - int getxPosition() - { - return this.xPos; - } + int getxPosition() { + return this.xPos; + } - int getyPosition() - { - return this.yPos; - } + int getyPosition() { + return this.yPos; + } } diff --git a/src/main/java/appeng/client/me/InternalSlotME.java b/src/main/java/appeng/client/me/InternalSlotME.java index efbfb8448..e2db5bc1a 100644 --- a/src/main/java/appeng/client/me/InternalSlotME.java +++ b/src/main/java/appeng/client/me/InternalSlotME.java @@ -19,49 +19,41 @@ package appeng.client.me; +import appeng.api.storage.data.IAEItemStack; import net.minecraft.item.ItemStack; -import appeng.api.storage.data.IAEItemStack; +public class InternalSlotME { -public class InternalSlotME -{ + private final int offset; + private final int xPos; + private final int yPos; + private final ItemRepo repo; - private final int offset; - private final int xPos; - private final int yPos; - private final ItemRepo repo; + public InternalSlotME(final ItemRepo def, final int offset, final int displayX, final int displayY) { + this.repo = def; + this.offset = offset; + this.xPos = displayX; + this.yPos = displayY; + } - public InternalSlotME( final ItemRepo def, final int offset, final int displayX, final int displayY ) - { - this.repo = def; - this.offset = offset; - this.xPos = displayX; - this.yPos = displayY; - } + ItemStack getStack() { + return this.getAEStack() == null ? ItemStack.EMPTY : this.getAEStack().asItemStackRepresentation(); + } - ItemStack getStack() - { - return this.getAEStack() == null ? ItemStack.EMPTY : this.getAEStack().asItemStackRepresentation(); - } + IAEItemStack getAEStack() { + return this.repo.getReferenceItem(this.offset); + } - IAEItemStack getAEStack() - { - return this.repo.getReferenceItem( this.offset ); - } + boolean hasPower() { + return this.repo.hasPower(); + } - boolean hasPower() - { - return this.repo.hasPower(); - } + int getxPosition() { + return this.xPos; + } - int getxPosition() - { - return this.xPos; - } - - int getyPosition() - { - return this.yPos; - } + int getyPosition() { + return this.yPos; + } } diff --git a/src/main/java/appeng/client/me/ItemRepo.java b/src/main/java/appeng/client/me/ItemRepo.java index 5ada30367..2065dc865 100644 --- a/src/main/java/appeng/client/me/ItemRepo.java +++ b/src/main/java/appeng/client/me/ItemRepo.java @@ -19,21 +19,8 @@ package appeng.client.me; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.regex.Pattern; - -import javax.annotation.Nonnull; - -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; -import appeng.api.config.SearchBoxMode; -import appeng.api.config.Settings; -import appeng.api.config.SortOrder; -import appeng.api.config.ViewItems; -import appeng.api.config.YesNo; +import appeng.api.config.*; import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; @@ -46,255 +33,208 @@ import appeng.items.storage.ItemViewCell; import appeng.util.ItemSorters; import appeng.util.Platform; import appeng.util.prioritylist.IPartitionList; +import net.minecraft.item.ItemStack; + +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.regex.Pattern; -public class ItemRepo -{ +public class ItemRepo { - private final IItemList list = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - private final ArrayList view = new ArrayList<>(); - private final IScrollSource src; - private final ISortSource sortSrc; + private final IItemList list = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + private final ArrayList view = new ArrayList<>(); + private final IScrollSource src; + private final ISortSource sortSrc; - private int rowSize = 9; + private int rowSize = 9; - private String searchString = ""; - private IPartitionList myPartitionList; - private String innerSearch = ""; - private boolean hasPower; + private String searchString = ""; + private IPartitionList myPartitionList; + private String innerSearch = ""; + private boolean hasPower; - public ItemRepo( final IScrollSource src, final ISortSource sortSrc ) - { - this.src = src; - this.sortSrc = sortSrc; - } + public ItemRepo(final IScrollSource src, final ISortSource sortSrc) { + this.src = src; + this.sortSrc = sortSrc; + } - public IAEItemStack getReferenceItem( int idx ) - { - idx += this.src.getCurrentScroll() * this.rowSize; + public IAEItemStack getReferenceItem(int idx) { + idx += this.src.getCurrentScroll() * this.rowSize; - if( idx >= this.view.size() ) - { - return null; - } - return this.view.get( idx ); - } + if (idx >= this.view.size()) { + return null; + } + return this.view.get(idx); + } - void setSearch( final String search ) - { - this.searchString = search == null ? "" : search; - } + void setSearch(final String search) { + this.searchString = search == null ? "" : search; + } - public void postUpdate( final IAEItemStack is ) - { - final IAEItemStack st = this.list.findPrecise( is ); + public void postUpdate(final IAEItemStack is) { + final IAEItemStack st = this.list.findPrecise(is); - if( st != null ) - { - st.reset(); - st.add( is ); - } - else - { - this.list.add( is ); - } - } + if (st != null) { + st.reset(); + st.add(is); + } else { + this.list.add(is); + } + } - public long getItemCount( final IAEItemStack is ) - { - IAEItemStack st = this.list.findPrecise( is ); - return st == null ? 0 : st.getStackSize(); - } + public long getItemCount(final IAEItemStack is) { + IAEItemStack st = this.list.findPrecise(is); + return st == null ? 0 : st.getStackSize(); + } - public void setViewCell( final ItemStack[] list ) - { - this.myPartitionList = ItemViewCell.createFilter( list ); - this.updateView(); - } + public void setViewCell(final ItemStack[] list) { + this.myPartitionList = ItemViewCell.createFilter(list); + this.updateView(); + } - public void updateView() - { - this.view.clear(); + public void updateView() { + this.view.clear(); - this.view.ensureCapacity( this.list.size() ); + this.view.ensureCapacity(this.list.size()); - final Enum viewMode = this.sortSrc.getSortDisplay(); - final Enum searchMode = AEConfig.instance().getConfigManager().getSetting( Settings.SEARCH_MODE ); - final boolean needsZeroCopy = viewMode == ViewItems.CRAFTABLE; + final Enum viewMode = this.sortSrc.getSortDisplay(); + final Enum searchMode = AEConfig.instance().getConfigManager().getSetting(Settings.SEARCH_MODE); + final boolean needsZeroCopy = viewMode == ViewItems.CRAFTABLE; - if( searchMode == SearchBoxMode.JEI_AUTOSEARCH || searchMode == SearchBoxMode.JEI_MANUAL_SEARCH || searchMode == SearchBoxMode.JEI_AUTOSEARCH_KEEP || searchMode == SearchBoxMode.JEI_MANUAL_SEARCH_KEEP ) - { - this.updateJEI( this.searchString ); - } + if (searchMode == SearchBoxMode.JEI_AUTOSEARCH || searchMode == SearchBoxMode.JEI_MANUAL_SEARCH || searchMode == SearchBoxMode.JEI_AUTOSEARCH_KEEP || searchMode == SearchBoxMode.JEI_MANUAL_SEARCH_KEEP) { + this.updateJEI(this.searchString); + } - final boolean terminalSearchToolTips = AEConfig.instance().getConfigManager().getSetting( Settings.SEARCH_TOOLTIPS ) != YesNo.NO; + final boolean terminalSearchToolTips = AEConfig.instance().getConfigManager().getSetting(Settings.SEARCH_TOOLTIPS) != YesNo.NO; - boolean searchMod = false; + boolean searchMod = false; - this.innerSearch = searchString.toLowerCase(); - if( this.innerSearch.startsWith( "@" ) ) - { - searchMod = true; - this.innerSearch = this.innerSearch.substring( 1 ); - } + this.innerSearch = searchString.toLowerCase(); + if (this.innerSearch.startsWith("@")) { + searchMod = true; + this.innerSearch = this.innerSearch.substring(1); + } - Pattern m = null; - try - { - m = Pattern.compile( this.innerSearch, Pattern.CASE_INSENSITIVE ); - } - catch( final Throwable ignore ) - { - try - { - m = Pattern.compile( Pattern.quote( this.innerSearch ), Pattern.CASE_INSENSITIVE ); - } - catch( final Throwable __ ) - { - return; - } - } + Pattern m = null; + try { + m = Pattern.compile(this.innerSearch, Pattern.CASE_INSENSITIVE); + } catch (final Throwable ignore) { + try { + m = Pattern.compile(Pattern.quote(this.innerSearch), Pattern.CASE_INSENSITIVE); + } catch (final Throwable __) { + return; + } + } - boolean notDone = false; - for( IAEItemStack is : this.list ) - { - if( this.myPartitionList != null ) - { - if( !this.myPartitionList.isListed( is ) ) - { - continue; - } - } + boolean notDone = false; + for (IAEItemStack is : this.list) { + if (this.myPartitionList != null) { + if (!this.myPartitionList.isListed(is)) { + continue; + } + } - if( viewMode == ViewItems.CRAFTABLE && !is.isCraftable() ) - { - continue; - } + if (viewMode == ViewItems.CRAFTABLE && !is.isCraftable()) { + continue; + } - if( viewMode == ViewItems.STORED && is.getStackSize() == 0 ) - { - continue; - } + if (viewMode == ViewItems.STORED && is.getStackSize() == 0) { + continue; + } - final String dspName = ( searchMod ? Platform.getModId( is ) : Platform.getItemDisplayName( is ) ).toLowerCase(); - boolean foundMatchingItemStack = true; + final String dspName = (searchMod ? Platform.getModId(is) : Platform.getItemDisplayName(is)).toLowerCase(); + boolean foundMatchingItemStack = true; - for( String term : innerSearch.split( " " ) ) - { - if( term.length() > 1 && ( term.startsWith( "-" ) || term.startsWith( "!" ) ) ) - { - term = term.substring( 1 ); - if( dspName.contains( term ) ) - { - foundMatchingItemStack = false; - break; - } - } - else if( !dspName.contains( term ) ) - { - foundMatchingItemStack = false; - break; - } - } + for (String term : innerSearch.split(" ")) { + if (term.length() > 1 && (term.startsWith("-") || term.startsWith("!"))) { + term = term.substring(1); + if (dspName.contains(term)) { + foundMatchingItemStack = false; + break; + } + } else if (!dspName.contains(term)) { + foundMatchingItemStack = false; + break; + } + } - if( terminalSearchToolTips && !foundMatchingItemStack ) - { - final List tooltip = Platform.getTooltip( is ); - for( final String line : tooltip ) - { - if( m.matcher( line ).find() ) - { - foundMatchingItemStack = true; - break; - } - } - } + if (terminalSearchToolTips && !foundMatchingItemStack) { + final List tooltip = Platform.getTooltip(is); + for (final String line : tooltip) { + if (m.matcher(line).find()) { + foundMatchingItemStack = true; + break; + } + } + } - if( foundMatchingItemStack ) - { - if( needsZeroCopy ) - { - is = is.copy(); - is.setStackSize( 0 ); - } + if (foundMatchingItemStack) { + if (needsZeroCopy) { + is = is.copy(); + is.setStackSize(0); + } - this.view.add( is ); - } - } + this.view.add(is); + } + } - final Enum SortBy = this.sortSrc.getSortBy(); - final Enum SortDir = this.sortSrc.getSortDir(); + final Enum SortBy = this.sortSrc.getSortBy(); + final Enum SortDir = this.sortSrc.getSortDir(); - ItemSorters.setDirection( (appeng.api.config.SortDir) SortDir ); - ItemSorters.init(); + ItemSorters.setDirection((appeng.api.config.SortDir) SortDir); + ItemSorters.init(); - if( SortBy == SortOrder.MOD ) - { - Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_MOD ); - } - else if( SortBy == SortOrder.AMOUNT ) - { - Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_SIZE ); - } - else if( SortBy == SortOrder.INVTWEAKS ) - { - if( InventoryBogoSortModule.isLoaded() ) - { - Collections.sort( this.view, InventoryBogoSortModule.COMPARATOR ); - } - else - { - Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_INV_TWEAKS ); - } - } - else - { - Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_NAME ); - } - } + if (SortBy == SortOrder.MOD) { + Collections.sort(this.view, ItemSorters.CONFIG_BASED_SORT_BY_MOD); + } else if (SortBy == SortOrder.AMOUNT) { + Collections.sort(this.view, ItemSorters.CONFIG_BASED_SORT_BY_SIZE); + } else if (SortBy == SortOrder.INVTWEAKS) { + if (InventoryBogoSortModule.isLoaded()) { + Collections.sort(this.view, InventoryBogoSortModule.COMPARATOR); + } else { + Collections.sort(this.view, ItemSorters.CONFIG_BASED_SORT_BY_INV_TWEAKS); + } + } else { + Collections.sort(this.view, ItemSorters.CONFIG_BASED_SORT_BY_NAME); + } + } - private void updateJEI( String filter ) - { - Integrations.jei().setSearchText( filter ); - } + private void updateJEI(String filter) { + Integrations.jei().setSearchText(filter); + } - public int size() - { - return this.view.size(); - } + public int size() { + return this.view.size(); + } - public void clear() - { - this.list.resetStatus(); - } + public void clear() { + this.list.resetStatus(); + } - public boolean hasPower() - { - return this.hasPower; - } + public boolean hasPower() { + return this.hasPower; + } - public void setPower( final boolean hasPower ) - { - this.hasPower = hasPower; - } + public void setPower(final boolean hasPower) { + this.hasPower = hasPower; + } - public int getRowSize() - { - return this.rowSize; - } + public int getRowSize() { + return this.rowSize; + } - public void setRowSize( final int rowSize ) - { - this.rowSize = rowSize; - } + public void setRowSize(final int rowSize) { + this.rowSize = rowSize; + } - public String getSearchString() - { - return this.searchString; - } + public String getSearchString() { + return this.searchString; + } - public void setSearchString( @Nonnull final String searchString ) - { - this.searchString = searchString; - } + public void setSearchString(@Nonnull final String searchString) { + this.searchString = searchString; + } } diff --git a/src/main/java/appeng/client/me/SlotDisconnected.java b/src/main/java/appeng/client/me/SlotDisconnected.java index a2e7b1020..25f9847c9 100644 --- a/src/main/java/appeng/client/me/SlotDisconnected.java +++ b/src/main/java/appeng/client/me/SlotDisconnected.java @@ -19,90 +19,75 @@ package appeng.client.me; +import appeng.container.slot.AppEngSlot; import appeng.container.slot.IJEITargetSlot; +import appeng.items.misc.ItemEncodedPattern; +import appeng.util.Platform; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import appeng.container.slot.AppEngSlot; -import appeng.items.misc.ItemEncodedPattern; -import appeng.util.Platform; +public class SlotDisconnected extends AppEngSlot implements IJEITargetSlot { -public class SlotDisconnected extends AppEngSlot implements IJEITargetSlot -{ + private final ClientDCInternalInv mySlot; - private final ClientDCInternalInv mySlot; + public SlotDisconnected(final ClientDCInternalInv me, final int which, final int x, final int y) { + super(me.getInventory(), which, x, y); + this.mySlot = me; + } - public SlotDisconnected( final ClientDCInternalInv me, final int which, final int x, final int y ) - { - super( me.getInventory(), which, x, y ); - this.mySlot = me; - } + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + @Override + public void putStack(final ItemStack par1ItemStack) { - @Override - public void putStack( final ItemStack par1ItemStack ) - { + } - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public ItemStack getDisplayStack() { + if (Platform.isClient()) { + final ItemStack is = super.getStack(); + if (!is.isEmpty() && is.getItem() instanceof ItemEncodedPattern) { + final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + final ItemStack out = iep.getOutput(is); + if (!out.isEmpty()) { + return out; + } + } + } + return super.getStack(); + } - @Override - public ItemStack getDisplayStack() - { - if( Platform.isClient() ) - { - final ItemStack is = super.getStack(); - if( !is.isEmpty() && is.getItem() instanceof ItemEncodedPattern ) - { - final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - final ItemStack out = iep.getOutput( is ); - if( !out.isEmpty() ) - { - return out; - } - } - } - return super.getStack(); - } + @Override + public boolean getHasStack() { + return !this.getStack().isEmpty(); + } - @Override - public boolean getHasStack() - { - return !this.getStack().isEmpty(); - } + @Override + public int getSlotStackLimit() { + return 0; + } - @Override - public int getSlotStackLimit() - { - return 0; - } + @Override + public ItemStack decrStackSize(final int par1) { + return ItemStack.EMPTY; + } - @Override - public ItemStack decrStackSize( final int par1 ) - { - return ItemStack.EMPTY; - } + @Override + public boolean isHere(final IInventory inv, final int slotIn) { + return false; + } - @Override - public boolean isHere( final IInventory inv, final int slotIn ) - { - return false; - } - - public ClientDCInternalInv getSlot() - { - return this.mySlot; - } + public ClientDCInternalInv getSlot() { + return this.mySlot; + } } diff --git a/src/main/java/appeng/client/me/SlotFluidME.java b/src/main/java/appeng/client/me/SlotFluidME.java index 866648d9c..3c8be954d 100644 --- a/src/main/java/appeng/client/me/SlotFluidME.java +++ b/src/main/java/appeng/client/me/SlotFluidME.java @@ -19,15 +19,14 @@ package appeng.client.me; -import javax.annotation.Nonnull; - +import appeng.api.storage.data.IAEFluidStack; +import appeng.fluids.container.slots.IMEFluidSlot; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.items.SlotItemHandler; -import appeng.api.storage.data.IAEFluidStack; -import appeng.fluids.container.slots.IMEFluidSlot; +import javax.annotation.Nonnull; /** @@ -35,78 +34,65 @@ import appeng.fluids.container.slots.IMEFluidSlot; * @version rv6 - 22/05/2018 * @since rv6 22/05/2018 */ -public class SlotFluidME extends SlotItemHandler implements IMEFluidSlot -{ +public class SlotFluidME extends SlotItemHandler implements IMEFluidSlot { - private InternalFluidSlotME slot; + private final InternalFluidSlotME slot; - public SlotFluidME( InternalFluidSlotME slot ) - { - super( null, 0, slot.getxPosition(), slot.getyPosition() ); - this.slot = slot; - } + public SlotFluidME(InternalFluidSlotME slot) { + super(null, 0, slot.getxPosition(), slot.getyPosition()); + this.slot = slot; + } - @Override - public IAEFluidStack getAEFluidStack() - { - if( this.slot.hasPower() ) - { - return this.slot.getAEStack(); - } - return null; - } + @Override + public IAEFluidStack getAEFluidStack() { + if (this.slot.hasPower()) { + return this.slot.getAEStack(); + } + return null; + } - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - @Nonnull - @Override - public ItemStack getStack() - { - return ItemStack.EMPTY; - } + @Nonnull + @Override + public ItemStack getStack() { + return ItemStack.EMPTY; + } - @Override - public boolean getHasStack() - { - if( this.slot.hasPower() ) - { - return this.getAEFluidStack() != null; - } - return false; - } + @Override + public boolean getHasStack() { + if (this.slot.hasPower()) { + return this.getAEFluidStack() != null; + } + return false; + } - @Override - public void putStack( final ItemStack par1ItemStack ) - { + @Override + public void putStack(final ItemStack par1ItemStack) { - } + } - @Override - public int getSlotStackLimit() - { - return 0; - } + @Override + public int getSlotStackLimit() { + return 0; + } - @Nonnull - @Override - public ItemStack decrStackSize( final int par1 ) - { - return ItemStack.EMPTY; - } + @Nonnull + @Override + public ItemStack decrStackSize(final int par1) { + return ItemStack.EMPTY; + } - @Override - public boolean isHere( final IInventory inv, final int slotIn ) - { - return false; - } + @Override + public boolean isHere(final IInventory inv, final int slotIn) { + return false; + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } } diff --git a/src/main/java/appeng/client/me/SlotME.java b/src/main/java/appeng/client/me/SlotME.java index 1be6fdb5d..8f082b28e 100644 --- a/src/main/java/appeng/client/me/SlotME.java +++ b/src/main/java/appeng/client/me/SlotME.java @@ -19,87 +19,72 @@ package appeng.client.me; +import appeng.api.storage.data.IAEItemStack; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.items.SlotItemHandler; -import appeng.api.storage.data.IAEItemStack; +public class SlotME extends SlotItemHandler { -public class SlotME extends SlotItemHandler -{ + private final InternalSlotME mySlot; - private final InternalSlotME mySlot; + public SlotME(final InternalSlotME me) { + super(null, 0, me.getxPosition(), me.getyPosition()); + this.mySlot = me; + } - public SlotME( final InternalSlotME me ) - { - super( null, 0, me.getxPosition(), me.getyPosition() ); - this.mySlot = me; - } + public IAEItemStack getAEStack() { + if (this.mySlot.hasPower()) { + return this.mySlot.getAEStack(); + } + return null; + } - public IAEItemStack getAEStack() - { - if( this.mySlot.hasPower() ) - { - return this.mySlot.getAEStack(); - } - return null; - } + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + @Override + public ItemStack getStack() { + if (this.mySlot.hasPower()) { + return this.mySlot.getStack(); + } + return ItemStack.EMPTY; + } - @Override - public ItemStack getStack() - { - if( this.mySlot.hasPower() ) - { - return this.mySlot.getStack(); - } - return ItemStack.EMPTY; - } + @Override + public boolean getHasStack() { + if (this.mySlot.hasPower()) { + return !this.getStack().isEmpty(); + } + return false; + } - @Override - public boolean getHasStack() - { - if( this.mySlot.hasPower() ) - { - return !this.getStack().isEmpty(); - } - return false; - } + @Override + public void putStack(final ItemStack par1ItemStack) { - @Override - public void putStack( final ItemStack par1ItemStack ) - { + } - } + @Override + public int getSlotStackLimit() { + return 0; + } - @Override - public int getSlotStackLimit() - { - return 0; - } + @Override + public ItemStack decrStackSize(final int par1) { + return ItemStack.EMPTY; + } - @Override - public ItemStack decrStackSize( final int par1 ) - { - return ItemStack.EMPTY; - } + @Override + public boolean isHere(final IInventory inv, final int slotIn) { + return false; + } - @Override - public boolean isHere( final IInventory inv, final int slotIn ) - { - return false; - } - - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } } diff --git a/src/main/java/appeng/client/render/BlockPosHighlighter.java b/src/main/java/appeng/client/render/BlockPosHighlighter.java index 01fd90ff9..6ffb65615 100644 --- a/src/main/java/appeng/client/render/BlockPosHighlighter.java +++ b/src/main/java/appeng/client/render/BlockPosHighlighter.java @@ -3,16 +3,14 @@ package appeng.client.render; import net.minecraft.util.math.BlockPos; // taken from McJty's McJtyLib -public class BlockPosHighlighter -{ +public class BlockPosHighlighter { private static BlockPos hilightedBlock; private static long expireHilight; - private static int dimension; - public static void hilightBlock( BlockPos c, long expireHilight, int dimension ) { + public static void hilightBlock(BlockPos c, long expireHilight, int dimension) { hilightedBlock = c; BlockPosHighlighter.expireHilight = expireHilight; BlockPosHighlighter.dimension = dimension; @@ -26,8 +24,7 @@ public class BlockPosHighlighter return expireHilight; } - public static int getDimension() - { + public static int getDimension() { return dimension; } diff --git a/src/main/java/appeng/client/render/ColorableTileBlockColor.java b/src/main/java/appeng/client/render/ColorableTileBlockColor.java index 8aad8a03a..70eaf2d31 100644 --- a/src/main/java/appeng/client/render/ColorableTileBlockColor.java +++ b/src/main/java/appeng/client/render/ColorableTileBlockColor.java @@ -19,40 +19,35 @@ package appeng.client.render; -import javax.annotation.Nullable; - +import appeng.api.implementations.tiles.IColorableTile; +import appeng.api.util.AEColor; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.color.IBlockColor; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; -import appeng.api.implementations.tiles.IColorableTile; -import appeng.api.util.AEColor; +import javax.annotation.Nullable; /** * Automatically exposes the color of a colorable tile using tint indices 0-2 */ -public class ColorableTileBlockColor implements IBlockColor -{ +public class ColorableTileBlockColor implements IBlockColor { - public static final ColorableTileBlockColor INSTANCE = new ColorableTileBlockColor(); + public static final ColorableTileBlockColor INSTANCE = new ColorableTileBlockColor(); - @Override - public int colorMultiplier( IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex ) - { - AEColor color = AEColor.TRANSPARENT; // Default to a neutral color + @Override + public int colorMultiplier(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex) { + AEColor color = AEColor.TRANSPARENT; // Default to a neutral color - if( worldIn != null && pos != null ) - { - TileEntity te = worldIn.getTileEntity( pos ); - if( te instanceof IColorableTile ) - { - color = ( (IColorableTile) te ).getColor(); - } - } + if (worldIn != null && pos != null) { + TileEntity te = worldIn.getTileEntity(pos); + if (te instanceof IColorableTile) { + color = ((IColorableTile) te).getColor(); + } + } - return color.getVariantByTintIndex( tintIndex ); - } + return color.getVariantByTintIndex(tintIndex); + } } diff --git a/src/main/java/appeng/client/render/DelegateBakedModel.java b/src/main/java/appeng/client/render/DelegateBakedModel.java index 93ca2fe74..4d562d82b 100644 --- a/src/main/java/appeng/client/render/DelegateBakedModel.java +++ b/src/main/java/appeng/client/render/DelegateBakedModel.java @@ -19,51 +19,43 @@ package appeng.client.render; -import javax.vecmath.Matrix4f; - -import org.apache.commons.lang3.tuple.Pair; - import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import org.apache.commons.lang3.tuple.Pair; + +import javax.vecmath.Matrix4f; -public abstract class DelegateBakedModel implements IBakedModel -{ - private IBakedModel baseModel; +public abstract class DelegateBakedModel implements IBakedModel { + private final IBakedModel baseModel; - protected DelegateBakedModel( IBakedModel base ) - { - this.baseModel = base; - } + protected DelegateBakedModel(IBakedModel base) { + this.baseModel = base; + } - @Override - public Pair handlePerspective( ItemCameraTransforms.TransformType type ) - { - Pair pair = this.baseModel.handlePerspective( type ); - return Pair.of( this, pair.getValue() ); - } + @Override + public Pair handlePerspective(ItemCameraTransforms.TransformType type) { + Pair pair = this.baseModel.handlePerspective(type); + return Pair.of(this, pair.getValue()); + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.baseModel.getParticleTexture(); - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.baseModel.getParticleTexture(); + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return this.baseModel.getItemCameraTransforms(); - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return this.baseModel.getItemCameraTransforms(); + } - @Override - public boolean isAmbientOcclusion() - { - return this.baseModel.isAmbientOcclusion(); - } + @Override + public boolean isAmbientOcclusion() { + return this.baseModel.isAmbientOcclusion(); + } - public IBakedModel getBaseModel() - { - return this.baseModel; - } + public IBakedModel getBaseModel() { + return this.baseModel; + } } diff --git a/src/main/java/appeng/client/render/DummyFluidBakedModel.java b/src/main/java/appeng/client/render/DummyFluidBakedModel.java index abd1ffd5a..a6133fd4e 100644 --- a/src/main/java/appeng/client/render/DummyFluidBakedModel.java +++ b/src/main/java/appeng/client/render/DummyFluidBakedModel.java @@ -19,12 +19,7 @@ package appeng.client.render; -import java.util.List; - -import javax.annotation.Nullable; - import com.google.common.collect.ImmutableList; - import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -32,54 +27,49 @@ import net.minecraft.client.renderer.block.model.ItemOverrideList; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.util.EnumFacing; +import javax.annotation.Nullable; +import java.util.List; + /** * @author DrummerMC * @version rv6 - 2018-01-22 * @since rv6 2018-01-22 */ -public class DummyFluidBakedModel implements IBakedModel -{ - private final ImmutableList quads; +public class DummyFluidBakedModel implements IBakedModel { + private final ImmutableList quads; - public DummyFluidBakedModel( ImmutableList quads ) - { - this.quads = quads; - } + public DummyFluidBakedModel(ImmutableList quads) { + this.quads = quads; + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - return this.quads; - } + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + return this.quads; + } - @Override - public boolean isAmbientOcclusion() - { - return false; - } + @Override + public boolean isAmbientOcclusion() { + return false; + } - @Override - public boolean isGui3d() - { - return false; - } + @Override + public boolean isGui3d() { + return false; + } - @Override - public boolean isBuiltInRenderer() - { - return false; - } + @Override + public boolean isBuiltInRenderer() { + return false; + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return null; - } + @Override + public TextureAtlasSprite getParticleTexture() { + return null; + } - @Override - public ItemOverrideList getOverrides() - { - return null; - } + @Override + public ItemOverrideList getOverrides() { + return null; + } } diff --git a/src/main/java/appeng/client/render/DummyFluidDispatcherBakedModel.java b/src/main/java/appeng/client/render/DummyFluidDispatcherBakedModel.java index 33af2ef31..5f207cace 100644 --- a/src/main/java/appeng/client/render/DummyFluidDispatcherBakedModel.java +++ b/src/main/java/appeng/client/render/DummyFluidDispatcherBakedModel.java @@ -19,15 +19,8 @@ package appeng.client.render; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.function.Function; - -import javax.annotation.Nullable; - +import appeng.fluids.items.FluidDummyItem; import com.google.common.collect.ImmutableList; - import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -44,7 +37,11 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; -import appeng.fluids.items.FluidDummyItem; +import javax.annotation.Nullable; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; /** @@ -52,66 +49,55 @@ import appeng.fluids.items.FluidDummyItem; * on the item stack. * A custom Item Override List is used to accomplish this. */ -public class DummyFluidDispatcherBakedModel extends DelegateBakedModel -{ - private final VertexFormat format; - private final Function bakedTextureGetter; +public class DummyFluidDispatcherBakedModel extends DelegateBakedModel { + private final VertexFormat format; + private final Function bakedTextureGetter; - public DummyFluidDispatcherBakedModel( IBakedModel baseModel, VertexFormat format, Function bakedTextureGetter ) - { - super( baseModel ); - this.format = format; - this.bakedTextureGetter = bakedTextureGetter; - } + public DummyFluidDispatcherBakedModel(IBakedModel baseModel, VertexFormat format, Function bakedTextureGetter) { + super(baseModel); + this.format = format; + this.bakedTextureGetter = bakedTextureGetter; + } - // This is never used. See the item override list below. - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - return Collections.emptyList(); - } + // This is never used. See the item override list below. + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + return Collections.emptyList(); + } - @Override - public boolean isGui3d() - { - return this.getBaseModel().isGui3d(); - } + @Override + public boolean isGui3d() { + return this.getBaseModel().isGui3d(); + } - @Override - public boolean isBuiltInRenderer() - { - return false; - } + @Override + public boolean isBuiltInRenderer() { + return false; + } - @Override - public ItemOverrideList getOverrides() - { - return new ItemOverrideList( Collections.emptyList() ) - { - @Override - public IBakedModel handleItemState( IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity ) - { - if( !( stack.getItem() instanceof FluidDummyItem ) ) - { - return originalModel; - } + @Override + public ItemOverrideList getOverrides() { + return new ItemOverrideList(Collections.emptyList()) { + @Override + public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity) { + if (!(stack.getItem() instanceof FluidDummyItem)) { + return originalModel; + } - FluidDummyItem itemFacade = (FluidDummyItem) stack.getItem(); + FluidDummyItem itemFacade = (FluidDummyItem) stack.getItem(); - FluidStack fluidStack = itemFacade.getFluidStack( stack ); - if( fluidStack == null ) - { - fluidStack = new FluidStack( FluidRegistry.WATER, Fluid.BUCKET_VOLUME ); - } + FluidStack fluidStack = itemFacade.getFluidStack(stack); + if (fluidStack == null) { + fluidStack = new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME); + } - TextureAtlasSprite sprite = DummyFluidDispatcherBakedModel.this.bakedTextureGetter.apply( fluidStack.getFluid().getStill( fluidStack ) ); - if( sprite == null ) - { - return new DummyFluidBakedModel( ImmutableList.of() ); - } + TextureAtlasSprite sprite = DummyFluidDispatcherBakedModel.this.bakedTextureGetter.apply(fluidStack.getFluid().getStill(fluidStack)); + if (sprite == null) { + return new DummyFluidBakedModel(ImmutableList.of()); + } - return new DummyFluidBakedModel( ItemLayerModel.getQuadsForSprite( 0, sprite, DummyFluidDispatcherBakedModel.this.format, Optional.empty() ) ); - } - }; - } + return new DummyFluidBakedModel(ItemLayerModel.getQuadsForSprite(0, sprite, DummyFluidDispatcherBakedModel.this.format, Optional.empty())); + } + }; + } } diff --git a/src/main/java/appeng/client/render/DummyFluidItemModel.java b/src/main/java/appeng/client/render/DummyFluidItemModel.java index 6d609b56b..4240e67bb 100644 --- a/src/main/java/appeng/client/render/DummyFluidItemModel.java +++ b/src/main/java/appeng/client/render/DummyFluidItemModel.java @@ -19,10 +19,7 @@ package appeng.client.render; -import java.util.Collection; -import java.util.Collections; -import java.util.function.Function; - +import appeng.core.AppEng; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -31,59 +28,51 @@ import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.model.IModelState; -import appeng.core.AppEng; +import java.util.Collection; +import java.util.Collections; +import java.util.function.Function; /** * The model class for facades. Since facades wrap existing models, they don't declare any dependencies here other * than the cable anchor. */ -public class DummyFluidItemModel implements IModel -{ - // We use this to get the default item transforms and make our lives easier - private static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "item/dummy_fluid_item_base" ); +public class DummyFluidItemModel implements IModel { + // We use this to get the default item transforms and make our lives easier + private static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "item/dummy_fluid_item_base"); - private IModel baseModel = null; + private IModel baseModel = null; - private IModel getBaseModel() - { - if( this.baseModel == null ) - { - try - { - this.baseModel = ModelLoaderRegistry.getModel( MODEL_BASE ); - } - catch( Exception e ) - { - throw new RuntimeException( e ); - } - } - return this.baseModel; - } + private IModel getBaseModel() { + if (this.baseModel == null) { + try { + this.baseModel = ModelLoaderRegistry.getModel(MODEL_BASE); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + return this.baseModel; + } - @Override - public Collection getDependencies() - { - return Collections.emptyList(); - } + @Override + public Collection getDependencies() { + return Collections.emptyList(); + } - @Override - public Collection getTextures() - { - return Collections.emptyList(); - } + @Override + public Collection getTextures() { + return Collections.emptyList(); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - IBakedModel bakedBaseModel = this.getBaseModel().bake( state, format, bakedTextureGetter ); + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + IBakedModel bakedBaseModel = this.getBaseModel().bake(state, format, bakedTextureGetter); - return new DummyFluidDispatcherBakedModel( bakedBaseModel, format, bakedTextureGetter ); - } + return new DummyFluidDispatcherBakedModel(bakedBaseModel, format, bakedTextureGetter); + } - @Override - public IModelState getDefaultState() - { - return this.getBaseModel().getDefaultState(); - } + @Override + public IModelState getDefaultState() { + return this.getBaseModel().getDefaultState(); + } } diff --git a/src/main/java/appeng/client/render/FacadeBakedItemModel.java b/src/main/java/appeng/client/render/FacadeBakedItemModel.java index c22f128ea..8b851ae72 100644 --- a/src/main/java/appeng/client/render/FacadeBakedItemModel.java +++ b/src/main/java/appeng/client/render/FacadeBakedItemModel.java @@ -19,12 +19,7 @@ package appeng.client.render; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nullable; - +import appeng.client.render.cablebus.FacadeBuilder; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -32,7 +27,10 @@ import net.minecraft.client.renderer.block.model.ItemOverrideList; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; -import appeng.client.render.cablebus.FacadeBuilder; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; /** @@ -40,52 +38,44 @@ import appeng.client.render.cablebus.FacadeBuilder; * * @author covers1624 */ -public class FacadeBakedItemModel extends DelegateBakedModel -{ +public class FacadeBakedItemModel extends DelegateBakedModel { - private final ItemStack textureStack; - private final FacadeBuilder facadeBuilder; - private List quads = null; + private final ItemStack textureStack; + private final FacadeBuilder facadeBuilder; + private List quads = null; - protected FacadeBakedItemModel( IBakedModel base, ItemStack textureStack, FacadeBuilder facadeBuilder ) - { - super( base ); - this.textureStack = textureStack; - this.facadeBuilder = facadeBuilder; - } + protected FacadeBakedItemModel(IBakedModel base, ItemStack textureStack, FacadeBuilder facadeBuilder) { + super(base); + this.textureStack = textureStack; + this.facadeBuilder = facadeBuilder; + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - if( side != null ) - { - return Collections.emptyList(); - } - if( quads == null ) - { - quads = new ArrayList<>(); - quads.addAll( this.facadeBuilder.buildFacadeItemQuads( this.textureStack, EnumFacing.NORTH ) ); - quads.addAll( this.getBaseModel().getQuads( state, side, rand ) ); - quads = Collections.unmodifiableList( quads ); + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + if (side != null) { + return Collections.emptyList(); } - return quads; - } + if (quads == null) { + quads = new ArrayList<>(); + quads.addAll(this.facadeBuilder.buildFacadeItemQuads(this.textureStack, EnumFacing.NORTH)); + quads.addAll(this.getBaseModel().getQuads(state, side, rand)); + quads = Collections.unmodifiableList(quads); + } + return quads; + } - @Override - public boolean isGui3d() - { - return false; - } + @Override + public boolean isGui3d() { + return false; + } - @Override - public boolean isBuiltInRenderer() - { - return false; - } + @Override + public boolean isBuiltInRenderer() { + return false; + } - @Override - public ItemOverrideList getOverrides() - { - return ItemOverrideList.NONE; - } + @Override + public ItemOverrideList getOverrides() { + return ItemOverrideList.NONE; + } } diff --git a/src/main/java/appeng/client/render/FacadeDispatcherBakedModel.java b/src/main/java/appeng/client/render/FacadeDispatcherBakedModel.java index 893e84405..e7ef460ba 100644 --- a/src/main/java/appeng/client/render/FacadeDispatcherBakedModel.java +++ b/src/main/java/appeng/client/render/FacadeDispatcherBakedModel.java @@ -19,12 +19,8 @@ package appeng.client.render; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -import javax.annotation.Nullable; - +import appeng.client.render.cablebus.FacadeBuilder; +import appeng.items.parts.ItemFacade; import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import net.minecraft.block.state.IBlockState; @@ -37,8 +33,10 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -import appeng.client.render.cablebus.FacadeBuilder; -import appeng.items.parts.ItemFacade; +import javax.annotation.Nullable; +import java.util.Collections; +import java.util.List; +import java.util.Objects; /** @@ -46,65 +44,55 @@ import appeng.items.parts.ItemFacade; * on the item stack. * A custom Item Override List is used to accomplish this. */ -public class FacadeDispatcherBakedModel extends DelegateBakedModel -{ - private final VertexFormat format; - private final FacadeBuilder facadeBuilder; - private final Int2ObjectMap cache = new Int2ObjectArrayMap<>(); +public class FacadeDispatcherBakedModel extends DelegateBakedModel { + private final VertexFormat format; + private final FacadeBuilder facadeBuilder; + private final Int2ObjectMap cache = new Int2ObjectArrayMap<>(); - public FacadeDispatcherBakedModel( IBakedModel baseModel, VertexFormat format, FacadeBuilder facadeBuilder ) - { - super( baseModel ); - this.format = format; - this.facadeBuilder = facadeBuilder; - } + public FacadeDispatcherBakedModel(IBakedModel baseModel, VertexFormat format, FacadeBuilder facadeBuilder) { + super(baseModel); + this.format = format; + this.facadeBuilder = facadeBuilder; + } - // This is never used. See the item override list below. - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - return Collections.emptyList(); - } + // This is never used. See the item override list below. + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + return Collections.emptyList(); + } - @Override - public boolean isGui3d() - { - return this.getBaseModel().isGui3d(); - } + @Override + public boolean isGui3d() { + return this.getBaseModel().isGui3d(); + } - @Override - public boolean isBuiltInRenderer() - { - return false; - } + @Override + public boolean isBuiltInRenderer() { + return false; + } - @Override - public ItemOverrideList getOverrides() - { - return new ItemOverrideList( Collections.emptyList() ) - { - @Override - public IBakedModel handleItemState( IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity ) - { - if( !( stack.getItem() instanceof ItemFacade ) ) - { - return originalModel; - } + @Override + public ItemOverrideList getOverrides() { + return new ItemOverrideList(Collections.emptyList()) { + @Override + public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity) { + if (!(stack.getItem() instanceof ItemFacade)) { + return originalModel; + } - ItemFacade itemFacade = (ItemFacade) stack.getItem(); + ItemFacade itemFacade = (ItemFacade) stack.getItem(); - ItemStack textureItem = itemFacade.getTextureItem( stack ); + ItemStack textureItem = itemFacade.getTextureItem(stack); - int hash = Objects.hash( textureItem.getItem().getRegistryName(), textureItem.getMetadata(), textureItem.getTagCompound() ); - FacadeBakedItemModel model = FacadeDispatcherBakedModel.this.cache.get( hash ); - if( model == null ) - { - model = new FacadeBakedItemModel(FacadeDispatcherBakedModel.this.getBaseModel(), textureItem, FacadeDispatcherBakedModel.this.facadeBuilder); + int hash = Objects.hash(textureItem.getItem().getRegistryName(), textureItem.getMetadata(), textureItem.getTagCompound()); + FacadeBakedItemModel model = FacadeDispatcherBakedModel.this.cache.get(hash); + if (model == null) { + model = new FacadeBakedItemModel(FacadeDispatcherBakedModel.this.getBaseModel(), textureItem, FacadeDispatcherBakedModel.this.facadeBuilder); FacadeDispatcherBakedModel.this.cache.put(hash, model); } - return model; - } - }; - } + return model; + } + }; + } } diff --git a/src/main/java/appeng/client/render/FacadeItemModel.java b/src/main/java/appeng/client/render/FacadeItemModel.java index cc05a07d5..2f0d17b22 100644 --- a/src/main/java/appeng/client/render/FacadeItemModel.java +++ b/src/main/java/appeng/client/render/FacadeItemModel.java @@ -19,10 +19,8 @@ package appeng.client.render; -import java.util.Collection; -import java.util.Collections; -import java.util.function.Function; - +import appeng.client.render.cablebus.FacadeBuilder; +import appeng.core.AppEng; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -31,55 +29,47 @@ import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.model.IModelState; -import appeng.client.render.cablebus.FacadeBuilder; -import appeng.core.AppEng; +import java.util.Collection; +import java.util.Collections; +import java.util.function.Function; /** * The model class for facades. Since facades wrap existing models, they don't declare any dependencies here other * than the cable anchor. */ -public class FacadeItemModel implements IModel -{ - // We use this to get the default item transforms and make our lives easier - private static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "item/facade_base" ); +public class FacadeItemModel implements IModel { + // We use this to get the default item transforms and make our lives easier + private static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "item/facade_base"); - private IModel getBaseModel() - { - try - { - return ModelLoaderRegistry.getModel( MODEL_BASE ); - } - catch( Exception e ) - { - throw new RuntimeException( e ); - } - } + private IModel getBaseModel() { + try { + return ModelLoaderRegistry.getModel(MODEL_BASE); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - @Override - public Collection getDependencies() - { - return Collections.emptyList(); - } + @Override + public Collection getDependencies() { + return Collections.emptyList(); + } - @Override - public Collection getTextures() - { - return Collections.emptyList(); - } + @Override + public Collection getTextures() { + return Collections.emptyList(); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - IBakedModel bakedBaseModel = this.getBaseModel().bake( state, format, bakedTextureGetter ); - FacadeBuilder facadeBuilder = new FacadeBuilder(); + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + IBakedModel bakedBaseModel = this.getBaseModel().bake(state, format, bakedTextureGetter); + FacadeBuilder facadeBuilder = new FacadeBuilder(); - return new FacadeDispatcherBakedModel( bakedBaseModel, format, facadeBuilder ); - } + return new FacadeDispatcherBakedModel(bakedBaseModel, format, facadeBuilder); + } - @Override - public IModelState getDefaultState() - { - return this.getBaseModel().getDefaultState(); - } + @Override + public IModelState getDefaultState() { + return this.getBaseModel().getDefaultState(); + } } diff --git a/src/main/java/appeng/client/render/FacingToRotation.java b/src/main/java/appeng/client/render/FacingToRotation.java index e5a732829..ff3ce505b 100644 --- a/src/main/java/appeng/client/render/FacingToRotation.java +++ b/src/main/java/appeng/client/render/FacingToRotation.java @@ -19,109 +19,99 @@ package appeng.client.render; -import javax.vecmath.Matrix4f; -import javax.vecmath.Vector3f; - import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.model.TRSRTransformation; +import javax.vecmath.Matrix4f; +import javax.vecmath.Vector3f; + /** * TODO: Removed useless stuff. */ -public enum FacingToRotation -{ +public enum FacingToRotation { - // DUNSWE - // @formatter:off - DOWN_DOWN( new Vector3f( 0, 0, 0 ) ), // NOOP - DOWN_UP( new Vector3f( 0, 0, 0 ) ), // NOOP - DOWN_NORTH( new Vector3f( -90, 0, 0 ) ), - DOWN_SOUTH( new Vector3f( -90, 0, 180 ) ), - DOWN_WEST( new Vector3f( -90, 0, 90 ) ), - DOWN_EAST( new Vector3f( -90, 0, -90 ) ), - UP_DOWN( new Vector3f( 0, 0, 0 ) ), // NOOP - UP_UP( new Vector3f( 0, 0, 0 ) ), // NOOP - UP_NORTH( new Vector3f( 90, 0, 180 ) ), - UP_SOUTH( new Vector3f( 90, 0, 0 ) ), - UP_WEST( new Vector3f( 90, 0, 90 ) ), - UP_EAST( new Vector3f( 90, 0, -90 ) ), - NORTH_DOWN( new Vector3f( 0, 0, 180 ) ), - NORTH_UP( new Vector3f( 0, 0, 0 ) ), - NORTH_NORTH( new Vector3f( 0, 0, 0 ) ), // NOOP - NORTH_SOUTH( new Vector3f( 0, 0, 0 ) ), // NOOP - NORTH_WEST( new Vector3f( 0, 0, 90 ) ), - NORTH_EAST( new Vector3f( 0, 0, -90 ) ), - SOUTH_DOWN( new Vector3f( 0, 180, 180 ) ), - SOUTH_UP( new Vector3f( 0, 180, 0 ) ), - SOUTH_NORTH( new Vector3f( 0, 0, 0 ) ), // NOOP - SOUTH_SOUTH( new Vector3f( 0, 0, 0 ) ), // NOOP - SOUTH_WEST( new Vector3f( 0, 180, -90 ) ), - SOUTH_EAST( new Vector3f( 0, 180, 90 ) ), - WEST_DOWN( new Vector3f( 0, 90, 180 ) ), - WEST_UP( new Vector3f( 0, 90, 0 ) ), - WEST_NORTH( new Vector3f( 0, 90, -90 ) ), - WEST_SOUTH( new Vector3f( 0, 90, 90 ) ), - WEST_WEST( new Vector3f( 0, 0, 0 ) ), // NOOP - WEST_EAST( new Vector3f( 0, 0, 0 ) ), // NOOP - EAST_DOWN( new Vector3f( 0, -90, 180 ) ), - EAST_UP( new Vector3f( 0, -90, 0 ) ), - EAST_NORTH( new Vector3f( 0, -90, 90 ) ), - EAST_SOUTH( new Vector3f( 0, -90, -90 ) ), - EAST_WEST( new Vector3f( 0, 0, 0 ) ), // NOOP - EAST_EAST( new Vector3f( 0, 0, 0 ) ); // NOOP - // @formatter:on + // DUNSWE + // @formatter:off + DOWN_DOWN(new Vector3f(0, 0, 0)), // NOOP + DOWN_UP(new Vector3f(0, 0, 0)), // NOOP + DOWN_NORTH(new Vector3f(-90, 0, 0)), + DOWN_SOUTH(new Vector3f(-90, 0, 180)), + DOWN_WEST(new Vector3f(-90, 0, 90)), + DOWN_EAST(new Vector3f(-90, 0, -90)), + UP_DOWN(new Vector3f(0, 0, 0)), // NOOP + UP_UP(new Vector3f(0, 0, 0)), // NOOP + UP_NORTH(new Vector3f(90, 0, 180)), + UP_SOUTH(new Vector3f(90, 0, 0)), + UP_WEST(new Vector3f(90, 0, 90)), + UP_EAST(new Vector3f(90, 0, -90)), + NORTH_DOWN(new Vector3f(0, 0, 180)), + NORTH_UP(new Vector3f(0, 0, 0)), + NORTH_NORTH(new Vector3f(0, 0, 0)), // NOOP + NORTH_SOUTH(new Vector3f(0, 0, 0)), // NOOP + NORTH_WEST(new Vector3f(0, 0, 90)), + NORTH_EAST(new Vector3f(0, 0, -90)), + SOUTH_DOWN(new Vector3f(0, 180, 180)), + SOUTH_UP(new Vector3f(0, 180, 0)), + SOUTH_NORTH(new Vector3f(0, 0, 0)), // NOOP + SOUTH_SOUTH(new Vector3f(0, 0, 0)), // NOOP + SOUTH_WEST(new Vector3f(0, 180, -90)), + SOUTH_EAST(new Vector3f(0, 180, 90)), + WEST_DOWN(new Vector3f(0, 90, 180)), + WEST_UP(new Vector3f(0, 90, 0)), + WEST_NORTH(new Vector3f(0, 90, -90)), + WEST_SOUTH(new Vector3f(0, 90, 90)), + WEST_WEST(new Vector3f(0, 0, 0)), // NOOP + WEST_EAST(new Vector3f(0, 0, 0)), // NOOP + EAST_DOWN(new Vector3f(0, -90, 180)), + EAST_UP(new Vector3f(0, -90, 0)), + EAST_NORTH(new Vector3f(0, -90, 90)), + EAST_SOUTH(new Vector3f(0, -90, -90)), + EAST_WEST(new Vector3f(0, 0, 0)), // NOOP + EAST_EAST(new Vector3f(0, 0, 0)); // NOOP + // @formatter:on - private final Vector3f rot; - private final Matrix4f mat; + private final Vector3f rot; + private final Matrix4f mat; - private FacingToRotation( Vector3f rot ) - { - this.rot = rot; - this.mat = TRSRTransformation - .toVecmath( new org.lwjgl.util.vector.Matrix4f().rotate( (float) Math.toRadians( rot.x ), new org.lwjgl.util.vector.Vector3f( 1, 0, 0 ) ) - .rotate( (float) Math.toRadians( rot.y ), new org.lwjgl.util.vector.Vector3f( 0, 1, 0 ) ) - .rotate( (float) Math.toRadians( rot.z ), new org.lwjgl.util.vector.Vector3f( 0, 0, 1 ) ) ); - } + FacingToRotation(Vector3f rot) { + this.rot = rot; + this.mat = TRSRTransformation + .toVecmath(new org.lwjgl.util.vector.Matrix4f().rotate((float) Math.toRadians(rot.x), new org.lwjgl.util.vector.Vector3f(1, 0, 0)) + .rotate((float) Math.toRadians(rot.y), new org.lwjgl.util.vector.Vector3f(0, 1, 0)) + .rotate((float) Math.toRadians(rot.z), new org.lwjgl.util.vector.Vector3f(0, 0, 1))); + } - public Vector3f getRot() - { - return this.rot; - } + public Vector3f getRot() { + return this.rot; + } - public Matrix4f getMat() - { - return new Matrix4f( this.mat ); - } + public Matrix4f getMat() { + return new Matrix4f(this.mat); + } - public void glRotateCurrentMat() - { - GlStateManager.rotate( this.rot.x, 1, 0, 0 ); - GlStateManager.rotate( this.rot.y, 0, 1, 0 ); - GlStateManager.rotate( this.rot.z, 0, 0, 1 ); - } + public void glRotateCurrentMat() { + GlStateManager.rotate(this.rot.x, 1, 0, 0); + GlStateManager.rotate(this.rot.y, 0, 1, 0); + GlStateManager.rotate(this.rot.z, 0, 0, 1); + } - public EnumFacing rotate( EnumFacing facing ) - { - return TRSRTransformation.rotate( this.mat, facing ); - } + public EnumFacing rotate(EnumFacing facing) { + return TRSRTransformation.rotate(this.mat, facing); + } - public EnumFacing resultingRotate( EnumFacing facing ) - { - for( EnumFacing face : EnumFacing.values() ) - { - if( this.rotate( face ) == facing ) - { - return face; - } - } - return null; - } + public EnumFacing resultingRotate(EnumFacing facing) { + for (EnumFacing face : EnumFacing.values()) { + if (this.rotate(face) == facing) { + return face; + } + } + return null; + } - public static FacingToRotation get( EnumFacing forward, EnumFacing up ) - { - return values()[forward.ordinal() * 6 + up.ordinal()]; - } + public static FacingToRotation get(EnumFacing forward, EnumFacing up) { + return values()[forward.ordinal() * 6 + up.ordinal()]; + } } \ No newline at end of file diff --git a/src/main/java/appeng/client/render/SpatialSkyRender.java b/src/main/java/appeng/client/render/SpatialSkyRender.java index 2714a5a5e..61f5d7524 100644 --- a/src/main/java/appeng/client/render/SpatialSkyRender.java +++ b/src/main/java/appeng/client/render/SpatialSkyRender.java @@ -19,183 +19,161 @@ package appeng.client.render; -import java.util.Random; - -import org.lwjgl.opengl.GL11; - import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; -import net.minecraft.client.renderer.BufferBuilder; -import net.minecraft.client.renderer.GLAllocation; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.OpenGlHelper; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.*; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraftforge.client.IRenderHandler; +import org.lwjgl.opengl.GL11; + +import java.util.Random; -public class SpatialSkyRender extends IRenderHandler -{ +public class SpatialSkyRender extends IRenderHandler { - private static final SpatialSkyRender INSTANCE = new SpatialSkyRender(); + private static final SpatialSkyRender INSTANCE = new SpatialSkyRender(); - private final Random random = new Random(); - private final int dspList; - private long cycle = 0; + private final Random random = new Random(); + private final int dspList; + private long cycle = 0; - public SpatialSkyRender() - { - this.dspList = GLAllocation.generateDisplayLists( 1 ); - } + public SpatialSkyRender() { + this.dspList = GLAllocation.generateDisplayLists(1); + } - public static IRenderHandler getInstance() - { - return INSTANCE; - } + public static IRenderHandler getInstance() { + return INSTANCE; + } - @Override - public void render( final float partialTicks, final WorldClient world, final Minecraft mc ) - { + @Override + public void render(final float partialTicks, final WorldClient world, final Minecraft mc) { - final long now = System.currentTimeMillis(); - if( now - this.cycle > 2000 ) - { - this.cycle = now; - GlStateManager.glNewList( this.dspList, GL11.GL_COMPILE ); - this.renderTwinkles(); - GlStateManager.glEndList(); - } + final long now = System.currentTimeMillis(); + if (now - this.cycle > 2000) { + this.cycle = now; + GlStateManager.glNewList(this.dspList, GL11.GL_COMPILE); + this.renderTwinkles(); + GlStateManager.glEndList(); + } - float fade = now - this.cycle; - fade /= 1000; - fade = 0.15f * ( 1.0f - Math.abs( ( fade - 1.0f ) * ( fade - 1.0f ) ) ); + float fade = now - this.cycle; + fade /= 1000; + fade = 0.15f * (1.0f - Math.abs((fade - 1.0f) * (fade - 1.0f))); - GlStateManager.disableFog(); - GlStateManager.disableAlpha(); - GlStateManager.disableBlend(); - GlStateManager.depthMask( false ); - GlStateManager.color( 0.0f, 0.0f, 0.0f, 1.0f ); - final Tessellator tessellator = Tessellator.getInstance(); - final BufferBuilder VertexBuffer = tessellator.getBuffer(); + GlStateManager.disableFog(); + GlStateManager.disableAlpha(); + GlStateManager.disableBlend(); + GlStateManager.depthMask(false); + GlStateManager.color(0.0f, 0.0f, 0.0f, 1.0f); + final Tessellator tessellator = Tessellator.getInstance(); + final BufferBuilder VertexBuffer = tessellator.getBuffer(); - // This renders a skybox around the player at a far, fixed distance from them. - // The skybox is pitch black and untextured - for( int i = 0; i < 6; ++i ) - { - GlStateManager.pushMatrix(); + // This renders a skybox around the player at a far, fixed distance from them. + // The skybox is pitch black and untextured + for (int i = 0; i < 6; ++i) { + GlStateManager.pushMatrix(); - if( i == 1 ) - { - GlStateManager.rotate( 90.0F, 1.0F, 0.0F, 0.0F ); - } + if (i == 1) { + GlStateManager.rotate(90.0F, 1.0F, 0.0F, 0.0F); + } - if( i == 2 ) - { - GlStateManager.rotate( -90.0F, 1.0F, 0.0F, 0.0F ); - } + if (i == 2) { + GlStateManager.rotate(-90.0F, 1.0F, 0.0F, 0.0F); + } - if( i == 3 ) - { - GlStateManager.rotate( 180.0F, 1.0F, 0.0F, 0.0F ); - } + if (i == 3) { + GlStateManager.rotate(180.0F, 1.0F, 0.0F, 0.0F); + } - if( i == 4 ) - { - GlStateManager.rotate( 90.0F, 0.0F, 0.0F, 1.0F ); - } + if (i == 4) { + GlStateManager.rotate(90.0F, 0.0F, 0.0F, 1.0F); + } - if( i == 5 ) - { - GlStateManager.rotate( -90.0F, 0.0F, 0.0F, 1.0F ); - } + if (i == 5) { + GlStateManager.rotate(-90.0F, 0.0F, 0.0F, 1.0F); + } - GlStateManager.disableTexture2D(); - VertexBuffer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION ); - VertexBuffer.pos( -100.0D, -100.0D, -100.0D ).endVertex(); - VertexBuffer.pos( -100.0D, -100.0D, 100.0D ).endVertex(); - VertexBuffer.pos( 100.0D, -100.0D, 100.0D ).endVertex(); - VertexBuffer.pos( 100.0D, -100.0D, -100.0D ).endVertex(); - tessellator.draw(); - GlStateManager.enableTexture2D(); - GlStateManager.popMatrix(); - } + GlStateManager.disableTexture2D(); + VertexBuffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION); + VertexBuffer.pos(-100.0D, -100.0D, -100.0D).endVertex(); + VertexBuffer.pos(-100.0D, -100.0D, 100.0D).endVertex(); + VertexBuffer.pos(100.0D, -100.0D, 100.0D).endVertex(); + VertexBuffer.pos(100.0D, -100.0D, -100.0D).endVertex(); + tessellator.draw(); + GlStateManager.enableTexture2D(); + GlStateManager.popMatrix(); + } - GlStateManager.depthMask( true ); + GlStateManager.depthMask(true); - if( fade > 0.0f ) - { - GlStateManager.disableFog(); - GlStateManager.disableAlpha(); - GlStateManager.enableBlend(); - GlStateManager.disableTexture2D(); - GlStateManager.depthMask( false ); - OpenGlHelper.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0 ); + if (fade > 0.0f) { + GlStateManager.disableFog(); + GlStateManager.disableAlpha(); + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.depthMask(false); + OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); - RenderHelper.disableStandardItemLighting(); + RenderHelper.disableStandardItemLighting(); - GlStateManager.color( fade, fade, fade, 1.0f ); - GlStateManager.callList( this.dspList ); - } + GlStateManager.color(fade, fade, fade, 1.0f); + GlStateManager.callList(this.dspList); + } - GlStateManager.depthMask( true ); - GlStateManager.enableBlend(); - GlStateManager.enableAlpha(); - GlStateManager.enableTexture2D(); - GlStateManager.enableFog(); + GlStateManager.depthMask(true); + GlStateManager.enableBlend(); + GlStateManager.enableAlpha(); + GlStateManager.enableTexture2D(); + GlStateManager.enableFog(); - GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f ); - } + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + } - private void renderTwinkles() - { - final Tessellator tessellator = Tessellator.getInstance(); - final BufferBuilder VertexBuffer = tessellator.getBuffer(); - VertexBuffer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION ); + private void renderTwinkles() { + final Tessellator tessellator = Tessellator.getInstance(); + final BufferBuilder VertexBuffer = tessellator.getBuffer(); + VertexBuffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION); - for( int i = 0; i < 50; ++i ) - { - double iX = this.random.nextFloat() * 2.0F - 1.0F; - double iY = this.random.nextFloat() * 2.0F - 1.0F; - double iZ = this.random.nextFloat() * 2.0F - 1.0F; - final double d3 = 0.05F + this.random.nextFloat() * 0.1F; - double dist = iX * iX + iY * iY + iZ * iZ; + for (int i = 0; i < 50; ++i) { + double iX = this.random.nextFloat() * 2.0F - 1.0F; + double iY = this.random.nextFloat() * 2.0F - 1.0F; + double iZ = this.random.nextFloat() * 2.0F - 1.0F; + final double d3 = 0.05F + this.random.nextFloat() * 0.1F; + double dist = iX * iX + iY * iY + iZ * iZ; - if( dist < 1.0D && dist > 0.01D ) - { - dist = 1.0D / Math.sqrt( dist ); - iX *= dist; - iY *= dist; - iZ *= dist; - final double x = iX * 100.0D; - final double y = iY * 100.0D; - final double z = iZ * 100.0D; - final double d8 = Math.atan2( iX, iZ ); - final double d9 = Math.sin( d8 ); - final double d10 = Math.cos( d8 ); - final double d11 = Math.atan2( Math.sqrt( iX * iX + iZ * iZ ), iY ); - final double d12 = Math.sin( d11 ); - final double d13 = Math.cos( d11 ); - final double d14 = this.random.nextDouble() * Math.PI * 2.0D; - final double d15 = Math.sin( d14 ); - final double d16 = Math.cos( d14 ); + if (dist < 1.0D && dist > 0.01D) { + dist = 1.0D / Math.sqrt(dist); + iX *= dist; + iY *= dist; + iZ *= dist; + final double x = iX * 100.0D; + final double y = iY * 100.0D; + final double z = iZ * 100.0D; + final double d8 = Math.atan2(iX, iZ); + final double d9 = Math.sin(d8); + final double d10 = Math.cos(d8); + final double d11 = Math.atan2(Math.sqrt(iX * iX + iZ * iZ), iY); + final double d12 = Math.sin(d11); + final double d13 = Math.cos(d11); + final double d14 = this.random.nextDouble() * Math.PI * 2.0D; + final double d15 = Math.sin(d14); + final double d16 = Math.cos(d14); - for( int j = 0; j < 4; ++j ) - { - final double d17 = 0.0D; - final double d18 = ( ( j & 2 ) - 1 ) * d3; - final double d19 = ( ( j + 1 & 2 ) - 1 ) * d3; - final double d20 = d18 * d16 - d19 * d15; - final double d21 = d19 * d16 + d18 * d15; - final double d22 = d20 * d12 + d17 * d13; - final double d23 = d17 * d12 - d20 * d13; - final double d24 = d23 * d9 - d21 * d10; - final double d25 = d21 * d9 + d23 * d10; - VertexBuffer.pos( x + d24, y + d22, z + d25 ).endVertex(); - } - } - } + for (int j = 0; j < 4; ++j) { + final double d17 = 0.0D; + final double d18 = ((j & 2) - 1) * d3; + final double d19 = ((j + 1 & 2) - 1) * d3; + final double d20 = d18 * d16 - d19 * d15; + final double d21 = d19 * d16 + d18 * d15; + final double d22 = d20 * d12 + d17 * d13; + final double d23 = d17 * d12 - d20 * d13; + final double d24 = d23 * d9 - d21 * d10; + final double d25 = d21 * d9 + d23 * d10; + VertexBuffer.pos(x + d24, y + d22, z + d25).endVertex(); + } + } + } - tessellator.draw(); - } + tessellator.draw(); + } } diff --git a/src/main/java/appeng/client/render/StackSizeRenderer.java b/src/main/java/appeng/client/render/StackSizeRenderer.java index a39994eda..76fedc84a 100644 --- a/src/main/java/appeng/client/render/StackSizeRenderer.java +++ b/src/main/java/appeng/client/render/StackSizeRenderer.java @@ -19,15 +19,14 @@ package appeng.client.render; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.GlStateManager; - import appeng.api.storage.data.IAEItemStack; import appeng.core.AEConfig; import appeng.core.localization.GuiText; import appeng.util.ISlimReadableNumberConverter; import appeng.util.IWideReadableNumberConverter; import appeng.util.ReadableNumberConverter; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.renderer.GlStateManager; /** @@ -36,72 +35,63 @@ import appeng.util.ReadableNumberConverter; * @version rv2 * @since rv0 */ -public class StackSizeRenderer -{ - private static final ISlimReadableNumberConverter SLIM_CONVERTER = ReadableNumberConverter.INSTANCE; - private static final IWideReadableNumberConverter WIDE_CONVERTER = ReadableNumberConverter.INSTANCE; +public class StackSizeRenderer { + private static final ISlimReadableNumberConverter SLIM_CONVERTER = ReadableNumberConverter.INSTANCE; + private static final IWideReadableNumberConverter WIDE_CONVERTER = ReadableNumberConverter.INSTANCE; - public void renderStackSize( FontRenderer fontRenderer, IAEItemStack aeStack, int xPos, int yPos ) - { - if( aeStack != null ) - { - final float scaleFactor = AEConfig.instance().useTerminalUseLargeFont() ? 0.85f : 0.5f; - final float inverseScaleFactor = 1.0f / scaleFactor; - final int offset = AEConfig.instance().useTerminalUseLargeFont() ? 0 : -1; + public void renderStackSize(FontRenderer fontRenderer, IAEItemStack aeStack, int xPos, int yPos) { + if (aeStack != null) { + final float scaleFactor = AEConfig.instance().useTerminalUseLargeFont() ? 0.85f : 0.5f; + final float inverseScaleFactor = 1.0f / scaleFactor; + final int offset = AEConfig.instance().useTerminalUseLargeFont() ? 0 : -1; - final boolean unicodeFlag = fontRenderer.getUnicodeFlag(); - fontRenderer.setUnicodeFlag( false ); + final boolean unicodeFlag = fontRenderer.getUnicodeFlag(); + fontRenderer.setUnicodeFlag(false); - if( aeStack.getStackSize() == 0 && aeStack.isCraftable() ) - { - final String craftLabelText = AEConfig.instance().useTerminalUseLargeFont() ? GuiText.LargeFontCraft.getLocal() : GuiText.SmallFontCraft - .getLocal(); - GlStateManager.disableLighting(); - GlStateManager.disableDepth(); - GlStateManager.disableBlend(); - GlStateManager.pushMatrix(); - GlStateManager.scale( scaleFactor, scaleFactor, scaleFactor ); - final int X = (int) ( ( (float) xPos + offset + 16.0f - fontRenderer.getStringWidth( craftLabelText ) * scaleFactor ) * inverseScaleFactor ); - final int Y = (int) ( ( (float) yPos + offset + 16.0f - 7.0f * scaleFactor ) * inverseScaleFactor ); - fontRenderer.drawStringWithShadow( craftLabelText, X, Y, 16777215 ); - GlStateManager.popMatrix(); - GlStateManager.enableLighting(); - GlStateManager.enableDepth(); - GlStateManager.enableBlend(); - } + if (aeStack.getStackSize() == 0 && aeStack.isCraftable()) { + final String craftLabelText = AEConfig.instance().useTerminalUseLargeFont() ? GuiText.LargeFontCraft.getLocal() : GuiText.SmallFontCraft + .getLocal(); + GlStateManager.disableLighting(); + GlStateManager.disableDepth(); + GlStateManager.disableBlend(); + GlStateManager.pushMatrix(); + GlStateManager.scale(scaleFactor, scaleFactor, scaleFactor); + final int X = (int) (((float) xPos + offset + 16.0f - fontRenderer.getStringWidth(craftLabelText) * scaleFactor) * inverseScaleFactor); + final int Y = (int) (((float) yPos + offset + 16.0f - 7.0f * scaleFactor) * inverseScaleFactor); + fontRenderer.drawStringWithShadow(craftLabelText, X, Y, 16777215); + GlStateManager.popMatrix(); + GlStateManager.enableLighting(); + GlStateManager.enableDepth(); + GlStateManager.enableBlend(); + } - if( aeStack.getStackSize() > 0 ) - { - final String stackSize = this.getToBeRenderedStackSize( aeStack.getStackSize() ); + if (aeStack.getStackSize() > 0) { + final String stackSize = this.getToBeRenderedStackSize(aeStack.getStackSize()); - GlStateManager.disableLighting(); - GlStateManager.disableDepth(); - GlStateManager.disableBlend(); - GlStateManager.pushMatrix(); - GlStateManager.scale( scaleFactor, scaleFactor, scaleFactor ); - final int X = (int) ( ( (float) xPos + offset + 16.0f - fontRenderer.getStringWidth( stackSize ) * scaleFactor ) * inverseScaleFactor ); - final int Y = (int) ( ( (float) yPos + offset + 16.0f - 7.0f * scaleFactor ) * inverseScaleFactor ); - fontRenderer.drawStringWithShadow( stackSize, X, Y, 16777215 ); - GlStateManager.popMatrix(); - GlStateManager.enableLighting(); - GlStateManager.enableDepth(); - GlStateManager.enableBlend(); - } + GlStateManager.disableLighting(); + GlStateManager.disableDepth(); + GlStateManager.disableBlend(); + GlStateManager.pushMatrix(); + GlStateManager.scale(scaleFactor, scaleFactor, scaleFactor); + final int X = (int) (((float) xPos + offset + 16.0f - fontRenderer.getStringWidth(stackSize) * scaleFactor) * inverseScaleFactor); + final int Y = (int) (((float) yPos + offset + 16.0f - 7.0f * scaleFactor) * inverseScaleFactor); + fontRenderer.drawStringWithShadow(stackSize, X, Y, 16777215); + GlStateManager.popMatrix(); + GlStateManager.enableLighting(); + GlStateManager.enableDepth(); + GlStateManager.enableBlend(); + } - fontRenderer.setUnicodeFlag( unicodeFlag ); - } - } + fontRenderer.setUnicodeFlag(unicodeFlag); + } + } - private String getToBeRenderedStackSize( final long originalSize ) - { - if( AEConfig.instance().useTerminalUseLargeFont() ) - { - return SLIM_CONVERTER.toSlimReadableForm( originalSize ); - } - else - { - return WIDE_CONVERTER.toWideReadableForm( originalSize ); - } - } + private String getToBeRenderedStackSize(final long originalSize) { + if (AEConfig.instance().useTerminalUseLargeFont()) { + return SLIM_CONVERTER.toSlimReadableForm(originalSize); + } else { + return WIDE_CONVERTER.toWideReadableForm(originalSize); + } + } } diff --git a/src/main/java/appeng/client/render/StaticBlockColor.java b/src/main/java/appeng/client/render/StaticBlockColor.java index 366f9dd17..e70f79db1 100644 --- a/src/main/java/appeng/client/render/StaticBlockColor.java +++ b/src/main/java/appeng/client/render/StaticBlockColor.java @@ -19,33 +19,29 @@ package appeng.client.render; -import javax.annotation.Nullable; - +import appeng.api.util.AEColor; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.color.IBlockColor; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; -import appeng.api.util.AEColor; +import javax.annotation.Nullable; /** * Returns the shades of a single AE color for tint indices 0, 1, and 2. */ -public class StaticBlockColor implements IBlockColor -{ +public class StaticBlockColor implements IBlockColor { - private final AEColor color; + private final AEColor color; - public StaticBlockColor( AEColor color ) - { - this.color = color; - } + public StaticBlockColor(AEColor color) { + this.color = color; + } - @Override - public int colorMultiplier( IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex ) - { - return this.color.getVariantByTintIndex( tintIndex ); - } + @Override + public int colorMultiplier(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex) { + return this.color.getVariantByTintIndex(tintIndex); + } } diff --git a/src/main/java/appeng/client/render/StaticItemColor.java b/src/main/java/appeng/client/render/StaticItemColor.java index 29734f63e..d81a970e0 100644 --- a/src/main/java/appeng/client/render/StaticItemColor.java +++ b/src/main/java/appeng/client/render/StaticItemColor.java @@ -19,29 +19,25 @@ package appeng.client.render; +import appeng.api.util.AEColor; import net.minecraft.client.renderer.color.IItemColor; import net.minecraft.item.ItemStack; -import appeng.api.util.AEColor; - /** * Returns the shades of a single AE color for tint indices 0, 1, and 2. */ -public class StaticItemColor implements IItemColor -{ +public class StaticItemColor implements IItemColor { - private final AEColor color; + private final AEColor color; - public StaticItemColor( AEColor color ) - { - this.color = color; - } + public StaticItemColor(AEColor color) { + this.color = color; + } - @Override - public int colorMultiplier( ItemStack stack, int tintIndex ) - { - return this.color.getVariantByTintIndex( tintIndex ); - } + @Override + public int colorMultiplier(ItemStack stack, int tintIndex) { + return this.color.getVariantByTintIndex(tintIndex); + } } diff --git a/src/main/java/appeng/client/render/TesrRenderHelper.java b/src/main/java/appeng/client/render/TesrRenderHelper.java index 7060560f0..e14303639 100644 --- a/src/main/java/appeng/client/render/TesrRenderHelper.java +++ b/src/main/java/appeng/client/render/TesrRenderHelper.java @@ -20,6 +20,9 @@ package appeng.client.render; import appeng.api.storage.data.IAEFluidStack; +import appeng.api.storage.data.IAEItemStack; +import appeng.util.IWideReadableNumberConverter; +import appeng.util.ReadableNumberConverter; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.*; @@ -28,10 +31,6 @@ import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; - -import appeng.api.storage.data.IAEItemStack; -import appeng.util.IWideReadableNumberConverter; -import appeng.util.ReadableNumberConverter; import net.minecraftforge.fluids.FluidStack; import org.lwjgl.opengl.GL11; @@ -39,174 +38,164 @@ import org.lwjgl.opengl.GL11; /** * Helper methods for rendering TESRs. */ -public class TesrRenderHelper -{ +public class TesrRenderHelper { - private static final IWideReadableNumberConverter NUMBER_CONVERTER = ReadableNumberConverter.INSTANCE; + private static final IWideReadableNumberConverter NUMBER_CONVERTER = ReadableNumberConverter.INSTANCE; - /** - * Move the current coordinate system to the center of the given block face, assuming that the origin is currently - * at the center of a block. - */ - public static void moveToFace( EnumFacing face ) - { - GlStateManager.translate( face.getFrontOffsetX() * 0.50, face.getFrontOffsetY() * 0.50, face.getFrontOffsetZ() * 0.50 ); - } + /** + * Move the current coordinate system to the center of the given block face, assuming that the origin is currently + * at the center of a block. + */ + public static void moveToFace(EnumFacing face) { + GlStateManager.translate(face.getFrontOffsetX() * 0.50, face.getFrontOffsetY() * 0.50, face.getFrontOffsetZ() * 0.50); + } - /** - * Rotate the current coordinate system so it is on the face of the given block side. This can be used to render on - * the given face as if it was - * a 2D canvas. - */ - public static void rotateToFace( EnumFacing face, byte spin ) - { - switch( face ) - { - case UP: - GlStateManager.scale( 1.0f, -1.0f, 1.0f ); - GlStateManager.rotate( 90.0f, 1.0f, 0.0f, 0.0f ); - GlStateManager.rotate( spin * 90.0F, 0, 0, 1 ); - break; + /** + * Rotate the current coordinate system so it is on the face of the given block side. This can be used to render on + * the given face as if it was + * a 2D canvas. + */ + public static void rotateToFace(EnumFacing face, byte spin) { + switch (face) { + case UP: + GlStateManager.scale(1.0f, -1.0f, 1.0f); + GlStateManager.rotate(90.0f, 1.0f, 0.0f, 0.0f); + GlStateManager.rotate(spin * 90.0F, 0, 0, 1); + break; - case DOWN: - GlStateManager.scale( 1.0f, -1.0f, 1.0f ); - GlStateManager.rotate( -90.0f, 1.0f, 0.0f, 0.0f ); - GlStateManager.rotate( spin * -90.0F, 0, 0, 1 ); - break; + case DOWN: + GlStateManager.scale(1.0f, -1.0f, 1.0f); + GlStateManager.rotate(-90.0f, 1.0f, 0.0f, 0.0f); + GlStateManager.rotate(spin * -90.0F, 0, 0, 1); + break; - case EAST: - GlStateManager.scale( -1.0f, -1.0f, -1.0f ); - GlStateManager.rotate( -90.0f, 0.0f, 1.0f, 0.0f ); - break; + case EAST: + GlStateManager.scale(-1.0f, -1.0f, -1.0f); + GlStateManager.rotate(-90.0f, 0.0f, 1.0f, 0.0f); + break; - case WEST: - GlStateManager.scale( -1.0f, -1.0f, -1.0f ); - GlStateManager.rotate( 90.0f, 0.0f, 1.0f, 0.0f ); - break; + case WEST: + GlStateManager.scale(-1.0f, -1.0f, -1.0f); + GlStateManager.rotate(90.0f, 0.0f, 1.0f, 0.0f); + break; - case NORTH: - GlStateManager.scale( -1.0f, -1.0f, -1.0f ); - break; + case NORTH: + GlStateManager.scale(-1.0f, -1.0f, -1.0f); + break; - case SOUTH: - GlStateManager.scale( -1.0f, -1.0f, -1.0f ); - GlStateManager.rotate( 180.0f, 0.0f, 1.0f, 0.0f ); - break; + case SOUTH: + GlStateManager.scale(-1.0f, -1.0f, -1.0f); + GlStateManager.rotate(180.0f, 0.0f, 1.0f, 0.0f); + break; - default: - break; - } - } + default: + break; + } + } - /** - * Render an item in 2D. - */ - public static void renderItem2d( ItemStack itemStack, float scale ) - { - if( !itemStack.isEmpty() ) - { - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, 240.f, 240.0f ); + /** + * Render an item in 2D. + */ + public static void renderItem2d(ItemStack itemStack, float scale) { + if (!itemStack.isEmpty()) { + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.f, 240.0f); - GlStateManager.pushMatrix(); + GlStateManager.pushMatrix(); - // The Z-scaling by 0.0001 causes the model to be visually "flattened" - // This cannot replace a proper projection, but it's cheap and gives the desired - // effect at least from head-on - GlStateManager.scale( scale / 32.0f, scale / 32.0f, 0.0001f ); - // Position the item icon at the top middle of the panel - GlStateManager.translate( -8, -11, 0 ); + // The Z-scaling by 0.0001 causes the model to be visually "flattened" + // This cannot replace a proper projection, but it's cheap and gives the desired + // effect at least from head-on + GlStateManager.scale(scale / 32.0f, scale / 32.0f, 0.0001f); + // Position the item icon at the top middle of the panel + GlStateManager.translate(-8, -11, 0); - RenderItem renderItem = Minecraft.getMinecraft().getRenderItem(); - renderItem.renderItemAndEffectIntoGUI( itemStack, 0, 0 ); + RenderItem renderItem = Minecraft.getMinecraft().getRenderItem(); + renderItem.renderItemAndEffectIntoGUI(itemStack, 0, 0); - GlStateManager.popMatrix(); - } - } + GlStateManager.popMatrix(); + } + } - public static void renderFluid2d( FluidStack fluidStack, float scale ) - { - if( fluidStack != null ) - { - GlStateManager.pushMatrix(); - int color = fluidStack.getFluid().getColor( fluidStack ); - float r = ( color >> 16 & 255 ) / 255.0f; - float g = ( color >> 8 & 255 ) / 255.0f; - float b = ( color & 255 ) / 255.0f; - TextureAtlasSprite sprite = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite( fluidStack.getFluid().getStill( fluidStack ).toString() ); - GlStateManager.enableBlend(); - GlStateManager.blendFunc( GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA ); - GlStateManager.disableAlpha(); - GlStateManager.disableLighting(); - Minecraft.getMinecraft().getTextureManager().bindTexture( TextureMap.LOCATION_BLOCKS_TEXTURE ); - Tessellator tess = Tessellator.getInstance(); - BufferBuilder buf = tess.getBuffer(); + public static void renderFluid2d(FluidStack fluidStack, float scale) { + if (fluidStack != null) { + GlStateManager.pushMatrix(); + int color = fluidStack.getFluid().getColor(fluidStack); + float r = (color >> 16 & 255) / 255.0f; + float g = (color >> 8 & 255) / 255.0f; + float b = (color & 255) / 255.0f; + TextureAtlasSprite sprite = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(fluidStack.getFluid().getStill(fluidStack).toString()); + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); + GlStateManager.disableAlpha(); + GlStateManager.disableLighting(); + Minecraft.getMinecraft().getTextureManager().bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); + Tessellator tess = Tessellator.getInstance(); + BufferBuilder buf = tess.getBuffer(); - float width = 0.4f; - float height = 0.4f; - float alpha = 1.0f; - float z = 0.0001f; - float x = -0.20f; - float y = -0.25f; + float width = 0.4f; + float height = 0.4f; + float alpha = 1.0f; + float z = 0.0001f; + float x = -0.20f; + float y = -0.25f; - buf.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR ); - double uMin = sprite.getInterpolatedU( 16D - width * 16D ), uMax = sprite.getInterpolatedU( width * 16D ); - double vMin = sprite.getMinV(), vMax = sprite.getInterpolatedV( height * 16D ); - buf.pos( x, y, z ).tex( uMin, vMin ).color( r, g, b, alpha ).endVertex(); - buf.pos( x, y + height, z ).tex( uMin, vMax ).color( r, g, b, alpha ).endVertex(); - buf.pos( x + width, y + height, z ).tex( uMax, vMax ).color( r, g, b, alpha ).endVertex(); - buf.pos( x + width, y, z ).tex( uMax, vMin ).color( r, g, b, alpha ).endVertex(); + buf.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); + double uMin = sprite.getInterpolatedU(16D - width * 16D), uMax = sprite.getInterpolatedU(width * 16D); + double vMin = sprite.getMinV(), vMax = sprite.getInterpolatedV(height * 16D); + buf.pos(x, y, z).tex(uMin, vMin).color(r, g, b, alpha).endVertex(); + buf.pos(x, y + height, z).tex(uMin, vMax).color(r, g, b, alpha).endVertex(); + buf.pos(x + width, y + height, z).tex(uMax, vMax).color(r, g, b, alpha).endVertex(); + buf.pos(x + width, y, z).tex(uMax, vMin).color(r, g, b, alpha).endVertex(); - tess.draw(); - GlStateManager.enableLighting(); - GlStateManager.enableAlpha(); - GlStateManager.disableBlend(); - GlStateManager.color( 1F, 1F, 1F, 1F ); - GlStateManager.popMatrix(); + tess.draw(); + GlStateManager.enableLighting(); + GlStateManager.enableAlpha(); + GlStateManager.disableBlend(); + GlStateManager.color(1F, 1F, 1F, 1F); + GlStateManager.popMatrix(); - } - } + } + } - /** - * Render an item in 2D and the given text below it. - * - * @param spacing Specifies how far apart the item and the item stack amount are rendered. - */ - public static void renderItem2dWithAmount( IAEItemStack itemStack, float itemScale, float spacing ) - { - final ItemStack renderStack = itemStack.asItemStackRepresentation(); + /** + * Render an item in 2D and the given text below it. + * + * @param spacing Specifies how far apart the item and the item stack amount are rendered. + */ + public static void renderItem2dWithAmount(IAEItemStack itemStack, float itemScale, float spacing) { + final ItemStack renderStack = itemStack.asItemStackRepresentation(); - TesrRenderHelper.renderItem2d( renderStack, itemScale ); + TesrRenderHelper.renderItem2d(renderStack, itemScale); - final long stackSize = itemStack.getStackSize(); - final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm( stackSize ); + final long stackSize = itemStack.getStackSize(); + final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm(stackSize); - // Render the item count - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - final int width = fr.getStringWidth( renderedStackSize ); - GlStateManager.translate( 0.0f, spacing, 0 ); - GlStateManager.scale( 1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f ); - GlStateManager.translate( -0.5f * width, 0.0f, 0.5f ); - fr.drawString( renderedStackSize, 0, 0, 0 ); + // Render the item count + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + final int width = fr.getStringWidth(renderedStackSize); + GlStateManager.translate(0.0f, spacing, 0); + GlStateManager.scale(1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f); + GlStateManager.translate(-0.5f * width, 0.0f, 0.5f); + fr.drawString(renderedStackSize, 0, 0, 0); - } + } - public static void renderFluid2dWithAmount( IAEFluidStack fluidStack, float scale, float spacing ) - { - final FluidStack renderStack = fluidStack.getFluidStack(); + public static void renderFluid2dWithAmount(IAEFluidStack fluidStack, float scale, float spacing) { + final FluidStack renderStack = fluidStack.getFluidStack(); - TesrRenderHelper.renderFluid2d( renderStack, scale ); + TesrRenderHelper.renderFluid2d(renderStack, scale); - final long stackSize = fluidStack.getStackSize() / 1000; - final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm( stackSize ) + "B"; + final long stackSize = fluidStack.getStackSize() / 1000; + final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm(stackSize) + "B"; - // Render the item count - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - final int width = fr.getStringWidth( renderedStackSize ); - GlStateManager.translate( 0.0f, spacing, 0 ); - GlStateManager.scale( 1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f ); - GlStateManager.translate( -0.5f * width, 0.0f, 0.5f ); - fr.drawString( renderedStackSize, 0, 0, 0 ); + // Render the item count + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + final int width = fr.getStringWidth(renderedStackSize); + GlStateManager.translate(0.0f, spacing, 0); + GlStateManager.scale(1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f); + GlStateManager.translate(-0.5f * width, 0.0f, 0.5f); + fr.drawString(renderedStackSize, 0, 0, 0); - } + } } diff --git a/src/main/java/appeng/client/render/VertexFormats.java b/src/main/java/appeng/client/render/VertexFormats.java index 063286d51..1a40fb63d 100644 --- a/src/main/java/appeng/client/render/VertexFormats.java +++ b/src/main/java/appeng/client/render/VertexFormats.java @@ -28,42 +28,31 @@ import net.minecraftforge.fml.client.FMLClientHandler; /** * Utility for managing extended Vertex Formats without having to re-clone existing vertex formats over and over again. */ -public final class VertexFormats -{ +public final class VertexFormats { - // Standard item format extended with lightmap coordinates - private static final VertexFormat itemFormatWithLightMap = new VertexFormat( DefaultVertexFormats.ITEM ).addElement( DefaultVertexFormats.TEX_2S ); + // Standard item format extended with lightmap coordinates + private static final VertexFormat itemFormatWithLightMap = new VertexFormat(DefaultVertexFormats.ITEM).addElement(DefaultVertexFormats.TEX_2S); - private VertexFormats() - { - } + private VertexFormats() { + } - public static VertexFormat getFormatWithLightMap( VertexFormat format ) - { - // Do not use this when Optifine is present or if the vanilla lighting pipeline is used - if( FMLClientHandler.instance().hasOptifine() || !ForgeModContainer.forgeLightPipelineEnabled ) - { - return format; - } + public static VertexFormat getFormatWithLightMap(VertexFormat format) { + // Do not use this when Optifine is present or if the vanilla lighting pipeline is used + if (FMLClientHandler.instance().hasOptifine() || !ForgeModContainer.forgeLightPipelineEnabled) { + return format; + } - VertexFormat result; - if( format == DefaultVertexFormats.BLOCK ) - { - result = DefaultVertexFormats.BLOCK; - } - else if( format == DefaultVertexFormats.ITEM ) - { - result = itemFormatWithLightMap; - } - else if( !format.hasUvOffset( 1 ) ) - { - result = new VertexFormat( format ); - result.addElement( DefaultVertexFormats.TEX_2S ); - } - else - { - result = format; // Already has the needed UV, so keep it - } - return result; - } + VertexFormat result; + if (format == DefaultVertexFormats.BLOCK) { + result = DefaultVertexFormats.BLOCK; + } else if (format == DefaultVertexFormats.ITEM) { + result = itemFormatWithLightMap; + } else if (!format.hasUvOffset(1)) { + result = new VertexFormat(format); + result.addElement(DefaultVertexFormats.TEX_2S); + } else { + result = format; // Already has the needed UV, so keep it + } + return result; + } } diff --git a/src/main/java/appeng/client/render/cablebus/CableBuilder.java b/src/main/java/appeng/client/render/cablebus/CableBuilder.java index 0090c61d1..5d67db071 100644 --- a/src/main/java/appeng/client/render/cablebus/CableBuilder.java +++ b/src/main/java/appeng/client/render/cablebus/CableBuilder.java @@ -19,760 +19,694 @@ package appeng.client.render.cablebus; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.List; -import java.util.function.Function; - +import appeng.api.util.AECableType; +import appeng.api.util.AEColor; +import appeng.core.AppEng; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; -import appeng.api.util.AECableType; -import appeng.api.util.AEColor; -import appeng.core.AppEng; +import java.util.*; +import java.util.function.Function; /** * A helper class that builds quads for cable connections. */ -class CableBuilder -{ - - private final VertexFormat format; - - // Textures for the cable core types, one per type/color pair - private final EnumMap> coreTextures; - - // Textures for rendering the actual connection cubes, one per type/color pair - private final EnumMap> connectionTextures; - - private final SmartCableTextures smartCableTextures; - - CableBuilder( VertexFormat format, Function bakedTextureGetter ) - { - this.format = format; - this.coreTextures = new EnumMap<>( CableCoreType.class ); - - for( CableCoreType type : CableCoreType.values() ) - { - EnumMap colorTextures = new EnumMap<>( AEColor.class ); - - for( AEColor color : AEColor.values() ) - { - colorTextures.put( color, bakedTextureGetter.apply( type.getTexture( color ) ) ); - } - - this.coreTextures.put( type, colorTextures ); - } - - this.connectionTextures = new EnumMap<>( AECableType.class ); - - for( AECableType type : AECableType.VALIDCABLES ) - { - EnumMap colorTextures = new EnumMap<>( AEColor.class ); - - for( AEColor color : AEColor.values() ) - { - colorTextures.put( color, bakedTextureGetter.apply( getConnectionTexture( type, color ) ) ); - } - - this.connectionTextures.put( type, colorTextures ); - } - - this.smartCableTextures = new SmartCableTextures( bakedTextureGetter ); - } - - static ResourceLocation getConnectionTexture( AECableType cableType, AEColor color ) - { - String textureFolder; - switch( cableType ) - { - case GLASS: - textureFolder = "parts/cable/glass/"; - break; - case COVERED: - textureFolder = "parts/cable/covered/"; - break; - case SMART: - textureFolder = "parts/cable/smart/"; - break; - case DENSE_COVERED: - textureFolder = "parts/cable/dense_covered/"; - break; - case DENSE_SMART: - textureFolder = "parts/cable/dense_smart/"; - break; - default: - throw new IllegalStateException( "Cable type " + cableType + " does not support connections." ); - } - - return new ResourceLocation( AppEng.MOD_ID, textureFolder + color.name().toLowerCase() ); - } - - /** - * Adds the core of a cable to the given list of quads. - * - * The type of cable core is automatically deduced from the given cable type. - */ - public void addCableCore( AECableType cableType, AEColor color, List quadsOut ) - { - switch( cableType ) - { - case GLASS: - this.addCableCore( CableCoreType.GLASS, color, quadsOut ); - break; - case COVERED: - case SMART: - this.addCableCore( CableCoreType.COVERED, color, quadsOut ); - break; - case DENSE_COVERED: - case DENSE_SMART: - this.addCableCore( CableCoreType.DENSE, color, quadsOut ); - break; - default: - } - } - - public void addCableCore( CableCoreType coreType, AEColor color, List quadsOut ) - { - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); - - TextureAtlasSprite texture = this.coreTextures.get( coreType ).get( color ); - cubeBuilder.setTexture( texture ); - - switch( coreType ) - { - case GLASS: - cubeBuilder.addCube( 6, 6, 6, 10, 10, 10 ); - break; - case COVERED: - cubeBuilder.addCube( 5, 5, 5, 11, 11, 11 ); - break; - case DENSE: - cubeBuilder.addCube( 3, 3, 3, 13, 13, 13 ); - break; - } - } - - public void addGlassConnection( EnumFacing facing, AEColor cableColor, AECableType connectionType, boolean cableBusAdjacent, List quadsOut ) - { - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); - - // We render all faces except the one on the connection side - cubeBuilder.setDrawFaces( EnumSet.complementOf( EnumSet.of( facing ) ) ); - - // For to-machine connections, use a thicker end-cap for the connection - if( connectionType != AECableType.GLASS && !cableBusAdjacent ) - { - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.COVERED ).get( cableColor ); - cubeBuilder.setTexture( texture ); - - this.addBigCoveredCableSizedCube( facing, cubeBuilder ); - } - - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.GLASS ).get( cableColor ); - cubeBuilder.setTexture( texture ); - - switch( facing ) - { - case DOWN: - cubeBuilder.addCube( 6, 0, 6, 10, 6, 10 ); - break; - case EAST: - cubeBuilder.addCube( 10, 6, 6, 16, 10, 10 ); - break; - case NORTH: - cubeBuilder.addCube( 6, 6, 0, 10, 10, 6 ); - break; - case SOUTH: - cubeBuilder.addCube( 6, 6, 10, 10, 10, 16 ); - break; - case UP: - cubeBuilder.addCube( 6, 10, 6, 10, 16, 10 ); - break; - case WEST: - cubeBuilder.addCube( 0, 6, 6, 6, 10, 10 ); - break; - } - } - - public void addStraightGlassConnection( EnumFacing facing, AEColor cableColor, List quadsOut ) - { - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); - - // We render all faces except the connection caps. We can do this because the glass cable is the smallest one - // and its ends will always be covered by something - cubeBuilder.setDrawFaces( EnumSet.complementOf( EnumSet.of( facing, facing.getOpposite() ) ) ); - - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.GLASS ).get( cableColor ); - cubeBuilder.setTexture( texture ); - - switch( facing ) - { - case DOWN: - case UP: - cubeBuilder.addCube( 6, 0, 6, 10, 16, 10 ); - break; - case NORTH: - case SOUTH: - cubeBuilder.addCube( 6, 6, 0, 10, 10, 16 ); - break; - case EAST: - case WEST: - cubeBuilder.addCube( 0, 6, 6, 16, 10, 10 ); - break; - } - } - - public void addConstrainedGlassConnection( EnumFacing facing, AEColor cableColor, int distanceFromEdge, List quadsOut ) - { - - // Glass connections reach only 6 voxels from the edge - if( distanceFromEdge >= 6 ) - { - return; - } - - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); - - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.GLASS ).get( cableColor ); - cubeBuilder.setTexture( texture ); - - switch( facing ) - { - case DOWN: - cubeBuilder.addCube( 6, distanceFromEdge, 6, 10, 6, 10 ); - break; - case EAST: - cubeBuilder.addCube( 10, 6, 6, 16 - distanceFromEdge, 10, 10 ); - break; - case NORTH: - cubeBuilder.addCube( 6, 6, distanceFromEdge, 10, 10, 6 ); - break; - case SOUTH: - cubeBuilder.addCube( 6, 6, 10, 10, 10, 16 - distanceFromEdge ); - break; - case UP: - cubeBuilder.addCube( 6, 10, 6, 10, 16 - distanceFromEdge, 10 ); - break; - case WEST: - cubeBuilder.addCube( distanceFromEdge, 6, 6, 6, 10, 10 ); - break; - } - } - - public void addCoveredConnection( EnumFacing facing, AEColor cableColor, AECableType connectionType, boolean cableBusAdjacent, List quadsOut ) - { - - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); - - // We render all faces except the one on the connection side - cubeBuilder.setDrawFaces( EnumSet.complementOf( EnumSet.of( facing ) ) ); - - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.COVERED ).get( cableColor ); - cubeBuilder.setTexture( texture ); - - // Draw a covered connection, if anything but glass is requested - if( connectionType != AECableType.GLASS && !cableBusAdjacent ) - { - this.addBigCoveredCableSizedCube( facing, cubeBuilder ); - } - - addCoveredCableSizedCube( facing, cubeBuilder ); - } - - public void addStraightCoveredConnection( EnumFacing facing, AEColor cableColor, List quadsOut ) - { - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); - - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.COVERED ).get( cableColor ); - cubeBuilder.setTexture( texture ); - - setStraightCableUVs( cubeBuilder, facing, 5, 11 ); - - addStraightCoveredCableSizedCube( facing, cubeBuilder ); - - } - - private static void setStraightCableUVs( CubeBuilder cubeBuilder, EnumFacing facing, int x, int y ) - { - switch( facing ) - { - case DOWN: - case UP: - cubeBuilder.setCustomUv( EnumFacing.NORTH, x, 0, y, x ); - cubeBuilder.setCustomUv( EnumFacing.EAST, x, 0, y, x ); - cubeBuilder.setCustomUv( EnumFacing.SOUTH, x, 0, y, x ); - cubeBuilder.setCustomUv( EnumFacing.WEST, x, 0, y, x ); - break; - case EAST: - case WEST: - cubeBuilder.setCustomUv( EnumFacing.UP, 0, x, x, y ); - cubeBuilder.setCustomUv( EnumFacing.DOWN, 0, x, x, y ); - cubeBuilder.setCustomUv( EnumFacing.NORTH, 0, x, x, y ); - cubeBuilder.setCustomUv( EnumFacing.SOUTH, 0, x, x, y ); - break; - case NORTH: - case SOUTH: - cubeBuilder.setCustomUv( EnumFacing.UP, x, 0, y, x ); - cubeBuilder.setCustomUv( EnumFacing.DOWN, x, 0, y, x ); - cubeBuilder.setCustomUv( EnumFacing.EAST, 0, x, x, y ); - cubeBuilder.setCustomUv( EnumFacing.WEST, 0, x, x, y ); - break; - } - } - - public void addConstrainedCoveredConnection( EnumFacing facing, AEColor cableColor, int distanceFromEdge, List quadsOut ) - { - // The core of a covered cable reaches up to 5 voxels from the block edge, so - // drawing a connection can only occur from there onwards - if( distanceFromEdge >= 5 ) - { - return; - } - - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); - - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.COVERED ).get( cableColor ); - cubeBuilder.setTexture( texture ); - - addCoveredCableSizedCube( facing, distanceFromEdge, cubeBuilder ); - - } - - public void addSmartConnection( EnumFacing facing, AEColor cableColor, AECableType connectionType, boolean cableBusAdjacent, int channels, List quadsOut ) - { - if( connectionType == AECableType.COVERED || connectionType == AECableType.GLASS ) - { - this.addCoveredConnection( facing, cableColor, connectionType, cableBusAdjacent, quadsOut ); - return; - } - - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); - - // We render all faces except the one on the connection side - cubeBuilder.setDrawFaces( EnumSet.complementOf( EnumSet.of( facing ) ) ); - - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.SMART ).get( cableColor ); - cubeBuilder.setTexture( texture ); - - TextureAtlasSprite oddChannel = this.smartCableTextures.getOddTextureForChannels( channels ); - TextureAtlasSprite evenChannel = this.smartCableTextures.getEvenTextureForChannels( channels ); - - // For to-machine connections, use a thicker end-cap for the connection - if( connectionType != AECableType.GLASS && !cableBusAdjacent ) - { - this.addBigCoveredCableSizedCube( facing, cubeBuilder ); - - // Render the channel indicators brightly lit at night - cubeBuilder.setRenderFullBright( true ); - - cubeBuilder.setTexture( oddChannel ); - cubeBuilder.setColorRGB( cableColor.blackVariant ); - this.addBigCoveredCableSizedCube( facing, cubeBuilder ); - - cubeBuilder.setTexture( evenChannel ); - cubeBuilder.setColorRGB( cableColor.whiteVariant ); - this.addBigCoveredCableSizedCube( facing, cubeBuilder ); - - // Reset back to normal rendering for the rest - cubeBuilder.setRenderFullBright( false ); - cubeBuilder.setTexture( texture ); - } - - addCoveredCableSizedCube( facing, cubeBuilder ); - - // Render the channel indicators brightly lit at night - cubeBuilder.setRenderFullBright( true ); - - cubeBuilder.setTexture( oddChannel ); - cubeBuilder.setColorRGB( cableColor.blackVariant ); - addCoveredCableSizedCube( facing, cubeBuilder ); - - cubeBuilder.setTexture( evenChannel ); - cubeBuilder.setColorRGB( cableColor.whiteVariant ); - addCoveredCableSizedCube( facing, cubeBuilder ); - } - - public void addStraightSmartConnection( EnumFacing facing, AEColor cableColor, int channels, List quadsOut ) - { - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); - - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.SMART ).get( cableColor ); - cubeBuilder.setTexture( texture ); - - setStraightCableUVs( cubeBuilder, facing, 5, 11 ); - - addStraightCoveredCableSizedCube( facing, cubeBuilder ); - - TextureAtlasSprite oddChannel = this.smartCableTextures.getOddTextureForChannels( channels ); - TextureAtlasSprite evenChannel = this.smartCableTextures.getEvenTextureForChannels( channels ); - - // Render the channel indicators brightly lit at night - cubeBuilder.setRenderFullBright( true ); - - cubeBuilder.setTexture( oddChannel ); - cubeBuilder.setColorRGB( cableColor.blackVariant ); - addStraightCoveredCableSizedCube( facing, cubeBuilder ); +class CableBuilder { + + private final VertexFormat format; + + // Textures for the cable core types, one per type/color pair + private final EnumMap> coreTextures; + + // Textures for rendering the actual connection cubes, one per type/color pair + private final EnumMap> connectionTextures; + + private final SmartCableTextures smartCableTextures; + + CableBuilder(VertexFormat format, Function bakedTextureGetter) { + this.format = format; + this.coreTextures = new EnumMap<>(CableCoreType.class); + + for (CableCoreType type : CableCoreType.values()) { + EnumMap colorTextures = new EnumMap<>(AEColor.class); + + for (AEColor color : AEColor.values()) { + colorTextures.put(color, bakedTextureGetter.apply(type.getTexture(color))); + } + + this.coreTextures.put(type, colorTextures); + } + + this.connectionTextures = new EnumMap<>(AECableType.class); + + for (AECableType type : AECableType.VALIDCABLES) { + EnumMap colorTextures = new EnumMap<>(AEColor.class); + + for (AEColor color : AEColor.values()) { + colorTextures.put(color, bakedTextureGetter.apply(getConnectionTexture(type, color))); + } + + this.connectionTextures.put(type, colorTextures); + } + + this.smartCableTextures = new SmartCableTextures(bakedTextureGetter); + } + + static ResourceLocation getConnectionTexture(AECableType cableType, AEColor color) { + String textureFolder; + switch (cableType) { + case GLASS: + textureFolder = "parts/cable/glass/"; + break; + case COVERED: + textureFolder = "parts/cable/covered/"; + break; + case SMART: + textureFolder = "parts/cable/smart/"; + break; + case DENSE_COVERED: + textureFolder = "parts/cable/dense_covered/"; + break; + case DENSE_SMART: + textureFolder = "parts/cable/dense_smart/"; + break; + default: + throw new IllegalStateException("Cable type " + cableType + " does not support connections."); + } + + return new ResourceLocation(AppEng.MOD_ID, textureFolder + color.name().toLowerCase()); + } + + /** + * Adds the core of a cable to the given list of quads. + *

+ * The type of cable core is automatically deduced from the given cable type. + */ + public void addCableCore(AECableType cableType, AEColor color, List quadsOut) { + switch (cableType) { + case GLASS: + this.addCableCore(CableCoreType.GLASS, color, quadsOut); + break; + case COVERED: + case SMART: + this.addCableCore(CableCoreType.COVERED, color, quadsOut); + break; + case DENSE_COVERED: + case DENSE_SMART: + this.addCableCore(CableCoreType.DENSE, color, quadsOut); + break; + default: + } + } + + public void addCableCore(CableCoreType coreType, AEColor color, List quadsOut) { + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); + + TextureAtlasSprite texture = this.coreTextures.get(coreType).get(color); + cubeBuilder.setTexture(texture); + + switch (coreType) { + case GLASS: + cubeBuilder.addCube(6, 6, 6, 10, 10, 10); + break; + case COVERED: + cubeBuilder.addCube(5, 5, 5, 11, 11, 11); + break; + case DENSE: + cubeBuilder.addCube(3, 3, 3, 13, 13, 13); + break; + } + } + + public void addGlassConnection(EnumFacing facing, AEColor cableColor, AECableType connectionType, boolean cableBusAdjacent, List quadsOut) { + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); + + // We render all faces except the one on the connection side + cubeBuilder.setDrawFaces(EnumSet.complementOf(EnumSet.of(facing))); + + // For to-machine connections, use a thicker end-cap for the connection + if (connectionType != AECableType.GLASS && !cableBusAdjacent) { + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.COVERED).get(cableColor); + cubeBuilder.setTexture(texture); + + this.addBigCoveredCableSizedCube(facing, cubeBuilder); + } + + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.GLASS).get(cableColor); + cubeBuilder.setTexture(texture); + + switch (facing) { + case DOWN: + cubeBuilder.addCube(6, 0, 6, 10, 6, 10); + break; + case EAST: + cubeBuilder.addCube(10, 6, 6, 16, 10, 10); + break; + case NORTH: + cubeBuilder.addCube(6, 6, 0, 10, 10, 6); + break; + case SOUTH: + cubeBuilder.addCube(6, 6, 10, 10, 10, 16); + break; + case UP: + cubeBuilder.addCube(6, 10, 6, 10, 16, 10); + break; + case WEST: + cubeBuilder.addCube(0, 6, 6, 6, 10, 10); + break; + } + } + + public void addStraightGlassConnection(EnumFacing facing, AEColor cableColor, List quadsOut) { + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); + + // We render all faces except the connection caps. We can do this because the glass cable is the smallest one + // and its ends will always be covered by something + cubeBuilder.setDrawFaces(EnumSet.complementOf(EnumSet.of(facing, facing.getOpposite()))); + + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.GLASS).get(cableColor); + cubeBuilder.setTexture(texture); + + switch (facing) { + case DOWN: + case UP: + cubeBuilder.addCube(6, 0, 6, 10, 16, 10); + break; + case NORTH: + case SOUTH: + cubeBuilder.addCube(6, 6, 0, 10, 10, 16); + break; + case EAST: + case WEST: + cubeBuilder.addCube(0, 6, 6, 16, 10, 10); + break; + } + } + + public void addConstrainedGlassConnection(EnumFacing facing, AEColor cableColor, int distanceFromEdge, List quadsOut) { + + // Glass connections reach only 6 voxels from the edge + if (distanceFromEdge >= 6) { + return; + } + + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); + + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.GLASS).get(cableColor); + cubeBuilder.setTexture(texture); + + switch (facing) { + case DOWN: + cubeBuilder.addCube(6, distanceFromEdge, 6, 10, 6, 10); + break; + case EAST: + cubeBuilder.addCube(10, 6, 6, 16 - distanceFromEdge, 10, 10); + break; + case NORTH: + cubeBuilder.addCube(6, 6, distanceFromEdge, 10, 10, 6); + break; + case SOUTH: + cubeBuilder.addCube(6, 6, 10, 10, 10, 16 - distanceFromEdge); + break; + case UP: + cubeBuilder.addCube(6, 10, 6, 10, 16 - distanceFromEdge, 10); + break; + case WEST: + cubeBuilder.addCube(distanceFromEdge, 6, 6, 6, 10, 10); + break; + } + } + + public void addCoveredConnection(EnumFacing facing, AEColor cableColor, AECableType connectionType, boolean cableBusAdjacent, List quadsOut) { + + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); + + // We render all faces except the one on the connection side + cubeBuilder.setDrawFaces(EnumSet.complementOf(EnumSet.of(facing))); + + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.COVERED).get(cableColor); + cubeBuilder.setTexture(texture); + + // Draw a covered connection, if anything but glass is requested + if (connectionType != AECableType.GLASS && !cableBusAdjacent) { + this.addBigCoveredCableSizedCube(facing, cubeBuilder); + } + + addCoveredCableSizedCube(facing, cubeBuilder); + } + + public void addStraightCoveredConnection(EnumFacing facing, AEColor cableColor, List quadsOut) { + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); + + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.COVERED).get(cableColor); + cubeBuilder.setTexture(texture); + + setStraightCableUVs(cubeBuilder, facing, 5, 11); + + addStraightCoveredCableSizedCube(facing, cubeBuilder); + + } + + private static void setStraightCableUVs(CubeBuilder cubeBuilder, EnumFacing facing, int x, int y) { + switch (facing) { + case DOWN: + case UP: + cubeBuilder.setCustomUv(EnumFacing.NORTH, x, 0, y, x); + cubeBuilder.setCustomUv(EnumFacing.EAST, x, 0, y, x); + cubeBuilder.setCustomUv(EnumFacing.SOUTH, x, 0, y, x); + cubeBuilder.setCustomUv(EnumFacing.WEST, x, 0, y, x); + break; + case EAST: + case WEST: + cubeBuilder.setCustomUv(EnumFacing.UP, 0, x, x, y); + cubeBuilder.setCustomUv(EnumFacing.DOWN, 0, x, x, y); + cubeBuilder.setCustomUv(EnumFacing.NORTH, 0, x, x, y); + cubeBuilder.setCustomUv(EnumFacing.SOUTH, 0, x, x, y); + break; + case NORTH: + case SOUTH: + cubeBuilder.setCustomUv(EnumFacing.UP, x, 0, y, x); + cubeBuilder.setCustomUv(EnumFacing.DOWN, x, 0, y, x); + cubeBuilder.setCustomUv(EnumFacing.EAST, 0, x, x, y); + cubeBuilder.setCustomUv(EnumFacing.WEST, 0, x, x, y); + break; + } + } + + public void addConstrainedCoveredConnection(EnumFacing facing, AEColor cableColor, int distanceFromEdge, List quadsOut) { + // The core of a covered cable reaches up to 5 voxels from the block edge, so + // drawing a connection can only occur from there onwards + if (distanceFromEdge >= 5) { + return; + } + + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); - cubeBuilder.setTexture( evenChannel ); - cubeBuilder.setColorRGB( cableColor.whiteVariant ); - addStraightCoveredCableSizedCube( facing, cubeBuilder ); - } + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.COVERED).get(cableColor); + cubeBuilder.setTexture(texture); - public void addConstrainedSmartConnection( EnumFacing facing, AEColor cableColor, int distanceFromEdge, int channels, List quadsOut ) - { - // Same as with covered cables, the smart cable's core extends up to 5 voxels away from the edge. - // Drawing a connection to any point before that point is fruitless - if( distanceFromEdge >= 5 ) - { - return; - } + addCoveredCableSizedCube(facing, distanceFromEdge, cubeBuilder); + + } - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); + public void addSmartConnection(EnumFacing facing, AEColor cableColor, AECableType connectionType, boolean cableBusAdjacent, int channels, List quadsOut) { + if (connectionType == AECableType.COVERED || connectionType == AECableType.GLASS) { + this.addCoveredConnection(facing, cableColor, connectionType, cableBusAdjacent, quadsOut); + return; + } + + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); + + // We render all faces except the one on the connection side + cubeBuilder.setDrawFaces(EnumSet.complementOf(EnumSet.of(facing))); + + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.SMART).get(cableColor); + cubeBuilder.setTexture(texture); - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.SMART ).get( cableColor ); - cubeBuilder.setTexture( texture ); + TextureAtlasSprite oddChannel = this.smartCableTextures.getOddTextureForChannels(channels); + TextureAtlasSprite evenChannel = this.smartCableTextures.getEvenTextureForChannels(channels); - addCoveredCableSizedCube( facing, distanceFromEdge, cubeBuilder ); + // For to-machine connections, use a thicker end-cap for the connection + if (connectionType != AECableType.GLASS && !cableBusAdjacent) { + this.addBigCoveredCableSizedCube(facing, cubeBuilder); - TextureAtlasSprite oddChannel = this.smartCableTextures.getOddTextureForChannels( channels ); - TextureAtlasSprite evenChannel = this.smartCableTextures.getEvenTextureForChannels( channels ); + // Render the channel indicators brightly lit at night + cubeBuilder.setRenderFullBright(true); - // Render the channel indicators brightly lit at night - cubeBuilder.setRenderFullBright( true ); + cubeBuilder.setTexture(oddChannel); + cubeBuilder.setColorRGB(cableColor.blackVariant); + this.addBigCoveredCableSizedCube(facing, cubeBuilder); - cubeBuilder.setTexture( oddChannel ); - cubeBuilder.setColorRGB( cableColor.blackVariant ); - addCoveredCableSizedCube( facing, distanceFromEdge, cubeBuilder ); + cubeBuilder.setTexture(evenChannel); + cubeBuilder.setColorRGB(cableColor.whiteVariant); + this.addBigCoveredCableSizedCube(facing, cubeBuilder); - cubeBuilder.setTexture( evenChannel ); - cubeBuilder.setColorRGB( cableColor.whiteVariant ); - addCoveredCableSizedCube( facing, distanceFromEdge, cubeBuilder ); - } + // Reset back to normal rendering for the rest + cubeBuilder.setRenderFullBright(false); + cubeBuilder.setTexture(texture); + } - public void addDenseCoveredConnection( EnumFacing facing, AEColor cableColor, AECableType connectionType, boolean cableBusAdjacent, List quadsOut ) - { - // Dense cables only render their connections as dense if the adjacent blocks actually wants that - if( connectionType == AECableType.COVERED || connectionType == AECableType.SMART || connectionType == AECableType.GLASS ) - { - this.addCoveredConnection( facing, cableColor, connectionType, cableBusAdjacent, quadsOut ); - return; - } + addCoveredCableSizedCube(facing, cubeBuilder); + + // Render the channel indicators brightly lit at night + cubeBuilder.setRenderFullBright(true); - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); + cubeBuilder.setTexture(oddChannel); + cubeBuilder.setColorRGB(cableColor.blackVariant); + addCoveredCableSizedCube(facing, cubeBuilder); - // We render all faces except the one on the connection side - cubeBuilder.setDrawFaces( EnumSet.complementOf( EnumSet.of( facing ) ) ); + cubeBuilder.setTexture(evenChannel); + cubeBuilder.setColorRGB(cableColor.whiteVariant); + addCoveredCableSizedCube(facing, cubeBuilder); + } - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.DENSE_COVERED ).get( cableColor ); - cubeBuilder.setTexture( texture ); + public void addStraightSmartConnection(EnumFacing facing, AEColor cableColor, int channels, List quadsOut) { + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); - addDenseCableSizedCube( facing, cubeBuilder ); + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.SMART).get(cableColor); + cubeBuilder.setTexture(texture); - // Reset back to normal rendering for the rest - cubeBuilder.setRenderFullBright( false ); - cubeBuilder.setTexture( texture ); - } + setStraightCableUVs(cubeBuilder, facing, 5, 11); - public void addDenseSmartConnection( EnumFacing facing, AEColor cableColor, AECableType connectionType, boolean cableBusAdjacent, int channels, List quadsOut ) - { - // Dense cables only render their connections as dense if the adjacent blocks actually wants that - if( connectionType == AECableType.SMART ) - { - this.addSmartConnection( facing, cableColor, connectionType, cableBusAdjacent, channels, quadsOut ); - return; - } - else if( connectionType == AECableType.COVERED || connectionType == AECableType.GLASS ) - { - this.addCoveredConnection( facing, cableColor, connectionType, cableBusAdjacent, quadsOut ); - return; - } - else if( connectionType == AECableType.DENSE_COVERED ) - { - this.addDenseCoveredConnection( facing, cableColor, connectionType, cableBusAdjacent, quadsOut ); - return; - } - - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); - - // We render all faces except the one on the connection side - cubeBuilder.setDrawFaces( EnumSet.complementOf( EnumSet.of( facing ) ) ); - - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.DENSE_SMART ).get( cableColor ); - cubeBuilder.setTexture( texture ); - - addDenseCableSizedCube( facing, cubeBuilder ); - - // Dense cables show used channels in groups of 4, rounded up - channels = ( channels + 3 ) / 4; - - TextureAtlasSprite oddChannel = this.smartCableTextures.getOddTextureForChannels( channels ); - TextureAtlasSprite evenChannel = this.smartCableTextures.getEvenTextureForChannels( channels ); - - // Render the channel indicators brightly lit at night - cubeBuilder.setRenderFullBright( true ); - - cubeBuilder.setTexture( oddChannel ); - cubeBuilder.setColorRGB( cableColor.blackVariant ); - addDenseCableSizedCube( facing, cubeBuilder ); - - cubeBuilder.setTexture( evenChannel ); - cubeBuilder.setColorRGB( cableColor.whiteVariant ); - addDenseCableSizedCube( facing, cubeBuilder ); - - // Reset back to normal rendering for the rest - cubeBuilder.setRenderFullBright( false ); - cubeBuilder.setTexture( texture ); - - } - - public void addStraightDenseCoveredConnection( EnumFacing facing, AEColor cableColor, List quadsOut ) - { - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); - - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.DENSE_COVERED ).get( cableColor ); - cubeBuilder.setTexture( texture ); - - setStraightCableUVs( cubeBuilder, facing, 5, 11 ); - - addStraightDenseCableSizedCube( facing, cubeBuilder ); - } - - public void addStraightDenseSmartConnection( EnumFacing facing, AEColor cableColor, int channels, List quadsOut ) - { - CubeBuilder cubeBuilder = new CubeBuilder( this.format, quadsOut ); - - TextureAtlasSprite texture = this.connectionTextures.get( AECableType.DENSE_SMART ).get( cableColor ); - cubeBuilder.setTexture( texture ); - - setStraightCableUVs( cubeBuilder, facing, 5, 11 ); - - addStraightDenseCableSizedCube( facing, cubeBuilder ); - - // Dense cables show used channels in groups of 4, rounded up - channels = ( channels + 3 ) / 4; - - TextureAtlasSprite oddChannel = this.smartCableTextures.getOddTextureForChannels( channels ); - TextureAtlasSprite evenChannel = this.smartCableTextures.getEvenTextureForChannels( channels ); - - // Render the channel indicators brightly lit at night - cubeBuilder.setRenderFullBright( true ); - - cubeBuilder.setTexture( oddChannel ); - cubeBuilder.setColorRGB( cableColor.blackVariant ); - addStraightDenseCableSizedCube( facing, cubeBuilder ); - - cubeBuilder.setTexture( evenChannel ); - cubeBuilder.setColorRGB( cableColor.whiteVariant ); - addStraightDenseCableSizedCube( facing, cubeBuilder ); - } - - private static void addDenseCableSizedCube( EnumFacing facing, CubeBuilder cubeBuilder ) - { - switch( facing ) - { - case DOWN: - cubeBuilder.addCube( 4, 0, 4, 12, 5, 12 ); - break; - case EAST: - cubeBuilder.addCube( 11, 4, 4, 16, 12, 12 ); - break; - case NORTH: - cubeBuilder.addCube( 4, 4, 0, 12, 12, 5 ); - break; - case SOUTH: - cubeBuilder.addCube( 4, 4, 11, 12, 12, 16 ); - break; - case UP: - cubeBuilder.addCube( 4, 11, 4, 12, 16, 12 ); - break; - case WEST: - cubeBuilder.addCube( 0, 4, 4, 5, 12, 12 ); - break; - } - } - - // Adds a cube to the given cube builder that has the size of a dense cable connection and spans the entire block - // for the given direction - private static void addStraightDenseCableSizedCube( EnumFacing facing, CubeBuilder cubeBuilder ) - { - switch( facing ) - { - case DOWN: - case UP: - cubeBuilder.setUvRotation( EnumFacing.EAST, 3 ); - cubeBuilder.addCube( 3, 0, 3, 13, 16, 13 ); - cubeBuilder.setUvRotation( EnumFacing.EAST, 0 ); - break; - case EAST: - case WEST: - cubeBuilder.setUvRotation( EnumFacing.SOUTH, 3 ); - cubeBuilder.setUvRotation( EnumFacing.NORTH, 3 ); - cubeBuilder.addCube( 0, 3, 3, 16, 13, 13 ); - cubeBuilder.setUvRotation( EnumFacing.SOUTH, 0 ); - cubeBuilder.setUvRotation( EnumFacing.NORTH, 0 ); - break; - case NORTH: - case SOUTH: - cubeBuilder.setUvRotation( EnumFacing.EAST, 3 ); - cubeBuilder.setUvRotation( EnumFacing.WEST, 3 ); - cubeBuilder.addCube( 3, 3, 0, 13, 13, 16 ); - cubeBuilder.setUvRotation( EnumFacing.EAST, 0 ); - cubeBuilder.setUvRotation( EnumFacing.WEST, 0 ); - break; - } - - } - - // Adds a cube to the given cube builder that has the size of a covered cable connection from the core of the cable - // to the given face - private static void addCoveredCableSizedCube( EnumFacing facing, CubeBuilder cubeBuilder ) - { - switch( facing ) - { - case DOWN: - cubeBuilder.addCube( 6, 0, 6, 10, 5, 10 ); - break; - case EAST: - cubeBuilder.addCube( 11, 6, 6, 16, 10, 10 ); - break; - case NORTH: - cubeBuilder.addCube( 6, 6, 0, 10, 10, 5 ); - break; - case SOUTH: - cubeBuilder.addCube( 6, 6, 11, 10, 10, 16 ); - break; - case UP: - cubeBuilder.addCube( 6, 11, 6, 10, 16, 10 ); - break; - case WEST: - cubeBuilder.addCube( 0, 6, 6, 5, 10, 10 ); - break; - } - } - - // Adds a cube to the given cube builder that has the size of a covered cable connection and spans the entire block - // for the given direction - private static void addStraightCoveredCableSizedCube( EnumFacing facing, CubeBuilder cubeBuilder ) - { - switch( facing ) - { - case DOWN: - case UP: - cubeBuilder.setUvRotation( EnumFacing.EAST, 3 ); - cubeBuilder.addCube( 5, 0, 5, 11, 16, 11 ); - cubeBuilder.setUvRotation( EnumFacing.EAST, 0 ); - break; - case EAST: - case WEST: - cubeBuilder.setUvRotation( EnumFacing.SOUTH, 3 ); - cubeBuilder.setUvRotation( EnumFacing.NORTH, 3 ); - cubeBuilder.addCube( 0, 5, 5, 16, 11, 11 ); - cubeBuilder.setUvRotation( EnumFacing.SOUTH, 0 ); - cubeBuilder.setUvRotation( EnumFacing.NORTH, 0 ); - break; - case NORTH: - case SOUTH: - cubeBuilder.setUvRotation( EnumFacing.EAST, 3 ); - cubeBuilder.setUvRotation( EnumFacing.WEST, 3 ); - cubeBuilder.addCube( 5, 5, 0, 11, 11, 16 ); - cubeBuilder.setUvRotation( EnumFacing.EAST, 0 ); - cubeBuilder.setUvRotation( EnumFacing.WEST, 0 ); - break; - } - } - - private static void addCoveredCableSizedCube( EnumFacing facing, int distanceFromEdge, CubeBuilder cubeBuilder ) - { - switch( facing ) - { - case DOWN: - cubeBuilder.addCube( 6, distanceFromEdge, 6, 10, 5, 10 ); - break; - case EAST: - cubeBuilder.addCube( 11, 6, 6, 16 - distanceFromEdge, 10, 10 ); - break; - case NORTH: - cubeBuilder.addCube( 6, 6, distanceFromEdge, 10, 10, 5 ); - break; - case SOUTH: - cubeBuilder.addCube( 6, 6, 11, 10, 10, 16 - distanceFromEdge ); - break; - case UP: - cubeBuilder.addCube( 6, 11, 6, 10, 16 - distanceFromEdge, 10 ); - break; - case WEST: - cubeBuilder.addCube( distanceFromEdge, 6, 6, 5, 10, 10 ); - break; - } - } - - /** - * This renders a slightly bigger covered cable connection to the specified side. This is used to connect cable - * cores with adjacent machines - * that do not want to be connected to using a glass cable connection. This applies to most machines (interfaces, - * etc.) - */ - private void addBigCoveredCableSizedCube( EnumFacing facing, CubeBuilder cubeBuilder ) - { - switch( facing ) - { - case DOWN: - cubeBuilder.addCube( 5, 0, 5, 11, 4, 11 ); - break; - case EAST: - cubeBuilder.addCube( 12, 5, 5, 16, 11, 11 ); - break; - case NORTH: - cubeBuilder.addCube( 5, 5, 0, 11, 11, 4 ); - break; - case SOUTH: - cubeBuilder.addCube( 5, 5, 12, 11, 11, 16 ); - break; - case UP: - cubeBuilder.addCube( 5, 12, 5, 11, 16, 11 ); - break; - case WEST: - cubeBuilder.addCube( 0, 5, 5, 4, 11, 11 ); - break; - } - } - - // Get all textures needed for building the actual cable quads - public static List getTextures() - { - List locations = new ArrayList<>(); - - for( CableCoreType coreType : CableCoreType.values() ) - { - for( AEColor color : AEColor.values() ) - { - locations.add( coreType.getTexture( color ) ); - } - } - - for( AECableType cableType : AECableType.VALIDCABLES ) - { - for( AEColor color : AEColor.values() ) - { - locations.add( getConnectionTexture( cableType, color ) ); - } - } - - Collections.addAll( locations, SmartCableTextures.SMART_CHANNELS_TEXTURES ); - - return locations; - } - - public TextureAtlasSprite getCoreTexture( CableCoreType coreType, AEColor color ) - { - return this.coreTextures.get( coreType ).get( color ); - } + addStraightCoveredCableSizedCube(facing, cubeBuilder); + + TextureAtlasSprite oddChannel = this.smartCableTextures.getOddTextureForChannels(channels); + TextureAtlasSprite evenChannel = this.smartCableTextures.getEvenTextureForChannels(channels); + + // Render the channel indicators brightly lit at night + cubeBuilder.setRenderFullBright(true); + + cubeBuilder.setTexture(oddChannel); + cubeBuilder.setColorRGB(cableColor.blackVariant); + addStraightCoveredCableSizedCube(facing, cubeBuilder); + + cubeBuilder.setTexture(evenChannel); + cubeBuilder.setColorRGB(cableColor.whiteVariant); + addStraightCoveredCableSizedCube(facing, cubeBuilder); + } + + public void addConstrainedSmartConnection(EnumFacing facing, AEColor cableColor, int distanceFromEdge, int channels, List quadsOut) { + // Same as with covered cables, the smart cable's core extends up to 5 voxels away from the edge. + // Drawing a connection to any point before that point is fruitless + if (distanceFromEdge >= 5) { + return; + } + + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); + + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.SMART).get(cableColor); + cubeBuilder.setTexture(texture); + + addCoveredCableSizedCube(facing, distanceFromEdge, cubeBuilder); + + TextureAtlasSprite oddChannel = this.smartCableTextures.getOddTextureForChannels(channels); + TextureAtlasSprite evenChannel = this.smartCableTextures.getEvenTextureForChannels(channels); + + // Render the channel indicators brightly lit at night + cubeBuilder.setRenderFullBright(true); + + cubeBuilder.setTexture(oddChannel); + cubeBuilder.setColorRGB(cableColor.blackVariant); + addCoveredCableSizedCube(facing, distanceFromEdge, cubeBuilder); + + cubeBuilder.setTexture(evenChannel); + cubeBuilder.setColorRGB(cableColor.whiteVariant); + addCoveredCableSizedCube(facing, distanceFromEdge, cubeBuilder); + } + + public void addDenseCoveredConnection(EnumFacing facing, AEColor cableColor, AECableType connectionType, boolean cableBusAdjacent, List quadsOut) { + // Dense cables only render their connections as dense if the adjacent blocks actually wants that + if (connectionType == AECableType.COVERED || connectionType == AECableType.SMART || connectionType == AECableType.GLASS) { + this.addCoveredConnection(facing, cableColor, connectionType, cableBusAdjacent, quadsOut); + return; + } + + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); + + // We render all faces except the one on the connection side + cubeBuilder.setDrawFaces(EnumSet.complementOf(EnumSet.of(facing))); + + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.DENSE_COVERED).get(cableColor); + cubeBuilder.setTexture(texture); + + addDenseCableSizedCube(facing, cubeBuilder); + + // Reset back to normal rendering for the rest + cubeBuilder.setRenderFullBright(false); + cubeBuilder.setTexture(texture); + } + + public void addDenseSmartConnection(EnumFacing facing, AEColor cableColor, AECableType connectionType, boolean cableBusAdjacent, int channels, List quadsOut) { + // Dense cables only render their connections as dense if the adjacent blocks actually wants that + if (connectionType == AECableType.SMART) { + this.addSmartConnection(facing, cableColor, connectionType, cableBusAdjacent, channels, quadsOut); + return; + } else if (connectionType == AECableType.COVERED || connectionType == AECableType.GLASS) { + this.addCoveredConnection(facing, cableColor, connectionType, cableBusAdjacent, quadsOut); + return; + } else if (connectionType == AECableType.DENSE_COVERED) { + this.addDenseCoveredConnection(facing, cableColor, connectionType, cableBusAdjacent, quadsOut); + return; + } + + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); + + // We render all faces except the one on the connection side + cubeBuilder.setDrawFaces(EnumSet.complementOf(EnumSet.of(facing))); + + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.DENSE_SMART).get(cableColor); + cubeBuilder.setTexture(texture); + + addDenseCableSizedCube(facing, cubeBuilder); + + // Dense cables show used channels in groups of 4, rounded up + channels = (channels + 3) / 4; + + TextureAtlasSprite oddChannel = this.smartCableTextures.getOddTextureForChannels(channels); + TextureAtlasSprite evenChannel = this.smartCableTextures.getEvenTextureForChannels(channels); + + // Render the channel indicators brightly lit at night + cubeBuilder.setRenderFullBright(true); + + cubeBuilder.setTexture(oddChannel); + cubeBuilder.setColorRGB(cableColor.blackVariant); + addDenseCableSizedCube(facing, cubeBuilder); + + cubeBuilder.setTexture(evenChannel); + cubeBuilder.setColorRGB(cableColor.whiteVariant); + addDenseCableSizedCube(facing, cubeBuilder); + + // Reset back to normal rendering for the rest + cubeBuilder.setRenderFullBright(false); + cubeBuilder.setTexture(texture); + + } + + public void addStraightDenseCoveredConnection(EnumFacing facing, AEColor cableColor, List quadsOut) { + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); + + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.DENSE_COVERED).get(cableColor); + cubeBuilder.setTexture(texture); + + setStraightCableUVs(cubeBuilder, facing, 5, 11); + + addStraightDenseCableSizedCube(facing, cubeBuilder); + } + + public void addStraightDenseSmartConnection(EnumFacing facing, AEColor cableColor, int channels, List quadsOut) { + CubeBuilder cubeBuilder = new CubeBuilder(this.format, quadsOut); + + TextureAtlasSprite texture = this.connectionTextures.get(AECableType.DENSE_SMART).get(cableColor); + cubeBuilder.setTexture(texture); + + setStraightCableUVs(cubeBuilder, facing, 5, 11); + + addStraightDenseCableSizedCube(facing, cubeBuilder); + + // Dense cables show used channels in groups of 4, rounded up + channels = (channels + 3) / 4; + + TextureAtlasSprite oddChannel = this.smartCableTextures.getOddTextureForChannels(channels); + TextureAtlasSprite evenChannel = this.smartCableTextures.getEvenTextureForChannels(channels); + + // Render the channel indicators brightly lit at night + cubeBuilder.setRenderFullBright(true); + + cubeBuilder.setTexture(oddChannel); + cubeBuilder.setColorRGB(cableColor.blackVariant); + addStraightDenseCableSizedCube(facing, cubeBuilder); + + cubeBuilder.setTexture(evenChannel); + cubeBuilder.setColorRGB(cableColor.whiteVariant); + addStraightDenseCableSizedCube(facing, cubeBuilder); + } + + private static void addDenseCableSizedCube(EnumFacing facing, CubeBuilder cubeBuilder) { + switch (facing) { + case DOWN: + cubeBuilder.addCube(4, 0, 4, 12, 5, 12); + break; + case EAST: + cubeBuilder.addCube(11, 4, 4, 16, 12, 12); + break; + case NORTH: + cubeBuilder.addCube(4, 4, 0, 12, 12, 5); + break; + case SOUTH: + cubeBuilder.addCube(4, 4, 11, 12, 12, 16); + break; + case UP: + cubeBuilder.addCube(4, 11, 4, 12, 16, 12); + break; + case WEST: + cubeBuilder.addCube(0, 4, 4, 5, 12, 12); + break; + } + } + + // Adds a cube to the given cube builder that has the size of a dense cable connection and spans the entire block + // for the given direction + private static void addStraightDenseCableSizedCube(EnumFacing facing, CubeBuilder cubeBuilder) { + switch (facing) { + case DOWN: + case UP: + cubeBuilder.setUvRotation(EnumFacing.EAST, 3); + cubeBuilder.addCube(3, 0, 3, 13, 16, 13); + cubeBuilder.setUvRotation(EnumFacing.EAST, 0); + break; + case EAST: + case WEST: + cubeBuilder.setUvRotation(EnumFacing.SOUTH, 3); + cubeBuilder.setUvRotation(EnumFacing.NORTH, 3); + cubeBuilder.addCube(0, 3, 3, 16, 13, 13); + cubeBuilder.setUvRotation(EnumFacing.SOUTH, 0); + cubeBuilder.setUvRotation(EnumFacing.NORTH, 0); + break; + case NORTH: + case SOUTH: + cubeBuilder.setUvRotation(EnumFacing.EAST, 3); + cubeBuilder.setUvRotation(EnumFacing.WEST, 3); + cubeBuilder.addCube(3, 3, 0, 13, 13, 16); + cubeBuilder.setUvRotation(EnumFacing.EAST, 0); + cubeBuilder.setUvRotation(EnumFacing.WEST, 0); + break; + } + + } + + // Adds a cube to the given cube builder that has the size of a covered cable connection from the core of the cable + // to the given face + private static void addCoveredCableSizedCube(EnumFacing facing, CubeBuilder cubeBuilder) { + switch (facing) { + case DOWN: + cubeBuilder.addCube(6, 0, 6, 10, 5, 10); + break; + case EAST: + cubeBuilder.addCube(11, 6, 6, 16, 10, 10); + break; + case NORTH: + cubeBuilder.addCube(6, 6, 0, 10, 10, 5); + break; + case SOUTH: + cubeBuilder.addCube(6, 6, 11, 10, 10, 16); + break; + case UP: + cubeBuilder.addCube(6, 11, 6, 10, 16, 10); + break; + case WEST: + cubeBuilder.addCube(0, 6, 6, 5, 10, 10); + break; + } + } + + // Adds a cube to the given cube builder that has the size of a covered cable connection and spans the entire block + // for the given direction + private static void addStraightCoveredCableSizedCube(EnumFacing facing, CubeBuilder cubeBuilder) { + switch (facing) { + case DOWN: + case UP: + cubeBuilder.setUvRotation(EnumFacing.EAST, 3); + cubeBuilder.addCube(5, 0, 5, 11, 16, 11); + cubeBuilder.setUvRotation(EnumFacing.EAST, 0); + break; + case EAST: + case WEST: + cubeBuilder.setUvRotation(EnumFacing.SOUTH, 3); + cubeBuilder.setUvRotation(EnumFacing.NORTH, 3); + cubeBuilder.addCube(0, 5, 5, 16, 11, 11); + cubeBuilder.setUvRotation(EnumFacing.SOUTH, 0); + cubeBuilder.setUvRotation(EnumFacing.NORTH, 0); + break; + case NORTH: + case SOUTH: + cubeBuilder.setUvRotation(EnumFacing.EAST, 3); + cubeBuilder.setUvRotation(EnumFacing.WEST, 3); + cubeBuilder.addCube(5, 5, 0, 11, 11, 16); + cubeBuilder.setUvRotation(EnumFacing.EAST, 0); + cubeBuilder.setUvRotation(EnumFacing.WEST, 0); + break; + } + } + + private static void addCoveredCableSizedCube(EnumFacing facing, int distanceFromEdge, CubeBuilder cubeBuilder) { + switch (facing) { + case DOWN: + cubeBuilder.addCube(6, distanceFromEdge, 6, 10, 5, 10); + break; + case EAST: + cubeBuilder.addCube(11, 6, 6, 16 - distanceFromEdge, 10, 10); + break; + case NORTH: + cubeBuilder.addCube(6, 6, distanceFromEdge, 10, 10, 5); + break; + case SOUTH: + cubeBuilder.addCube(6, 6, 11, 10, 10, 16 - distanceFromEdge); + break; + case UP: + cubeBuilder.addCube(6, 11, 6, 10, 16 - distanceFromEdge, 10); + break; + case WEST: + cubeBuilder.addCube(distanceFromEdge, 6, 6, 5, 10, 10); + break; + } + } + + /** + * This renders a slightly bigger covered cable connection to the specified side. This is used to connect cable + * cores with adjacent machines + * that do not want to be connected to using a glass cable connection. This applies to most machines (interfaces, + * etc.) + */ + private void addBigCoveredCableSizedCube(EnumFacing facing, CubeBuilder cubeBuilder) { + switch (facing) { + case DOWN: + cubeBuilder.addCube(5, 0, 5, 11, 4, 11); + break; + case EAST: + cubeBuilder.addCube(12, 5, 5, 16, 11, 11); + break; + case NORTH: + cubeBuilder.addCube(5, 5, 0, 11, 11, 4); + break; + case SOUTH: + cubeBuilder.addCube(5, 5, 12, 11, 11, 16); + break; + case UP: + cubeBuilder.addCube(5, 12, 5, 11, 16, 11); + break; + case WEST: + cubeBuilder.addCube(0, 5, 5, 4, 11, 11); + break; + } + } + + // Get all textures needed for building the actual cable quads + public static List getTextures() { + List locations = new ArrayList<>(); + + for (CableCoreType coreType : CableCoreType.values()) { + for (AEColor color : AEColor.values()) { + locations.add(coreType.getTexture(color)); + } + } + + for (AECableType cableType : AECableType.VALIDCABLES) { + for (AEColor color : AEColor.values()) { + locations.add(getConnectionTexture(cableType, color)); + } + } + + Collections.addAll(locations, SmartCableTextures.SMART_CHANNELS_TEXTURES); + + return locations; + } + + public TextureAtlasSprite getCoreTexture(CableCoreType coreType, AEColor color) { + return this.coreTextures.get(coreType).get(color); + } } diff --git a/src/main/java/appeng/client/render/cablebus/CableBusBakedModel.java b/src/main/java/appeng/client/render/cablebus/CableBusBakedModel.java index 82c8cf40c..65d3edea9 100644 --- a/src/main/java/appeng/client/render/cablebus/CableBusBakedModel.java +++ b/src/main/java/appeng/client/render/cablebus/CableBusBakedModel.java @@ -19,17 +19,11 @@ package appeng.client.render.cablebus; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.annotation.Nullable; - +import appeng.api.parts.IPartBakedModel; +import appeng.api.parts.IPartModel; +import appeng.api.util.AECableType; +import appeng.api.util.AEColor; +import appeng.block.networking.BlockCableBus; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.BakedQuad; @@ -44,326 +38,285 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.common.property.IExtendedBlockState; -import appeng.api.parts.IPartBakedModel; -import appeng.api.parts.IPartModel; -import appeng.api.util.AECableType; -import appeng.api.util.AEColor; -import appeng.block.networking.BlockCableBus; +import javax.annotation.Nullable; +import java.util.*; +import java.util.Map.Entry; -public class CableBusBakedModel implements IBakedModel -{ +public class CableBusBakedModel implements IBakedModel { - private static final Map> CABLE_MODEL_CACHE = new HashMap<>(); + private static final Map> CABLE_MODEL_CACHE = new HashMap<>(); - private final CableBuilder cableBuilder; + private final CableBuilder cableBuilder; - private final FacadeBuilder facadeBuilder; + private final FacadeBuilder facadeBuilder; - private final Map partModels; + private final Map partModels; - private final TextureAtlasSprite particleTexture; + private final TextureAtlasSprite particleTexture; - private final TextureMap textureMap = Minecraft.getMinecraft().getTextureMapBlocks(); + private final TextureMap textureMap = Minecraft.getMinecraft().getTextureMapBlocks(); - CableBusBakedModel( CableBuilder cableBuilder, FacadeBuilder facadeBuilder, Map partModels, TextureAtlasSprite particleTexture ) - { - this.cableBuilder = cableBuilder; - this.facadeBuilder = facadeBuilder; - this.partModels = partModels; - this.particleTexture = particleTexture; - } + CableBusBakedModel(CableBuilder cableBuilder, FacadeBuilder facadeBuilder, Map partModels, TextureAtlasSprite particleTexture) { + this.cableBuilder = cableBuilder; + this.facadeBuilder = facadeBuilder; + this.partModels = partModels; + this.particleTexture = particleTexture; + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - CableBusRenderState renderState = getRenderingState( state ); + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + CableBusRenderState renderState = getRenderingState(state); - if( renderState == null || side != null ) - { - return Collections.emptyList(); - } + if (renderState == null || side != null) { + return Collections.emptyList(); + } - BlockRenderLayer layer = MinecraftForgeClient.getRenderLayer(); + BlockRenderLayer layer = MinecraftForgeClient.getRenderLayer(); - List quads = new ArrayList<>(); + List quads = new ArrayList<>(); - // The core parts of the cable will only be rendered in the CUTOUT layer. - // Facades will add them selves to what ever the block would be rendered with, - // except when transparent facades are enabled, they are forced to TRANSPARENT. - if( layer == BlockRenderLayer.CUTOUT ) - { + // The core parts of the cable will only be rendered in the CUTOUT layer. + // Facades will add them selves to what ever the block would be rendered with, + // except when transparent facades are enabled, they are forced to TRANSPARENT. + if (layer == BlockRenderLayer.CUTOUT) { - // First, handle the cable at the center of the cable bus - final List cableModel = CABLE_MODEL_CACHE.computeIfAbsent( renderState, k -> - { - final List model = new ArrayList<>(); - this.addCableQuads( renderState, model ); - return model; - } ); - quads.addAll( cableModel ); + // First, handle the cable at the center of the cable bus + final List cableModel = CABLE_MODEL_CACHE.computeIfAbsent(renderState, k -> + { + final List model = new ArrayList<>(); + this.addCableQuads(renderState, model); + return model; + }); + quads.addAll(cableModel); - // Then handle attachments - for( EnumFacing facing : EnumFacing.values() ) - { - final IPartModel partModel = renderState.getAttachments().get( facing ); - if( partModel == null ) - { - continue; - } + // Then handle attachments + for (EnumFacing facing : EnumFacing.values()) { + final IPartModel partModel = renderState.getAttachments().get(facing); + if (partModel == null) { + continue; + } - for( ResourceLocation model : partModel.getModels() ) - { - IBakedModel bakedModel = this.partModels.get( model ); + for (ResourceLocation model : partModel.getModels()) { + IBakedModel bakedModel = this.partModels.get(model); - if( bakedModel == null ) - { - throw new IllegalStateException( "Trying to use an unregistered part model: " + model ); - } + if (bakedModel == null) { + throw new IllegalStateException("Trying to use an unregistered part model: " + model); + } - List partQuads; - if( bakedModel instanceof IPartBakedModel ) - { - partQuads = ( (IPartBakedModel) bakedModel ).getPartQuads( renderState.getPartFlags().get( facing ), rand ); - } - else - { - partQuads = bakedModel.getQuads( state, null, rand ); - } + List partQuads; + if (bakedModel instanceof IPartBakedModel) { + partQuads = ((IPartBakedModel) bakedModel).getPartQuads(renderState.getPartFlags().get(facing), rand); + } else { + partQuads = bakedModel.getQuads(state, null, rand); + } - // Rotate quads accordingly - QuadRotator rotator = new QuadRotator(); - partQuads = rotator.rotateQuads( partQuads, facing, EnumFacing.UP ); + // Rotate quads accordingly + QuadRotator rotator = new QuadRotator(); + partQuads = rotator.rotateQuads(partQuads, facing, EnumFacing.UP); - quads.addAll( partQuads ); - } - } - } - this.facadeBuilder.buildFacadeQuads( layer, renderState, rand, quads, this.partModels::get ); + quads.addAll(partQuads); + } + } + } + this.facadeBuilder.buildFacadeQuads(layer, renderState, rand, quads, this.partModels::get); - return quads; - } + return quads; + } - // Determines whether a cable is connected to exactly two sides that are opposite each other - private static boolean isStraightLine( AECableType cableType, EnumMap sides ) - { - final Iterator> it = sides.entrySet().iterator(); - if( !it.hasNext() ) - { - return false; // No connections - } + // Determines whether a cable is connected to exactly two sides that are opposite each other + private static boolean isStraightLine(AECableType cableType, EnumMap sides) { + final Iterator> it = sides.entrySet().iterator(); + if (!it.hasNext()) { + return false; // No connections + } - final Entry nextConnection = it.next(); - final EnumFacing firstSide = nextConnection.getKey(); - final AECableType firstType = nextConnection.getValue(); + final Entry nextConnection = it.next(); + final EnumFacing firstSide = nextConnection.getKey(); + final AECableType firstType = nextConnection.getValue(); - if( !it.hasNext() ) - { - return false; // Only a single connection - } - if( firstSide.getOpposite() != it.next().getKey() ) - { - return false; // Connected to two sides that are not opposite each other - } - if( it.hasNext() ) - { - return false; // Must not have any other connection points - } + if (!it.hasNext()) { + return false; // Only a single connection + } + if (firstSide.getOpposite() != it.next().getKey()) { + return false; // Connected to two sides that are not opposite each other + } + if (it.hasNext()) { + return false; // Must not have any other connection points + } - final AECableType secondType = sides.get( firstSide.getOpposite() ); + final AECableType secondType = sides.get(firstSide.getOpposite()); - return firstType == secondType && cableType == firstType && cableType == secondType; - } + return firstType == secondType && cableType == firstType && cableType == secondType; + } - private void addCableQuads( CableBusRenderState renderState, List quadsOut ) - { - AECableType cableType = renderState.getCableType(); - if( cableType == AECableType.NONE ) - { - return; - } + private void addCableQuads(CableBusRenderState renderState, List quadsOut) { + AECableType cableType = renderState.getCableType(); + if (cableType == AECableType.NONE) { + return; + } - AEColor cableColor = renderState.getCableColor(); - EnumMap connectionTypes = renderState.getConnectionTypes(); + AEColor cableColor = renderState.getCableColor(); + EnumMap connectionTypes = renderState.getConnectionTypes(); - // If the connection is straight, no busses are attached, and no covered core has been forced (in case of glass - // cables), then render the cable as a simplified straight line. - boolean noAttachments = !renderState.getAttachments().values().stream().anyMatch( IPartModel::requireCableConnection ); - if( noAttachments && isStraightLine( cableType, connectionTypes ) ) - { - EnumFacing facing = connectionTypes.keySet().iterator().next(); + // If the connection is straight, no busses are attached, and no covered core has been forced (in case of glass + // cables), then render the cable as a simplified straight line. + boolean noAttachments = !renderState.getAttachments().values().stream().anyMatch(IPartModel::requireCableConnection); + if (noAttachments && isStraightLine(cableType, connectionTypes)) { + EnumFacing facing = connectionTypes.keySet().iterator().next(); - switch( cableType ) - { - case GLASS: - this.cableBuilder.addStraightGlassConnection( facing, cableColor, quadsOut ); - break; - case COVERED: - this.cableBuilder.addStraightCoveredConnection( facing, cableColor, quadsOut ); - break; - case SMART: - this.cableBuilder.addStraightSmartConnection( facing, cableColor, renderState.getChannelsOnSide().get( facing ), quadsOut ); - break; - case DENSE_COVERED: - this.cableBuilder.addStraightDenseCoveredConnection( facing, cableColor, quadsOut ); - break; - case DENSE_SMART: - this.cableBuilder.addStraightDenseSmartConnection( facing, cableColor, renderState.getChannelsOnSide().get( facing ), quadsOut ); - break; - default: - break; - } + switch (cableType) { + case GLASS: + this.cableBuilder.addStraightGlassConnection(facing, cableColor, quadsOut); + break; + case COVERED: + this.cableBuilder.addStraightCoveredConnection(facing, cableColor, quadsOut); + break; + case SMART: + this.cableBuilder.addStraightSmartConnection(facing, cableColor, renderState.getChannelsOnSide().get(facing), quadsOut); + break; + case DENSE_COVERED: + this.cableBuilder.addStraightDenseCoveredConnection(facing, cableColor, quadsOut); + break; + case DENSE_SMART: + this.cableBuilder.addStraightDenseSmartConnection(facing, cableColor, renderState.getChannelsOnSide().get(facing), quadsOut); + break; + default: + break; + } - return; // Don't render the other form of connection - } + return; // Don't render the other form of connection + } - this.cableBuilder.addCableCore( renderState.getCoreType(), cableColor, quadsOut ); + this.cableBuilder.addCableCore(renderState.getCoreType(), cableColor, quadsOut); - // Render all internal connections to attachments - EnumMap attachmentConnections = renderState.getAttachmentConnections(); - for( EnumFacing facing : attachmentConnections.keySet() ) - { - int distance = attachmentConnections.get( facing ); - int channels = renderState.getChannelsOnSide().get( facing ); + // Render all internal connections to attachments + EnumMap attachmentConnections = renderState.getAttachmentConnections(); + for (EnumFacing facing : attachmentConnections.keySet()) { + int distance = attachmentConnections.get(facing); + int channels = renderState.getChannelsOnSide().get(facing); - switch( cableType ) - { - case GLASS: - this.cableBuilder.addConstrainedGlassConnection( facing, cableColor, distance, quadsOut ); - break; - case COVERED: - this.cableBuilder.addConstrainedCoveredConnection( facing, cableColor, distance, quadsOut ); - break; - case SMART: - this.cableBuilder.addConstrainedSmartConnection( facing, cableColor, distance, channels, quadsOut ); - break; - case DENSE_COVERED: - case DENSE_SMART: - // Dense cables do not render connections to parts since none can be attached - break; - default: - break; - } - } + switch (cableType) { + case GLASS: + this.cableBuilder.addConstrainedGlassConnection(facing, cableColor, distance, quadsOut); + break; + case COVERED: + this.cableBuilder.addConstrainedCoveredConnection(facing, cableColor, distance, quadsOut); + break; + case SMART: + this.cableBuilder.addConstrainedSmartConnection(facing, cableColor, distance, channels, quadsOut); + break; + case DENSE_COVERED: + case DENSE_SMART: + // Dense cables do not render connections to parts since none can be attached + break; + default: + break; + } + } - // Render all outgoing connections using the appropriate type - for( final Entry connection : connectionTypes.entrySet() ) - { - final EnumFacing facing = connection.getKey(); - final AECableType connectionType = connection.getValue(); - final boolean cableBusAdjacent = renderState.getCableBusAdjacent().contains( facing ); - final int channels = renderState.getChannelsOnSide().get( facing ); + // Render all outgoing connections using the appropriate type + for (final Entry connection : connectionTypes.entrySet()) { + final EnumFacing facing = connection.getKey(); + final AECableType connectionType = connection.getValue(); + final boolean cableBusAdjacent = renderState.getCableBusAdjacent().contains(facing); + final int channels = renderState.getChannelsOnSide().get(facing); - switch( cableType ) - { - case GLASS: - this.cableBuilder.addGlassConnection( facing, cableColor, connectionType, cableBusAdjacent, quadsOut ); - break; - case COVERED: - this.cableBuilder.addCoveredConnection( facing, cableColor, connectionType, cableBusAdjacent, quadsOut ); - break; - case SMART: - this.cableBuilder.addSmartConnection( facing, cableColor, connectionType, cableBusAdjacent, channels, quadsOut ); - break; - case DENSE_COVERED: - this.cableBuilder.addDenseCoveredConnection( facing, cableColor, connectionType, cableBusAdjacent, quadsOut ); - break; - case DENSE_SMART: - this.cableBuilder.addDenseSmartConnection( facing, cableColor, connectionType, cableBusAdjacent, channels, quadsOut ); - break; - default: - break; - } - } - } + switch (cableType) { + case GLASS: + this.cableBuilder.addGlassConnection(facing, cableColor, connectionType, cableBusAdjacent, quadsOut); + break; + case COVERED: + this.cableBuilder.addCoveredConnection(facing, cableColor, connectionType, cableBusAdjacent, quadsOut); + break; + case SMART: + this.cableBuilder.addSmartConnection(facing, cableColor, connectionType, cableBusAdjacent, channels, quadsOut); + break; + case DENSE_COVERED: + this.cableBuilder.addDenseCoveredConnection(facing, cableColor, connectionType, cableBusAdjacent, quadsOut); + break; + case DENSE_SMART: + this.cableBuilder.addDenseSmartConnection(facing, cableColor, connectionType, cableBusAdjacent, channels, quadsOut); + break; + default: + break; + } + } + } - /** - * Gets a list of texture sprites appropriate for particles (digging, etc.) given the render state for a cable bus. - */ - public List getParticleTextures( CableBusRenderState renderState ) - { - CableCoreType coreType = CableCoreType.fromCableType( renderState.getCableType() ); - AEColor cableColor = renderState.getCableColor(); + /** + * Gets a list of texture sprites appropriate for particles (digging, etc.) given the render state for a cable bus. + */ + public List getParticleTextures(CableBusRenderState renderState) { + CableCoreType coreType = CableCoreType.fromCableType(renderState.getCableType()); + AEColor cableColor = renderState.getCableColor(); - List result = new ArrayList<>(); + List result = new ArrayList<>(); - if( coreType != null ) - { - result.add( this.cableBuilder.getCoreTexture( coreType, cableColor ) ); - } + if (coreType != null) { + result.add(this.cableBuilder.getCoreTexture(coreType, cableColor)); + } - // If no core is present, just use the first part that comes into play - for( EnumFacing side : renderState.getAttachments().keySet() ) - { - IPartModel partModel = renderState.getAttachments().get( side ); + // If no core is present, just use the first part that comes into play + for (EnumFacing side : renderState.getAttachments().keySet()) { + IPartModel partModel = renderState.getAttachments().get(side); - for( ResourceLocation model : partModel.getModels() ) - { - IBakedModel bakedModel = this.partModels.get( model ); + for (ResourceLocation model : partModel.getModels()) { + IBakedModel bakedModel = this.partModels.get(model); - if( bakedModel == null ) - { - throw new IllegalStateException( "Trying to use an unregistered part model: " + model ); - } + if (bakedModel == null) { + throw new IllegalStateException("Trying to use an unregistered part model: " + model); + } - TextureAtlasSprite particleTexture = bakedModel.getParticleTexture(); + TextureAtlasSprite particleTexture = bakedModel.getParticleTexture(); - // If a part sub-model has no particle texture (indicated by it being the missing texture), - // don't add it, so we don't get ugly missing texture break particles. - if( this.textureMap.getMissingSprite() != particleTexture ) - { - result.add( particleTexture ); - } - } - } + // If a part sub-model has no particle texture (indicated by it being the missing texture), + // don't add it, so we don't get ugly missing texture break particles. + if (this.textureMap.getMissingSprite() != particleTexture) { + result.add(particleTexture); + } + } + } - return result; - } + return result; + } - private static CableBusRenderState getRenderingState( IBlockState state ) - { - if( state == null || !( state instanceof IExtendedBlockState ) ) - { - return null; - } + private static CableBusRenderState getRenderingState(IBlockState state) { + if (state == null || !(state instanceof IExtendedBlockState)) { + return null; + } - IExtendedBlockState extendedBlockState = (IExtendedBlockState) state; - return extendedBlockState.getValue( BlockCableBus.RENDER_STATE_PROPERTY ); - } + IExtendedBlockState extendedBlockState = (IExtendedBlockState) state; + return extendedBlockState.getValue(BlockCableBus.RENDER_STATE_PROPERTY); + } - @Override - public boolean isAmbientOcclusion() - { - return true; - } + @Override + public boolean isAmbientOcclusion() { + return true; + } - @Override - public boolean isGui3d() - { - return false; - } + @Override + public boolean isGui3d() { + return false; + } - @Override - public boolean isBuiltInRenderer() - { - return false; - } + @Override + public boolean isBuiltInRenderer() { + return false; + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.particleTexture; - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.particleTexture; + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return ItemCameraTransforms.DEFAULT; - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return ItemCameraTransforms.DEFAULT; + } - @Override - public ItemOverrideList getOverrides() - { - return ItemOverrideList.NONE; - } + @Override + public ItemOverrideList getOverrides() { + return ItemOverrideList.NONE; + } } diff --git a/src/main/java/appeng/client/render/cablebus/CableBusModel.java b/src/main/java/appeng/client/render/cablebus/CableBusModel.java index 56856cd3e..8dcc9c836 100644 --- a/src/main/java/appeng/client/render/cablebus/CableBusModel.java +++ b/src/main/java/appeng/client/render/cablebus/CableBusModel.java @@ -19,13 +19,11 @@ package appeng.client.render.cablebus; -import java.util.Collection; -import java.util.Map; -import java.util.function.Function; - +import appeng.api.util.AEColor; +import appeng.core.AELog; +import appeng.core.features.registries.PartModels; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; - import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -35,84 +33,72 @@ import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; -import appeng.api.util.AEColor; -import appeng.core.AELog; -import appeng.core.features.registries.PartModels; +import java.util.Collection; +import java.util.Map; +import java.util.function.Function; /** * The built-in model for the cable bus block. */ -public class CableBusModel implements IModel -{ +public class CableBusModel implements IModel { - private final PartModels partModels; + private final PartModels partModels; - public CableBusModel( PartModels partModels ) - { - this.partModels = partModels; - } + public CableBusModel(PartModels partModels) { + this.partModels = partModels; + } - @Override - public Collection getDependencies() - { - this.partModels.setInitialized( true ); - return this.partModels.getModels(); - } + @Override + public Collection getDependencies() { + this.partModels.setInitialized(true); + return this.partModels.getModels(); + } - @Override - public Collection getTextures() - { - return ImmutableList.builder() - .addAll( CableBuilder.getTextures() ) - .build(); - } + @Override + public Collection getTextures() { + return ImmutableList.builder() + .addAll(CableBuilder.getTextures()) + .build(); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - Map partModels = this.loadPartModels( state, format, bakedTextureGetter ); + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + Map partModels = this.loadPartModels(state, format, bakedTextureGetter); - CableBuilder cableBuilder = new CableBuilder( format, bakedTextureGetter ); - FacadeBuilder facadeBuilder = new FacadeBuilder(); + CableBuilder cableBuilder = new CableBuilder(format, bakedTextureGetter); + FacadeBuilder facadeBuilder = new FacadeBuilder(); - // This should normally not be used, but we *have* to provide a particle texture or otherwise damage models will - // crash - TextureAtlasSprite particleTexture = cableBuilder.getCoreTexture( CableCoreType.GLASS, AEColor.TRANSPARENT ); + // This should normally not be used, but we *have* to provide a particle texture or otherwise damage models will + // crash + TextureAtlasSprite particleTexture = cableBuilder.getCoreTexture(CableCoreType.GLASS, AEColor.TRANSPARENT); - return new CableBusBakedModel( cableBuilder, facadeBuilder, partModels, particleTexture ); - } + return new CableBusBakedModel(cableBuilder, facadeBuilder, partModels, particleTexture); + } - private Map loadPartModels( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - ImmutableMap.Builder result = ImmutableMap.builder(); + private Map loadPartModels(IModelState state, VertexFormat format, Function bakedTextureGetter) { + ImmutableMap.Builder result = ImmutableMap.builder(); - for( ResourceLocation location : this.partModels.getModels() ) - { - IModel model = this.tryLoadPartModel( location ); - IBakedModel bakedModel = model.bake( state, format, bakedTextureGetter ); - result.put( location, bakedModel ); - } + for (ResourceLocation location : this.partModels.getModels()) { + IModel model = this.tryLoadPartModel(location); + IBakedModel bakedModel = model.bake(state, format, bakedTextureGetter); + result.put(location, bakedModel); + } - return result.build(); - } + return result.build(); + } - private IModel tryLoadPartModel( ResourceLocation location ) - { - try - { - return ModelLoaderRegistry.getModel( location ); - } - catch( Exception e ) - { - AELog.error( e, "Unable to load part model " + location ); - return ModelLoaderRegistry.getMissingModel(); - } - } + private IModel tryLoadPartModel(ResourceLocation location) { + try { + return ModelLoaderRegistry.getModel(location); + } catch (Exception e) { + AELog.error(e, "Unable to load part model " + location); + return ModelLoaderRegistry.getMissingModel(); + } + } - @Override - public IModelState getDefaultState() - { - return TRSRTransformation.identity(); - } + @Override + public IModelState getDefaultState() { + return TRSRTransformation.identity(); + } } diff --git a/src/main/java/appeng/client/render/cablebus/CableBusRenderState.java b/src/main/java/appeng/client/render/cablebus/CableBusRenderState.java index 28e2f8bf4..5b1ef8b09 100644 --- a/src/main/java/appeng/client/render/cablebus/CableBusRenderState.java +++ b/src/main/java/appeng/client/render/cablebus/CableBusRenderState.java @@ -19,212 +19,180 @@ package appeng.client.render.cablebus; -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.List; -import java.util.Objects; - +import appeng.api.parts.IPartModel; +import appeng.api.util.AECableType; +import appeng.api.util.AEColor; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; -import appeng.api.parts.IPartModel; -import appeng.api.util.AECableType; -import appeng.api.util.AEColor; +import java.lang.ref.WeakReference; +import java.util.*; /** * This class captures the entire rendering state needed for a cable bus and transports it to the rendering thread * for processing. */ -public class CableBusRenderState -{ +public class CableBusRenderState { - // The cable type used for rendering the outgoing connections to other blocks and attached parts - private AECableType cableType = AECableType.NONE; + // The cable type used for rendering the outgoing connections to other blocks and attached parts + private AECableType cableType = AECableType.NONE; - // The type to use for rendering the core of the cable. - private CableCoreType coreType; + // The type to use for rendering the core of the cable. + private CableCoreType coreType; - private AEColor cableColor = AEColor.TRANSPARENT; + private AEColor cableColor = AEColor.TRANSPARENT; - // Describes the outgoing connections of this cable bus to other blocks, and how they should be rendered - private EnumMap connectionTypes = new EnumMap<>( EnumFacing.class ); + // Describes the outgoing connections of this cable bus to other blocks, and how they should be rendered + private EnumMap connectionTypes = new EnumMap<>(EnumFacing.class); - // Indicate on which sides signified by connectionTypes above, there is another cable bus. If a side is connected, - // but it is absent from this - // set, then it means that there is a Grid host, but not a cable bus on that side (i.e. an interface, a controller, - // etc.) - private EnumSet cableBusAdjacent = EnumSet.noneOf( EnumFacing.class ); + // Indicate on which sides signified by connectionTypes above, there is another cable bus. If a side is connected, + // but it is absent from this + // set, then it means that there is a Grid host, but not a cable bus on that side (i.e. an interface, a controller, + // etc.) + private EnumSet cableBusAdjacent = EnumSet.noneOf(EnumFacing.class); - // Specifies the number of channels used for the connection to a given side. Only contains entries if - // connections contains a corresponding entry. - private EnumMap channelsOnSide = new EnumMap<>( EnumFacing.class ); + // Specifies the number of channels used for the connection to a given side. Only contains entries if + // connections contains a corresponding entry. + private EnumMap channelsOnSide = new EnumMap<>(EnumFacing.class); - private EnumMap attachments = new EnumMap<>( EnumFacing.class ); + private final EnumMap attachments = new EnumMap<>(EnumFacing.class); - // For each attachment, this contains the distance from the edge until which a cable connection should be drawn - private EnumMap attachmentConnections = new EnumMap<>( EnumFacing.class ); + // For each attachment, this contains the distance from the edge until which a cable connection should be drawn + private final EnumMap attachmentConnections = new EnumMap<>(EnumFacing.class); - // Contains the facade to use for each side that has a facade attached - private EnumMap facades = new EnumMap<>( EnumFacing.class ); + // Contains the facade to use for each side that has a facade attached + private final EnumMap facades = new EnumMap<>(EnumFacing.class); - // Used for Facades. - private WeakReference world; - private BlockPos pos; + // Used for Facades. + private WeakReference world; + private BlockPos pos; - // Contains the bounding boxes of all parts on the cable bus to allow facades to cut out holes for the parts. This - // list is only populated if there are - // facades on this cable bus - private List boundingBoxes = new ArrayList<>(); + // Contains the bounding boxes of all parts on the cable bus to allow facades to cut out holes for the parts. This + // list is only populated if there are + // facades on this cable bus + private final List boundingBoxes = new ArrayList<>(); - private EnumMap partFlags = new EnumMap<>( EnumFacing.class ); + private final EnumMap partFlags = new EnumMap<>(EnumFacing.class); - public CableCoreType getCoreType() - { - return this.coreType; - } + public CableCoreType getCoreType() { + return this.coreType; + } - public void setCoreType( CableCoreType coreType ) - { - this.coreType = coreType; - } + public void setCoreType(CableCoreType coreType) { + this.coreType = coreType; + } - public AECableType getCableType() - { - return this.cableType; - } + public AECableType getCableType() { + return this.cableType; + } - public void setCableType( AECableType cableType ) - { - this.cableType = cableType; - } + public void setCableType(AECableType cableType) { + this.cableType = cableType; + } - public AEColor getCableColor() - { - return this.cableColor; - } + public AEColor getCableColor() { + return this.cableColor; + } - public void setCableColor( AEColor cableColor ) - { - this.cableColor = cableColor; - } + public void setCableColor(AEColor cableColor) { + this.cableColor = cableColor; + } - public EnumMap getChannelsOnSide() - { - return this.channelsOnSide; - } + public EnumMap getChannelsOnSide() { + return this.channelsOnSide; + } - public EnumMap getConnectionTypes() - { - return this.connectionTypes; - } + public EnumMap getConnectionTypes() { + return this.connectionTypes; + } - public void setConnectionTypes( EnumMap connectionTypes ) - { - this.connectionTypes = connectionTypes; - } + public void setConnectionTypes(EnumMap connectionTypes) { + this.connectionTypes = connectionTypes; + } - public void setChannelsOnSide( EnumMap channelsOnSide ) - { - this.channelsOnSide = channelsOnSide; - } + public void setChannelsOnSide(EnumMap channelsOnSide) { + this.channelsOnSide = channelsOnSide; + } - public EnumSet getCableBusAdjacent() - { - return this.cableBusAdjacent; - } + public EnumSet getCableBusAdjacent() { + return this.cableBusAdjacent; + } - public void setCableBusAdjacent( EnumSet cableBusAdjacent ) - { - this.cableBusAdjacent = cableBusAdjacent; - } + public void setCableBusAdjacent(EnumSet cableBusAdjacent) { + this.cableBusAdjacent = cableBusAdjacent; + } - public EnumMap getAttachments() - { - return this.attachments; - } + public EnumMap getAttachments() { + return this.attachments; + } - public EnumMap getAttachmentConnections() - { - return this.attachmentConnections; - } + public EnumMap getAttachmentConnections() { + return this.attachmentConnections; + } - public EnumMap getFacades() - { - return this.facades; - } + public EnumMap getFacades() { + return this.facades; + } - public IBlockAccess getWorld() - { - return this.world.get(); - } + public IBlockAccess getWorld() { + return this.world.get(); + } - public void setWorld( IBlockAccess world ) - { - this.world = new WeakReference<>( world ); - } + public void setWorld(IBlockAccess world) { + this.world = new WeakReference<>(world); + } - public BlockPos getPos() - { - return this.pos; - } + public BlockPos getPos() { + return this.pos; + } - public void setPos( BlockPos pos ) - { - this.pos = pos; - } + public void setPos(BlockPos pos) { + this.pos = pos; + } - public List getBoundingBoxes() - { - return this.boundingBoxes; - } + public List getBoundingBoxes() { + return this.boundingBoxes; + } - public EnumMap getPartFlags() - { - return this.partFlags; - } + public EnumMap getPartFlags() { + return this.partFlags; + } - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ( ( this.attachmentConnections == null ) ? 0 : this.attachmentConnections.hashCode() ); - result = prime * result + ( ( this.cableBusAdjacent == null ) ? 0 : this.cableBusAdjacent.hashCode() ); - result = prime * result + ( ( this.cableColor == null ) ? 0 : this.cableColor.hashCode() ); - result = prime * result + ( ( this.cableType == null ) ? 0 : this.cableType.hashCode() ); - result = prime * result + ( ( this.channelsOnSide == null ) ? 0 : this.channelsOnSide.hashCode() ); - result = prime * result + ( ( this.connectionTypes == null ) ? 0 : this.connectionTypes.hashCode() ); - result = prime * result + ( ( this.coreType == null ) ? 0 : this.coreType.hashCode() ); - result = prime * result + ( ( this.partFlags == null ) ? 0 : this.partFlags.hashCode() ); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.attachmentConnections == null) ? 0 : this.attachmentConnections.hashCode()); + result = prime * result + ((this.cableBusAdjacent == null) ? 0 : this.cableBusAdjacent.hashCode()); + result = prime * result + ((this.cableColor == null) ? 0 : this.cableColor.hashCode()); + result = prime * result + ((this.cableType == null) ? 0 : this.cableType.hashCode()); + result = prime * result + ((this.channelsOnSide == null) ? 0 : this.channelsOnSide.hashCode()); + result = prime * result + ((this.connectionTypes == null) ? 0 : this.connectionTypes.hashCode()); + result = prime * result + ((this.coreType == null) ? 0 : this.coreType.hashCode()); + result = prime * result + ((this.partFlags == null) ? 0 : this.partFlags.hashCode()); + return result; + } - @Override - public boolean equals( Object obj ) - { - if( this == obj ) - { - return true; - } - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } - final CableBusRenderState other = (CableBusRenderState) obj; + final CableBusRenderState other = (CableBusRenderState) obj; - return this.cableColor == other.cableColor && this.cableType == other.cableType && this.coreType == other.coreType && Objects - .equals( this.attachmentConnections, other.attachmentConnections ) && Objects.equals( this.cableBusAdjacent, other.cableBusAdjacent ) && Objects - .equals( this.channelsOnSide, other.channelsOnSide ) && Objects.equals( this.connectionTypes, other.connectionTypes ) && Objects - .equals( this.partFlags, other.partFlags ); - } + return this.cableColor == other.cableColor && this.cableType == other.cableType && this.coreType == other.coreType && Objects + .equals(this.attachmentConnections, other.attachmentConnections) && Objects.equals(this.cableBusAdjacent, other.cableBusAdjacent) && Objects + .equals(this.channelsOnSide, other.channelsOnSide) && Objects.equals(this.connectionTypes, other.connectionTypes) && Objects + .equals(this.partFlags, other.partFlags); + } } diff --git a/src/main/java/appeng/client/render/cablebus/CableCoreType.java b/src/main/java/appeng/client/render/cablebus/CableCoreType.java index 0a0c58c2f..c33ed1795 100644 --- a/src/main/java/appeng/client/render/cablebus/CableCoreType.java +++ b/src/main/java/appeng/client/render/cablebus/CableCoreType.java @@ -19,16 +19,14 @@ package appeng.client.render.cablebus; -import java.util.EnumMap; -import java.util.Map; - -import com.google.common.collect.ImmutableMap; - -import net.minecraft.util.ResourceLocation; - import appeng.api.util.AECableType; import appeng.api.util.AEColor; import appeng.core.AppEng; +import com.google.common.collect.ImmutableMap; +import net.minecraft.util.ResourceLocation; + +import java.util.EnumMap; +import java.util.Map; /** @@ -38,49 +36,44 @@ import appeng.core.AppEng; * - Covered (also used by the Smart Cable) * - Dense */ -public enum CableCoreType -{ - GLASS( "parts/cable/core/glass" ), COVERED( "parts/cable/core/covered" ), DENSE( "parts/cable/core/dense_smart" ); +public enum CableCoreType { + GLASS("parts/cable/core/glass"), COVERED("parts/cable/core/covered"), DENSE("parts/cable/core/dense_smart"); - private static final Map cableMapping = generateCableMapping(); + private static final Map cableMapping = generateCableMapping(); - /** - * Creates the mapping that assigns a cable core type to an AE cable type. - */ - private static Map generateCableMapping() - { + /** + * Creates the mapping that assigns a cable core type to an AE cable type. + */ + private static Map generateCableMapping() { - Map result = new EnumMap<>( AECableType.class ); + Map result = new EnumMap<>(AECableType.class); - result.put( AECableType.GLASS, CableCoreType.GLASS ); - result.put( AECableType.COVERED, CableCoreType.COVERED ); - result.put( AECableType.SMART, CableCoreType.COVERED ); - result.put( AECableType.DENSE_COVERED, CableCoreType.DENSE ); - result.put( AECableType.DENSE_SMART, CableCoreType.DENSE ); + result.put(AECableType.GLASS, CableCoreType.GLASS); + result.put(AECableType.COVERED, CableCoreType.COVERED); + result.put(AECableType.SMART, CableCoreType.COVERED); + result.put(AECableType.DENSE_COVERED, CableCoreType.DENSE); + result.put(AECableType.DENSE_SMART, CableCoreType.DENSE); - return ImmutableMap.copyOf( result ); - } + return ImmutableMap.copyOf(result); + } - private final String textureFolder; + private final String textureFolder; - CableCoreType( String textureFolder ) - { - this.textureFolder = textureFolder; - } + CableCoreType(String textureFolder) { + this.textureFolder = textureFolder; + } - /** - * @return The type of core that should be rendered when the given cable isn't straight and needs to have a core to - * attach connections to. - * Is null for the NULL cable. - */ - public static CableCoreType fromCableType( AECableType cableType ) - { - return cableMapping.get( cableType ); - } + /** + * @return The type of core that should be rendered when the given cable isn't straight and needs to have a core to + * attach connections to. + * Is null for the NULL cable. + */ + public static CableCoreType fromCableType(AECableType cableType) { + return cableMapping.get(cableType); + } - public ResourceLocation getTexture( AEColor color ) - { - return new ResourceLocation( AppEng.MOD_ID, this.textureFolder + "/" + color.name().toLowerCase() ); - } + public ResourceLocation getTexture(AEColor color) { + return new ResourceLocation(AppEng.MOD_ID, this.textureFolder + "/" + color.name().toLowerCase()); + } } \ No newline at end of file diff --git a/src/main/java/appeng/client/render/cablebus/CubeBuilder.java b/src/main/java/appeng/client/render/cablebus/CubeBuilder.java index 3d229dcc9..89e74a3ac 100644 --- a/src/main/java/appeng/client/render/cablebus/CubeBuilder.java +++ b/src/main/java/appeng/client/render/cablebus/CubeBuilder.java @@ -19,15 +19,8 @@ package appeng.client.render.cablebus; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.List; - -import javax.vecmath.Vector4f; - +import appeng.client.render.VertexFormats; import com.google.common.base.Preconditions; - import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; @@ -36,517 +29,468 @@ import net.minecraft.client.renderer.vertex.VertexFormatElement; import net.minecraft.util.EnumFacing; import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad; -import appeng.client.render.VertexFormats; +import javax.vecmath.Vector4f; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.List; /** * Builds the quads for a cube. */ -public class CubeBuilder -{ +public class CubeBuilder { - private VertexFormat format; + private VertexFormat format; - private final List output; + private final List output; - private final EnumMap textures = new EnumMap<>( EnumFacing.class ); + private final EnumMap textures = new EnumMap<>(EnumFacing.class); - private EnumSet drawFaces = EnumSet.allOf( EnumFacing.class ); + private EnumSet drawFaces = EnumSet.allOf(EnumFacing.class); - private final EnumMap customUv = new EnumMap<>( EnumFacing.class ); + private final EnumMap customUv = new EnumMap<>(EnumFacing.class); - private byte[] uvRotations = new byte[EnumFacing.values().length]; + private final byte[] uvRotations = new byte[EnumFacing.values().length]; - private int color = 0xFFFFFFFF; + private int color = 0xFFFFFFFF; - private boolean useStandardUV = false; + private boolean useStandardUV = false; - private boolean renderFullBright; + private boolean renderFullBright; - public CubeBuilder( VertexFormat format, List output ) - { - this.output = output; - this.format = format; - } + public CubeBuilder(VertexFormat format, List output) { + this.output = output; + this.format = format; + } - public CubeBuilder( VertexFormat format ) - { - this( format, new ArrayList<>( 6 ) ); - } + public CubeBuilder(VertexFormat format) { + this(format, new ArrayList<>(6)); + } - public void addCube( float x1, float y1, float z1, float x2, float y2, float z2 ) - { - x1 /= 16.0f; - y1 /= 16.0f; - z1 /= 16.0f; - x2 /= 16.0f; - y2 /= 16.0f; - z2 /= 16.0f; + public void addCube(float x1, float y1, float z1, float x2, float y2, float z2) { + x1 /= 16.0f; + y1 /= 16.0f; + z1 /= 16.0f; + x2 /= 16.0f; + y2 /= 16.0f; + z2 /= 16.0f; - // If brightness is forced to specific values, extend the vertex format to contain the multi-texturing lightmap - // offset - VertexFormat savedFormat = null; - if( this.renderFullBright ) - { - savedFormat = this.format; - this.format = VertexFormats.getFormatWithLightMap( this.format ); - } + // If brightness is forced to specific values, extend the vertex format to contain the multi-texturing lightmap + // offset + VertexFormat savedFormat = null; + if (this.renderFullBright) { + savedFormat = this.format; + this.format = VertexFormats.getFormatWithLightMap(this.format); + } - for( EnumFacing face : this.drawFaces ) - { - this.putFace( face, x1, y1, z1, x2, y2, z2 ); - } + for (EnumFacing face : this.drawFaces) { + this.putFace(face, x1, y1, z1, x2, y2, z2); + } - // Restore old format - if( savedFormat != null ) - { - this.format = savedFormat; - } - } + // Restore old format + if (savedFormat != null) { + this.format = savedFormat; + } + } - public void addQuad( EnumFacing face, float x1, float y1, float z1, float x2, float y2, float z2 ) - { - // If brightness is forced to specific values, extend the vertex format to contain the multi-texturing lightmap - // offset - VertexFormat savedFormat = null; - if( this.renderFullBright ) - { - savedFormat = this.format; - this.format = new VertexFormat( savedFormat ); - if( !this.format.getElements().contains( DefaultVertexFormats.TEX_2S ) ) - { - this.format.addElement( DefaultVertexFormats.TEX_2S ); - } - } + public void addQuad(EnumFacing face, float x1, float y1, float z1, float x2, float y2, float z2) { + // If brightness is forced to specific values, extend the vertex format to contain the multi-texturing lightmap + // offset + VertexFormat savedFormat = null; + if (this.renderFullBright) { + savedFormat = this.format; + this.format = new VertexFormat(savedFormat); + if (!this.format.getElements().contains(DefaultVertexFormats.TEX_2S)) { + this.format.addElement(DefaultVertexFormats.TEX_2S); + } + } - this.putFace( face, x1, y1, z1, x2, y2, z2 ); + this.putFace(face, x1, y1, z1, x2, y2, z2); - // Restore old format - if( savedFormat != null ) - { - this.format = savedFormat; - } - } + // Restore old format + if (savedFormat != null) { + this.format = savedFormat; + } + } - private static final class UvVector - { - float u1; - float u2; - float v1; - float v2; - } + private static final class UvVector { + float u1; + float u2; + float v1; + float v2; + } - private void putFace( EnumFacing face, float x1, float y1, float z1, float x2, float y2, float z2 ) - { + private void putFace(EnumFacing face, float x1, float y1, float z1, float x2, float y2, float z2) { - TextureAtlasSprite texture = this.textures.get( face ); + TextureAtlasSprite texture = this.textures.get(face); - UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder( this.format ); - builder.setTexture( texture ); - builder.setQuadOrientation( face ); - builder.setQuadTint( -1 ); - builder.setApplyDiffuseLighting( true ); + UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder(this.format); + builder.setTexture(texture); + builder.setQuadOrientation(face); + builder.setQuadTint(-1); + builder.setApplyDiffuseLighting(true); - UvVector uv = new UvVector(); + UvVector uv = new UvVector(); - // The user might have set specific UV coordinates for this face - Vector4f customUv = this.customUv.get( face ); - if( customUv != null ) - { - uv.u1 = texture.getInterpolatedU( customUv.x ); - uv.v1 = texture.getInterpolatedV( customUv.y ); - uv.u2 = texture.getInterpolatedU( customUv.z ); - uv.v2 = texture.getInterpolatedV( customUv.w ); - } - else if( this.useStandardUV ) - { - uv = this.getStandardUv( face, texture, x1, y1, z1, x2, y2, z2 ); - } - else - { - uv = this.getDefaultUv( face, texture, x1, y1, z1, x2, y2, z2 ); - } + // The user might have set specific UV coordinates for this face + Vector4f customUv = this.customUv.get(face); + if (customUv != null) { + uv.u1 = texture.getInterpolatedU(customUv.x); + uv.v1 = texture.getInterpolatedV(customUv.y); + uv.u2 = texture.getInterpolatedU(customUv.z); + uv.v2 = texture.getInterpolatedV(customUv.w); + } else if (this.useStandardUV) { + uv = this.getStandardUv(face, texture, x1, y1, z1, x2, y2, z2); + } else { + uv = this.getDefaultUv(face, texture, x1, y1, z1, x2, y2, z2); + } - switch( face ) - { - case DOWN: - this.putVertexTR( builder, face, x2, y1, z1, uv ); - this.putVertexBR( builder, face, x2, y1, z2, uv ); - this.putVertexBL( builder, face, x1, y1, z2, uv ); - this.putVertexTL( builder, face, x1, y1, z1, uv ); - break; - case UP: - this.putVertexTL( builder, face, x1, y2, z1, uv ); - this.putVertexBL( builder, face, x1, y2, z2, uv ); - this.putVertexBR( builder, face, x2, y2, z2, uv ); - this.putVertexTR( builder, face, x2, y2, z1, uv ); - break; - case NORTH: - this.putVertexBR( builder, face, x2, y2, z1, uv ); - this.putVertexTR( builder, face, x2, y1, z1, uv ); - this.putVertexTL( builder, face, x1, y1, z1, uv ); - this.putVertexBL( builder, face, x1, y2, z1, uv ); - break; - case SOUTH: - this.putVertexBL( builder, face, x1, y2, z2, uv ); - this.putVertexTL( builder, face, x1, y1, z2, uv ); - this.putVertexTR( builder, face, x2, y1, z2, uv ); - this.putVertexBR( builder, face, x2, y2, z2, uv ); - break; - case WEST: - this.putVertexTL( builder, face, x1, y1, z1, uv ); - this.putVertexTR( builder, face, x1, y1, z2, uv ); - this.putVertexBR( builder, face, x1, y2, z2, uv ); - this.putVertexBL( builder, face, x1, y2, z1, uv ); - break; - case EAST: - this.putVertexBR( builder, face, x2, y2, z1, uv ); - this.putVertexBL( builder, face, x2, y2, z2, uv ); - this.putVertexTL( builder, face, x2, y1, z2, uv ); - this.putVertexTR( builder, face, x2, y1, z1, uv ); - break; - } + switch (face) { + case DOWN: + this.putVertexTR(builder, face, x2, y1, z1, uv); + this.putVertexBR(builder, face, x2, y1, z2, uv); + this.putVertexBL(builder, face, x1, y1, z2, uv); + this.putVertexTL(builder, face, x1, y1, z1, uv); + break; + case UP: + this.putVertexTL(builder, face, x1, y2, z1, uv); + this.putVertexBL(builder, face, x1, y2, z2, uv); + this.putVertexBR(builder, face, x2, y2, z2, uv); + this.putVertexTR(builder, face, x2, y2, z1, uv); + break; + case NORTH: + this.putVertexBR(builder, face, x2, y2, z1, uv); + this.putVertexTR(builder, face, x2, y1, z1, uv); + this.putVertexTL(builder, face, x1, y1, z1, uv); + this.putVertexBL(builder, face, x1, y2, z1, uv); + break; + case SOUTH: + this.putVertexBL(builder, face, x1, y2, z2, uv); + this.putVertexTL(builder, face, x1, y1, z2, uv); + this.putVertexTR(builder, face, x2, y1, z2, uv); + this.putVertexBR(builder, face, x2, y2, z2, uv); + break; + case WEST: + this.putVertexTL(builder, face, x1, y1, z1, uv); + this.putVertexTR(builder, face, x1, y1, z2, uv); + this.putVertexBR(builder, face, x1, y2, z2, uv); + this.putVertexBL(builder, face, x1, y2, z1, uv); + break; + case EAST: + this.putVertexBR(builder, face, x2, y2, z1, uv); + this.putVertexBL(builder, face, x2, y2, z2, uv); + this.putVertexTL(builder, face, x2, y1, z2, uv); + this.putVertexTR(builder, face, x2, y1, z1, uv); + break; + } - this.output.add( builder.build() ); - } + this.output.add(builder.build()); + } - private UvVector getDefaultUv( EnumFacing face, TextureAtlasSprite texture, float x1, float y1, float z1, float x2, float y2, float z2 ) - { + private UvVector getDefaultUv(EnumFacing face, TextureAtlasSprite texture, float x1, float y1, float z1, float x2, float y2, float z2) { - UvVector uv = new UvVector(); + UvVector uv = new UvVector(); - switch( face ) - { - case DOWN: - uv.u1 = texture.getInterpolatedU( x1 * 16 ); - uv.v1 = texture.getInterpolatedV( z1 * 16 ); - uv.u2 = texture.getInterpolatedU( x2 * 16 ); - uv.v2 = texture.getInterpolatedV( z2 * 16 ); - break; - case UP: - uv.u1 = texture.getInterpolatedU( x1 * 16 ); - uv.v1 = texture.getInterpolatedV( z1 * 16 ); - uv.u2 = texture.getInterpolatedU( x2 * 16 ); - uv.v2 = texture.getInterpolatedV( z2 * 16 ); - break; - case NORTH: - uv.u1 = texture.getInterpolatedU( x1 * 16 ); - uv.v1 = texture.getInterpolatedV( 16 - y1 * 16 ); - uv.u2 = texture.getInterpolatedU( x2 * 16 ); - uv.v2 = texture.getInterpolatedV( 16 - y2 * 16 ); - break; - case SOUTH: - uv.u1 = texture.getInterpolatedU( x1 * 16 ); - uv.v1 = texture.getInterpolatedV( 16 - y1 * 16 ); - uv.u2 = texture.getInterpolatedU( x2 * 16 ); - uv.v2 = texture.getInterpolatedV( 16 - y2 * 16 ); - break; - case WEST: - uv.u1 = texture.getInterpolatedU( z1 * 16 ); - uv.v1 = texture.getInterpolatedV( 16 - y1 * 16 ); - uv.u2 = texture.getInterpolatedU( z2 * 16 ); - uv.v2 = texture.getInterpolatedV( 16 - y2 * 16 ); - break; - case EAST: - uv.u1 = texture.getInterpolatedU( z2 * 16 ); - uv.v1 = texture.getInterpolatedV( 16 - y1 * 16 ); - uv.u2 = texture.getInterpolatedU( z1 * 16 ); - uv.v2 = texture.getInterpolatedV( 16 - y2 * 16 ); - break; - } + switch (face) { + case DOWN: + uv.u1 = texture.getInterpolatedU(x1 * 16); + uv.v1 = texture.getInterpolatedV(z1 * 16); + uv.u2 = texture.getInterpolatedU(x2 * 16); + uv.v2 = texture.getInterpolatedV(z2 * 16); + break; + case UP: + uv.u1 = texture.getInterpolatedU(x1 * 16); + uv.v1 = texture.getInterpolatedV(z1 * 16); + uv.u2 = texture.getInterpolatedU(x2 * 16); + uv.v2 = texture.getInterpolatedV(z2 * 16); + break; + case NORTH: + uv.u1 = texture.getInterpolatedU(x1 * 16); + uv.v1 = texture.getInterpolatedV(16 - y1 * 16); + uv.u2 = texture.getInterpolatedU(x2 * 16); + uv.v2 = texture.getInterpolatedV(16 - y2 * 16); + break; + case SOUTH: + uv.u1 = texture.getInterpolatedU(x1 * 16); + uv.v1 = texture.getInterpolatedV(16 - y1 * 16); + uv.u2 = texture.getInterpolatedU(x2 * 16); + uv.v2 = texture.getInterpolatedV(16 - y2 * 16); + break; + case WEST: + uv.u1 = texture.getInterpolatedU(z1 * 16); + uv.v1 = texture.getInterpolatedV(16 - y1 * 16); + uv.u2 = texture.getInterpolatedU(z2 * 16); + uv.v2 = texture.getInterpolatedV(16 - y2 * 16); + break; + case EAST: + uv.u1 = texture.getInterpolatedU(z2 * 16); + uv.v1 = texture.getInterpolatedV(16 - y1 * 16); + uv.u2 = texture.getInterpolatedU(z1 * 16); + uv.v2 = texture.getInterpolatedV(16 - y2 * 16); + break; + } - return uv; - } + return uv; + } - private UvVector getStandardUv( EnumFacing face, TextureAtlasSprite texture, float x1, float y1, float z1, float x2, float y2, float z2 ) - { - UvVector uv = new UvVector(); - switch( face ) - { - case DOWN: - uv.u1 = texture.getInterpolatedU( x1 * 16 ); - uv.v1 = texture.getInterpolatedV( 16 - z1 * 16 ); - uv.u2 = texture.getInterpolatedU( x2 * 16 ); - uv.v2 = texture.getInterpolatedV( 16 - z2 * 16 ); - break; - case UP: - uv.u1 = texture.getInterpolatedU( x1 * 16 ); - uv.v1 = texture.getInterpolatedV( z1 * 16 ); - uv.u2 = texture.getInterpolatedU( x2 * 16 ); - uv.v2 = texture.getInterpolatedV( z2 * 16 ); - break; - case NORTH: - uv.u1 = texture.getInterpolatedU( 16 - x1 * 16 ); - uv.v1 = texture.getInterpolatedV( 16 - y1 * 16 ); - uv.u2 = texture.getInterpolatedU( 16 - x2 * 16 ); - uv.v2 = texture.getInterpolatedV( 16 - y2 * 16 ); - break; - case SOUTH: - uv.u1 = texture.getInterpolatedU( x1 * 16 ); - uv.v1 = texture.getInterpolatedV( 16 - y1 * 16 ); - uv.u2 = texture.getInterpolatedU( x2 * 16 ); - uv.v2 = texture.getInterpolatedV( 16 - y2 * 16 ); - break; - case WEST: - uv.u1 = texture.getInterpolatedU( z1 * 16 ); - uv.v1 = texture.getInterpolatedV( 16 - y1 * 16 ); - uv.u2 = texture.getInterpolatedU( z2 * 16 ); - uv.v2 = texture.getInterpolatedV( 16 - y2 * 16 ); - break; - case EAST: - uv.u1 = texture.getInterpolatedU( 16 - z2 * 16 ); - uv.v1 = texture.getInterpolatedV( 16 - y1 * 16 ); - uv.u2 = texture.getInterpolatedU( 16 - z1 * 16 ); - uv.v2 = texture.getInterpolatedV( 16 - y2 * 16 ); - break; - } - return uv; - } + private UvVector getStandardUv(EnumFacing face, TextureAtlasSprite texture, float x1, float y1, float z1, float x2, float y2, float z2) { + UvVector uv = new UvVector(); + switch (face) { + case DOWN: + uv.u1 = texture.getInterpolatedU(x1 * 16); + uv.v1 = texture.getInterpolatedV(16 - z1 * 16); + uv.u2 = texture.getInterpolatedU(x2 * 16); + uv.v2 = texture.getInterpolatedV(16 - z2 * 16); + break; + case UP: + uv.u1 = texture.getInterpolatedU(x1 * 16); + uv.v1 = texture.getInterpolatedV(z1 * 16); + uv.u2 = texture.getInterpolatedU(x2 * 16); + uv.v2 = texture.getInterpolatedV(z2 * 16); + break; + case NORTH: + uv.u1 = texture.getInterpolatedU(16 - x1 * 16); + uv.v1 = texture.getInterpolatedV(16 - y1 * 16); + uv.u2 = texture.getInterpolatedU(16 - x2 * 16); + uv.v2 = texture.getInterpolatedV(16 - y2 * 16); + break; + case SOUTH: + uv.u1 = texture.getInterpolatedU(x1 * 16); + uv.v1 = texture.getInterpolatedV(16 - y1 * 16); + uv.u2 = texture.getInterpolatedU(x2 * 16); + uv.v2 = texture.getInterpolatedV(16 - y2 * 16); + break; + case WEST: + uv.u1 = texture.getInterpolatedU(z1 * 16); + uv.v1 = texture.getInterpolatedV(16 - y1 * 16); + uv.u2 = texture.getInterpolatedU(z2 * 16); + uv.v2 = texture.getInterpolatedV(16 - y2 * 16); + break; + case EAST: + uv.u1 = texture.getInterpolatedU(16 - z2 * 16); + uv.v1 = texture.getInterpolatedV(16 - y1 * 16); + uv.u2 = texture.getInterpolatedU(16 - z1 * 16); + uv.v2 = texture.getInterpolatedV(16 - y2 * 16); + break; + } + return uv; + } - // uv.u1, uv.v1 - private void putVertexTL( UnpackedBakedQuad.Builder builder, EnumFacing face, float x, float y, float z, UvVector uv ) - { - float u, v; + // uv.u1, uv.v1 + private void putVertexTL(UnpackedBakedQuad.Builder builder, EnumFacing face, float x, float y, float z, UvVector uv) { + float u, v; - switch( this.uvRotations[face.ordinal()] ) - { - default: - case 0: - u = uv.u1; - v = uv.v1; - break; - case 1: // 90° clockwise - u = uv.u1; - v = uv.v2; - break; - case 2: // 180° clockwise - u = uv.u2; - v = uv.v2; - break; - case 3: // 270° clockwise - u = uv.u2; - v = uv.v1; - break; - } + switch (this.uvRotations[face.ordinal()]) { + default: + case 0: + u = uv.u1; + v = uv.v1; + break; + case 1: // 90° clockwise + u = uv.u1; + v = uv.v2; + break; + case 2: // 180° clockwise + u = uv.u2; + v = uv.v2; + break; + case 3: // 270° clockwise + u = uv.u2; + v = uv.v1; + break; + } - this.putVertex( builder, face, x, y, z, u, v ); - } + this.putVertex(builder, face, x, y, z, u, v); + } - // uv.u2, uv.v1 - private void putVertexTR( UnpackedBakedQuad.Builder builder, EnumFacing face, float x, float y, float z, UvVector uv ) - { - float u, v; + // uv.u2, uv.v1 + private void putVertexTR(UnpackedBakedQuad.Builder builder, EnumFacing face, float x, float y, float z, UvVector uv) { + float u, v; - switch( this.uvRotations[face.ordinal()] ) - { - default: - case 0: - u = uv.u2; - v = uv.v1; - break; - case 1: // 90° clockwise - u = uv.u1; - v = uv.v1; - break; - case 2: // 180° clockwise - u = uv.u1; - v = uv.v2; - break; - case 3: // 270° clockwise - u = uv.u2; - v = uv.v2; - break; - } - this.putVertex( builder, face, x, y, z, u, v ); - } + switch (this.uvRotations[face.ordinal()]) { + default: + case 0: + u = uv.u2; + v = uv.v1; + break; + case 1: // 90° clockwise + u = uv.u1; + v = uv.v1; + break; + case 2: // 180° clockwise + u = uv.u1; + v = uv.v2; + break; + case 3: // 270° clockwise + u = uv.u2; + v = uv.v2; + break; + } + this.putVertex(builder, face, x, y, z, u, v); + } - // uv.u2, uv.v2 - private void putVertexBR( UnpackedBakedQuad.Builder builder, EnumFacing face, float x, float y, float z, UvVector uv ) - { + // uv.u2, uv.v2 + private void putVertexBR(UnpackedBakedQuad.Builder builder, EnumFacing face, float x, float y, float z, UvVector uv) { - float u; - float v; + float u; + float v; - switch( this.uvRotations[face.ordinal()] ) - { - default: - case 0: - u = uv.u2; - v = uv.v2; - break; - case 1: // 90° clockwise - u = uv.u2; - v = uv.v1; - break; - case 2: // 180° clockwise - u = uv.u1; - v = uv.v1; - break; - case 3: // 270° clockwise - u = uv.u1; - v = uv.v2; - break; - } + switch (this.uvRotations[face.ordinal()]) { + default: + case 0: + u = uv.u2; + v = uv.v2; + break; + case 1: // 90° clockwise + u = uv.u2; + v = uv.v1; + break; + case 2: // 180° clockwise + u = uv.u1; + v = uv.v1; + break; + case 3: // 270° clockwise + u = uv.u1; + v = uv.v2; + break; + } - this.putVertex( builder, face, x, y, z, u, v ); - } + this.putVertex(builder, face, x, y, z, u, v); + } - // uv.u1, uv.v2 - private void putVertexBL( UnpackedBakedQuad.Builder builder, EnumFacing face, float x, float y, float z, UvVector uv ) - { + // uv.u1, uv.v2 + private void putVertexBL(UnpackedBakedQuad.Builder builder, EnumFacing face, float x, float y, float z, UvVector uv) { - float u; - float v; + float u; + float v; - switch( this.uvRotations[face.ordinal()] ) - { - default: - case 0: - u = uv.u1; - v = uv.v2; - break; - case 1: // 90° clockwise - u = uv.u2; - v = uv.v2; - break; - case 2: // 180° clockwise - u = uv.u2; - v = uv.v1; - break; - case 3: // 270° clockwise - u = uv.u1; - v = uv.v1; - break; - } + switch (this.uvRotations[face.ordinal()]) { + default: + case 0: + u = uv.u1; + v = uv.v2; + break; + case 1: // 90° clockwise + u = uv.u2; + v = uv.v2; + break; + case 2: // 180° clockwise + u = uv.u2; + v = uv.v1; + break; + case 3: // 270° clockwise + u = uv.u1; + v = uv.v1; + break; + } - this.putVertex( builder, face, x, y, z, u, v ); - } + this.putVertex(builder, face, x, y, z, u, v); + } - private void putVertex( UnpackedBakedQuad.Builder builder, EnumFacing face, float x, float y, float z, float u, float v ) - { - VertexFormat format = builder.getVertexFormat(); + private void putVertex(UnpackedBakedQuad.Builder builder, EnumFacing face, float x, float y, float z, float u, float v) { + VertexFormat format = builder.getVertexFormat(); - for( int i = 0; i < format.getElementCount(); i++ ) - { - VertexFormatElement e = format.getElement( i ); - switch( e.getUsage() ) - { - case POSITION: - builder.put( i, x, y, z ); - break; - case NORMAL: - builder.put( i, face.getFrontOffsetX(), face.getFrontOffsetY(), face.getFrontOffsetZ() ); - break; - case COLOR: - // Color format is RGBA - float r = ( this.color >> 16 & 0xFF ) / 255f; - float g = ( this.color >> 8 & 0xFF ) / 255f; - float b = ( this.color & 0xFF ) / 255f; - float a = ( this.color >> 24 & 0xFF ) / 255f; - builder.put( i, r, g, b, a ); - break; - case UV: - if( e.getIndex() == 0 ) - { - builder.put( i, u, v ); - } - else - { - // Force Brightness to 15, this is for full bright mode - // this vertex element will only be present in that case - final float lightMapU = (float) ( 15 * 0x20 ) / 0xFFFF; - final float lightMapV = (float) ( 15 * 0x20 ) / 0xFFFF; - builder.put( i, lightMapU, lightMapV ); - } - break; - default: - builder.put( i ); - break; - } - } - } + for (int i = 0; i < format.getElementCount(); i++) { + VertexFormatElement e = format.getElement(i); + switch (e.getUsage()) { + case POSITION: + builder.put(i, x, y, z); + break; + case NORMAL: + builder.put(i, face.getFrontOffsetX(), face.getFrontOffsetY(), face.getFrontOffsetZ()); + break; + case COLOR: + // Color format is RGBA + float r = (this.color >> 16 & 0xFF) / 255f; + float g = (this.color >> 8 & 0xFF) / 255f; + float b = (this.color & 0xFF) / 255f; + float a = (this.color >> 24 & 0xFF) / 255f; + builder.put(i, r, g, b, a); + break; + case UV: + if (e.getIndex() == 0) { + builder.put(i, u, v); + } else { + // Force Brightness to 15, this is for full bright mode + // this vertex element will only be present in that case + final float lightMapU = (float) (15 * 0x20) / 0xFFFF; + final float lightMapV = (float) (15 * 0x20) / 0xFFFF; + builder.put(i, lightMapU, lightMapV); + } + break; + default: + builder.put(i); + break; + } + } + } - public void setTexture( TextureAtlasSprite texture ) - { - for( EnumFacing face : EnumFacing.values() ) - { - this.textures.put( face, texture ); - } - } + public void setTexture(TextureAtlasSprite texture) { + for (EnumFacing face : EnumFacing.values()) { + this.textures.put(face, texture); + } + } - public void setTextures( TextureAtlasSprite up, TextureAtlasSprite down, TextureAtlasSprite north, TextureAtlasSprite south, TextureAtlasSprite east, TextureAtlasSprite west ) - { - this.textures.put( EnumFacing.UP, up ); - this.textures.put( EnumFacing.DOWN, down ); - this.textures.put( EnumFacing.NORTH, north ); - this.textures.put( EnumFacing.SOUTH, south ); - this.textures.put( EnumFacing.EAST, east ); - this.textures.put( EnumFacing.WEST, west ); - } + public void setTextures(TextureAtlasSprite up, TextureAtlasSprite down, TextureAtlasSprite north, TextureAtlasSprite south, TextureAtlasSprite east, TextureAtlasSprite west) { + this.textures.put(EnumFacing.UP, up); + this.textures.put(EnumFacing.DOWN, down); + this.textures.put(EnumFacing.NORTH, north); + this.textures.put(EnumFacing.SOUTH, south); + this.textures.put(EnumFacing.EAST, east); + this.textures.put(EnumFacing.WEST, west); + } - public void setTexture( EnumFacing facing, TextureAtlasSprite sprite ) - { - this.textures.put( facing, sprite ); - } + public void setTexture(EnumFacing facing, TextureAtlasSprite sprite) { + this.textures.put(facing, sprite); + } - public void setDrawFaces( EnumSet drawFaces ) - { - this.drawFaces = drawFaces; - } + public void setDrawFaces(EnumSet drawFaces) { + this.drawFaces = drawFaces; + } - public void setColor( int color ) - { - this.color = color; - } + public void setColor(int color) { + this.color = color; + } - /** - * Sets the vertex color for future vertices to the given RGB value, and forces the alpha component to 255. - */ - public void setColorRGB( int color ) - { - this.setColor( color | 0xFF000000 ); - } + /** + * Sets the vertex color for future vertices to the given RGB value, and forces the alpha component to 255. + */ + public void setColorRGB(int color) { + this.setColor(color | 0xFF000000); + } - public void setColorRGB( float r, float g, float b ) - { - this.setColorRGB( (int) ( r * 255 ) << 16 | (int) ( g * 255 ) << 8 | (int) ( b * 255 ) ); - } + public void setColorRGB(float r, float g, float b) { + this.setColorRGB((int) (r * 255) << 16 | (int) (g * 255) << 8 | (int) (b * 255)); + } - public void setRenderFullBright( boolean renderFullBright ) - { - this.renderFullBright = renderFullBright; - } + public void setRenderFullBright(boolean renderFullBright) { + this.renderFullBright = renderFullBright; + } - public void setCustomUv( EnumFacing facing, float u1, float v1, float u2, float v2 ) - { - this.customUv.put( facing, new Vector4f( u1, v1, u2, v2 ) ); - } + public void setCustomUv(EnumFacing facing, float u1, float v1, float u2, float v2) { + this.customUv.put(facing, new Vector4f(u1, v1, u2, v2)); + } - public void setUvRotation( EnumFacing facing, int rotation ) - { - if( rotation == 2 ) - { - rotation = 3; - } - else if( rotation == 3 ) - { - rotation = 2; - } - Preconditions.checkArgument( rotation >= 0 && rotation <= 3, "rotation" ); - this.uvRotations[facing.ordinal()] = (byte) rotation; - } + public void setUvRotation(EnumFacing facing, int rotation) { + if (rotation == 2) { + rotation = 3; + } else if (rotation == 3) { + rotation = 2; + } + Preconditions.checkArgument(rotation >= 0 && rotation <= 3, "rotation"); + this.uvRotations[facing.ordinal()] = (byte) rotation; + } - /** - * CubeBuilder uses UV optimized for cables by default. - * This switches to standard UV coordinates. - */ - public void useStandardUV() - { - this.useStandardUV = true; - } + /** + * CubeBuilder uses UV optimized for cables by default. + * This switches to standard UV coordinates. + */ + public void useStandardUV() { + this.useStandardUV = true; + } - public List getOutput() - { - return this.output; - } + public List getOutput() { + return this.output; + } } diff --git a/src/main/java/appeng/client/render/cablebus/FacadeBlockAccess.java b/src/main/java/appeng/client/render/cablebus/FacadeBlockAccess.java index 733f038ef..a7c114fd8 100644 --- a/src/main/java/appeng/client/render/cablebus/FacadeBlockAccess.java +++ b/src/main/java/appeng/client/render/cablebus/FacadeBlockAccess.java @@ -19,8 +19,6 @@ package appeng.client.render.cablebus; -import javax.annotation.Nullable; - import net.minecraft.block.state.IBlockState; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; @@ -29,6 +27,8 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.WorldType; import net.minecraft.world.biome.Biome; +import javax.annotation.Nullable; + /** * This is used to retrieve the ExtendedState of a block for facade rendering. @@ -36,80 +36,66 @@ import net.minecraft.world.biome.Biome; * * @author covers1624 */ -public class FacadeBlockAccess implements IBlockAccess -{ +public class FacadeBlockAccess implements IBlockAccess { - private final IBlockAccess world; - private final BlockPos pos; - private final EnumFacing side; - private final IBlockState state; + private final IBlockAccess world; + private final BlockPos pos; + private final EnumFacing side; + private final IBlockState state; - public FacadeBlockAccess( IBlockAccess world, BlockPos pos, EnumFacing side, IBlockState state ) - { - this.world = world; - this.pos = pos; - this.side = side; - this.state = state; - } + public FacadeBlockAccess(IBlockAccess world, BlockPos pos, EnumFacing side, IBlockState state) { + this.world = world; + this.pos = pos; + this.side = side; + this.state = state; + } - @Nullable - @Override - public TileEntity getTileEntity( BlockPos pos ) - { - return this.world.getTileEntity( pos ); - } + @Nullable + @Override + public TileEntity getTileEntity(BlockPos pos) { + return this.world.getTileEntity(pos); + } - @Override - public int getCombinedLight( BlockPos pos, int lightValue ) - { - return this.world.getCombinedLight( pos, lightValue ); - } + @Override + public int getCombinedLight(BlockPos pos, int lightValue) { + return this.world.getCombinedLight(pos, lightValue); + } - @Override - public IBlockState getBlockState( BlockPos pos ) - { - if( this.pos == pos ) - { - return this.state; - } - return this.world.getBlockState( pos ); - } + @Override + public IBlockState getBlockState(BlockPos pos) { + if (this.pos == pos) { + return this.state; + } + return this.world.getBlockState(pos); + } - @Override - public boolean isAirBlock( BlockPos pos ) - { - IBlockState state = this.getBlockState( pos ); - return state.getBlock().isAir( state, this.world, pos ); - } + @Override + public boolean isAirBlock(BlockPos pos) { + IBlockState state = this.getBlockState(pos); + return state.getBlock().isAir(state, this.world, pos); + } - @Override - public Biome getBiome( BlockPos pos ) - { - return this.world.getBiome( pos ); - } + @Override + public Biome getBiome(BlockPos pos) { + return this.world.getBiome(pos); + } - @Override - public int getStrongPower( BlockPos pos, EnumFacing direction ) - { - return this.world.getStrongPower( pos, direction ); - } + @Override + public int getStrongPower(BlockPos pos, EnumFacing direction) { + return this.world.getStrongPower(pos, direction); + } - @Override - public WorldType getWorldType() - { - return this.world.getWorldType(); - } + @Override + public WorldType getWorldType() { + return this.world.getWorldType(); + } - @Override - public boolean isSideSolid( BlockPos pos, EnumFacing side, boolean _default ) - { - if( pos.getX() < -30000000 || pos.getZ() < -30000000 || pos.getX() >= 30000000 || pos.getZ() >= 30000000 ) - { - return _default; - } - else - { - return this.getBlockState( pos ).isSideSolid( this, pos, side ); - } - } + @Override + public boolean isSideSolid(BlockPos pos, EnumFacing side, boolean _default) { + if (pos.getX() < -30000000 || pos.getZ() < -30000000 || pos.getX() >= 30000000 || pos.getZ() >= 30000000) { + return _default; + } else { + return this.getBlockState(pos).isSideSolid(this, pos, side); + } + } } diff --git a/src/main/java/appeng/client/render/cablebus/FacadeBuilder.java b/src/main/java/appeng/client/render/cablebus/FacadeBuilder.java index 34218e970..5b80c9e72 100644 --- a/src/main/java/appeng/client/render/cablebus/FacadeBuilder.java +++ b/src/main/java/appeng/client/render/cablebus/FacadeBuilder.java @@ -19,16 +19,13 @@ package appeng.client.render.cablebus; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.function.Function; - -import javax.annotation.Nullable; - +import appeng.api.AEApi; +import appeng.api.util.AEAxisAlignedBB; +import appeng.parts.misc.PartCableAnchor; +import appeng.thirdparty.codechicken.lib.model.CachedFormat; +import appeng.thirdparty.codechicken.lib.model.Quad; +import appeng.thirdparty.codechicken.lib.model.pipeline.BakedPipeline; +import appeng.thirdparty.codechicken.lib.model.pipeline.transformers.*; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BlockRendererDispatcher; @@ -45,18 +42,10 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.ForgeHooksClient; -import appeng.api.AEApi; -import appeng.api.util.AEAxisAlignedBB; -import appeng.parts.misc.PartCableAnchor; -import appeng.thirdparty.codechicken.lib.model.CachedFormat; -import appeng.thirdparty.codechicken.lib.model.Quad; -import appeng.thirdparty.codechicken.lib.model.pipeline.BakedPipeline; -import appeng.thirdparty.codechicken.lib.model.pipeline.transformers.QuadAlphaOverride; -import appeng.thirdparty.codechicken.lib.model.pipeline.transformers.QuadClamper; -import appeng.thirdparty.codechicken.lib.model.pipeline.transformers.QuadCornerKicker; -import appeng.thirdparty.codechicken.lib.model.pipeline.transformers.QuadFaceStripper; -import appeng.thirdparty.codechicken.lib.model.pipeline.transformers.QuadReInterpolator; -import appeng.thirdparty.codechicken.lib.model.pipeline.transformers.QuadTinter; +import javax.annotation.Nullable; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.Function; /** @@ -64,428 +53,375 @@ import appeng.thirdparty.codechicken.lib.model.pipeline.transformers.QuadTinter; * * @author covers1624 */ -public class FacadeBuilder -{ +public class FacadeBuilder { - public static final double THICK_THICKNESS = 2D / 16D; - public static final double THIN_THICKNESS = 1D / 16D; + public static final double THICK_THICKNESS = 2D / 16D; + public static final double THIN_THICKNESS = 1D / 16D; - public static final AxisAlignedBB[] THICK_FACADE_BOXES = new AxisAlignedBB[] { - new AxisAlignedBB( 0.0, 0.0, 0.0, 1.0, THICK_THICKNESS, 1.0 ), - new AxisAlignedBB( 0.0, 1.0 - THICK_THICKNESS, 0.0, 1.0, 1.0, 1.0 ), - new AxisAlignedBB( 0.0, 0.0, 0.0, 1.0, 1.0, THICK_THICKNESS ), - new AxisAlignedBB( 0.0, 0.0, 1.0 - THICK_THICKNESS, 1.0, 1.0, 1.0 ), - new AxisAlignedBB( 0.0, 0.0, 0.0, THICK_THICKNESS, 1.0, 1.0 ), - new AxisAlignedBB( 1.0 - THICK_THICKNESS, 0.0, 0.0, 1.0, 1.0, 1.0 ) - }; + public static final AxisAlignedBB[] THICK_FACADE_BOXES = new AxisAlignedBB[]{ + new AxisAlignedBB(0.0, 0.0, 0.0, 1.0, THICK_THICKNESS, 1.0), + new AxisAlignedBB(0.0, 1.0 - THICK_THICKNESS, 0.0, 1.0, 1.0, 1.0), + new AxisAlignedBB(0.0, 0.0, 0.0, 1.0, 1.0, THICK_THICKNESS), + new AxisAlignedBB(0.0, 0.0, 1.0 - THICK_THICKNESS, 1.0, 1.0, 1.0), + new AxisAlignedBB(0.0, 0.0, 0.0, THICK_THICKNESS, 1.0, 1.0), + new AxisAlignedBB(1.0 - THICK_THICKNESS, 0.0, 0.0, 1.0, 1.0, 1.0) + }; - public static final AxisAlignedBB[] THIN_FACADE_BOXES = new AxisAlignedBB[] { - new AxisAlignedBB( 0.0, 0.0, 0.0, 1.0, THIN_THICKNESS, 1.0 ), - new AxisAlignedBB( 0.0, 1.0 - THIN_THICKNESS, 0.0, 1.0, 1.0, 1.0 ), - new AxisAlignedBB( 0.0, 0.0, 0.0, 1.0, 1.0, THIN_THICKNESS ), - new AxisAlignedBB( 0.0, 0.0, 1.0 - THIN_THICKNESS, 1.0, 1.0, 1.0 ), - new AxisAlignedBB( 0.0, 0.0, 0.0, THIN_THICKNESS, 1.0, 1.0 ), - new AxisAlignedBB( 1.0 - THIN_THICKNESS, 0.0, 0.0, 1.0, 1.0, 1.0 ) - }; + public static final AxisAlignedBB[] THIN_FACADE_BOXES = new AxisAlignedBB[]{ + new AxisAlignedBB(0.0, 0.0, 0.0, 1.0, THIN_THICKNESS, 1.0), + new AxisAlignedBB(0.0, 1.0 - THIN_THICKNESS, 0.0, 1.0, 1.0, 1.0), + new AxisAlignedBB(0.0, 0.0, 0.0, 1.0, 1.0, THIN_THICKNESS), + new AxisAlignedBB(0.0, 0.0, 1.0 - THIN_THICKNESS, 1.0, 1.0, 1.0), + new AxisAlignedBB(0.0, 0.0, 0.0, THIN_THICKNESS, 1.0, 1.0), + new AxisAlignedBB(1.0 - THIN_THICKNESS, 0.0, 0.0, 1.0, 1.0, 1.0) + }; - private ThreadLocal pipelines = ThreadLocal.withInitial( () -> BakedPipeline.builder() - // Clamper is responsible for clamping the vertex to the bounds specified. - .addElement( "clamper", QuadClamper.FACTORY ) - // Strips faces if they match a mask. - .addElement( "face_stripper", QuadFaceStripper.FACTORY ) - // Kicks the edge inner corners in, solves Z fighting - .addElement( "corner_kicker", QuadCornerKicker.FACTORY ) - // Re-Interpolates the UV's for the quad. - .addElement( "interp", QuadReInterpolator.FACTORY ) - // Tints the quad if we need it to. Disabled by default. - .addElement( "tinter", QuadTinter.FACTORY, false ) - // Overrides the quad's alpha if we are forcing transparent facades. - .addElement( "transparent", QuadAlphaOverride.FACTORY, false, e -> e.setAlphaOverride( 0x4C / 255F ) ) - .build()// - ); - private ThreadLocal collectors = ThreadLocal.withInitial( Quad::new ); + private final ThreadLocal pipelines = ThreadLocal.withInitial(() -> BakedPipeline.builder() + // Clamper is responsible for clamping the vertex to the bounds specified. + .addElement("clamper", QuadClamper.FACTORY) + // Strips faces if they match a mask. + .addElement("face_stripper", QuadFaceStripper.FACTORY) + // Kicks the edge inner corners in, solves Z fighting + .addElement("corner_kicker", QuadCornerKicker.FACTORY) + // Re-Interpolates the UV's for the quad. + .addElement("interp", QuadReInterpolator.FACTORY) + // Tints the quad if we need it to. Disabled by default. + .addElement("tinter", QuadTinter.FACTORY, false) + // Overrides the quad's alpha if we are forcing transparent facades. + .addElement("transparent", QuadAlphaOverride.FACTORY, false, e -> e.setAlphaOverride(0x4C / 255F)) + .build()// + ); + private final ThreadLocal collectors = ThreadLocal.withInitial(Quad::new); - public void buildFacadeQuads( BlockRenderLayer layer, CableBusRenderState renderState, long rand, List quads, Function modelLookup ) - { - BakedPipeline pipeline = this.pipelines.get(); - Quad collectorQuad = this.collectors.get(); - boolean transparent = AEApi.instance().partHelper().getCableRenderMode().transparentFacades; - Map facadeStates = renderState.getFacades(); - List partBoxes = renderState.getBoundingBoxes(); - Set sidesWithParts = renderState.getAttachments().keySet(); - IBlockAccess parentWorld = renderState.getWorld(); - BlockPos pos = renderState.getPos(); - BlockColors blockColors = Minecraft.getMinecraft().getBlockColors(); - boolean thinFacades = isUseThinFacades( partBoxes ); + public void buildFacadeQuads(BlockRenderLayer layer, CableBusRenderState renderState, long rand, List quads, Function modelLookup) { + BakedPipeline pipeline = this.pipelines.get(); + Quad collectorQuad = this.collectors.get(); + boolean transparent = AEApi.instance().partHelper().getCableRenderMode().transparentFacades; + Map facadeStates = renderState.getFacades(); + List partBoxes = renderState.getBoundingBoxes(); + Set sidesWithParts = renderState.getAttachments().keySet(); + IBlockAccess parentWorld = renderState.getWorld(); + BlockPos pos = renderState.getPos(); + BlockColors blockColors = Minecraft.getMinecraft().getBlockColors(); + boolean thinFacades = isUseThinFacades(partBoxes); - for( Entry entry : facadeStates.entrySet() ) - { - EnumFacing side = entry.getKey(); - int sideIndex = side.ordinal(); - FacadeRenderState facadeRenderState = entry.getValue(); - boolean renderStilt = !sidesWithParts.contains( side ); - if( layer == BlockRenderLayer.CUTOUT && renderStilt ) - { - for( ResourceLocation part : PartCableAnchor.FACADE_MODELS.getModels() ) - { - IBakedModel partModel = modelLookup.apply( part ); - QuadRotator rotator = new QuadRotator(); - quads.addAll( rotator.rotateQuads( gatherQuads( partModel, null, rand ), side, EnumFacing.UP ) ); - } - } - // If we are forcing transparency and this isn't the Translucent layer. - if( transparent && layer != BlockRenderLayer.TRANSLUCENT ) - { - continue; - } + for (Entry entry : facadeStates.entrySet()) { + EnumFacing side = entry.getKey(); + int sideIndex = side.ordinal(); + FacadeRenderState facadeRenderState = entry.getValue(); + boolean renderStilt = !sidesWithParts.contains(side); + if (layer == BlockRenderLayer.CUTOUT && renderStilt) { + for (ResourceLocation part : PartCableAnchor.FACADE_MODELS.getModels()) { + IBakedModel partModel = modelLookup.apply(part); + QuadRotator rotator = new QuadRotator(); + quads.addAll(rotator.rotateQuads(gatherQuads(partModel, null, rand), side, EnumFacing.UP)); + } + } + // If we are forcing transparency and this isn't the Translucent layer. + if (transparent && layer != BlockRenderLayer.TRANSLUCENT) { + continue; + } - IBlockState blockState = facadeRenderState.getSourceBlock(); - // If we aren't forcing transparency let the block decide if it should render. - if( !transparent && layer != null ) - { - if( !blockState.getBlock().canRenderInLayer( blockState, layer ) ) - { - continue; - } - } + IBlockState blockState = facadeRenderState.getSourceBlock(); + // If we aren't forcing transparency let the block decide if it should render. + if (!transparent && layer != null) { + if (!blockState.getBlock().canRenderInLayer(blockState, layer)) { + continue; + } + } - AxisAlignedBB fullBounds = thinFacades ? THIN_FACADE_BOXES[sideIndex] : THICK_FACADE_BOXES[sideIndex]; - AxisAlignedBB facadeBox = fullBounds; - // If we are a transparent facade, we need to modify out BB. - if( facadeRenderState.isTransparent() ) - { - double offset = thinFacades ? THIN_THICKNESS : THICK_THICKNESS; - AEAxisAlignedBB tmpBB = null; - for( EnumFacing face : EnumFacing.VALUES ) - { - // Only faces that aren't on our axis - if( face.getAxis() != side.getAxis() ) - { - FacadeRenderState otherState = facadeStates.get( face ); - if( otherState != null && !otherState.isTransparent() ) - { - if( tmpBB == null ) - { - tmpBB = AEAxisAlignedBB.fromBounds( facadeBox ); - } - switch( face ) - { - case DOWN: - tmpBB.minY += offset; - break; - case UP: - tmpBB.maxY -= offset; - break; - case NORTH: - tmpBB.minZ += offset; - break; - case SOUTH: - tmpBB.maxZ -= offset; - break; - case WEST: - tmpBB.minX += offset; - break; - case EAST: - tmpBB.maxX -= offset; - break; - default: - throw new RuntimeException( "Switch falloff. " + String.valueOf( face ) ); - } - } - } - } - if( tmpBB != null ) - { - facadeBox = tmpBB.getBoundingBox(); - } - } + AxisAlignedBB fullBounds = thinFacades ? THIN_FACADE_BOXES[sideIndex] : THICK_FACADE_BOXES[sideIndex]; + AxisAlignedBB facadeBox = fullBounds; + // If we are a transparent facade, we need to modify out BB. + if (facadeRenderState.isTransparent()) { + double offset = thinFacades ? THIN_THICKNESS : THICK_THICKNESS; + AEAxisAlignedBB tmpBB = null; + for (EnumFacing face : EnumFacing.VALUES) { + // Only faces that aren't on our axis + if (face.getAxis() != side.getAxis()) { + FacadeRenderState otherState = facadeStates.get(face); + if (otherState != null && !otherState.isTransparent()) { + if (tmpBB == null) { + tmpBB = AEAxisAlignedBB.fromBounds(facadeBox); + } + switch (face) { + case DOWN: + tmpBB.minY += offset; + break; + case UP: + tmpBB.maxY -= offset; + break; + case NORTH: + tmpBB.minZ += offset; + break; + case SOUTH: + tmpBB.maxZ -= offset; + break; + case WEST: + tmpBB.minX += offset; + break; + case EAST: + tmpBB.maxX -= offset; + break; + default: + throw new RuntimeException("Switch falloff. " + face); + } + } + } + } + if (tmpBB != null) { + facadeBox = tmpBB.getBoundingBox(); + } + } - AEAxisAlignedBB cutOutBox = getCutOutBox( facadeBox, partBoxes ); - List holeStrips = getBoxes( facadeBox, cutOutBox, side.getAxis() ); - IBlockAccess facadeAccess = new FacadeBlockAccess( parentWorld, pos, side, blockState ); + AEAxisAlignedBB cutOutBox = getCutOutBox(facadeBox, partBoxes); + List holeStrips = getBoxes(facadeBox, cutOutBox, side.getAxis()); + IBlockAccess facadeAccess = new FacadeBlockAccess(parentWorld, pos, side, blockState); - BlockRendererDispatcher dispatcher = Minecraft.getMinecraft().getBlockRendererDispatcher(); + BlockRendererDispatcher dispatcher = Minecraft.getMinecraft().getBlockRendererDispatcher(); - try - { - blockState = blockState.getActualState( facadeAccess, pos ); - } - catch( Exception ignored ) - { - } - IBakedModel model = dispatcher.getModelForState( blockState ); - try - { - blockState = blockState.getBlock().getExtendedState( blockState, facadeAccess, pos ); - } - catch( Exception ignored ) - { - } + try { + blockState = blockState.getActualState(facadeAccess, pos); + } catch (Exception ignored) { + } + IBakedModel model = dispatcher.getModelForState(blockState); + try { + blockState = blockState.getBlock().getExtendedState(blockState, facadeAccess, pos); + } catch (Exception ignored) { + } - List modelQuads = new ArrayList<>(); - // If we are forcing transparent facades, fake the render layer, and grab all quads. - if( transparent || layer == null ) - { - for( BlockRenderLayer forcedLayer : BlockRenderLayer.values() ) - { - // Check if the block renders on the layer we want to force. - if( blockState.getBlock().canRenderInLayer( blockState, forcedLayer ) ) - { - // Force the layer and gather quads. - ForgeHooksClient.setRenderLayer( forcedLayer ); - modelQuads.addAll( gatherQuads( model, blockState, rand ) ); - } - } + List modelQuads = new ArrayList<>(); + // If we are forcing transparent facades, fake the render layer, and grab all quads. + if (transparent || layer == null) { + for (BlockRenderLayer forcedLayer : BlockRenderLayer.values()) { + // Check if the block renders on the layer we want to force. + if (blockState.getBlock().canRenderInLayer(blockState, forcedLayer)) { + // Force the layer and gather quads. + ForgeHooksClient.setRenderLayer(forcedLayer); + modelQuads.addAll(gatherQuads(model, blockState, rand)); + } + } - // Reset. - ForgeHooksClient.setRenderLayer( layer ); - } - else - { - modelQuads.addAll( gatherQuads( model, blockState, rand ) ); - } + // Reset. + ForgeHooksClient.setRenderLayer(layer); + } else { + modelQuads.addAll(gatherQuads(model, blockState, rand)); + } - // No quads.. Cool, next! - if( modelQuads.isEmpty() ) - { - continue; - } + // No quads.. Cool, next! + if (modelQuads.isEmpty()) { + continue; + } - // Grab out pipeline elements. - QuadClamper clamper = pipeline.getElement( "clamper", QuadClamper.class ); - QuadFaceStripper edgeStripper = pipeline.getElement( "face_stripper", QuadFaceStripper.class ); - QuadTinter tinter = pipeline.getElement( "tinter", QuadTinter.class ); - QuadCornerKicker kicker = pipeline.getElement( "corner_kicker", QuadCornerKicker.class ); + // Grab out pipeline elements. + QuadClamper clamper = pipeline.getElement("clamper", QuadClamper.class); + QuadFaceStripper edgeStripper = pipeline.getElement("face_stripper", QuadFaceStripper.class); + QuadTinter tinter = pipeline.getElement("tinter", QuadTinter.class); + QuadCornerKicker kicker = pipeline.getElement("corner_kicker", QuadCornerKicker.class); - // Set global element states. + // Set global element states. - // calculate the side mask. - int facadeMask = 0; - for( Entry ent : facadeStates.entrySet() ) - { - EnumFacing s = ent.getKey(); - if( s.getAxis() != side.getAxis() ) - { - FacadeRenderState otherState = ent.getValue(); - if( !otherState.isTransparent() ) - { - facadeMask |= 1 << s.ordinal(); - } - } - } - // Setup the edge stripper. - edgeStripper.setBounds( fullBounds ); - edgeStripper.setMask( facadeMask ); + // calculate the side mask. + int facadeMask = 0; + for (Entry ent : facadeStates.entrySet()) { + EnumFacing s = ent.getKey(); + if (s.getAxis() != side.getAxis()) { + FacadeRenderState otherState = ent.getValue(); + if (!otherState.isTransparent()) { + facadeMask |= 1 << s.ordinal(); + } + } + } + // Setup the edge stripper. + edgeStripper.setBounds(fullBounds); + edgeStripper.setMask(facadeMask); - // Setup the kicker. - kicker.setSide( sideIndex ); - kicker.setFacadeMask( facadeMask ); - kicker.setBox( fullBounds ); - kicker.setThickness( thinFacades ? THIN_THICKNESS : THICK_THICKNESS ); + // Setup the kicker. + kicker.setSide(sideIndex); + kicker.setFacadeMask(facadeMask); + kicker.setBox(fullBounds); + kicker.setThickness(thinFacades ? THIN_THICKNESS : THICK_THICKNESS); - for( BakedQuad quad : modelQuads ) - { - // lookup the format in CachedFormat. - CachedFormat format = CachedFormat.lookup( quad.getFormat() ); - // If this quad has a tint index, setup the tinter. - if( quad.hasTintIndex() ) - { - tinter.setTint( blockColors.colorMultiplier( blockState, facadeAccess, pos, quad.getTintIndex() ) ); - } - for( AxisAlignedBB box : holeStrips ) - { - // setup the clamper for this box - clamper.setClampBounds( box ); - // Reset the pipeline, clears all enabled/disabled states. - pipeline.reset( format ); - // Reset out collector. - collectorQuad.reset( format ); - // Enable / disable the optional elements - pipeline.setElementState( "tinter", quad.hasTintIndex() ); - pipeline.setElementState( "transparent", transparent ); - // Prepare the pipeline for a quad. - pipeline.prepare( collectorQuad ); + for (BakedQuad quad : modelQuads) { + // lookup the format in CachedFormat. + CachedFormat format = CachedFormat.lookup(quad.getFormat()); + // If this quad has a tint index, setup the tinter. + if (quad.hasTintIndex()) { + tinter.setTint(blockColors.colorMultiplier(blockState, facadeAccess, pos, quad.getTintIndex())); + } + for (AxisAlignedBB box : holeStrips) { + // setup the clamper for this box + clamper.setClampBounds(box); + // Reset the pipeline, clears all enabled/disabled states. + pipeline.reset(format); + // Reset out collector. + collectorQuad.reset(format); + // Enable / disable the optional elements + pipeline.setElementState("tinter", quad.hasTintIndex()); + pipeline.setElementState("transparent", transparent); + // Prepare the pipeline for a quad. + pipeline.prepare(collectorQuad); - // Pipe our quad into the pipeline. - quad.pipe( pipeline ); - // Check if the collector got any data. - if( collectorQuad.full ) - { - // Add the result. - quads.add( collectorQuad.bake() ); - } - } - } - } - } + // Pipe our quad into the pipeline. + quad.pipe(pipeline); + // Check if the collector got any data. + if (collectorQuad.full) { + // Add the result. + quads.add(collectorQuad.bake()); + } + } + } + } + } - /** - * This is slow, so should be cached. - * - * @return The model. - */ - public List buildFacadeItemQuads( ItemStack textureItem, EnumFacing side ) - { - List facadeQuads = new ArrayList<>(); - IBakedModel model = Minecraft.getMinecraft().getRenderItem().getItemModelWithOverrides( textureItem, null, null ); - List modelQuads = gatherQuads( model, null, 0 ); + /** + * This is slow, so should be cached. + * + * @return The model. + */ + public List buildFacadeItemQuads(ItemStack textureItem, EnumFacing side) { + List facadeQuads = new ArrayList<>(); + IBakedModel model = Minecraft.getMinecraft().getRenderItem().getItemModelWithOverrides(textureItem, null, null); + List modelQuads = gatherQuads(model, null, 0); - BakedPipeline pipeline = this.pipelines.get(); - Quad collectorQuad = this.collectors.get(); + BakedPipeline pipeline = this.pipelines.get(); + Quad collectorQuad = this.collectors.get(); - // Grab pipeline elements. - QuadClamper clamper = pipeline.getElement( "clamper", QuadClamper.class ); - QuadTinter tinter = pipeline.getElement( "tinter", QuadTinter.class ); + // Grab pipeline elements. + QuadClamper clamper = pipeline.getElement("clamper", QuadClamper.class); + QuadTinter tinter = pipeline.getElement("tinter", QuadTinter.class); - for( BakedQuad quad : modelQuads ) - { - // Lookup the CachedFormat for this quads format. - CachedFormat format = CachedFormat.lookup( quad.getFormat() ); - // Reset the pipeline. - pipeline.reset( format ); - // Reset the collector. - collectorQuad.reset( format ); - // If we have a tint index, setup the tinter and enable it. - if( quad.hasTintIndex() ) - { - tinter.setTint( Minecraft.getMinecraft().getItemColors().colorMultiplier( textureItem, quad.getTintIndex() ) ); - pipeline.enableElement( "tinter" ); - } - // Disable elements we don't need for items. - pipeline.disableElement( "face_stripper" ); - pipeline.disableElement( "corner_kicker" ); - // Setup the clamper - clamper.setClampBounds( THICK_FACADE_BOXES[side.ordinal()] ); - // Prepare the pipeline. - pipeline.prepare( collectorQuad ); - // Pipe our quad into the pipeline. - quad.pipe( pipeline ); - // Check the collector for data and add the quad if there was. - if( collectorQuad.full ) - { - facadeQuads.add( collectorQuad.bakeUnpacked() ); - } - } - return facadeQuads; - } + for (BakedQuad quad : modelQuads) { + // Lookup the CachedFormat for this quads format. + CachedFormat format = CachedFormat.lookup(quad.getFormat()); + // Reset the pipeline. + pipeline.reset(format); + // Reset the collector. + collectorQuad.reset(format); + // If we have a tint index, setup the tinter and enable it. + if (quad.hasTintIndex()) { + tinter.setTint(Minecraft.getMinecraft().getItemColors().colorMultiplier(textureItem, quad.getTintIndex())); + pipeline.enableElement("tinter"); + } + // Disable elements we don't need for items. + pipeline.disableElement("face_stripper"); + pipeline.disableElement("corner_kicker"); + // Setup the clamper + clamper.setClampBounds(THICK_FACADE_BOXES[side.ordinal()]); + // Prepare the pipeline. + pipeline.prepare(collectorQuad); + // Pipe our quad into the pipeline. + quad.pipe(pipeline); + // Check the collector for data and add the quad if there was. + if (collectorQuad.full) { + facadeQuads.add(collectorQuad.bakeUnpacked()); + } + } + return facadeQuads; + } - // Helper to gather all quads from a model into a list. - private static List gatherQuads( IBakedModel model, IBlockState state, long rand ) - { - List modelQuads = new ArrayList<>(); - for( EnumFacing face : EnumFacing.VALUES ) - { - modelQuads.addAll( model.getQuads( state, face, rand ) ); - } - modelQuads.addAll( model.getQuads( state, null, rand ) ); - return modelQuads; - } + // Helper to gather all quads from a model into a list. + private static List gatherQuads(IBakedModel model, IBlockState state, long rand) { + List modelQuads = new ArrayList<>(); + for (EnumFacing face : EnumFacing.VALUES) { + modelQuads.addAll(model.getQuads(state, face, rand)); + } + modelQuads.addAll(model.getQuads(state, null, rand)); + return modelQuads; + } - /** - * Given the actual facade bounding box, and the bounding boxes of all parts, determine the biggest union of AABB - * that intersect with the facade's bounding - * box. This AABB will need to be "cut out" when the facade is rendered. - */ - @Nullable - private static AEAxisAlignedBB getCutOutBox( AxisAlignedBB facadeBox, List partBoxes ) - { - AEAxisAlignedBB b = null; - for( AxisAlignedBB bb : partBoxes ) - { - if( bb.intersects( facadeBox ) ) - { - if( b == null ) - { - b = AEAxisAlignedBB.fromBounds( bb ); - } - else - { - b.maxX = Math.max( b.maxX, bb.maxX ); - b.maxY = Math.max( b.maxY, bb.maxY ); - b.maxZ = Math.max( b.maxZ, bb.maxZ ); - b.minX = Math.min( b.minX, bb.minX ); - b.minY = Math.min( b.minY, bb.minY ); - b.minZ = Math.min( b.minZ, bb.minZ ); - } - } - } - return b; - } + /** + * Given the actual facade bounding box, and the bounding boxes of all parts, determine the biggest union of AABB + * that intersect with the facade's bounding + * box. This AABB will need to be "cut out" when the facade is rendered. + */ + @Nullable + private static AEAxisAlignedBB getCutOutBox(AxisAlignedBB facadeBox, List partBoxes) { + AEAxisAlignedBB b = null; + for (AxisAlignedBB bb : partBoxes) { + if (bb.intersects(facadeBox)) { + if (b == null) { + b = AEAxisAlignedBB.fromBounds(bb); + } else { + b.maxX = Math.max(b.maxX, bb.maxX); + b.maxY = Math.max(b.maxY, bb.maxY); + b.maxZ = Math.max(b.maxZ, bb.maxZ); + b.minX = Math.min(b.minX, bb.minX); + b.minY = Math.min(b.minY, bb.minY); + b.minZ = Math.min(b.minZ, bb.minZ); + } + } + } + return b; + } - /** - * Generates the box segments around the specified hole. If the specified hole is null, a Singleton of the Facade - * box is returned. - * - * @param fb The Facade's box. - * @param hole The hole to 'cut'. - * @param axis The axis the facade is on. - * - * @return The box segments. - */ - private static List getBoxes( AxisAlignedBB fb, AEAxisAlignedBB hole, Axis axis ) - { - if( hole == null ) - { - return Collections.singletonList( fb ); - } - List boxes = new ArrayList<>(); - switch( axis ) - { - case Y: - boxes.add( new AxisAlignedBB( fb.minX, fb.minY, fb.minZ, hole.minX, fb.maxY, fb.maxZ ) ); - boxes.add( new AxisAlignedBB( hole.maxX, fb.minY, fb.minZ, fb.maxX, fb.maxY, fb.maxZ ) ); + /** + * Generates the box segments around the specified hole. If the specified hole is null, a Singleton of the Facade + * box is returned. + * + * @param fb The Facade's box. + * @param hole The hole to 'cut'. + * @param axis The axis the facade is on. + * @return The box segments. + */ + private static List getBoxes(AxisAlignedBB fb, AEAxisAlignedBB hole, Axis axis) { + if (hole == null) { + return Collections.singletonList(fb); + } + List boxes = new ArrayList<>(); + switch (axis) { + case Y: + boxes.add(new AxisAlignedBB(fb.minX, fb.minY, fb.minZ, hole.minX, fb.maxY, fb.maxZ)); + boxes.add(new AxisAlignedBB(hole.maxX, fb.minY, fb.minZ, fb.maxX, fb.maxY, fb.maxZ)); - boxes.add( new AxisAlignedBB( hole.minX, fb.minY, fb.minZ, hole.maxX, fb.maxY, hole.minZ ) ); - boxes.add( new AxisAlignedBB( hole.minX, fb.minY, hole.maxZ, hole.maxX, fb.maxY, fb.maxZ ) ); + boxes.add(new AxisAlignedBB(hole.minX, fb.minY, fb.minZ, hole.maxX, fb.maxY, hole.minZ)); + boxes.add(new AxisAlignedBB(hole.minX, fb.minY, hole.maxZ, hole.maxX, fb.maxY, fb.maxZ)); - break; - case Z: - boxes.add( new AxisAlignedBB( fb.minX, fb.minY, fb.minZ, fb.maxX, hole.minY, fb.maxZ ) ); - boxes.add( new AxisAlignedBB( fb.minX, hole.maxY, fb.minZ, fb.maxX, fb.maxY, fb.maxZ ) ); + break; + case Z: + boxes.add(new AxisAlignedBB(fb.minX, fb.minY, fb.minZ, fb.maxX, hole.minY, fb.maxZ)); + boxes.add(new AxisAlignedBB(fb.minX, hole.maxY, fb.minZ, fb.maxX, fb.maxY, fb.maxZ)); - boxes.add( new AxisAlignedBB( fb.minX, hole.minY, fb.minZ, hole.minX, hole.maxY, fb.maxZ ) ); - boxes.add( new AxisAlignedBB( hole.maxX, hole.minY, fb.minZ, fb.maxX, hole.maxY, fb.maxZ ) ); + boxes.add(new AxisAlignedBB(fb.minX, hole.minY, fb.minZ, hole.minX, hole.maxY, fb.maxZ)); + boxes.add(new AxisAlignedBB(hole.maxX, hole.minY, fb.minZ, fb.maxX, hole.maxY, fb.maxZ)); - break; - case X: - boxes.add( new AxisAlignedBB( fb.minX, fb.minY, fb.minZ, fb.maxX, hole.minY, fb.maxZ ) ); - boxes.add( new AxisAlignedBB( fb.minX, hole.maxY, fb.minZ, fb.maxX, fb.maxY, fb.maxZ ) ); + break; + case X: + boxes.add(new AxisAlignedBB(fb.minX, fb.minY, fb.minZ, fb.maxX, hole.minY, fb.maxZ)); + boxes.add(new AxisAlignedBB(fb.minX, hole.maxY, fb.minZ, fb.maxX, fb.maxY, fb.maxZ)); - boxes.add( new AxisAlignedBB( fb.minX, hole.minY, fb.minZ, fb.maxX, hole.maxY, hole.minZ ) ); - boxes.add( new AxisAlignedBB( fb.minX, hole.minY, hole.maxZ, fb.maxX, hole.maxY, fb.maxZ ) ); - break; - default: - // should never happen. - throw new RuntimeException( "switch falloff. " + String.valueOf( axis ) ); - } + boxes.add(new AxisAlignedBB(fb.minX, hole.minY, fb.minZ, fb.maxX, hole.maxY, hole.minZ)); + boxes.add(new AxisAlignedBB(fb.minX, hole.minY, hole.maxZ, fb.maxX, hole.maxY, fb.maxZ)); + break; + default: + // should never happen. + throw new RuntimeException("switch falloff. " + axis); + } - return boxes; - } + return boxes; + } - /** - * Determines if any of the part's bounding boxes intersects with the outside 2 voxel wide layer. If so, we should - * use thinner facades (1 voxel deep). - */ - private static boolean isUseThinFacades( List partBoxes ) - { - final double min = 2.0 / 16.0; - final double max = 14.0 / 16.0; + /** + * Determines if any of the part's bounding boxes intersects with the outside 2 voxel wide layer. If so, we should + * use thinner facades (1 voxel deep). + */ + private static boolean isUseThinFacades(List partBoxes) { + final double min = 2.0 / 16.0; + final double max = 14.0 / 16.0; - for( AxisAlignedBB bb : partBoxes ) - { - int o = 0; - o += bb.maxX > max ? 1 : 0; - o += bb.maxY > max ? 1 : 0; - o += bb.maxZ > max ? 1 : 0; - o += bb.minX < min ? 1 : 0; - o += bb.minY < min ? 1 : 0; - o += bb.minZ < min ? 1 : 0; + for (AxisAlignedBB bb : partBoxes) { + int o = 0; + o += bb.maxX > max ? 1 : 0; + o += bb.maxY > max ? 1 : 0; + o += bb.maxZ > max ? 1 : 0; + o += bb.minX < min ? 1 : 0; + o += bb.minY < min ? 1 : 0; + o += bb.minZ < min ? 1 : 0; - if( o >= 2 ) - { - return true; - } - } - return false; - } + if (o >= 2) { + return true; + } + } + return false; + } } diff --git a/src/main/java/appeng/client/render/cablebus/FacadeRenderState.java b/src/main/java/appeng/client/render/cablebus/FacadeRenderState.java index 82fb75f48..25f67271f 100644 --- a/src/main/java/appeng/client/render/cablebus/FacadeRenderState.java +++ b/src/main/java/appeng/client/render/cablebus/FacadeRenderState.java @@ -1,4 +1,3 @@ - package appeng.client.render.cablebus; @@ -8,27 +7,23 @@ import net.minecraft.block.state.IBlockState; /** * Captures the state required to render a facade properly. */ -public class FacadeRenderState -{ +public class FacadeRenderState { - // The block state to use for rendering this facade - private final IBlockState sourceBlock; + // The block state to use for rendering this facade + private final IBlockState sourceBlock; - private final boolean transparent; + private final boolean transparent; - public FacadeRenderState( IBlockState sourceBlock, boolean transparent ) - { - this.sourceBlock = sourceBlock; - this.transparent = transparent; - } + public FacadeRenderState(IBlockState sourceBlock, boolean transparent) { + this.sourceBlock = sourceBlock; + this.transparent = transparent; + } - public IBlockState getSourceBlock() - { - return this.sourceBlock; - } + public IBlockState getSourceBlock() { + return this.sourceBlock; + } - public boolean isTransparent() - { - return this.transparent; - } + public boolean isTransparent() { + return this.transparent; + } } diff --git a/src/main/java/appeng/client/render/cablebus/P2PTunnelFrequencyBakedModel.java b/src/main/java/appeng/client/render/cablebus/P2PTunnelFrequencyBakedModel.java index c264ea2a6..fa60eb16b 100644 --- a/src/main/java/appeng/client/render/cablebus/P2PTunnelFrequencyBakedModel.java +++ b/src/main/java/appeng/client/render/cablebus/P2PTunnelFrequencyBakedModel.java @@ -1,14 +1,11 @@ - package appeng.client.render.cablebus; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ExecutionException; - +import appeng.api.parts.IPartBakedModel; +import appeng.api.util.AEColor; +import appeng.util.Platform; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; - import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -17,126 +14,106 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.EnumFacing; -import appeng.api.parts.IPartBakedModel; -import appeng.api.util.AEColor; -import appeng.util.Platform; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ExecutionException; -public class P2PTunnelFrequencyBakedModel implements IBakedModel, IPartBakedModel -{ - private final VertexFormat format; - private final TextureAtlasSprite texture; +public class P2PTunnelFrequencyBakedModel implements IBakedModel, IPartBakedModel { + private final VertexFormat format; + private final TextureAtlasSprite texture; - private final static Cache> modelCache = CacheBuilder.newBuilder().maximumSize( 100 ).build(); + private final static Cache> modelCache = CacheBuilder.newBuilder().maximumSize(100).build(); - private static final int[][] QUAD_OFFSETS = new int[][] { - { 4, 10, 2 }, - { 10, 10, 2 }, - { 4, 4, 2 }, - { 10, 4, 2 } - }; + private static final int[][] QUAD_OFFSETS = new int[][]{ + {4, 10, 2}, + {10, 10, 2}, + {4, 4, 2}, + {10, 4, 2} + }; - public P2PTunnelFrequencyBakedModel( final VertexFormat format, final TextureAtlasSprite texture ) - { - this.format = format; - this.texture = texture; - } + public P2PTunnelFrequencyBakedModel(final VertexFormat format, final TextureAtlasSprite texture) { + this.format = format; + this.texture = texture; + } - @Override - public List getPartQuads( Long partFlags, long rand ) - { - try - { - return modelCache.get( partFlags, () -> - { - short frequency = 0; - boolean active = false; - if( partFlags != null ) - { - frequency = (short) ( partFlags.longValue() & 0xffffL ); - active = ( partFlags.longValue() & 0x10000L ) != 0; - } - return this.getQuadsForFrequency( frequency, active ); - } ); - } - catch( ExecutionException e ) - { - return Collections.emptyList(); - } - } + @Override + public List getPartQuads(Long partFlags, long rand) { + try { + return modelCache.get(partFlags, () -> + { + short frequency = 0; + boolean active = false; + if (partFlags != null) { + frequency = (short) (partFlags.longValue() & 0xffffL); + active = (partFlags.longValue() & 0x10000L) != 0; + } + return this.getQuadsForFrequency(frequency, active); + }); + } catch (ExecutionException e) { + return Collections.emptyList(); + } + } - @Override - public List getQuads( IBlockState state, EnumFacing side, long rand ) - { - if( side != null ) - { - return Collections.emptyList(); - } - return this.getPartQuads( null, rand ); - } + @Override + public List getQuads(IBlockState state, EnumFacing side, long rand) { + if (side != null) { + return Collections.emptyList(); + } + return this.getPartQuads(null, rand); + } - private List getQuadsForFrequency( final short frequency, final boolean active ) - { - final AEColor[] colors = Platform.p2p().toColors( frequency ); - final CubeBuilder cb = new CubeBuilder( this.format ); + private List getQuadsForFrequency(final short frequency, final boolean active) { + final AEColor[] colors = Platform.p2p().toColors(frequency); + final CubeBuilder cb = new CubeBuilder(this.format); - cb.setTexture( this.texture ); - cb.useStandardUV(); - cb.setRenderFullBright( active ); + cb.setTexture(this.texture); + cb.useStandardUV(); + cb.setRenderFullBright(active); - for( int i = 0; i < 4; ++i ) - { - final int[] offs = QUAD_OFFSETS[i]; - for( int j = 0; j < 4; ++j ) - { - final AEColor c = colors[j]; - if( active ) - { - cb.setColorRGB( c.dye.getColorValue() ); - } - else - { - final float cv[] = c.dye.getColorComponentValues(); - cb.setColorRGB( cv[0] * 0.5f, cv[1] * 0.5f, cv[2] * 0.5f ); - } + for (int i = 0; i < 4; ++i) { + final int[] offs = QUAD_OFFSETS[i]; + for (int j = 0; j < 4; ++j) { + final AEColor c = colors[j]; + if (active) { + cb.setColorRGB(c.dye.getColorValue()); + } else { + final float[] cv = c.dye.getColorComponentValues(); + cb.setColorRGB(cv[0] * 0.5f, cv[1] * 0.5f, cv[2] * 0.5f); + } - final int startx = j % 2; - final int starty = 1 - j / 2; + final int startx = j % 2; + final int starty = 1 - j / 2; - cb.addCube( offs[0] + startx, offs[1] + starty, offs[2], offs[0] + startx + 1, offs[1] + starty + 1, offs[2] + 1 ); - } + cb.addCube(offs[0] + startx, offs[1] + starty, offs[2], offs[0] + startx + 1, offs[1] + starty + 1, offs[2] + 1); + } - } - return cb.getOutput(); - } + } + return cb.getOutput(); + } - @Override - public boolean isAmbientOcclusion() - { - return false; - } + @Override + public boolean isAmbientOcclusion() { + return false; + } - @Override - public boolean isGui3d() - { - return false; - } + @Override + public boolean isGui3d() { + return false; + } - @Override - public boolean isBuiltInRenderer() - { - return true; - } + @Override + public boolean isBuiltInRenderer() { + return true; + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.texture; - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.texture; + } - @Override - public ItemOverrideList getOverrides() - { - return ItemOverrideList.NONE; - } + @Override + public ItemOverrideList getOverrides() { + return ItemOverrideList.NONE; + } } diff --git a/src/main/java/appeng/client/render/cablebus/P2PTunnelFrequencyModel.java b/src/main/java/appeng/client/render/cablebus/P2PTunnelFrequencyModel.java index 6e6fcb927..d250e7051 100644 --- a/src/main/java/appeng/client/render/cablebus/P2PTunnelFrequencyModel.java +++ b/src/main/java/appeng/client/render/cablebus/P2PTunnelFrequencyModel.java @@ -1,11 +1,7 @@ - package appeng.client.render.cablebus; -import java.util.Collection; -import java.util.Collections; -import java.util.function.Function; - +import appeng.core.AppEng; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -13,31 +9,27 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.IModel; import net.minecraftforge.common.model.IModelState; -import appeng.core.AppEng; +import java.util.Collection; +import java.util.Collections; +import java.util.function.Function; -public class P2PTunnelFrequencyModel implements IModel -{ - private static final ResourceLocation TEXTURE = new ResourceLocation( AppEng.MOD_ID, "parts/p2p_tunnel_frequency" ); +public class P2PTunnelFrequencyModel implements IModel { + private static final ResourceLocation TEXTURE = new ResourceLocation(AppEng.MOD_ID, "parts/p2p_tunnel_frequency"); - @Override - public Collection getTextures() - { - return Collections.singletonList( TEXTURE ); - } + @Override + public Collection getTextures() { + return Collections.singletonList(TEXTURE); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - try - { - final TextureAtlasSprite texture = bakedTextureGetter.apply( TEXTURE ); - return new P2PTunnelFrequencyBakedModel( format, texture ); - } - catch( Exception e ) - { - throw new RuntimeException( e ); - } - } + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + try { + final TextureAtlasSprite texture = bakedTextureGetter.apply(TEXTURE); + return new P2PTunnelFrequencyBakedModel(format, texture); + } catch (Exception e) { + throw new RuntimeException(e); + } + } } diff --git a/src/main/java/appeng/client/render/cablebus/QuadRotator.java b/src/main/java/appeng/client/render/cablebus/QuadRotator.java index 69de80d7a..cc441bb08 100644 --- a/src/main/java/appeng/client/render/cablebus/QuadRotator.java +++ b/src/main/java/appeng/client/render/cablebus/QuadRotator.java @@ -19,171 +19,144 @@ package appeng.client.render.cablebus; -import java.util.ArrayList; -import java.util.List; - -import javax.vecmath.Matrix4f; -import javax.vecmath.Point3f; -import javax.vecmath.Vector3f; - +import appeng.client.render.FacingToRotation; +import appeng.core.AELog; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.client.renderer.vertex.VertexFormatElement; import net.minecraft.util.EnumFacing; -import appeng.client.render.FacingToRotation; -import appeng.core.AELog; +import javax.vecmath.Matrix4f; +import javax.vecmath.Point3f; +import javax.vecmath.Vector3f; +import java.util.ArrayList; +import java.util.List; /** * Assuming a default-orientation of forward=NORTH and up=UP, this class rotates a given list of quads to the desired * facing */ -public class QuadRotator -{ +public class QuadRotator { - public List rotateQuads( List quads, EnumFacing newForward, EnumFacing newUp ) - { - if( newForward == EnumFacing.NORTH && newUp == EnumFacing.UP ) - { - return quads; // This is the default orientation - } + public List rotateQuads(List quads, EnumFacing newForward, EnumFacing newUp) { + if (newForward == EnumFacing.NORTH && newUp == EnumFacing.UP) { + return quads; // This is the default orientation + } - List result = new ArrayList<>( quads.size() ); + List result = new ArrayList<>(quads.size()); - for( BakedQuad quad : quads ) - { - result.add( this.rotateQuad( quad, newForward, newUp ) ); - } + for (BakedQuad quad : quads) { + result.add(this.rotateQuad(quad, newForward, newUp)); + } - return result; - } + return result; + } - private BakedQuad rotateQuad( BakedQuad quad, EnumFacing forward, EnumFacing up ) - { - // Sanitize forward/up - if( forward.getAxis() == up.getAxis() ) - { - if( up.getAxis() == EnumFacing.Axis.Y ) - { - up = EnumFacing.NORTH; - } - else - { - up = EnumFacing.UP; - } - } + private BakedQuad rotateQuad(BakedQuad quad, EnumFacing forward, EnumFacing up) { + // Sanitize forward/up + if (forward.getAxis() == up.getAxis()) { + if (up.getAxis() == EnumFacing.Axis.Y) { + up = EnumFacing.NORTH; + } else { + up = EnumFacing.UP; + } + } - FacingToRotation rotation = FacingToRotation.get( forward, up ); - Matrix4f mat = rotation.getMat(); + FacingToRotation rotation = FacingToRotation.get(forward, up); + Matrix4f mat = rotation.getMat(); - // Clone the vertex data used by the quad - int[] newData = quad.getVertexData().clone(); + // Clone the vertex data used by the quad + int[] newData = quad.getVertexData().clone(); - // Figure out where the position is in the array - VertexFormat format = quad.getFormat(); - int posIdx = this.findPositionOffset( format ) / 4; - int stride = format.getNextOffset() / 4; - int normalIdx = format.getNormalOffset(); - VertexFormatElement.EnumType normalType = null; - // Figure out the type of the normals - if( normalIdx != -1 ) - { - for( int i = 0; i < format.getElements().size(); i++ ) - { - VertexFormatElement element = format.getElement( i ); - if( element.getUsage() == VertexFormatElement.EnumUsage.NORMAL ) - { - normalType = element.getType(); - } - } - } + // Figure out where the position is in the array + VertexFormat format = quad.getFormat(); + int posIdx = this.findPositionOffset(format) / 4; + int stride = format.getNextOffset() / 4; + int normalIdx = format.getNormalOffset(); + VertexFormatElement.EnumType normalType = null; + // Figure out the type of the normals + if (normalIdx != -1) { + for (int i = 0; i < format.getElements().size(); i++) { + VertexFormatElement element = format.getElement(i); + if (element.getUsage() == VertexFormatElement.EnumUsage.NORMAL) { + normalType = element.getType(); + } + } + } - for( int i = 0; i < 4; i++ ) - { - Point3f pos = new Point3f( Float.intBitsToFloat( newData[i * stride + posIdx] ) - 0.5f, Float - .intBitsToFloat( newData[i * stride + posIdx + 1] ) - 0.5f, Float.intBitsToFloat( newData[i * stride + posIdx + 2] ) - 0.5f ); + for (int i = 0; i < 4; i++) { + Point3f pos = new Point3f(Float.intBitsToFloat(newData[i * stride + posIdx]) - 0.5f, Float + .intBitsToFloat(newData[i * stride + posIdx + 1]) - 0.5f, Float.intBitsToFloat(newData[i * stride + posIdx + 2]) - 0.5f); - // Rotate stuff around - mat.transform( pos ); + // Rotate stuff around + mat.transform(pos); - // Write back - newData[i * stride + posIdx] = Float.floatToIntBits( pos.getX() + 0.5f ); - newData[i * stride + posIdx + 1] = Float.floatToIntBits( pos.getY() + 0.5f ); - newData[i * stride + posIdx + 2] = Float.floatToIntBits( pos.getZ() + 0.5f ); + // Write back + newData[i * stride + posIdx] = Float.floatToIntBits(pos.getX() + 0.5f); + newData[i * stride + posIdx + 1] = Float.floatToIntBits(pos.getY() + 0.5f); + newData[i * stride + posIdx + 2] = Float.floatToIntBits(pos.getZ() + 0.5f); - // Transform the normal if one is present - if( normalIdx != -1 ) - { - if( normalType == VertexFormatElement.EnumType.FLOAT ) - { - Vector3f normal = new Vector3f( Float.intBitsToFloat( newData[i * stride + normalIdx] ), Float - .intBitsToFloat( newData[i * stride + normalIdx + 1] ), Float.intBitsToFloat( newData[i * stride + normalIdx + 2] ) ); + // Transform the normal if one is present + if (normalIdx != -1) { + if (normalType == VertexFormatElement.EnumType.FLOAT) { + Vector3f normal = new Vector3f(Float.intBitsToFloat(newData[i * stride + normalIdx]), Float + .intBitsToFloat(newData[i * stride + normalIdx + 1]), Float.intBitsToFloat(newData[i * stride + normalIdx + 2])); - // Rotate stuff around - mat.transform( normal ); + // Rotate stuff around + mat.transform(normal); - // Write back - newData[i * stride + normalIdx] = Float.floatToIntBits( normal.getX() ); - newData[i * stride + normalIdx + 1] = Float.floatToIntBits( normal.getY() ); - newData[i * stride + normalIdx + 2] = Float.floatToIntBits( normal.getZ() ); - } - else if( normalType == VertexFormatElement.EnumType.BYTE ) - { - int idx = i * stride * 4 + normalIdx; - Vector3f normal = new Vector3f( getByte( newData, idx ) / 127.0f, getByte( newData, idx + 1 ) / 127.0f, getByte( newData, - idx + 2 ) / 127.0f ); + // Write back + newData[i * stride + normalIdx] = Float.floatToIntBits(normal.getX()); + newData[i * stride + normalIdx + 1] = Float.floatToIntBits(normal.getY()); + newData[i * stride + normalIdx + 2] = Float.floatToIntBits(normal.getZ()); + } else if (normalType == VertexFormatElement.EnumType.BYTE) { + int idx = i * stride * 4 + normalIdx; + Vector3f normal = new Vector3f(getByte(newData, idx) / 127.0f, getByte(newData, idx + 1) / 127.0f, getByte(newData, + idx + 2) / 127.0f); - // Rotate stuff around - mat.transform( normal ); + // Rotate stuff around + mat.transform(normal); - // Write back - setByte( newData, idx, (int) ( normal.getX() * 127 ) ); - setByte( newData, idx + 1, (int) ( normal.getY() * 127 ) ); - setByte( newData, idx + 2, (int) ( normal.getZ() * 127 ) ); - } - else - { - AELog.warn( "Unsupported normal format: {}", normalType ); - } - } - } + // Write back + setByte(newData, idx, (int) (normal.getX() * 127)); + setByte(newData, idx + 1, (int) (normal.getY() * 127)); + setByte(newData, idx + 2, (int) (normal.getZ() * 127)); + } else { + AELog.warn("Unsupported normal format: {}", normalType); + } + } + } - EnumFacing newFace = rotation.rotate( quad.getFace() ); - return new BakedQuad( newData, quad.getTintIndex(), newFace, quad.getSprite(), quad.shouldApplyDiffuseLighting(), quad.getFormat() ); - } + EnumFacing newFace = rotation.rotate(quad.getFace()); + return new BakedQuad(newData, quad.getTintIndex(), newFace, quad.getSprite(), quad.shouldApplyDiffuseLighting(), quad.getFormat()); + } - private static int getByte( int[] data, int offset ) - { - int idx = offset / 4; - int subOffset = offset % 4; - return (byte) ( data[idx] >> ( subOffset * 8 ) ); - } + private static int getByte(int[] data, int offset) { + int idx = offset / 4; + int subOffset = offset % 4; + return (byte) (data[idx] >> (subOffset * 8)); + } - private static void setByte( int[] data, int offset, int value ) - { - int idx = offset / 4; - int subOffset = offset % 4; - int mask = 0xFF << ( subOffset * 8 ); - data[idx] = data[idx] & ( ~mask ) | ( ( value & 0xFF ) << ( subOffset * 8 ) ); - } + private static void setByte(int[] data, int offset, int value) { + int idx = offset / 4; + int subOffset = offset % 4; + int mask = 0xFF << (subOffset * 8); + data[idx] = data[idx] & (~mask) | ((value & 0xFF) << (subOffset * 8)); + } - private int findPositionOffset( VertexFormat format ) - { - List elements = format.getElements(); - for( int i = 0; i < elements.size(); i++ ) - { - VertexFormatElement e = elements.get( i ); - if( e.isPositionElement() ) - { - if( e.getType() != VertexFormatElement.EnumType.FLOAT ) - { - throw new IllegalArgumentException( "Only floating point positions are supported" ); - } - return i; - } - } + private int findPositionOffset(VertexFormat format) { + List elements = format.getElements(); + for (int i = 0; i < elements.size(); i++) { + VertexFormatElement e = elements.get(i); + if (e.isPositionElement()) { + if (e.getType() != VertexFormatElement.EnumType.FLOAT) { + throw new IllegalArgumentException("Only floating point positions are supported"); + } + return i; + } + } - throw new IllegalArgumentException( "Vertex format " + format + " has no position attribute!" ); - } + throw new IllegalArgumentException("Vertex format " + format + " has no position attribute!"); + } } diff --git a/src/main/java/appeng/client/render/cablebus/SmartCableTextures.java b/src/main/java/appeng/client/render/cablebus/SmartCableTextures.java index 1bbc7eb84..3e932812e 100644 --- a/src/main/java/appeng/client/render/cablebus/SmartCableTextures.java +++ b/src/main/java/appeng/client/render/cablebus/SmartCableTextures.java @@ -19,73 +19,58 @@ package appeng.client.render.cablebus; -import java.util.Arrays; -import java.util.function.Function; - +import appeng.core.AppEng; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.util.ResourceLocation; -import appeng.core.AppEng; +import java.util.Arrays; +import java.util.function.Function; /** * Manages the channel textures for smart cables. */ -public class SmartCableTextures -{ +public class SmartCableTextures { - public static final ResourceLocation[] SMART_CHANNELS_TEXTURES = { new ResourceLocation( AppEng.MOD_ID, "parts/cable/smart/channels_00" ), - new ResourceLocation( AppEng.MOD_ID, "parts/cable/smart/channels_01" ), new ResourceLocation( AppEng.MOD_ID, "parts/cable/smart/channels_02" ), - new ResourceLocation( AppEng.MOD_ID, "parts/cable/smart/channels_03" ), new ResourceLocation( AppEng.MOD_ID, "parts/cable/smart/channels_04" ), - new ResourceLocation( AppEng.MOD_ID, "parts/cable/smart/channels_10" ), new ResourceLocation( AppEng.MOD_ID, "parts/cable/smart/channels_11" ), - new ResourceLocation( AppEng.MOD_ID, "parts/cable/smart/channels_12" ), new ResourceLocation( AppEng.MOD_ID, "parts/cable/smart/channels_13" ), - new ResourceLocation( AppEng.MOD_ID, "parts/cable/smart/channels_14" ) - }; + public static final ResourceLocation[] SMART_CHANNELS_TEXTURES = {new ResourceLocation(AppEng.MOD_ID, "parts/cable/smart/channels_00"), + new ResourceLocation(AppEng.MOD_ID, "parts/cable/smart/channels_01"), new ResourceLocation(AppEng.MOD_ID, "parts/cable/smart/channels_02"), + new ResourceLocation(AppEng.MOD_ID, "parts/cable/smart/channels_03"), new ResourceLocation(AppEng.MOD_ID, "parts/cable/smart/channels_04"), + new ResourceLocation(AppEng.MOD_ID, "parts/cable/smart/channels_10"), new ResourceLocation(AppEng.MOD_ID, "parts/cable/smart/channels_11"), + new ResourceLocation(AppEng.MOD_ID, "parts/cable/smart/channels_12"), new ResourceLocation(AppEng.MOD_ID, "parts/cable/smart/channels_13"), + new ResourceLocation(AppEng.MOD_ID, "parts/cable/smart/channels_14") + }; - // Textures used to display channels on smart cables. There's two sets of 5 textures each, and - // one of each set are composed together to get even/odd colored channels - private final TextureAtlasSprite[] textures; + // Textures used to display channels on smart cables. There's two sets of 5 textures each, and + // one of each set are composed together to get even/odd colored channels + private final TextureAtlasSprite[] textures; - public SmartCableTextures( Function bakedTextureGetter ) - { - this.textures = Arrays.stream( SMART_CHANNELS_TEXTURES ).map( bakedTextureGetter::apply ).toArray( TextureAtlasSprite[]::new ); - } + public SmartCableTextures(Function bakedTextureGetter) { + this.textures = Arrays.stream(SMART_CHANNELS_TEXTURES).map(bakedTextureGetter::apply).toArray(TextureAtlasSprite[]::new); + } - /** - * The odd variant is used for displaying channels 1-4 as in use. - */ - public TextureAtlasSprite getOddTextureForChannels( int channels ) - { - if( channels < 0 ) - { - return this.textures[0]; - } - else if( channels <= 4 ) - { - return this.textures[channels]; - } - else - { - return this.textures[4]; - } - } + /** + * The odd variant is used for displaying channels 1-4 as in use. + */ + public TextureAtlasSprite getOddTextureForChannels(int channels) { + if (channels < 0) { + return this.textures[0]; + } else if (channels <= 4) { + return this.textures[channels]; + } else { + return this.textures[4]; + } + } - /** - * The odd variant is used for displaying channels 5-8 as in use. - */ - public TextureAtlasSprite getEvenTextureForChannels( int channels ) - { - if( channels < 5 ) - { - return this.textures[5]; - } - else if( channels <= 8 ) - { - return this.textures[1 + channels]; - } - else - { - return this.textures[9]; - } - } + /** + * The odd variant is used for displaying channels 5-8 as in use. + */ + public TextureAtlasSprite getEvenTextureForChannels(int channels) { + if (channels < 5) { + return this.textures[5]; + } else if (channels <= 8) { + return this.textures[1 + channels]; + } else { + return this.textures[9]; + } + } } diff --git a/src/main/java/appeng/client/render/crafting/CraftingCubeBakedModel.java b/src/main/java/appeng/client/render/crafting/CraftingCubeBakedModel.java index 2aa1c661a..0f9c58a15 100644 --- a/src/main/java/appeng/client/render/crafting/CraftingCubeBakedModel.java +++ b/src/main/java/appeng/client/render/crafting/CraftingCubeBakedModel.java @@ -19,13 +19,8 @@ package appeng.client.render.crafting; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; - -import javax.annotation.Nullable; - +import appeng.block.crafting.BlockCraftingUnit; +import appeng.client.render.cablebus.CubeBuilder; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -36,8 +31,11 @@ import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.property.IExtendedBlockState; -import appeng.block.crafting.BlockCraftingUnit; -import appeng.client.render.cablebus.CubeBuilder; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; /** @@ -45,269 +43,239 @@ import appeng.client.render.cablebus.CubeBuilder; * Primarily this base class handles adding the "ring" that frames the multi-block structure and delegates * rendering of the "inner" part of each block to the subclasses of this class. */ -abstract class CraftingCubeBakedModel implements IBakedModel -{ +abstract class CraftingCubeBakedModel implements IBakedModel { - private final VertexFormat format; + private final VertexFormat format; - private final TextureAtlasSprite ringCorner; + private final TextureAtlasSprite ringCorner; - private final TextureAtlasSprite ringHor; + private final TextureAtlasSprite ringHor; - private final TextureAtlasSprite ringVer; + private final TextureAtlasSprite ringVer; - CraftingCubeBakedModel( VertexFormat format, TextureAtlasSprite ringCorner, TextureAtlasSprite ringHor, TextureAtlasSprite ringVer ) - { - this.format = format; - this.ringCorner = ringCorner; - this.ringHor = ringHor; - this.ringVer = ringVer; - } + CraftingCubeBakedModel(VertexFormat format, TextureAtlasSprite ringCorner, TextureAtlasSprite ringHor, TextureAtlasSprite ringVer) { + this.format = format; + this.ringCorner = ringCorner; + this.ringHor = ringHor; + this.ringVer = ringVer; + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { - if( side == null ) - { - return Collections.emptyList(); // No generic quads for this model - } + if (side == null) { + return Collections.emptyList(); // No generic quads for this model + } - EnumSet connections = getConnections( state ); + EnumSet connections = getConnections(state); - List quads = new ArrayList<>(); - CubeBuilder builder = new CubeBuilder( this.format, quads ); + List quads = new ArrayList<>(); + CubeBuilder builder = new CubeBuilder(this.format, quads); - builder.setDrawFaces( EnumSet.of( side ) ); + builder.setDrawFaces(EnumSet.of(side)); - // Add the quads for the ring that frames the entire multi-block structure - this.addRing( builder, side, connections ); + // Add the quads for the ring that frames the entire multi-block structure + this.addRing(builder, side, connections); - // Calculate the bounds of the "inner" block that is framed by the border drawn above - float x2 = connections.contains( EnumFacing.EAST ) ? 16 : 13.01f; - float x1 = connections.contains( EnumFacing.WEST ) ? 0 : 2.99f; + // Calculate the bounds of the "inner" block that is framed by the border drawn above + float x2 = connections.contains(EnumFacing.EAST) ? 16 : 13.01f; + float x1 = connections.contains(EnumFacing.WEST) ? 0 : 2.99f; - float y2 = connections.contains( EnumFacing.UP ) ? 16 : 13.01f; - float y1 = connections.contains( EnumFacing.DOWN ) ? 0 : 2.99f; + float y2 = connections.contains(EnumFacing.UP) ? 16 : 13.01f; + float y1 = connections.contains(EnumFacing.DOWN) ? 0 : 2.99f; - float z2 = connections.contains( EnumFacing.SOUTH ) ? 16 : 13.01f; - float z1 = connections.contains( EnumFacing.NORTH ) ? 0 : 2.99f; + float z2 = connections.contains(EnumFacing.SOUTH) ? 16 : 13.01f; + float z1 = connections.contains(EnumFacing.NORTH) ? 0 : 2.99f; - // On the axis of the side that we're currently drawing, extend the dimensions - // out to the outer face of the block - switch( side ) - { - case DOWN: - case UP: - y1 = 0; - y2 = 16; - break; - case NORTH: - case SOUTH: - z1 = 0; - z2 = 16; - break; - case WEST: - case EAST: - x1 = 0; - x2 = 16; - break; - } + // On the axis of the side that we're currently drawing, extend the dimensions + // out to the outer face of the block + switch (side) { + case DOWN: + case UP: + y1 = 0; + y2 = 16; + break; + case NORTH: + case SOUTH: + z1 = 0; + z2 = 16; + break; + case WEST: + case EAST: + x1 = 0; + x2 = 16; + break; + } - this.addInnerCube( side, state, builder, x1, y1, z1, x2, y2, z2 ); + this.addInnerCube(side, state, builder, x1, y1, z1, x2, y2, z2); - return quads; - } + return quads; + } - private void addRing( CubeBuilder builder, @Nullable EnumFacing side, EnumSet connections ) - { - // Fill in the corners - builder.setTexture( this.ringCorner ); - this.addCornerCap( builder, connections, side, EnumFacing.UP, EnumFacing.EAST, EnumFacing.NORTH ); - this.addCornerCap( builder, connections, side, EnumFacing.UP, EnumFacing.EAST, EnumFacing.SOUTH ); - this.addCornerCap( builder, connections, side, EnumFacing.UP, EnumFacing.WEST, EnumFacing.NORTH ); - this.addCornerCap( builder, connections, side, EnumFacing.UP, EnumFacing.WEST, EnumFacing.SOUTH ); - this.addCornerCap( builder, connections, side, EnumFacing.DOWN, EnumFacing.EAST, EnumFacing.NORTH ); - this.addCornerCap( builder, connections, side, EnumFacing.DOWN, EnumFacing.EAST, EnumFacing.SOUTH ); - this.addCornerCap( builder, connections, side, EnumFacing.DOWN, EnumFacing.WEST, EnumFacing.NORTH ); - this.addCornerCap( builder, connections, side, EnumFacing.DOWN, EnumFacing.WEST, EnumFacing.SOUTH ); + private void addRing(CubeBuilder builder, @Nullable EnumFacing side, EnumSet connections) { + // Fill in the corners + builder.setTexture(this.ringCorner); + this.addCornerCap(builder, connections, side, EnumFacing.UP, EnumFacing.EAST, EnumFacing.NORTH); + this.addCornerCap(builder, connections, side, EnumFacing.UP, EnumFacing.EAST, EnumFacing.SOUTH); + this.addCornerCap(builder, connections, side, EnumFacing.UP, EnumFacing.WEST, EnumFacing.NORTH); + this.addCornerCap(builder, connections, side, EnumFacing.UP, EnumFacing.WEST, EnumFacing.SOUTH); + this.addCornerCap(builder, connections, side, EnumFacing.DOWN, EnumFacing.EAST, EnumFacing.NORTH); + this.addCornerCap(builder, connections, side, EnumFacing.DOWN, EnumFacing.EAST, EnumFacing.SOUTH); + this.addCornerCap(builder, connections, side, EnumFacing.DOWN, EnumFacing.WEST, EnumFacing.NORTH); + this.addCornerCap(builder, connections, side, EnumFacing.DOWN, EnumFacing.WEST, EnumFacing.SOUTH); - // Fill in the remaining stripes of the face - for( EnumFacing a : EnumFacing.values() ) - { - if( a == side || a == side.getOpposite() ) - { - continue; - } + // Fill in the remaining stripes of the face + for (EnumFacing a : EnumFacing.values()) { + if (a == side || a == side.getOpposite()) { + continue; + } - // Select the horizontal or vertical ring texture depending on which side we're filling in - if( ( side.getAxis() != EnumFacing.Axis.Y ) && ( a == EnumFacing.NORTH || a == EnumFacing.EAST || a == EnumFacing.WEST || a == EnumFacing.SOUTH ) ) - { - builder.setTexture( this.ringVer ); - } - else if( side.getAxis() == EnumFacing.Axis.Y && ( a == EnumFacing.EAST || a == EnumFacing.WEST ) ) - { - builder.setTexture( this.ringVer ); - } - else - { - builder.setTexture( this.ringHor ); - } + // Select the horizontal or vertical ring texture depending on which side we're filling in + if ((side.getAxis() != EnumFacing.Axis.Y) && (a == EnumFacing.NORTH || a == EnumFacing.EAST || a == EnumFacing.WEST || a == EnumFacing.SOUTH)) { + builder.setTexture(this.ringVer); + } else if (side.getAxis() == EnumFacing.Axis.Y && (a == EnumFacing.EAST || a == EnumFacing.WEST)) { + builder.setTexture(this.ringVer); + } else { + builder.setTexture(this.ringHor); + } - // If there's an adjacent crafting cube block on side a, then the core of the block already extends - // fully to this side. So only bother drawing the stripe, if there's no connection. - if( !connections.contains( a ) ) - { - // Note that since we're drawing something that "looks" 2-dimensional, - // two of the following will always be 0 and 16. - float x1 = 0, y1 = 0, z1 = 0, x2 = 16, y2 = 16, z2 = 16; + // If there's an adjacent crafting cube block on side a, then the core of the block already extends + // fully to this side. So only bother drawing the stripe, if there's no connection. + if (!connections.contains(a)) { + // Note that since we're drawing something that "looks" 2-dimensional, + // two of the following will always be 0 and 16. + float x1 = 0, y1 = 0, z1 = 0, x2 = 16, y2 = 16, z2 = 16; - switch( a ) - { - case DOWN: - y1 = 0; - y2 = 3; - break; - case UP: - y1 = 13.0f; - y2 = 16; - break; - case WEST: - x1 = 0; - x2 = 3; - break; - case EAST: - x1 = 13; - x2 = 16; - break; - case NORTH: - z1 = 0; - z2 = 3; - break; - case SOUTH: - z1 = 13; - z2 = 16; - break; - } + switch (a) { + case DOWN: + y1 = 0; + y2 = 3; + break; + case UP: + y1 = 13.0f; + y2 = 16; + break; + case WEST: + x1 = 0; + x2 = 3; + break; + case EAST: + x1 = 13; + x2 = 16; + break; + case NORTH: + z1 = 0; + z2 = 3; + break; + case SOUTH: + z1 = 13; + z2 = 16; + break; + } - // Constraint the stripe in the two directions perpendicular to a in case there has been a corner - // drawn in those directions. Since a corner is drawn if the three touching faces dont have adjacent - // crafting cube blocks, we'd have to check for a, side, and the perpendicular direction. But in this - // block, we've already checked for side (due to face culling) and a (see above). - EnumFacing perpendicular = a.rotateAround( side.getAxis() ); - for( EnumFacing cornerCandidate : EnumSet.of( perpendicular, perpendicular.getOpposite() ) ) - { - if( !connections.contains( cornerCandidate ) ) - { - // There's a cap in this direction - switch( cornerCandidate ) - { - case DOWN: - y1 = 3; - break; - case UP: - y2 = 13; - break; - case NORTH: - z1 = 3; - break; - case SOUTH: - z2 = 13; - break; - case WEST: - x1 = 3; - break; - case EAST: - x2 = 13; - break; - } - } - } + // Constraint the stripe in the two directions perpendicular to a in case there has been a corner + // drawn in those directions. Since a corner is drawn if the three touching faces dont have adjacent + // crafting cube blocks, we'd have to check for a, side, and the perpendicular direction. But in this + // block, we've already checked for side (due to face culling) and a (see above). + EnumFacing perpendicular = a.rotateAround(side.getAxis()); + for (EnumFacing cornerCandidate : EnumSet.of(perpendicular, perpendicular.getOpposite())) { + if (!connections.contains(cornerCandidate)) { + // There's a cap in this direction + switch (cornerCandidate) { + case DOWN: + y1 = 3; + break; + case UP: + y2 = 13; + break; + case NORTH: + z1 = 3; + break; + case SOUTH: + z2 = 13; + break; + case WEST: + x1 = 3; + break; + case EAST: + x2 = 13; + break; + } + } + } - builder.addCube( x1, y1, z1, x2, y2, z2 ); - } - } - } + builder.addCube(x1, y1, z1, x2, y2, z2); + } + } + } - /** - * Adds a 3x3x3 corner cap to the cube builder if there are no adjacent crafting cubes on that corner. - */ - private void addCornerCap( CubeBuilder builder, EnumSet connections, EnumFacing side, EnumFacing down, EnumFacing west, EnumFacing north ) - { - if( connections.contains( down ) || connections.contains( west ) || connections.contains( north ) ) - { - return; - } + /** + * Adds a 3x3x3 corner cap to the cube builder if there are no adjacent crafting cubes on that corner. + */ + private void addCornerCap(CubeBuilder builder, EnumSet connections, EnumFacing side, EnumFacing down, EnumFacing west, EnumFacing north) { + if (connections.contains(down) || connections.contains(west) || connections.contains(north)) { + return; + } - // Only add faces for sides that can actually be seen (the outside of the cube) - if( side != down && side != west && side != north ) - { - return; - } + // Only add faces for sides that can actually be seen (the outside of the cube) + if (side != down && side != west && side != north) { + return; + } - float x1 = ( west == EnumFacing.WEST ? 0 : 13 ); - float y1 = ( down == EnumFacing.DOWN ? 0 : 13 ); - float z1 = ( north == EnumFacing.NORTH ? 0 : 13 ); - float x2 = ( west == EnumFacing.WEST ? 3 : 16 ); - float y2 = ( down == EnumFacing.DOWN ? 3 : 16 ); - float z2 = ( north == EnumFacing.NORTH ? 3 : 16 ); - builder.addCube( x1, y1, z1, x2, y2, z2 ); - } + float x1 = (west == EnumFacing.WEST ? 0 : 13); + float y1 = (down == EnumFacing.DOWN ? 0 : 13); + float z1 = (north == EnumFacing.NORTH ? 0 : 13); + float x2 = (west == EnumFacing.WEST ? 3 : 16); + float y2 = (down == EnumFacing.DOWN ? 3 : 16); + float z2 = (north == EnumFacing.NORTH ? 3 : 16); + builder.addCube(x1, y1, z1, x2, y2, z2); + } - // Retrieve the cube connection state from the block state - // If none is present, just assume there are no adjacent crafting cube blocks - private static EnumSet getConnections( @Nullable IBlockState state ) - { - if( !( state instanceof IExtendedBlockState ) ) - { - return EnumSet.noneOf( EnumFacing.class ); - } + // Retrieve the cube connection state from the block state + // If none is present, just assume there are no adjacent crafting cube blocks + private static EnumSet getConnections(@Nullable IBlockState state) { + if (!(state instanceof IExtendedBlockState)) { + return EnumSet.noneOf(EnumFacing.class); + } - IExtendedBlockState extState = (IExtendedBlockState) state; - CraftingCubeState cubeState = extState.getValue( BlockCraftingUnit.STATE ); - if( cubeState == null ) - { - return EnumSet.noneOf( EnumFacing.class ); - } + IExtendedBlockState extState = (IExtendedBlockState) state; + CraftingCubeState cubeState = extState.getValue(BlockCraftingUnit.STATE); + if (cubeState == null) { + return EnumSet.noneOf(EnumFacing.class); + } - return cubeState.getConnections(); - } + return cubeState.getConnections(); + } - protected abstract void addInnerCube( EnumFacing facing, IBlockState state, CubeBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2 ); + protected abstract void addInnerCube(EnumFacing facing, IBlockState state, CubeBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2); - @Override - public boolean isAmbientOcclusion() - { - return false; - } + @Override + public boolean isAmbientOcclusion() { + return false; + } - @Override - public boolean isGui3d() - { - return false; - } + @Override + public boolean isGui3d() { + return false; + } - @Override - public boolean isBuiltInRenderer() - { - return false; - } + @Override + public boolean isBuiltInRenderer() { + return false; + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.ringCorner; - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.ringCorner; + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return ItemCameraTransforms.DEFAULT; - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return ItemCameraTransforms.DEFAULT; + } - @Override - public ItemOverrideList getOverrides() - { - return ItemOverrideList.NONE; - } + @Override + public ItemOverrideList getOverrides() { + return ItemOverrideList.NONE; + } } diff --git a/src/main/java/appeng/client/render/crafting/CraftingCubeModel.java b/src/main/java/appeng/client/render/crafting/CraftingCubeModel.java index b55624611..844adf057 100644 --- a/src/main/java/appeng/client/render/crafting/CraftingCubeModel.java +++ b/src/main/java/appeng/client/render/crafting/CraftingCubeModel.java @@ -19,12 +19,9 @@ package appeng.client.render.crafting; -import java.util.Collection; -import java.util.Collections; -import java.util.function.Function; - +import appeng.block.crafting.BlockCraftingUnit; +import appeng.core.AppEng; import com.google.common.collect.ImmutableList; - import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -33,106 +30,97 @@ import net.minecraftforge.client.model.IModel; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; -import appeng.block.crafting.BlockCraftingUnit; -import appeng.core.AppEng; +import java.util.Collection; +import java.util.Collections; +import java.util.function.Function; /** * The built-in model for the connected texture crafting cube. */ -class CraftingCubeModel implements IModel -{ +class CraftingCubeModel implements IModel { - private final static ResourceLocation RING_CORNER = texture( "ring_corner" ); - private final static ResourceLocation RING_SIDE_HOR = texture( "ring_side_hor" ); - private final static ResourceLocation RING_SIDE_VER = texture( "ring_side_ver" ); - private final static ResourceLocation UNIT_BASE = texture( "unit_base" ); - private final static ResourceLocation LIGHT_BASE = texture( "light_base" ); - private final static ResourceLocation ACCELERATOR_LIGHT = texture( "accelerator_light" ); - private final static ResourceLocation STORAGE_1K_LIGHT = texture( "storage_1k_light" ); - private final static ResourceLocation STORAGE_4K_LIGHT = texture( "storage_4k_light" ); - private final static ResourceLocation STORAGE_16K_LIGHT = texture( "storage_16k_light" ); - private final static ResourceLocation STORAGE_64K_LIGHT = texture( "storage_64k_light" ); - private final static ResourceLocation MONITOR_BASE = texture( "monitor_base" ); - private final static ResourceLocation MONITOR_LIGHT_DARK = texture( "monitor_light_dark" ); - private final static ResourceLocation MONITOR_LIGHT_MEDIUM = texture( "monitor_light_medium" ); - private final static ResourceLocation MONITOR_LIGHT_BRIGHT = texture( "monitor_light_bright" ); + private final static ResourceLocation RING_CORNER = texture("ring_corner"); + private final static ResourceLocation RING_SIDE_HOR = texture("ring_side_hor"); + private final static ResourceLocation RING_SIDE_VER = texture("ring_side_ver"); + private final static ResourceLocation UNIT_BASE = texture("unit_base"); + private final static ResourceLocation LIGHT_BASE = texture("light_base"); + private final static ResourceLocation ACCELERATOR_LIGHT = texture("accelerator_light"); + private final static ResourceLocation STORAGE_1K_LIGHT = texture("storage_1k_light"); + private final static ResourceLocation STORAGE_4K_LIGHT = texture("storage_4k_light"); + private final static ResourceLocation STORAGE_16K_LIGHT = texture("storage_16k_light"); + private final static ResourceLocation STORAGE_64K_LIGHT = texture("storage_64k_light"); + private final static ResourceLocation MONITOR_BASE = texture("monitor_base"); + private final static ResourceLocation MONITOR_LIGHT_DARK = texture("monitor_light_dark"); + private final static ResourceLocation MONITOR_LIGHT_MEDIUM = texture("monitor_light_medium"); + private final static ResourceLocation MONITOR_LIGHT_BRIGHT = texture("monitor_light_bright"); - private final BlockCraftingUnit.CraftingUnitType type; + private final BlockCraftingUnit.CraftingUnitType type; - CraftingCubeModel( BlockCraftingUnit.CraftingUnitType type ) - { - this.type = type; - } + CraftingCubeModel(BlockCraftingUnit.CraftingUnitType type) { + this.type = type; + } - @Override - public Collection getDependencies() - { - return Collections.emptyList(); - } + @Override + public Collection getDependencies() { + return Collections.emptyList(); + } - @Override - public Collection getTextures() - { - return ImmutableList.of( RING_CORNER, RING_SIDE_HOR, RING_SIDE_VER, UNIT_BASE, LIGHT_BASE, ACCELERATOR_LIGHT, STORAGE_1K_LIGHT, STORAGE_4K_LIGHT, - STORAGE_16K_LIGHT, STORAGE_64K_LIGHT, MONITOR_BASE, MONITOR_LIGHT_DARK, MONITOR_LIGHT_MEDIUM, MONITOR_LIGHT_BRIGHT ); - } + @Override + public Collection getTextures() { + return ImmutableList.of(RING_CORNER, RING_SIDE_HOR, RING_SIDE_VER, UNIT_BASE, LIGHT_BASE, ACCELERATOR_LIGHT, STORAGE_1K_LIGHT, STORAGE_4K_LIGHT, + STORAGE_16K_LIGHT, STORAGE_64K_LIGHT, MONITOR_BASE, MONITOR_LIGHT_DARK, MONITOR_LIGHT_MEDIUM, MONITOR_LIGHT_BRIGHT); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - // Retrieve our textures and pass them on to the baked model - TextureAtlasSprite ringCorner = bakedTextureGetter.apply( RING_CORNER ); - TextureAtlasSprite ringSideHor = bakedTextureGetter.apply( RING_SIDE_HOR ); - TextureAtlasSprite ringSideVer = bakedTextureGetter.apply( RING_SIDE_VER ); + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + // Retrieve our textures and pass them on to the baked model + TextureAtlasSprite ringCorner = bakedTextureGetter.apply(RING_CORNER); + TextureAtlasSprite ringSideHor = bakedTextureGetter.apply(RING_SIDE_HOR); + TextureAtlasSprite ringSideVer = bakedTextureGetter.apply(RING_SIDE_VER); - switch( this.type ) - { - case UNIT: - return new UnitBakedModel( format, ringCorner, ringSideHor, ringSideVer, bakedTextureGetter.apply( UNIT_BASE ) ); - case ACCELERATOR: - case STORAGE_1K: - case STORAGE_4K: - case STORAGE_16K: - case STORAGE_64K: - return new LightBakedModel( format, ringCorner, ringSideHor, ringSideVer, bakedTextureGetter - .apply( LIGHT_BASE ), getLightTexture( bakedTextureGetter, this.type ) ); - case MONITOR: - return new MonitorBakedModel( format, ringCorner, ringSideHor, ringSideVer, bakedTextureGetter.apply( UNIT_BASE ), bakedTextureGetter - .apply( MONITOR_BASE ), bakedTextureGetter.apply( - MONITOR_LIGHT_DARK ), bakedTextureGetter.apply( MONITOR_LIGHT_MEDIUM ), bakedTextureGetter.apply( MONITOR_LIGHT_BRIGHT ) ); - default: - throw new IllegalArgumentException( "Unsupported crafting unit type: " + this.type ); - } - } + switch (this.type) { + case UNIT: + return new UnitBakedModel(format, ringCorner, ringSideHor, ringSideVer, bakedTextureGetter.apply(UNIT_BASE)); + case ACCELERATOR: + case STORAGE_1K: + case STORAGE_4K: + case STORAGE_16K: + case STORAGE_64K: + return new LightBakedModel(format, ringCorner, ringSideHor, ringSideVer, bakedTextureGetter + .apply(LIGHT_BASE), getLightTexture(bakedTextureGetter, this.type)); + case MONITOR: + return new MonitorBakedModel(format, ringCorner, ringSideHor, ringSideVer, bakedTextureGetter.apply(UNIT_BASE), bakedTextureGetter + .apply(MONITOR_BASE), bakedTextureGetter.apply( + MONITOR_LIGHT_DARK), bakedTextureGetter.apply(MONITOR_LIGHT_MEDIUM), bakedTextureGetter.apply(MONITOR_LIGHT_BRIGHT)); + default: + throw new IllegalArgumentException("Unsupported crafting unit type: " + this.type); + } + } - private static TextureAtlasSprite getLightTexture( Function textureGetter, BlockCraftingUnit.CraftingUnitType type ) - { - switch( type ) - { - case ACCELERATOR: - return textureGetter.apply( ACCELERATOR_LIGHT ); - case STORAGE_1K: - return textureGetter.apply( STORAGE_1K_LIGHT ); - case STORAGE_4K: - return textureGetter.apply( STORAGE_4K_LIGHT ); - case STORAGE_16K: - return textureGetter.apply( STORAGE_16K_LIGHT ); - case STORAGE_64K: - return textureGetter.apply( STORAGE_64K_LIGHT ); - default: - throw new IllegalArgumentException( "Crafting unit type " + type + " does not use a light texture." ); - } - } + private static TextureAtlasSprite getLightTexture(Function textureGetter, BlockCraftingUnit.CraftingUnitType type) { + switch (type) { + case ACCELERATOR: + return textureGetter.apply(ACCELERATOR_LIGHT); + case STORAGE_1K: + return textureGetter.apply(STORAGE_1K_LIGHT); + case STORAGE_4K: + return textureGetter.apply(STORAGE_4K_LIGHT); + case STORAGE_16K: + return textureGetter.apply(STORAGE_16K_LIGHT); + case STORAGE_64K: + return textureGetter.apply(STORAGE_64K_LIGHT); + default: + throw new IllegalArgumentException("Crafting unit type " + type + " does not use a light texture."); + } + } - @Override - public IModelState getDefaultState() - { - return TRSRTransformation.identity(); - } + @Override + public IModelState getDefaultState() { + return TRSRTransformation.identity(); + } - private static ResourceLocation texture( String name ) - { - return new ResourceLocation( AppEng.MOD_ID, "blocks/crafting/" + name ); - } + private static ResourceLocation texture(String name) { + return new ResourceLocation(AppEng.MOD_ID, "blocks/crafting/" + name); + } } diff --git a/src/main/java/appeng/client/render/crafting/CraftingCubeRendering.java b/src/main/java/appeng/client/render/crafting/CraftingCubeRendering.java index 17f540271..d7b34279d 100644 --- a/src/main/java/appeng/client/render/crafting/CraftingCubeRendering.java +++ b/src/main/java/appeng/client/render/crafting/CraftingCubeRendering.java @@ -19,9 +19,11 @@ package appeng.client.render.crafting; -import java.util.HashMap; -import java.util.Map; - +import appeng.block.crafting.BlockCraftingUnit; +import appeng.bootstrap.BlockRenderingCustomizer; +import appeng.bootstrap.IBlockRendering; +import appeng.bootstrap.IItemRendering; +import appeng.core.AppEng; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.ModelResourceLocation; @@ -29,75 +31,62 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.block.crafting.BlockCraftingUnit; -import appeng.bootstrap.BlockRenderingCustomizer; -import appeng.bootstrap.IBlockRendering; -import appeng.bootstrap.IItemRendering; -import appeng.core.AppEng; +import java.util.HashMap; +import java.util.Map; /** * Rendering customization for the crafting cube. */ -public class CraftingCubeRendering extends BlockRenderingCustomizer -{ +public class CraftingCubeRendering extends BlockRenderingCustomizer { - private final String registryName; + private final String registryName; - private final BlockCraftingUnit.CraftingUnitType type; + private final BlockCraftingUnit.CraftingUnitType type; - public CraftingCubeRendering( String registryName, BlockCraftingUnit.CraftingUnitType type ) - { - this.registryName = registryName; - this.type = type; - } + public CraftingCubeRendering(String registryName, BlockCraftingUnit.CraftingUnitType type) { + this.registryName = registryName; + this.type = type; + } - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - ResourceLocation baseName = new ResourceLocation( AppEng.MOD_ID, this.registryName ); + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + ResourceLocation baseName = new ResourceLocation(AppEng.MOD_ID, this.registryName); - // Disable auto-rotation - if( this.type != BlockCraftingUnit.CraftingUnitType.MONITOR ) - { - rendering.modelCustomizer( ( loc, model ) -> model ); - } + // Disable auto-rotation + if (this.type != BlockCraftingUnit.CraftingUnitType.MONITOR) { + rendering.modelCustomizer((loc, model) -> model); + } - // This is the standard blockstate model - ModelResourceLocation defaultModel = new ModelResourceLocation( baseName, "normal" ); + // This is the standard blockstate model + ModelResourceLocation defaultModel = new ModelResourceLocation(baseName, "normal"); - // This is the built-in model - String builtInName = "models/block/crafting/" + this.registryName + "/builtin"; - ModelResourceLocation builtInModelName = new ModelResourceLocation( new ResourceLocation( AppEng.MOD_ID, builtInName ), "normal" ); + // This is the built-in model + String builtInName = "models/block/crafting/" + this.registryName + "/builtin"; + ModelResourceLocation builtInModelName = new ModelResourceLocation(new ResourceLocation(AppEng.MOD_ID, builtInName), "normal"); - rendering.builtInModel( builtInName, new CraftingCubeModel( this.type ) ); + rendering.builtInModel(builtInName, new CraftingCubeModel(this.type)); - rendering.stateMapper( block -> this.mapState( block, defaultModel, builtInModelName ) ); + rendering.stateMapper(block -> this.mapState(block, defaultModel, builtInModelName)); - if( this.type == BlockCraftingUnit.CraftingUnitType.MONITOR ) - { - rendering.tesr( new CraftingMonitorTESR() ); - } + if (this.type == BlockCraftingUnit.CraftingUnitType.MONITOR) { + rendering.tesr(new CraftingMonitorTESR()); + } - } + } - private Map mapState( Block block, ModelResourceLocation defaultModel, ModelResourceLocation formedModel ) - { - Map result = new HashMap<>(); - for( IBlockState state : block.getBlockState().getValidStates() ) - { - if( state.getValue( BlockCraftingUnit.FORMED ) ) - { - // Always use the builtin model if the multiblock is formed - result.put( state, formedModel ); - } - else - { - // Use the default model - result.put( state, defaultModel ); - } - } - return result; - } + private Map mapState(Block block, ModelResourceLocation defaultModel, ModelResourceLocation formedModel) { + Map result = new HashMap<>(); + for (IBlockState state : block.getBlockState().getValidStates()) { + if (state.getValue(BlockCraftingUnit.FORMED)) { + // Always use the builtin model if the multiblock is formed + result.put(state, formedModel); + } else { + // Use the default model + result.put(state, defaultModel); + } + } + return result; + } } diff --git a/src/main/java/appeng/client/render/crafting/CraftingCubeState.java b/src/main/java/appeng/client/render/crafting/CraftingCubeState.java index fec1f8c9d..a41cf8193 100644 --- a/src/main/java/appeng/client/render/crafting/CraftingCubeState.java +++ b/src/main/java/appeng/client/render/crafting/CraftingCubeState.java @@ -19,27 +19,24 @@ package appeng.client.render.crafting; -import java.util.EnumSet; - import net.minecraft.util.EnumFacing; +import java.util.EnumSet; + /** * Transports the rendering state for a block of a crafting cube. */ -public final class CraftingCubeState -{ +public final class CraftingCubeState { - // Contains information on which sides of the block are connected to other parts of a formed crafting cube - private final EnumSet connections; + // Contains information on which sides of the block are connected to other parts of a formed crafting cube + private final EnumSet connections; - public CraftingCubeState( EnumSet connections ) - { - this.connections = connections; - } + public CraftingCubeState(EnumSet connections) { + this.connections = connections; + } - public EnumSet getConnections() - { - return this.connections; - } + public EnumSet getConnections() { + return this.connections; + } } diff --git a/src/main/java/appeng/client/render/crafting/CraftingMonitorTESR.java b/src/main/java/appeng/client/render/crafting/CraftingMonitorTESR.java index 3c3336702..065761137 100644 --- a/src/main/java/appeng/client/render/crafting/CraftingMonitorTESR.java +++ b/src/main/java/appeng/client/render/crafting/CraftingMonitorTESR.java @@ -19,45 +19,40 @@ package appeng.client.render.crafting; +import appeng.api.storage.data.IAEItemStack; +import appeng.client.render.TesrRenderHelper; +import appeng.tile.crafting.TileCraftingMonitorTile; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.util.EnumFacing; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.storage.data.IAEItemStack; -import appeng.client.render.TesrRenderHelper; -import appeng.tile.crafting.TileCraftingMonitorTile; - /** * Renders the item currently being crafted */ -@SideOnly( Side.CLIENT ) -public class CraftingMonitorTESR extends TileEntitySpecialRenderer -{ +@SideOnly(Side.CLIENT) +public class CraftingMonitorTESR extends TileEntitySpecialRenderer { - @Override - public void render( TileCraftingMonitorTile te, double x, double y, double z, float partialTicks, int destroyStage, float p_render_10_ ) - { - if( te == null ) - { - return; - } + @Override + public void render(TileCraftingMonitorTile te, double x, double y, double z, float partialTicks, int destroyStage, float p_render_10_) { + if (te == null) { + return; + } - EnumFacing facing = te.getForward(); + EnumFacing facing = te.getForward(); - IAEItemStack jobProgress = te.getJobProgress(); - if( jobProgress != null ) - { - GlStateManager.pushMatrix(); - GlStateManager.translate( x + 0.5, y + 0.5, z + 0.5 ); + IAEItemStack jobProgress = te.getJobProgress(); + if (jobProgress != null) { + GlStateManager.pushMatrix(); + GlStateManager.translate(x + 0.5, y + 0.5, z + 0.5); - TesrRenderHelper.moveToFace( facing ); - TesrRenderHelper.rotateToFace( facing, (byte) 0 ); - TesrRenderHelper.renderItem2dWithAmount( jobProgress, 0.7f, 0.1f ); + TesrRenderHelper.moveToFace(facing); + TesrRenderHelper.rotateToFace(facing, (byte) 0); + TesrRenderHelper.renderItem2dWithAmount(jobProgress, 0.7f, 0.1f); - GlStateManager.popMatrix(); - } - } + GlStateManager.popMatrix(); + } + } } diff --git a/src/main/java/appeng/client/render/crafting/ItemEncodedPatternBakedModel.java b/src/main/java/appeng/client/render/crafting/ItemEncodedPatternBakedModel.java index 44e5f6b9c..5c914faab 100644 --- a/src/main/java/appeng/client/render/crafting/ItemEncodedPatternBakedModel.java +++ b/src/main/java/appeng/client/render/crafting/ItemEncodedPatternBakedModel.java @@ -1,17 +1,8 @@ - package appeng.client.render.crafting; -import java.util.List; - -import javax.annotation.Nullable; -import javax.vecmath.Matrix4f; - +import appeng.items.misc.ItemEncodedPattern; import com.google.common.collect.ImmutableMap; - -import org.apache.commons.lang3.tuple.Pair; -import org.lwjgl.input.Keyboard; - import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; @@ -26,8 +17,12 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.World; import net.minecraftforge.client.model.PerspectiveMapWrapper; import net.minecraftforge.common.model.TRSRTransformation; +import org.apache.commons.lang3.tuple.Pair; +import org.lwjgl.input.Keyboard; -import appeng.items.misc.ItemEncodedPattern; +import javax.annotation.Nullable; +import javax.vecmath.Matrix4f; +import java.util.List; /** @@ -37,206 +32,175 @@ import appeng.items.misc.ItemEncodedPattern; * the pattern is being * rendered in the GUI, and not anywhere else. */ -class ItemEncodedPatternBakedModel implements IBakedModel -{ - private final IBakedModel baseModel; +class ItemEncodedPatternBakedModel implements IBakedModel { + private final IBakedModel baseModel; - private final ImmutableMap transforms; + private final ImmutableMap transforms; - private final CustomOverrideList overrides; + private final CustomOverrideList overrides; - ItemEncodedPatternBakedModel( IBakedModel baseModel, ImmutableMap transforms ) - { - this.baseModel = baseModel; - this.transforms = transforms; - this.overrides = new CustomOverrideList(); - } + ItemEncodedPatternBakedModel(IBakedModel baseModel, ImmutableMap transforms) { + this.baseModel = baseModel; + this.transforms = transforms; + this.overrides = new CustomOverrideList(); + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - return this.baseModel.getQuads( state, side, rand ); - } + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + return this.baseModel.getQuads(state, side, rand); + } - @Override - public boolean isAmbientOcclusion() - { - return this.baseModel.isAmbientOcclusion(); - } + @Override + public boolean isAmbientOcclusion() { + return this.baseModel.isAmbientOcclusion(); + } - @Override - public boolean isGui3d() - { - return this.baseModel.isGui3d(); - } + @Override + public boolean isGui3d() { + return this.baseModel.isGui3d(); + } - @Override - public boolean isBuiltInRenderer() - { - return this.baseModel.isBuiltInRenderer(); - } + @Override + public boolean isBuiltInRenderer() { + return this.baseModel.isBuiltInRenderer(); + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.baseModel.getParticleTexture(); - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.baseModel.getParticleTexture(); + } - @Override - @Deprecated - public ItemCameraTransforms getItemCameraTransforms() - { - return this.baseModel.getItemCameraTransforms(); - } + @Override + @Deprecated + public ItemCameraTransforms getItemCameraTransforms() { + return this.baseModel.getItemCameraTransforms(); + } - @Override - public ItemOverrideList getOverrides() - { - return this.overrides; - } + @Override + public ItemOverrideList getOverrides() { + return this.overrides; + } - @Override - public Pair handlePerspective( ItemCameraTransforms.TransformType cameraTransformType ) - { - if( this.baseModel instanceof IBakedModel ) - { - return this.baseModel.handlePerspective( cameraTransformType ); - } + @Override + public Pair handlePerspective(ItemCameraTransforms.TransformType cameraTransformType) { + if (this.baseModel instanceof IBakedModel) { + return this.baseModel.handlePerspective(cameraTransformType); + } - return PerspectiveMapWrapper.handlePerspective( this, this.transforms, cameraTransformType ); - } + return PerspectiveMapWrapper.handlePerspective(this, this.transforms, cameraTransformType); + } - /** - * Since the ItemOverrideList handling comes before handling the perspective awareness (which is the first place - * where we - * know how we are being rendered) we need to remember the model of the crafting output, and make the decision on - * which to render later on. - * Sadly, Forge is pretty inconsistent when it will call the handlePerspective method, so some methods are called - * even on this interim-model. - * Usually those methods only matter for rendering on the ground and other cases, where we wouldn't render the - * crafting output model anyway, - * so in those cases we delegate to the model of the encoded pattern. - */ - private class ShiftHoldingModelWrapper implements IBakedModel - { + /** + * Since the ItemOverrideList handling comes before handling the perspective awareness (which is the first place + * where we + * know how we are being rendered) we need to remember the model of the crafting output, and make the decision on + * which to render later on. + * Sadly, Forge is pretty inconsistent when it will call the handlePerspective method, so some methods are called + * even on this interim-model. + * Usually those methods only matter for rendering on the ground and other cases, where we wouldn't render the + * crafting output model anyway, + * so in those cases we delegate to the model of the encoded pattern. + */ + private class ShiftHoldingModelWrapper implements IBakedModel { - private final IBakedModel outputModel; + private final IBakedModel outputModel; - private ShiftHoldingModelWrapper( IBakedModel outputModel ) - { - this.outputModel = outputModel; - } + private ShiftHoldingModelWrapper(IBakedModel outputModel) { + this.outputModel = outputModel; + } - @Override - public Pair handlePerspective( ItemCameraTransforms.TransformType cameraTransformType ) - { - final IBakedModel selectedModel; + @Override + public Pair handlePerspective(ItemCameraTransforms.TransformType cameraTransformType) { + final IBakedModel selectedModel; - // No need to re-check for shift being held since this model is only handed out in that case - if( cameraTransformType == ItemCameraTransforms.TransformType.GUI ) - { - selectedModel = this.outputModel; - } - else - { - selectedModel = ItemEncodedPatternBakedModel.this.baseModel; - } + // No need to re-check for shift being held since this model is only handed out in that case + if (cameraTransformType == ItemCameraTransforms.TransformType.GUI) { + selectedModel = this.outputModel; + } else { + selectedModel = ItemEncodedPatternBakedModel.this.baseModel; + } - // Now retroactively handle the isGui3d call, for which we always return false below - if( selectedModel.isGui3d() != ItemEncodedPatternBakedModel.this.baseModel.isGui3d() ) - { - GlStateManager.enableLighting(); - } + // Now retroactively handle the isGui3d call, for which we always return false below + if (selectedModel.isGui3d() != ItemEncodedPatternBakedModel.this.baseModel.isGui3d()) { + GlStateManager.enableLighting(); + } - if( selectedModel instanceof IBakedModel ) - { - return selectedModel.handlePerspective( cameraTransformType ); - } + if (selectedModel instanceof IBakedModel) { + return selectedModel.handlePerspective(cameraTransformType); + } - return PerspectiveMapWrapper.handlePerspective( this, ItemEncodedPatternBakedModel.this.transforms, cameraTransformType ); - } + return PerspectiveMapWrapper.handlePerspective(this, ItemEncodedPatternBakedModel.this.transforms, cameraTransformType); + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - // This may be called for items on the ground, in which case we will always fall back to the pattern - return ItemEncodedPatternBakedModel.this.baseModel.getQuads( state, side, rand ); - } + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + // This may be called for items on the ground, in which case we will always fall back to the pattern + return ItemEncodedPatternBakedModel.this.baseModel.getQuads(state, side, rand); + } - @Override - public boolean isAmbientOcclusion() - { - return ItemEncodedPatternBakedModel.this.baseModel.isAmbientOcclusion(); - } + @Override + public boolean isAmbientOcclusion() { + return ItemEncodedPatternBakedModel.this.baseModel.isAmbientOcclusion(); + } - @Override - public boolean isGui3d() - { - // NOTE: Sadly, Forge will let Minecraft call this method before handling the perspective awareness - return ItemEncodedPatternBakedModel.this.baseModel.isGui3d(); - } + @Override + public boolean isGui3d() { + // NOTE: Sadly, Forge will let Minecraft call this method before handling the perspective awareness + return ItemEncodedPatternBakedModel.this.baseModel.isGui3d(); + } - @Override - public boolean isBuiltInRenderer() - { - // This may be called for items on the ground, in which case we will always fall back to the pattern - return ItemEncodedPatternBakedModel.this.baseModel.isBuiltInRenderer(); - } + @Override + public boolean isBuiltInRenderer() { + // This may be called for items on the ground, in which case we will always fall back to the pattern + return ItemEncodedPatternBakedModel.this.baseModel.isBuiltInRenderer(); + } - @Override - public TextureAtlasSprite getParticleTexture() - { - // This may be called for items on the ground, in which case we will always fall back to the pattern - return ItemEncodedPatternBakedModel.this.baseModel.getParticleTexture(); - } + @Override + public TextureAtlasSprite getParticleTexture() { + // This may be called for items on the ground, in which case we will always fall back to the pattern + return ItemEncodedPatternBakedModel.this.baseModel.getParticleTexture(); + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - // This may be called for items on the ground, in which case we will always fall back to the pattern - return ItemEncodedPatternBakedModel.this.baseModel.getItemCameraTransforms(); - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + // This may be called for items on the ground, in which case we will always fall back to the pattern + return ItemEncodedPatternBakedModel.this.baseModel.getItemCameraTransforms(); + } - @Override - public ItemOverrideList getOverrides() - { - // This may be called for items on the ground, in which case we will always fall back to the pattern - return ItemEncodedPatternBakedModel.this.baseModel.getOverrides(); - } - } + @Override + public ItemOverrideList getOverrides() { + // This may be called for items on the ground, in which case we will always fall back to the pattern + return ItemEncodedPatternBakedModel.this.baseModel.getOverrides(); + } + } - /** - * Item Override Lists are the only point during item rendering where we can access the item stack that is being - * rendered. - * So this is the point where we actually check if shift is being held, and if so, determine the crafting output - * model. - */ - private class CustomOverrideList extends ItemOverrideList - { + /** + * Item Override Lists are the only point during item rendering where we can access the item stack that is being + * rendered. + * So this is the point where we actually check if shift is being held, and if so, determine the crafting output + * model. + */ + private class CustomOverrideList extends ItemOverrideList { - CustomOverrideList() - { - super( ItemEncodedPatternBakedModel.this.baseModel.getOverrides().getOverrides() ); - } + CustomOverrideList() { + super(ItemEncodedPatternBakedModel.this.baseModel.getOverrides().getOverrides()); + } - @Override - public IBakedModel handleItemState( IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity ) - { - boolean shiftHeld = Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) || Keyboard.isKeyDown( Keyboard.KEY_RSHIFT ); - if( shiftHeld ) - { - ItemEncodedPattern iep = (ItemEncodedPattern) stack.getItem(); - ItemStack output = iep.getOutput( stack ); - if( !output.isEmpty() ) - { - IBakedModel realModel = Minecraft.getMinecraft().getRenderItem().getItemModelMesher().getItemModel( output ); - // Give the item model a chance to handle the overrides as well - realModel = realModel.getOverrides().handleItemState( realModel, output, world, entity ); - return new ShiftHoldingModelWrapper( realModel ); - } - } + @Override + public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity) { + boolean shiftHeld = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + if (shiftHeld) { + ItemEncodedPattern iep = (ItemEncodedPattern) stack.getItem(); + ItemStack output = iep.getOutput(stack); + if (!output.isEmpty()) { + IBakedModel realModel = Minecraft.getMinecraft().getRenderItem().getItemModelMesher().getItemModel(output); + // Give the item model a chance to handle the overrides as well + realModel = realModel.getOverrides().handleItemState(realModel, output, world, entity); + return new ShiftHoldingModelWrapper(realModel); + } + } - return ItemEncodedPatternBakedModel.this.baseModel.getOverrides().handleItemState( originalModel, stack, world, entity ); - } - } + return ItemEncodedPatternBakedModel.this.baseModel.getOverrides().handleItemState(originalModel, stack, world, entity); + } + } } diff --git a/src/main/java/appeng/client/render/crafting/ItemEncodedPatternModel.java b/src/main/java/appeng/client/render/crafting/ItemEncodedPatternModel.java index 88ce1a1a7..3a7653a82 100644 --- a/src/main/java/appeng/client/render/crafting/ItemEncodedPatternModel.java +++ b/src/main/java/appeng/client/render/crafting/ItemEncodedPatternModel.java @@ -1,13 +1,8 @@ - package appeng.client.render.crafting; -import java.util.Collection; -import java.util.Collections; -import java.util.function.Function; - +import appeng.core.AppEng; import com.google.common.collect.ImmutableMap; - import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -19,50 +14,44 @@ import net.minecraftforge.client.model.PerspectiveMapWrapper; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; -import appeng.core.AppEng; +import java.util.Collection; +import java.util.Collections; +import java.util.function.Function; /** * Simple model for the encoded pattern built-in baked model. */ -class ItemEncodedPatternModel implements IModel -{ +class ItemEncodedPatternModel implements IModel { - private static final ResourceLocation BASE_MODEL = new ResourceLocation( AppEng.MOD_ID, "item/encoded_pattern" ); + private static final ResourceLocation BASE_MODEL = new ResourceLocation(AppEng.MOD_ID, "item/encoded_pattern"); - @Override - public Collection getDependencies() - { - return Collections.singletonList( BASE_MODEL ); - } + @Override + public Collection getDependencies() { + return Collections.singletonList(BASE_MODEL); + } - @Override - public Collection getTextures() - { - return Collections.emptyList(); - } + @Override + public Collection getTextures() { + return Collections.emptyList(); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - IBakedModel baseModel; - try - { - baseModel = ModelLoaderRegistry.getModel( BASE_MODEL ).bake( state, format, bakedTextureGetter ); - } - catch( Exception e ) - { - throw new RuntimeException( e ); - } + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + IBakedModel baseModel; + try { + baseModel = ModelLoaderRegistry.getModel(BASE_MODEL).bake(state, format, bakedTextureGetter); + } catch (Exception e) { + throw new RuntimeException(e); + } - ImmutableMap transforms = PerspectiveMapWrapper.getTransforms( state ); + ImmutableMap transforms = PerspectiveMapWrapper.getTransforms(state); - return new ItemEncodedPatternBakedModel( baseModel, transforms ); - } + return new ItemEncodedPatternBakedModel(baseModel, transforms); + } - @Override - public IModelState getDefaultState() - { - return TRSRTransformation.identity(); - } + @Override + public IModelState getDefaultState() { + return TRSRTransformation.identity(); + } } diff --git a/src/main/java/appeng/client/render/crafting/ItemEncodedPatternRendering.java b/src/main/java/appeng/client/render/crafting/ItemEncodedPatternRendering.java index e7ed4997a..d85302b36 100644 --- a/src/main/java/appeng/client/render/crafting/ItemEncodedPatternRendering.java +++ b/src/main/java/appeng/client/render/crafting/ItemEncodedPatternRendering.java @@ -1,28 +1,24 @@ - package appeng.client.render.crafting; +import appeng.bootstrap.IItemRendering; +import appeng.bootstrap.ItemRenderingCustomizer; +import appeng.core.AppEng; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.bootstrap.IItemRendering; -import appeng.bootstrap.ItemRenderingCustomizer; -import appeng.core.AppEng; +public class ItemEncodedPatternRendering extends ItemRenderingCustomizer { -public class ItemEncodedPatternRendering extends ItemRenderingCustomizer -{ + private static final ResourceLocation MODEL = new ResourceLocation(AppEng.MOD_ID, "builtin/encoded_pattern"); - private static final ResourceLocation MODEL = new ResourceLocation( AppEng.MOD_ID, "builtin/encoded_pattern" ); - - @Override - @SideOnly( Side.CLIENT ) - public void customize( IItemRendering rendering ) - { - rendering.builtInModel( "models/item/builtin/encoded_pattern", new ItemEncodedPatternModel() ); - rendering.model( new ModelResourceLocation( MODEL, "inventory" ) ).variants( MODEL ); - } + @Override + @SideOnly(Side.CLIENT) + public void customize(IItemRendering rendering) { + rendering.builtInModel("models/item/builtin/encoded_pattern", new ItemEncodedPatternModel()); + rendering.model(new ModelResourceLocation(MODEL, "inventory")).variants(MODEL); + } } diff --git a/src/main/java/appeng/client/render/crafting/LightBakedModel.java b/src/main/java/appeng/client/render/crafting/LightBakedModel.java index 7c7774607..ac690abae 100644 --- a/src/main/java/appeng/client/render/crafting/LightBakedModel.java +++ b/src/main/java/appeng/client/render/crafting/LightBakedModel.java @@ -19,42 +19,38 @@ package appeng.client.render.crafting; +import appeng.block.crafting.BlockCraftingUnit; +import appeng.client.render.cablebus.CubeBuilder; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.EnumFacing; -import appeng.block.crafting.BlockCraftingUnit; -import appeng.client.render.cablebus.CubeBuilder; - /** * Crafting cube baked model that adds a full-bright light texture on top of a normal base texture onto the inner cube. * The light texture is only drawn fullbright if the multiblock is currently powered. */ -class LightBakedModel extends CraftingCubeBakedModel -{ +class LightBakedModel extends CraftingCubeBakedModel { - private final TextureAtlasSprite baseTexture; + private final TextureAtlasSprite baseTexture; - private final TextureAtlasSprite lightTexture; + private final TextureAtlasSprite lightTexture; - LightBakedModel( VertexFormat format, TextureAtlasSprite ringCorner, TextureAtlasSprite ringHor, TextureAtlasSprite ringVer, TextureAtlasSprite baseTexture, TextureAtlasSprite lightTexture ) - { - super( format, ringCorner, ringHor, ringVer ); - this.baseTexture = baseTexture; - this.lightTexture = lightTexture; - } + LightBakedModel(VertexFormat format, TextureAtlasSprite ringCorner, TextureAtlasSprite ringHor, TextureAtlasSprite ringVer, TextureAtlasSprite baseTexture, TextureAtlasSprite lightTexture) { + super(format, ringCorner, ringHor, ringVer); + this.baseTexture = baseTexture; + this.lightTexture = lightTexture; + } - @Override - protected void addInnerCube( EnumFacing facing, IBlockState state, CubeBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2 ) - { - builder.setTexture( this.baseTexture ); - builder.addCube( x1, y1, z1, x2, y2, z2 ); + @Override + protected void addInnerCube(EnumFacing facing, IBlockState state, CubeBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2) { + builder.setTexture(this.baseTexture); + builder.addCube(x1, y1, z1, x2, y2, z2); - boolean powered = state.getValue( BlockCraftingUnit.POWERED ); - builder.setRenderFullBright( powered ); - builder.setTexture( this.lightTexture ); - builder.addCube( x1, y1, z1, x2, y2, z2 ); - } + boolean powered = state.getValue(BlockCraftingUnit.POWERED); + builder.setRenderFullBright(powered); + builder.setTexture(this.lightTexture); + builder.addCube(x1, y1, z1, x2, y2, z2); + } } diff --git a/src/main/java/appeng/client/render/crafting/MonitorBakedModel.java b/src/main/java/appeng/client/render/crafting/MonitorBakedModel.java index 00785c7e0..49fbc156c 100644 --- a/src/main/java/appeng/client/render/crafting/MonitorBakedModel.java +++ b/src/main/java/appeng/client/render/crafting/MonitorBakedModel.java @@ -19,16 +19,15 @@ package appeng.client.render.crafting; +import appeng.api.util.AEColor; +import appeng.block.crafting.BlockCraftingMonitor; +import appeng.client.render.cablebus.CubeBuilder; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.property.IExtendedBlockState; -import appeng.api.util.AEColor; -import appeng.block.crafting.BlockCraftingMonitor; -import appeng.client.render.cablebus.CubeBuilder; - /** * The baked model for the crafting monitor. Please note that this model doesn't handle the item being displayed. That @@ -37,92 +36,82 @@ import appeng.client.render.cablebus.CubeBuilder; * color. The textures * are full-bright if the cube is powered. */ -class MonitorBakedModel extends CraftingCubeBakedModel -{ +class MonitorBakedModel extends CraftingCubeBakedModel { - private final TextureAtlasSprite chassisTexture; + private final TextureAtlasSprite chassisTexture; - private final TextureAtlasSprite baseTexture; + private final TextureAtlasSprite baseTexture; - private final TextureAtlasSprite lightDarkTexture; + private final TextureAtlasSprite lightDarkTexture; - private final TextureAtlasSprite lightMediumTexture; + private final TextureAtlasSprite lightMediumTexture; - private final TextureAtlasSprite lightBrightTexture; + private final TextureAtlasSprite lightBrightTexture; - MonitorBakedModel( VertexFormat format, TextureAtlasSprite ringCorner, TextureAtlasSprite ringHor, TextureAtlasSprite ringVer, TextureAtlasSprite chassisTexture, TextureAtlasSprite baseTexture, TextureAtlasSprite lightDarkTexture, TextureAtlasSprite lightMediumTexture, TextureAtlasSprite lightBrightTexture ) - { - super( format, ringCorner, ringHor, ringVer ); - this.chassisTexture = chassisTexture; - this.baseTexture = baseTexture; - this.lightDarkTexture = lightDarkTexture; - this.lightMediumTexture = lightMediumTexture; - this.lightBrightTexture = lightBrightTexture; - } + MonitorBakedModel(VertexFormat format, TextureAtlasSprite ringCorner, TextureAtlasSprite ringHor, TextureAtlasSprite ringVer, TextureAtlasSprite chassisTexture, TextureAtlasSprite baseTexture, TextureAtlasSprite lightDarkTexture, TextureAtlasSprite lightMediumTexture, TextureAtlasSprite lightBrightTexture) { + super(format, ringCorner, ringHor, ringVer); + this.chassisTexture = chassisTexture; + this.baseTexture = baseTexture; + this.lightDarkTexture = lightDarkTexture; + this.lightMediumTexture = lightMediumTexture; + this.lightBrightTexture = lightBrightTexture; + } - @Override - protected void addInnerCube( EnumFacing side, IBlockState state, CubeBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2 ) - { - EnumFacing forward = getForward( state ); + @Override + protected void addInnerCube(EnumFacing side, IBlockState state, CubeBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2) { + EnumFacing forward = getForward(state); - // For sides other than the front, use the chassis texture - if( side != forward ) - { - builder.setTexture( this.chassisTexture ); - builder.addCube( x1, y1, z1, x2, y2, z2 ); - return; - } + // For sides other than the front, use the chassis texture + if (side != forward) { + builder.setTexture(this.chassisTexture); + builder.addCube(x1, y1, z1, x2, y2, z2); + return; + } - builder.setTexture( this.baseTexture ); - builder.addCube( x1, y1, z1, x2, y2, z2 ); + builder.setTexture(this.baseTexture); + builder.addCube(x1, y1, z1, x2, y2, z2); - // Now add the three layered light textures - AEColor color = getColor( state ); - boolean powered = state.getValue( BlockCraftingMonitor.POWERED ); + // Now add the three layered light textures + AEColor color = getColor(state); + boolean powered = state.getValue(BlockCraftingMonitor.POWERED); - builder.setRenderFullBright( powered ); + builder.setRenderFullBright(powered); - builder.setColorRGB( color.whiteVariant ); - builder.setTexture( this.lightBrightTexture ); - builder.addCube( x1, y1, z1, x2, y2, z2 ); + builder.setColorRGB(color.whiteVariant); + builder.setTexture(this.lightBrightTexture); + builder.addCube(x1, y1, z1, x2, y2, z2); - builder.setColorRGB( color.mediumVariant ); - builder.setTexture( this.lightMediumTexture ); - builder.addCube( x1, y1, z1, x2, y2, z2 ); + builder.setColorRGB(color.mediumVariant); + builder.setTexture(this.lightMediumTexture); + builder.addCube(x1, y1, z1, x2, y2, z2); - builder.setColorRGB( color.blackVariant ); - builder.setTexture( this.lightDarkTexture ); - builder.addCube( x1, y1, z1, x2, y2, z2 ); + builder.setColorRGB(color.blackVariant); + builder.setTexture(this.lightDarkTexture); + builder.addCube(x1, y1, z1, x2, y2, z2); - } + } - private static AEColor getColor( IBlockState state ) - { - if( state instanceof IExtendedBlockState ) - { - IExtendedBlockState extState = (IExtendedBlockState) state; - AEColor color = extState.getValue( BlockCraftingMonitor.COLOR ); - if( color != null ) - { - return color; - } - } + private static AEColor getColor(IBlockState state) { + if (state instanceof IExtendedBlockState) { + IExtendedBlockState extState = (IExtendedBlockState) state; + AEColor color = extState.getValue(BlockCraftingMonitor.COLOR); + if (color != null) { + return color; + } + } - return AEColor.TRANSPARENT; - } + return AEColor.TRANSPARENT; + } - private static EnumFacing getForward( IBlockState state ) - { - if( state instanceof IExtendedBlockState ) - { - IExtendedBlockState extState = (IExtendedBlockState) state; - EnumFacing forward = extState.getValue( BlockCraftingMonitor.FORWARD ); - if( forward != null ) - { - return forward; - } - } + private static EnumFacing getForward(IBlockState state) { + if (state instanceof IExtendedBlockState) { + IExtendedBlockState extState = (IExtendedBlockState) state; + EnumFacing forward = extState.getValue(BlockCraftingMonitor.FORWARD); + if (forward != null) { + return forward; + } + } - return EnumFacing.NORTH; - } + return EnumFacing.NORTH; + } } diff --git a/src/main/java/appeng/client/render/crafting/UnitBakedModel.java b/src/main/java/appeng/client/render/crafting/UnitBakedModel.java index b85e10f7f..84159e4af 100644 --- a/src/main/java/appeng/client/render/crafting/UnitBakedModel.java +++ b/src/main/java/appeng/client/render/crafting/UnitBakedModel.java @@ -19,32 +19,28 @@ package appeng.client.render.crafting; +import appeng.client.render.cablebus.CubeBuilder; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.EnumFacing; -import appeng.client.render.cablebus.CubeBuilder; - /** * A simple crafting unit model that uses an un-lit texture for the inner block. */ -class UnitBakedModel extends CraftingCubeBakedModel -{ +class UnitBakedModel extends CraftingCubeBakedModel { - private final TextureAtlasSprite unitTexture; + private final TextureAtlasSprite unitTexture; - UnitBakedModel( VertexFormat format, TextureAtlasSprite ringCorner, TextureAtlasSprite ringHor, TextureAtlasSprite ringVer, TextureAtlasSprite unitTexture ) - { - super( format, ringCorner, ringHor, ringVer ); - this.unitTexture = unitTexture; - } + UnitBakedModel(VertexFormat format, TextureAtlasSprite ringCorner, TextureAtlasSprite ringHor, TextureAtlasSprite ringVer, TextureAtlasSprite unitTexture) { + super(format, ringCorner, ringHor, ringVer); + this.unitTexture = unitTexture; + } - @Override - protected void addInnerCube( EnumFacing facing, IBlockState state, CubeBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2 ) - { - builder.setTexture( this.unitTexture ); - builder.addCube( x1, y1, z1, x2, y2, z2 ); - } + @Override + protected void addInnerCube(EnumFacing facing, IBlockState state, CubeBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2) { + builder.setTexture(this.unitTexture); + builder.addCube(x1, y1, z1, x2, y2, z2); + } } diff --git a/src/main/java/appeng/client/render/effects/AssemblerFX.java b/src/main/java/appeng/client/render/effects/AssemblerFX.java index 3b31f6778..82ca4a8ef 100644 --- a/src/main/java/appeng/client/render/effects/AssemblerFX.java +++ b/src/main/java/appeng/client/render/effects/AssemblerFX.java @@ -19,93 +19,80 @@ package appeng.client.render.effects; +import appeng.api.storage.data.IAEItemStack; +import appeng.client.EffectType; +import appeng.core.AppEng; +import appeng.entity.EntityFloatingItem; +import appeng.entity.ICanDie; import net.minecraft.client.particle.Particle; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.entity.Entity; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import appeng.api.storage.data.IAEItemStack; -import appeng.client.EffectType; -import appeng.core.AppEng; -import appeng.entity.EntityFloatingItem; -import appeng.entity.ICanDie; +public class AssemblerFX extends Particle implements ICanDie { -public class AssemblerFX extends Particle implements ICanDie -{ + private final EntityFloatingItem fi; + private final float speed; + private float time = 0; - private final EntityFloatingItem fi; - private final float speed; - private float time = 0; + public AssemblerFX(final World w, final double x, final double y, final double z, final double r, final double g, final double b, final float speed, final IAEItemStack is) { + super(w, x, y, z, r, g, b); + this.motionX = 0; + this.motionY = 0; + this.motionZ = 0; + this.speed = speed; + final ItemStack displayItem = is.asItemStackRepresentation(); + this.fi = new EntityFloatingItem(this, w, x, y, z, displayItem); + w.spawnEntity(this.fi); + this.particleMaxAge = (int) Math.ceil(Math.max(1, 100.0f / speed)) + 2; + } - public AssemblerFX( final World w, final double x, final double y, final double z, final double r, final double g, final double b, final float speed, final IAEItemStack is ) - { - super( w, x, y, z, r, g, b ); - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; - this.speed = speed; - final ItemStack displayItem = is.asItemStackRepresentation(); - this.fi = new EntityFloatingItem( this, w, x, y, z, displayItem ); - w.spawnEntity( this.fi ); - this.particleMaxAge = (int) Math.ceil( Math.max( 1, 100.0f / speed ) ) + 2; - } + @Override + public boolean isDead() { + return this.isExpired; + } - @Override - public boolean isDead() - { - return this.isExpired; - } + @Override + public int getBrightnessForRender(final float par1) { + final int j1 = 13; + return j1 << 20 | j1 << 4; + } - @Override - public int getBrightnessForRender( final float par1 ) - { - final int j1 = 13; - return j1 << 20 | j1 << 4; - } + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; - @Override - public void onUpdate() - { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; + if (this.particleAge++ >= this.particleMaxAge) { + this.setExpired(); + } - if( this.particleAge++ >= this.particleMaxAge ) - { - this.setExpired(); - } + this.motionY -= 0.04D * this.particleGravity; + this.move(this.motionX, this.motionY, this.motionZ); + this.motionX *= 0.9800000190734863D; + this.motionY *= 0.9800000190734863D; + this.motionZ *= 0.9800000190734863D; - this.motionY -= 0.04D * this.particleGravity; - this.move( this.motionX, this.motionY, this.motionZ ); - this.motionX *= 0.9800000190734863D; - this.motionY *= 0.9800000190734863D; - this.motionZ *= 0.9800000190734863D; + if (this.isExpired) { + this.fi.setDead(); + } else { + final float lifeSpan = (float) this.particleAge / (float) this.particleMaxAge; + this.fi.setProgress(lifeSpan); + } + } - if( this.isExpired ) - { - this.fi.setDead(); - } - else - { - final float lifeSpan = (float) this.particleAge / (float) this.particleMaxAge; - this.fi.setProgress( lifeSpan ); - } - } - - @Override - public void renderParticle( final BufferBuilder par1Tessellator, final Entity p_180434_2_, final float l, final float rX, final float rY, final float rZ, final float rYZ, final float rXY ) - { - this.time += l; - if( this.time > 4.0 ) - { - this.time -= 4.0; - // if ( AppEng.proxy.shouldAddParticles( r ) ) - for( int x = 0; x < (int) Math.ceil( this.speed / 5 ); x++ ) - { - AppEng.proxy.spawnEffect( EffectType.Crafting, this.world, this.posX, this.posY, this.posZ, null ); - } - } - } + @Override + public void renderParticle(final BufferBuilder par1Tessellator, final Entity p_180434_2_, final float l, final float rX, final float rY, final float rZ, final float rYZ, final float rXY) { + this.time += l; + if (this.time > 4.0) { + this.time -= 4.0; + // if ( AppEng.proxy.shouldAddParticles( r ) ) + for (int x = 0; x < (int) Math.ceil(this.speed / 5); x++) { + AppEng.proxy.spawnEffect(EffectType.Crafting, this.world, this.posX, this.posY, this.posZ, null); + } + } + } } diff --git a/src/main/java/appeng/client/render/effects/ChargedOreFX.java b/src/main/java/appeng/client/render/effects/ChargedOreFX.java index c83f7177f..50dc581b1 100644 --- a/src/main/java/appeng/client/render/effects/ChargedOreFX.java +++ b/src/main/java/appeng/client/render/effects/ChargedOreFX.java @@ -23,24 +23,20 @@ import net.minecraft.client.particle.ParticleRedstone; import net.minecraft.world.World; -public class ChargedOreFX extends ParticleRedstone -{ +public class ChargedOreFX extends ParticleRedstone { - public ChargedOreFX( final World w, final double x, final double y, final double z, final float r, final float g, final float b ) - { - super( w, x, y, z, 0.21f, 0.61f, 1.0f ); - } + public ChargedOreFX(final World w, final double x, final double y, final double z, final float r, final float g, final float b) { + super(w, x, y, z, 0.21f, 0.61f, 1.0f); + } - @Override - public int getBrightnessForRender( final float par1 ) - { - int j1 = super.getBrightnessForRender( par1 ); - j1 = Math.max( j1 >> 20, j1 >> 4 ); - j1 += 3; - if( j1 > 15 ) - { - j1 = 15; - } - return j1 << 20 | j1 << 4; - } + @Override + public int getBrightnessForRender(final float par1) { + int j1 = super.getBrightnessForRender(par1); + j1 = Math.max(j1 >> 20, j1 >> 4); + j1 += 3; + if (j1 > 15) { + j1 = 15; + } + return j1 << 20 | j1 << 4; + } } diff --git a/src/main/java/appeng/client/render/effects/CraftingFx.java b/src/main/java/appeng/client/render/effects/CraftingFx.java index 2d69d5881..4efec0651 100644 --- a/src/main/java/appeng/client/render/effects/CraftingFx.java +++ b/src/main/java/appeng/client/render/effects/CraftingFx.java @@ -19,6 +19,8 @@ package appeng.client.render.effects; +import appeng.api.util.AEPartLocation; +import appeng.client.render.textures.ParticleTextures; import net.minecraft.client.particle.ParticleBreaking; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -29,140 +31,125 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.util.AEPartLocation; -import appeng.client.render.textures.ParticleTextures; +@SideOnly(Side.CLIENT) +public class CraftingFx extends ParticleBreaking { -@SideOnly( Side.CLIENT ) -public class CraftingFx extends ParticleBreaking -{ + private final TextureAtlasSprite particleTextureIndex; - private final TextureAtlasSprite particleTextureIndex; + private final int startBlkX; + private final int startBlkY; + private final int startBlkZ; - private final int startBlkX; - private final int startBlkY; - private final int startBlkZ; + public CraftingFx(final World par1World, final double par2, final double par4, final double par6, final Item par8Item) { + super(par1World, par2, par4, par6, par8Item); + this.particleGravity = 0; + this.particleBlue = 1; + this.particleGreen = 0.9f; + this.particleRed = 1; + this.particleAlpha = 1.3f; + this.particleScale = 1.5f; + this.particleTextureIndex = ParticleTextures.BlockEnergyParticle; + this.particleMaxAge /= 1.2; - public CraftingFx( final World par1World, final double par2, final double par4, final double par6, final Item par8Item ) - { - super( par1World, par2, par4, par6, par8Item ); - this.particleGravity = 0; - this.particleBlue = 1; - this.particleGreen = 0.9f; - this.particleRed = 1; - this.particleAlpha = 1.3f; - this.particleScale = 1.5f; - this.particleTextureIndex = ParticleTextures.BlockEnergyParticle; - this.particleMaxAge /= 1.2; + this.startBlkX = MathHelper.floor(this.posX); + this.startBlkY = MathHelper.floor(this.posY); + this.startBlkZ = MathHelper.floor(this.posZ); + } - this.startBlkX = MathHelper.floor( this.posX ); - this.startBlkY = MathHelper.floor( this.posY ); - this.startBlkZ = MathHelper.floor( this.posZ ); - } + @Override + public int getFXLayer() { + return 1; + } - @Override - public int getFXLayer() - { - return 1; - } + @Override + public void renderParticle(final BufferBuilder par1Tessellator, final Entity p_180434_2_, final float partialTick, final float x, final float y, final float z, final float rx, final float rz) { + if (partialTick < 0 || partialTick > 1) { + return; + } - @Override - public void renderParticle( final BufferBuilder par1Tessellator, final Entity p_180434_2_, final float partialTick, final float x, final float y, final float z, final float rx, final float rz ) - { - if( partialTick < 0 || partialTick > 1 ) - { - return; - } + final float f6 = this.particleTextureIndex.getMinU(); + final float f7 = this.particleTextureIndex.getMaxU(); + final float f8 = this.particleTextureIndex.getMinV(); + final float f9 = this.particleTextureIndex.getMaxV(); + final float scale = 0.1F * this.particleScale; - final float f6 = this.particleTextureIndex.getMinU(); - final float f7 = this.particleTextureIndex.getMaxU(); - final float f8 = this.particleTextureIndex.getMinV(); - final float f9 = this.particleTextureIndex.getMaxV(); - final float scale = 0.1F * this.particleScale; + float offX = (float) (this.prevPosX + (this.posX - this.prevPosX) * partialTick); + float offY = (float) (this.prevPosY + (this.posY - this.prevPosY) * partialTick); + float offZ = (float) (this.prevPosZ + (this.posZ - this.prevPosZ) * partialTick); - float offX = (float) ( this.prevPosX + ( this.posX - this.prevPosX ) * partialTick ); - float offY = (float) ( this.prevPosY + ( this.posY - this.prevPosY ) * partialTick ); - float offZ = (float) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * partialTick ); + final int blkX = MathHelper.floor(offX); + final int blkY = MathHelper.floor(offY); + final int blkZ = MathHelper.floor(offZ); + if (blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ) { + offX -= interpPosX; + offY -= interpPosY; + offZ -= interpPosZ; - final int blkX = MathHelper.floor( offX ); - final int blkY = MathHelper.floor( offY ); - final int blkZ = MathHelper.floor( offZ ); - if( blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ ) - { - offX -= interpPosX; - offY -= interpPosY; - offZ -= interpPosZ; + int i = this.getBrightnessForRender(partialTick); + int j = i >> 16 & 65535; + int k = i & 65535; - int i = this.getBrightnessForRender( partialTick ); - int j = i >> 16 & 65535; - int k = i & 65535; + // AELog.info( "" + partialTick ); + final float f14 = 1.0F; + par1Tessellator.pos(offX - x * scale - rx * scale, offY - y * scale, offZ - z * scale - rz * scale) + .tex(f7, f9) + .color(this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha) + .lightmap(j, k) + .endVertex(); + par1Tessellator.pos(offX - x * scale + rx * scale, offY + y * scale, offZ - z * scale + rz * scale) + .tex(f7, f8) + .color(this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha) + .lightmap(j, k) + .endVertex(); + par1Tessellator.pos(offX + x * scale + rx * scale, offY + y * scale, offZ + z * scale + rz * scale) + .tex(f6, f8) + .color(this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha) + .lightmap(j, k) + .endVertex(); + par1Tessellator.pos(offX + x * scale - rx * scale, offY - y * scale, offZ + z * scale - rz * scale) + .tex(f6, f9) + .color(this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha) + .lightmap(j, k) + .endVertex(); + } + } - // AELog.info( "" + partialTick ); - final float f14 = 1.0F; - par1Tessellator.pos( offX - x * scale - rx * scale, offY - y * scale, offZ - z * scale - rz * scale ) - .tex( f7, f9 ) - .color( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ) - .lightmap( j, k ) - .endVertex(); - par1Tessellator.pos( offX - x * scale + rx * scale, offY + y * scale, offZ - z * scale + rz * scale ) - .tex( f7, f8 ) - .color( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ) - .lightmap( j, k ) - .endVertex(); - par1Tessellator.pos( offX + x * scale + rx * scale, offY + y * scale, offZ + z * scale + rz * scale ) - .tex( f6, f8 ) - .color( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ) - .lightmap( j, k ) - .endVertex(); - par1Tessellator.pos( offX + x * scale - rx * scale, offY - y * scale, offZ + z * scale - rz * scale ) - .tex( f6, f9 ) - .color( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ) - .lightmap( j, k ) - .endVertex(); - } - } + public void fromItem(final AEPartLocation d) { + this.posX += 0.2 * d.xOffset; + this.posY += 0.2 * d.yOffset; + this.posZ += 0.2 * d.zOffset; + this.particleScale *= 0.8f; + } - public void fromItem( final AEPartLocation d ) - { - this.posX += 0.2 * d.xOffset; - this.posY += 0.2 * d.yOffset; - this.posZ += 0.2 * d.zOffset; - this.particleScale *= 0.8f; - } + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; - @Override - public void onUpdate() - { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; + if (this.particleAge++ >= this.particleMaxAge) { + this.setExpired(); + } - if( this.particleAge++ >= this.particleMaxAge ) - { - this.setExpired(); - } + this.motionY -= 0.04D * this.particleGravity; + this.move(this.motionX, this.motionY, this.motionZ); + this.motionX *= 0.9800000190734863D; + this.motionY *= 0.9800000190734863D; + this.motionZ *= 0.9800000190734863D; + this.particleScale *= 0.51f; + this.particleAlpha *= 0.51f; + } - this.motionY -= 0.04D * this.particleGravity; - this.move( this.motionX, this.motionY, this.motionZ ); - this.motionX *= 0.9800000190734863D; - this.motionY *= 0.9800000190734863D; - this.motionZ *= 0.9800000190734863D; - this.particleScale *= 0.51f; - this.particleAlpha *= 0.51f; - } + public void setMotionX(float motionX) { + this.motionX = motionX; + } - public void setMotionX( float motionX ) - { - this.motionX = motionX; - } + public void setMotionY(float motionY) { + this.motionY = motionY; + } - public void setMotionY( float motionY ) - { - this.motionY = motionY; - } - - public void setMotionZ( float motionZ ) - { - this.motionZ = motionZ; - } + public void setMotionZ(float motionZ) { + this.motionZ = motionZ; + } } diff --git a/src/main/java/appeng/client/render/effects/EnergyFx.java b/src/main/java/appeng/client/render/effects/EnergyFx.java index bc0b78132..d3bdf1ea0 100644 --- a/src/main/java/appeng/client/render/effects/EnergyFx.java +++ b/src/main/java/appeng/client/render/effects/EnergyFx.java @@ -19,6 +19,8 @@ package appeng.client.render.effects; +import appeng.api.util.AEPartLocation; +import appeng.client.render.textures.ParticleTextures; import net.minecraft.client.particle.ParticleBreaking; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -29,131 +31,117 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.util.AEPartLocation; -import appeng.client.render.textures.ParticleTextures; +@SideOnly(Side.CLIENT) +public class EnergyFx extends ParticleBreaking { -@SideOnly( Side.CLIENT ) -public class EnergyFx extends ParticleBreaking -{ + private final TextureAtlasSprite particleTextureIndex; - private final TextureAtlasSprite particleTextureIndex; + private final int startBlkX; + private final int startBlkY; + private final int startBlkZ; - private final int startBlkX; - private final int startBlkY; - private final int startBlkZ; + public EnergyFx(final World par1World, final double par2, final double par4, final double par6, final Item par8Item) { + super(par1World, par2, par4, par6, par8Item); + this.particleGravity = 0; + this.particleBlue = 1; + this.particleGreen = 1; + this.particleRed = 1; + this.particleAlpha = 1.4f; + this.particleScale = 3.5f; + this.particleTextureIndex = ParticleTextures.BlockEnergyParticle; - public EnergyFx( final World par1World, final double par2, final double par4, final double par6, final Item par8Item ) - { - super( par1World, par2, par4, par6, par8Item ); - this.particleGravity = 0; - this.particleBlue = 1; - this.particleGreen = 1; - this.particleRed = 1; - this.particleAlpha = 1.4f; - this.particleScale = 3.5f; - this.particleTextureIndex = ParticleTextures.BlockEnergyParticle; + this.startBlkX = MathHelper.floor(this.posX); + this.startBlkY = MathHelper.floor(this.posY); + this.startBlkZ = MathHelper.floor(this.posZ); + } - this.startBlkX = MathHelper.floor( this.posX ); - this.startBlkY = MathHelper.floor( this.posY ); - this.startBlkZ = MathHelper.floor( this.posZ ); - } + @Override + public int getFXLayer() { + return 1; + } - @Override - public int getFXLayer() - { - return 1; - } + @Override + public void renderParticle(final BufferBuilder par1Tessellator, final Entity p_180434_2_, final float partialTicks, final float par3, final float par4, final float par5, final float par6, final float par7) { + final float f6 = this.particleTextureIndex.getMinU(); + final float f7 = this.particleTextureIndex.getMaxU(); + final float f8 = this.particleTextureIndex.getMinV(); + final float f9 = this.particleTextureIndex.getMaxV(); + final float f10 = 0.1F * this.particleScale; - @Override - public void renderParticle( final BufferBuilder par1Tessellator, final Entity p_180434_2_, final float partialTicks, final float par3, final float par4, final float par5, final float par6, final float par7 ) - { - final float f6 = this.particleTextureIndex.getMinU(); - final float f7 = this.particleTextureIndex.getMaxU(); - final float f8 = this.particleTextureIndex.getMinV(); - final float f9 = this.particleTextureIndex.getMaxV(); - final float f10 = 0.1F * this.particleScale; + final float f11 = (float) (this.prevPosX + (this.posX - this.prevPosX) * partialTicks - interpPosX); + final float f12 = (float) (this.prevPosY + (this.posY - this.prevPosY) * partialTicks - interpPosY); + final float f13 = (float) (this.prevPosZ + (this.posZ - this.prevPosZ) * partialTicks - interpPosZ); - final float f11 = (float) ( this.prevPosX + ( this.posX - this.prevPosX ) * partialTicks - interpPosX ); - final float f12 = (float) ( this.prevPosY + ( this.posY - this.prevPosY ) * partialTicks - interpPosY ); - final float f13 = (float) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * partialTicks - interpPosZ ); + final int blkX = MathHelper.floor(this.posX); + final int blkY = MathHelper.floor(this.posY); + final int blkZ = MathHelper.floor(this.posZ); - final int blkX = MathHelper.floor( this.posX ); - final int blkY = MathHelper.floor( this.posY ); - final int blkZ = MathHelper.floor( this.posZ ); + if (blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ) { + int i = this.getBrightnessForRender(partialTicks); + int j = i >> 16 & 65535; + int k = i & 65535; - if( blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ ) - { - int i = this.getBrightnessForRender( partialTicks ); - int j = i >> 16 & 65535; - int k = i & 65535; + final float f14 = 1.0F; + par1Tessellator.pos(f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10) + .tex(f7, f9) + .color(this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha) + .lightmap(j, k) + .endVertex(); + par1Tessellator.pos(f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10) + .tex(f7, f8) + .color(this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha) + .lightmap(j, k) + .endVertex(); + par1Tessellator.pos(f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10) + .tex(f6, f8) + .color(this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha) + .lightmap(j, k) + .endVertex(); + par1Tessellator.pos(f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10) + .tex(f6, f9) + .color(this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha) + .lightmap(j, k) + .endVertex(); + } + } - final float f14 = 1.0F; - par1Tessellator.pos( f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10 ) - .tex( f7, f9 ) - .color( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ) - .lightmap( j, k ) - .endVertex(); - par1Tessellator.pos( f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10 ) - .tex( f7, f8 ) - .color( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ) - .lightmap( j, k ) - .endVertex(); - par1Tessellator.pos( f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10 ) - .tex( f6, f8 ) - .color( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ) - .lightmap( j, k ) - .endVertex(); - par1Tessellator.pos( f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10 ) - .tex( f6, f9 ) - .color( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ) - .lightmap( j, k ) - .endVertex(); - } - } + public void fromItem(final AEPartLocation d) { + this.posX += 0.2 * d.xOffset; + this.posY += 0.2 * d.yOffset; + this.posZ += 0.2 * d.zOffset; + this.particleScale *= 0.8f; + } - public void fromItem( final AEPartLocation d ) - { - this.posX += 0.2 * d.xOffset; - this.posY += 0.2 * d.yOffset; - this.posZ += 0.2 * d.zOffset; - this.particleScale *= 0.8f; - } + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; - @Override - public void onUpdate() - { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; + if (this.particleAge++ >= this.particleMaxAge) { + this.setExpired(); + } - if( this.particleAge++ >= this.particleMaxAge ) - { - this.setExpired(); - } + this.motionY -= 0.04D * this.particleGravity; + this.move(this.motionX, this.motionY, this.motionZ); + this.motionX *= 0.9800000190734863D; + this.motionY *= 0.9800000190734863D; + this.motionZ *= 0.9800000190734863D; - this.motionY -= 0.04D * this.particleGravity; - this.move( this.motionX, this.motionY, this.motionZ ); - this.motionX *= 0.9800000190734863D; - this.motionY *= 0.9800000190734863D; - this.motionZ *= 0.9800000190734863D; + this.particleScale *= 0.89f; + this.particleAlpha *= 0.89f; + } - this.particleScale *= 0.89f; - this.particleAlpha *= 0.89f; - } + public void setMotionX(float motionX) { + this.motionX = motionX; + } - public void setMotionX( float motionX ) - { - this.motionX = motionX; - } + public void setMotionY(float motionY) { + this.motionY = motionY; + } - public void setMotionY( float motionY ) - { - this.motionY = motionY; - } - - public void setMotionZ( float motionZ ) - { - this.motionZ = motionZ; - } + public void setMotionZ(float motionZ) { + this.motionZ = motionZ; + } } diff --git a/src/main/java/appeng/client/render/effects/LightningArcFX.java b/src/main/java/appeng/client/render/effects/LightningArcFX.java index f88b44ca0..a85ab6d45 100644 --- a/src/main/java/appeng/client/render/effects/LightningArcFX.java +++ b/src/main/java/appeng/client/render/effects/LightningArcFX.java @@ -19,46 +19,42 @@ package appeng.client.render.effects; -import java.util.Random; - import net.minecraft.world.World; +import java.util.Random; -public class LightningArcFX extends LightningFX -{ - private static final Random RANDOM_GENERATOR = new Random(); - private final double rx; - private final double ry; - private final double rz; +public class LightningArcFX extends LightningFX { + private static final Random RANDOM_GENERATOR = new Random(); - public LightningArcFX( final World w, final double x, final double y, final double z, final double ex, final double ey, final double ez, final double r, final double g, final double b ) - { - super( w, x, y, z, r, g, b, 6 ); + private final double rx; + private final double ry; + private final double rz; - this.rx = ex - x; - this.ry = ey - y; - this.rz = ez - z; + public LightningArcFX(final World w, final double x, final double y, final double z, final double ex, final double ey, final double ez, final double r, final double g, final double b) { + super(w, x, y, z, r, g, b, 6); - this.regen(); - } + this.rx = ex - x; + this.ry = ey - y; + this.rz = ez - z; - @Override - protected void regen() - { - final double i = 1.0 / ( this.getSteps() - 1 ); - final double lastDirectionX = this.rx * i; - final double lastDirectionY = this.ry * i; - final double lastDirectionZ = this.rz * i; + this.regen(); + } - final double len = Math.sqrt( lastDirectionX * lastDirectionX + lastDirectionY * lastDirectionY + lastDirectionZ * lastDirectionZ ); - for( int s = 0; s < this.getSteps(); s++ ) - { - final double[][] localSteps = this.getPrecomputedSteps(); + @Override + protected void regen() { + final double i = 1.0 / (this.getSteps() - 1); + final double lastDirectionX = this.rx * i; + final double lastDirectionY = this.ry * i; + final double lastDirectionZ = this.rz * i; - localSteps[s][0] = ( lastDirectionX + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * len * 1.2 ) / 2.0; - localSteps[s][1] = ( lastDirectionY + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * len * 1.2 ) / 2.0; - localSteps[s][2] = ( lastDirectionZ + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * len * 1.2 ) / 2.0; - } - } + final double len = Math.sqrt(lastDirectionX * lastDirectionX + lastDirectionY * lastDirectionY + lastDirectionZ * lastDirectionZ); + for (int s = 0; s < this.getSteps(); s++) { + final double[][] localSteps = this.getPrecomputedSteps(); + + localSteps[s][0] = (lastDirectionX + (RANDOM_GENERATOR.nextDouble() - 0.5) * len * 1.2) / 2.0; + localSteps[s][1] = (lastDirectionY + (RANDOM_GENERATOR.nextDouble() - 0.5) * len * 1.2) / 2.0; + localSteps[s][2] = (lastDirectionZ + (RANDOM_GENERATOR.nextDouble() - 0.5) * len * 1.2) / 2.0; + } + } } diff --git a/src/main/java/appeng/client/render/effects/LightningFX.java b/src/main/java/appeng/client/render/effects/LightningFX.java index 97afced65..b9424ef10 100644 --- a/src/main/java/appeng/client/render/effects/LightningFX.java +++ b/src/main/java/appeng/client/render/effects/LightningFX.java @@ -19,8 +19,6 @@ package appeng.client.render.effects; -import java.util.Random; - import net.minecraft.client.Minecraft; import net.minecraft.client.particle.Particle; import net.minecraft.client.renderer.BufferBuilder; @@ -29,227 +27,205 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; +import java.util.Random; -public class LightningFX extends Particle -{ - private static final Random RANDOM_GENERATOR = new Random(); - private static final int STEPS = 5; - private static final int BRIGHTNESS = 13 << 4; +public class LightningFX extends Particle { - private final double[][] precomputedSteps; - private final double[] vertices = new double[3]; - private final double[] verticesWithUV = new double[3]; - private boolean hasData = false; + private static final Random RANDOM_GENERATOR = new Random(); + private static final int STEPS = 5; + private static final int BRIGHTNESS = 13 << 4; - public LightningFX( final World w, final double x, final double y, final double z, final double r, final double g, final double b ) - { - this( w, x, y, z, r, g, b, 6 ); - this.regen(); - } + private final double[][] precomputedSteps; + private final double[] vertices = new double[3]; + private final double[] verticesWithUV = new double[3]; + private boolean hasData = false; - protected LightningFX( final World w, final double x, final double y, final double z, final double r, final double g, final double b, final int maxAge ) - { - super( w, x, y, z, r, g, b ); - this.precomputedSteps = new double[LightningFX.STEPS][3]; - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; - this.particleMaxAge = maxAge; - } + public LightningFX(final World w, final double x, final double y, final double z, final double r, final double g, final double b) { + this(w, x, y, z, r, g, b, 6); + this.regen(); + } - protected void regen() - { - double lastDirectionX = ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9; - double lastDirectionY = ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9; - double lastDirectionZ = ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9; - for( int s = 0; s < LightningFX.STEPS; s++ ) - { - this.precomputedSteps[s][0] = lastDirectionX = ( lastDirectionX + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; - this.precomputedSteps[s][1] = lastDirectionY = ( lastDirectionY + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; - this.precomputedSteps[s][2] = lastDirectionZ = ( lastDirectionZ + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; - } - } + protected LightningFX(final World w, final double x, final double y, final double z, final double r, final double g, final double b, final int maxAge) { + super(w, x, y, z, r, g, b); + this.precomputedSteps = new double[LightningFX.STEPS][3]; + this.motionX = 0; + this.motionY = 0; + this.motionZ = 0; + this.particleMaxAge = maxAge; + } - protected int getSteps() - { - return LightningFX.STEPS; - } + protected void regen() { + double lastDirectionX = (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9; + double lastDirectionY = (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9; + double lastDirectionZ = (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9; + for (int s = 0; s < LightningFX.STEPS; s++) { + this.precomputedSteps[s][0] = lastDirectionX = (lastDirectionX + (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9) / 2.0; + this.precomputedSteps[s][1] = lastDirectionY = (lastDirectionY + (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9) / 2.0; + this.precomputedSteps[s][2] = lastDirectionZ = (lastDirectionZ + (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9) / 2.0; + } + } - @Override - public void onUpdate() - { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; + protected int getSteps() { + return LightningFX.STEPS; + } - if( this.particleAge++ >= this.particleMaxAge ) - { - this.setExpired(); - } + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; - this.motionY -= 0.04D * this.particleGravity; - this.move( this.motionX, this.motionY, this.motionZ ); - this.motionX *= 0.9800000190734863D; - this.motionY *= 0.9800000190734863D; - this.motionZ *= 0.9800000190734863D; - } + if (this.particleAge++ >= this.particleMaxAge) { + this.setExpired(); + } - @Override - public void renderParticle( final BufferBuilder tess, final Entity p_180434_2_, final float l, final float rX, final float rY, final float rZ, final float rYZ, final float rXY ) - { - final float j = 1.0f; - float red = this.particleRed * j * 0.9f; - float green = this.particleGreen * j * 0.95f; - float blue = this.particleBlue * j; - final float alpha = this.particleAlpha; + this.motionY -= 0.04D * this.particleGravity; + this.move(this.motionX, this.motionY, this.motionZ); + this.motionX *= 0.9800000190734863D; + this.motionY *= 0.9800000190734863D; + this.motionZ *= 0.9800000190734863D; + } - if( this.particleAge == 3 ) - { - this.regen(); - } - double f6 = this.particleTextureIndexX / 16.0; - final double f7 = f6 + 0.0324375F; - double f8 = this.particleTextureIndexY / 16.0; - final double f9 = f8 + 0.0324375F; + @Override + public void renderParticle(final BufferBuilder tess, final Entity p_180434_2_, final float l, final float rX, final float rY, final float rZ, final float rYZ, final float rXY) { + final float j = 1.0f; + float red = this.particleRed * j * 0.9f; + float green = this.particleGreen * j * 0.95f; + float blue = this.particleBlue * j; + final float alpha = this.particleAlpha; - f6 = f7; - f8 = f9; + if (this.particleAge == 3) { + this.regen(); + } + double f6 = this.particleTextureIndexX / 16.0; + final double f7 = f6 + 0.0324375F; + double f8 = this.particleTextureIndexY / 16.0; + final double f9 = f8 + 0.0324375F; - double scale = 0.02;// 0.02F * this.particleScale; + f6 = f7; + f8 = f9; - final double[] a = new double[3]; - final double[] b = new double[3]; + double scale = 0.02;// 0.02F * this.particleScale; - double ox = 0; - double oy = 0; - double oz = 0; + final double[] a = new double[3]; + final double[] b = new double[3]; - final EntityPlayer p = Minecraft.getMinecraft().player; - double offX = -rZ; - double offY = MathHelper.cos( (float) ( Math.PI / 2.0f + p.rotationPitch * 0.017453292F ) ); - double offZ = rX; + double ox = 0; + double oy = 0; + double oz = 0; - for( int layer = 0; layer < 2; layer++ ) - { - if( layer == 0 ) - { - scale = 0.04; - offX *= 0.001; - offY *= 0.001; - offZ *= 0.001; - red = this.particleRed * j * 0.4f; - green = this.particleGreen * j * 0.25f; - blue = this.particleBlue * j * 0.45f; - } - else - { - offX = 0; - offY = 0; - offZ = 0; - scale = 0.02; - red = this.particleRed * j * 0.9f; - green = this.particleGreen * j * 0.65f; - blue = this.particleBlue * j * 0.85f; - } + final EntityPlayer p = Minecraft.getMinecraft().player; + double offX = -rZ; + double offY = MathHelper.cos((float) (Math.PI / 2.0f + p.rotationPitch * 0.017453292F)); + double offZ = rX; - for( int cycle = 0; cycle < 3; cycle++ ) - { - this.clear(); + for (int layer = 0; layer < 2; layer++) { + if (layer == 0) { + scale = 0.04; + offX *= 0.001; + offY *= 0.001; + offZ *= 0.001; + red = this.particleRed * j * 0.4f; + green = this.particleGreen * j * 0.25f; + blue = this.particleBlue * j * 0.45f; + } else { + offX = 0; + offY = 0; + offZ = 0; + scale = 0.02; + red = this.particleRed * j * 0.9f; + green = this.particleGreen * j * 0.65f; + blue = this.particleBlue * j * 0.85f; + } - double x = ( this.prevPosX + ( this.posX - this.prevPosX ) * l - interpPosX ) - offX; - double y = ( this.prevPosY + ( this.posY - this.prevPosY ) * l - interpPosY ) - offY; - double z = ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * l - interpPosZ ) - offZ; + for (int cycle = 0; cycle < 3; cycle++) { + this.clear(); - for( int s = 0; s < LightningFX.STEPS; s++ ) - { - final double xN = x + this.precomputedSteps[s][0]; - final double yN = y + this.precomputedSteps[s][1]; - final double zN = z + this.precomputedSteps[s][2]; + double x = (this.prevPosX + (this.posX - this.prevPosX) * l - interpPosX) - offX; + double y = (this.prevPosY + (this.posY - this.prevPosY) * l - interpPosY) - offY; + double z = (this.prevPosZ + (this.posZ - this.prevPosZ) * l - interpPosZ) - offZ; - final double xD = xN - x; - final double yD = yN - y; - final double zD = zN - z; + for (int s = 0; s < LightningFX.STEPS; s++) { + final double xN = x + this.precomputedSteps[s][0]; + final double yN = y + this.precomputedSteps[s][1]; + final double zN = z + this.precomputedSteps[s][2]; - if( cycle == 0 ) - { - ox = ( yD * 0 ) - ( 1 * zD ); - oy = ( zD * 0 ) - ( 0 * xD ); - oz = ( xD * 1 ) - ( 0 * yD ); - } - if( cycle == 1 ) - { - ox = ( yD * 1 ) - ( 0 * zD ); - oy = ( zD * 0 ) - ( 1 * xD ); - oz = ( xD * 0 ) - ( 0 * yD ); - } - if( cycle == 2 ) - { - ox = ( yD * 0 ) - ( 0 * zD ); - oy = ( zD * 1 ) - ( 0 * xD ); - oz = ( xD * 0 ) - ( 1 * yD ); - } + final double xD = xN - x; + final double yD = yN - y; + final double zD = zN - z; - final double ss = Math - .sqrt( ox * ox + oy * oy + oz * oz ) / ( ( ( (double) LightningFX.STEPS - (double) s ) / LightningFX.STEPS ) * scale ); - ox /= ss; - oy /= ss; - oz /= ss; + if (cycle == 0) { + ox = (yD * 0) - (1 * zD); + oy = (zD * 0) - (0 * xD); + oz = (xD * 1) - (0 * yD); + } + if (cycle == 1) { + ox = (yD * 1) - (0 * zD); + oy = (zD * 0) - (1 * xD); + oz = (xD * 0) - (0 * yD); + } + if (cycle == 2) { + ox = (yD * 0) - (0 * zD); + oy = (zD * 1) - (0 * xD); + oz = (xD * 0) - (1 * yD); + } - a[0] = x + ox; - a[1] = y + oy; - a[2] = z + oz; + final double ss = Math + .sqrt(ox * ox + oy * oy + oz * oz) / ((((double) LightningFX.STEPS - (double) s) / LightningFX.STEPS) * scale); + ox /= ss; + oy /= ss; + oz /= ss; - b[0] = x; - b[1] = y; - b[2] = z; + a[0] = x + ox; + a[1] = y + oy; + a[2] = z + oz; - this.draw( red, green, blue, tess, a, b, f6, f8 ); + b[0] = x; + b[1] = y; + b[2] = z; - x = xN; - y = yN; - z = zN; - } - } - } - /* - * GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); GL11.glDisable( GL11.GL_CULL_FACE ); tess.draw(); - * GL11.glPopAttrib(); tess.startDrawingQuads(); - */ - } + this.draw(red, green, blue, tess, a, b, f6, f8); - private void clear() - { - this.hasData = false; - } + x = xN; + y = yN; + z = zN; + } + } + } + /* + * GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); GL11.glDisable( GL11.GL_CULL_FACE ); tess.draw(); + * GL11.glPopAttrib(); tess.startDrawingQuads(); + */ + } - private void draw( float red, float green, float blue, final BufferBuilder tess, final double[] a, final double[] b, final double f6, final double f8 ) - { - if( this.hasData ) - { - tess.pos( a[0], a[1], a[2] ).tex( f6, f8 ).color( red, green, blue, this.particleAlpha ).lightmap( BRIGHTNESS, BRIGHTNESS ).endVertex(); - tess.pos( this.vertices[0], this.vertices[1], this.vertices[2] ) - .tex( f6, f8 ) - .color( red, green, blue, this.particleAlpha ) - .lightmap( BRIGHTNESS, BRIGHTNESS ) - .endVertex(); - tess.pos( this.verticesWithUV[0], this.verticesWithUV[1], this.verticesWithUV[2] ) - .tex( f6, f8 ) - .color( red, green, blue, this.particleAlpha ) - .lightmap( BRIGHTNESS, BRIGHTNESS ) - .endVertex(); - tess.pos( b[0], b[1], b[2] ).tex( f6, f8 ).color( red, green, blue, this.particleAlpha ).lightmap( BRIGHTNESS, BRIGHTNESS ).endVertex(); - } - this.hasData = true; - for( int x = 0; x < 3; x++ ) - { - this.vertices[x] = a[x]; - this.verticesWithUV[x] = b[x]; - } - } + private void clear() { + this.hasData = false; + } - protected double[][] getPrecomputedSteps() - { - return this.precomputedSteps; - } + private void draw(float red, float green, float blue, final BufferBuilder tess, final double[] a, final double[] b, final double f6, final double f8) { + if (this.hasData) { + tess.pos(a[0], a[1], a[2]).tex(f6, f8).color(red, green, blue, this.particleAlpha).lightmap(BRIGHTNESS, BRIGHTNESS).endVertex(); + tess.pos(this.vertices[0], this.vertices[1], this.vertices[2]) + .tex(f6, f8) + .color(red, green, blue, this.particleAlpha) + .lightmap(BRIGHTNESS, BRIGHTNESS) + .endVertex(); + tess.pos(this.verticesWithUV[0], this.verticesWithUV[1], this.verticesWithUV[2]) + .tex(f6, f8) + .color(red, green, blue, this.particleAlpha) + .lightmap(BRIGHTNESS, BRIGHTNESS) + .endVertex(); + tess.pos(b[0], b[1], b[2]).tex(f6, f8).color(red, green, blue, this.particleAlpha).lightmap(BRIGHTNESS, BRIGHTNESS).endVertex(); + } + this.hasData = true; + for (int x = 0; x < 3; x++) { + this.vertices[x] = a[x]; + this.verticesWithUV[x] = b[x]; + } + } + + protected double[][] getPrecomputedSteps() { + return this.precomputedSteps; + } } diff --git a/src/main/java/appeng/client/render/effects/MatterCannonFX.java b/src/main/java/appeng/client/render/effects/MatterCannonFX.java index af8c5e079..930ccc74c 100644 --- a/src/main/java/appeng/client/render/effects/MatterCannonFX.java +++ b/src/main/java/appeng/client/render/effects/MatterCannonFX.java @@ -19,6 +19,8 @@ package appeng.client.render.effects; +import appeng.api.util.AEPartLocation; +import appeng.client.render.textures.ParticleTextures; import net.minecraft.client.particle.ParticleBreaking; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -26,100 +28,90 @@ import net.minecraft.entity.Entity; import net.minecraft.item.Item; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.client.render.textures.ParticleTextures; +public class MatterCannonFX extends ParticleBreaking { -public class MatterCannonFX extends ParticleBreaking -{ + private final TextureAtlasSprite particleTextureIndex; - private final TextureAtlasSprite particleTextureIndex; + public MatterCannonFX(final World par1World, final double par2, final double par4, final double par6, final Item par8Item) { + super(par1World, par2, par4, par6, par8Item); + this.particleGravity = 0; + this.particleBlue = 1; + this.particleGreen = 1; + this.particleRed = 1; + this.particleAlpha = 1.4f; + this.particleScale = 1.1f; + this.motionX = 0.0f; + this.motionY = 0.0f; + this.motionZ = 0.0f; + this.particleTextureIndex = ParticleTextures.BlockMatterCannonParticle; + } - public MatterCannonFX( final World par1World, final double par2, final double par4, final double par6, final Item par8Item ) - { - super( par1World, par2, par4, par6, par8Item ); - this.particleGravity = 0; - this.particleBlue = 1; - this.particleGreen = 1; - this.particleRed = 1; - this.particleAlpha = 1.4f; - this.particleScale = 1.1f; - this.motionX = 0.0f; - this.motionY = 0.0f; - this.motionZ = 0.0f; - this.particleTextureIndex = ParticleTextures.BlockMatterCannonParticle; - } + public void fromItem(final AEPartLocation d) { + this.particleScale *= 1.2f; + } - public void fromItem( final AEPartLocation d ) - { - this.particleScale *= 1.2f; - } + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; - @Override - public void onUpdate() - { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; + if (this.particleAge++ >= this.particleMaxAge) { + this.setExpired(); + } - if( this.particleAge++ >= this.particleMaxAge ) - { - this.setExpired(); - } + this.motionY -= 0.04D * this.particleGravity; + this.move(this.motionX, this.motionY, this.motionZ); + this.motionX *= 0.9800000190734863D; + this.motionY *= 0.9800000190734863D; + this.motionZ *= 0.9800000190734863D; - this.motionY -= 0.04D * this.particleGravity; - this.move( this.motionX, this.motionY, this.motionZ ); - this.motionX *= 0.9800000190734863D; - this.motionY *= 0.9800000190734863D; - this.motionZ *= 0.9800000190734863D; + this.particleScale *= 1.19f; + this.particleAlpha *= 0.59f; + } - this.particleScale *= 1.19f; - this.particleAlpha *= 0.59f; - } + @Override + public int getFXLayer() { + return 1; + } - @Override - public int getFXLayer() - { - return 1; - } + @Override + public void renderParticle(final BufferBuilder par1Tessellator, final Entity p_180434_2_, final float par2, final float par3, final float par4, final float par5, final float par6, final float par7) { + final float f6 = this.particleTextureIndex.getMinU(); + final float f7 = this.particleTextureIndex.getMaxU(); + final float f8 = this.particleTextureIndex.getMinV(); + final float f9 = this.particleTextureIndex.getMaxV(); + final float f10 = 0.05F * this.particleScale; - @Override - public void renderParticle( final BufferBuilder par1Tessellator, final Entity p_180434_2_, final float par2, final float par3, final float par4, final float par5, final float par6, final float par7 ) - { - final float f6 = this.particleTextureIndex.getMinU(); - final float f7 = this.particleTextureIndex.getMaxU(); - final float f8 = this.particleTextureIndex.getMinV(); - final float f9 = this.particleTextureIndex.getMaxV(); - final float f10 = 0.05F * this.particleScale; + final float f11 = (float) (this.prevPosX + (this.posX - this.prevPosX) * par2 - interpPosX); + final float f12 = (float) (this.prevPosY + (this.posY - this.prevPosY) * par2 - interpPosY); + final float f13 = (float) (this.prevPosZ + (this.posZ - this.prevPosZ) * par2 - interpPosZ); + final float f14 = 1.0F; - final float f11 = (float) ( this.prevPosX + ( this.posX - this.prevPosX ) * par2 - interpPosX ); - final float f12 = (float) ( this.prevPosY + ( this.posY - this.prevPosY ) * par2 - interpPosY ); - final float f13 = (float) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * par2 - interpPosZ ); - final float f14 = 1.0F; + int i = this.getBrightnessForRender(par2); + int j = i >> 16 & 65535; + int k = i & 65535; - int i = this.getBrightnessForRender( par2 ); - int j = i >> 16 & 65535; - int k = i & 65535; - - par1Tessellator.pos( f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10 ) - .tex( f7, f9 ) - .color( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ) - .lightmap( j, k ) - .endVertex(); - par1Tessellator.pos( f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10 ) - .tex( f7, f8 ) - .color( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ) - .lightmap( j, k ) - .endVertex(); - par1Tessellator.pos( f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10 ) - .tex( f6, f8 ) - .color( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ) - .lightmap( j, k ) - .endVertex(); - par1Tessellator.pos( f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10 ) - .tex( f6, f9 ) - .color( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ) - .lightmap( j, k ) - .endVertex(); - } + par1Tessellator.pos(f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10) + .tex(f7, f9) + .color(this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha) + .lightmap(j, k) + .endVertex(); + par1Tessellator.pos(f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10) + .tex(f7, f8) + .color(this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha) + .lightmap(j, k) + .endVertex(); + par1Tessellator.pos(f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10) + .tex(f6, f8) + .color(this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha) + .lightmap(j, k) + .endVertex(); + par1Tessellator.pos(f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10) + .tex(f6, f9) + .color(this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha) + .lightmap(j, k) + .endVertex(); + } } diff --git a/src/main/java/appeng/client/render/effects/VibrantFX.java b/src/main/java/appeng/client/render/effects/VibrantFX.java index 7730b326c..2eedbb7c2 100644 --- a/src/main/java/appeng/client/render/effects/VibrantFX.java +++ b/src/main/java/appeng/client/render/effects/VibrantFX.java @@ -25,52 +25,47 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -@SideOnly( Side.CLIENT ) -public class VibrantFX extends Particle -{ +@SideOnly(Side.CLIENT) +public class VibrantFX extends Particle { - public VibrantFX( final World par1World, final double x, final double y, final double z, final double par8, final double par10, final double par12 ) - { - super( par1World, x, y, z, par8, par10, par12 ); - final float f = this.rand.nextFloat() * 0.1F + 0.8F; - this.particleRed = f * 0.7f; - this.particleGreen = f * 0.89f; - this.particleBlue = f * 0.9f; - this.setParticleTextureIndex( 0 ); - this.setSize( 0.04F, 0.04F ); - this.particleScale *= this.rand.nextFloat() * 0.6F + 1.9F; - this.motionX = 0.0D; - this.motionY = 0.0D; - this.motionZ = 0.0D; - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - this.particleMaxAge = (int) ( 20.0D / ( Math.random() * 0.8D + 0.1D ) ); - } + public VibrantFX(final World par1World, final double x, final double y, final double z, final double par8, final double par10, final double par12) { + super(par1World, x, y, z, par8, par10, par12); + final float f = this.rand.nextFloat() * 0.1F + 0.8F; + this.particleRed = f * 0.7f; + this.particleGreen = f * 0.89f; + this.particleBlue = f * 0.9f; + this.setParticleTextureIndex(0); + this.setSize(0.04F, 0.04F); + this.particleScale *= this.rand.nextFloat() * 0.6F + 1.9F; + this.motionX = 0.0D; + this.motionY = 0.0D; + this.motionZ = 0.0D; + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + this.particleMaxAge = (int) (20.0D / (Math.random() * 0.8D + 0.1D)); + } - @Override - public int getBrightnessForRender( final float par1 ) - { - // This just means full brightness - return 15 << 20 | 15 << 4; - } + @Override + public int getBrightnessForRender(final float par1) { + // This just means full brightness + return 15 << 20 | 15 << 4; + } - /** - * Called to update the entity's position/logic. - */ - @Override - public void onUpdate() - { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - // this.moveEntity(this.motionX, this.motionY, this.motionZ); - this.particleScale *= 0.95; + /** + * Called to update the entity's position/logic. + */ + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + // this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.particleScale *= 0.95; - if( this.particleMaxAge <= 0 || this.particleScale < 0.1 ) - { - this.setExpired(); - } - this.particleMaxAge--; - } + if (this.particleMaxAge <= 0 || this.particleScale < 0.1) { + this.setExpired(); + } + this.particleMaxAge--; + } } diff --git a/src/main/java/appeng/client/render/model/AutoRotatingCacheKey.java b/src/main/java/appeng/client/render/model/AutoRotatingCacheKey.java index 45ab4a532..71af12ce7 100644 --- a/src/main/java/appeng/client/render/model/AutoRotatingCacheKey.java +++ b/src/main/java/appeng/client/render/model/AutoRotatingCacheKey.java @@ -26,64 +26,54 @@ import net.minecraft.util.EnumFacing; /** * Used as the cache key for caching automatically rotated baked models. */ -final class AutoRotatingCacheKey -{ - private final IBlockState blockState; - private final EnumFacing forward; - private final EnumFacing up; - private final EnumFacing side; +final class AutoRotatingCacheKey { + private final IBlockState blockState; + private final EnumFacing forward; + private final EnumFacing up; + private final EnumFacing side; - AutoRotatingCacheKey( IBlockState blockState, EnumFacing forward, EnumFacing up, EnumFacing side ) - { - this.blockState = blockState; - this.forward = forward; - this.up = up; - this.side = side; - } + AutoRotatingCacheKey(IBlockState blockState, EnumFacing forward, EnumFacing up, EnumFacing side) { + this.blockState = blockState; + this.forward = forward; + this.up = up; + this.side = side; + } - public IBlockState getBlockState() - { - return this.blockState; - } + public IBlockState getBlockState() { + return this.blockState; + } - public EnumFacing getForward() - { - return this.forward; - } + public EnumFacing getForward() { + return this.forward; + } - public EnumFacing getUp() - { - return this.up; - } + public EnumFacing getUp() { + return this.up; + } - public EnumFacing getSide() - { - return this.side; - } + public EnumFacing getSide() { + return this.side; + } - @Override - public boolean equals( Object o ) - { - if( this == o ) - { - return true; - } - if( o == null || this.getClass() != o.getClass() ) - { - return false; - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || this.getClass() != o.getClass()) { + return false; + } - AutoRotatingCacheKey cacheKey = (AutoRotatingCacheKey) o; - return this.blockState.equals( cacheKey.blockState ) && this.forward == cacheKey.forward && this.up == cacheKey.up && this.side == cacheKey.side; - } + AutoRotatingCacheKey cacheKey = (AutoRotatingCacheKey) o; + return this.blockState.equals(cacheKey.blockState) && this.forward == cacheKey.forward && this.up == cacheKey.up && this.side == cacheKey.side; + } - @Override - public int hashCode() - { - int result = this.blockState.hashCode(); - result = 31 * result + this.forward.hashCode(); - result = 31 * result + this.up.hashCode(); - result = 31 * result + ( this.side != null ? this.side.hashCode() : 0 ); - return result; - } + @Override + public int hashCode() { + int result = this.blockState.hashCode(); + result = 31 * result + this.forward.hashCode(); + result = 31 * result + this.up.hashCode(); + result = 31 * result + (this.side != null ? this.side.hashCode() : 0); + return result; + } } diff --git a/src/main/java/appeng/client/render/model/AutoRotatingModel.java b/src/main/java/appeng/client/render/model/AutoRotatingModel.java index ce98fa1cc..c11e96150 100644 --- a/src/main/java/appeng/client/render/model/AutoRotatingModel.java +++ b/src/main/java/appeng/client/render/model/AutoRotatingModel.java @@ -19,17 +19,12 @@ package appeng.client.render.model; -import java.util.ArrayList; -import java.util.List; - -import javax.vecmath.Vector3f; -import javax.vecmath.Vector4f; - +import appeng.block.AEBaseTileBlock; +import appeng.client.render.FacingToRotation; import com.google.common.base.Objects; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; - import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -45,293 +40,252 @@ import net.minecraftforge.client.model.pipeline.QuadGatheringTransformer; import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad; import net.minecraftforge.common.property.IExtendedBlockState; -import appeng.block.AEBaseTileBlock; -import appeng.client.render.FacingToRotation; +import javax.vecmath.Vector3f; +import javax.vecmath.Vector4f; +import java.util.ArrayList; +import java.util.List; -public class AutoRotatingModel implements IBakedModel -{ +public class AutoRotatingModel implements IBakedModel { - private final IBakedModel parent; - private final LoadingCache> quadCache; + private final IBakedModel parent; + private final LoadingCache> quadCache; - public AutoRotatingModel( IBakedModel parent ) - { - this.parent = parent; - // 6 (DUNSWE) * 6 (DUNSWE) * 7 (DUNSWE + null) = 252 - this.quadCache = CacheBuilder.newBuilder().maximumSize( 252 ).build( new CacheLoader>() - { - @Override - public List load( AutoRotatingCacheKey key ) throws Exception - { - return AutoRotatingModel.this.getRotatedModel( key.getBlockState(), key.getSide(), key.getForward(), key.getUp() ); - } - } ); - } + public AutoRotatingModel(IBakedModel parent) { + this.parent = parent; + // 6 (DUNSWE) * 6 (DUNSWE) * 7 (DUNSWE + null) = 252 + this.quadCache = CacheBuilder.newBuilder().maximumSize(252).build(new CacheLoader>() { + @Override + public List load(AutoRotatingCacheKey key) throws Exception { + return AutoRotatingModel.this.getRotatedModel(key.getBlockState(), key.getSide(), key.getForward(), key.getUp()); + } + }); + } - private List getRotatedModel( IBlockState state, EnumFacing side, EnumFacing forward, EnumFacing up ) - { - FacingToRotation f2r = FacingToRotation.get( forward, up ); - List original = AutoRotatingModel.this.parent.getQuads( state, f2r.resultingRotate( side ), 0 ); - List rotated = new ArrayList<>( original.size() ); - for( BakedQuad quad : original ) - { - VertexFormat format = quad.getFormat(); - UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder( format ); - VertexRotator rot = new VertexRotator( f2r, quad.getFace() ); - rot.setParent( builder ); - quad.pipe( rot ); - if( quad.getFace() != null ) - { - builder.setQuadOrientation( f2r.rotate( quad.getFace() ) ); - } - else - { - builder.setQuadOrientation( null ); + private List getRotatedModel(IBlockState state, EnumFacing side, EnumFacing forward, EnumFacing up) { + FacingToRotation f2r = FacingToRotation.get(forward, up); + List original = AutoRotatingModel.this.parent.getQuads(state, f2r.resultingRotate(side), 0); + List rotated = new ArrayList<>(original.size()); + for (BakedQuad quad : original) { + VertexFormat format = quad.getFormat(); + UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder(format); + VertexRotator rot = new VertexRotator(f2r, quad.getFace()); + rot.setParent(builder); + quad.pipe(rot); + if (quad.getFace() != null) { + builder.setQuadOrientation(f2r.rotate(quad.getFace())); + } else { + builder.setQuadOrientation(null); - } - BakedQuad unpackedQuad = builder.build(); + } + BakedQuad unpackedQuad = builder.build(); - // Make a copy of it to resolve the vertex data and throw away the unpacked stuff - // This also fixes a bug in Forge's UnpackedBakedQuad, which unpacks a byte-based normal like 0,0,-1 - // to 0,0,-0.99607843. We replace these normals with the proper 0,0,-1 when rotation, which - // causes a bug in the AO lighter, if an unpacked quad pipes this value back to it. - // Packing it back to the vanilla vertex format will fix this inconsistency because it converts - // the normal back to a byte-based format, which then re-applies Forge's own bug when piping it - // to the AO lighter, thus fixing our problem. - BakedQuad packedQuad = new BakedQuad( unpackedQuad.getVertexData(), quad.getTintIndex(), unpackedQuad.getFace(), quad.getSprite(), quad - .shouldApplyDiffuseLighting(), quad.getFormat() ); - rotated.add( packedQuad ); - } - return rotated; - } + // Make a copy of it to resolve the vertex data and throw away the unpacked stuff + // This also fixes a bug in Forge's UnpackedBakedQuad, which unpacks a byte-based normal like 0,0,-1 + // to 0,0,-0.99607843. We replace these normals with the proper 0,0,-1 when rotation, which + // causes a bug in the AO lighter, if an unpacked quad pipes this value back to it. + // Packing it back to the vanilla vertex format will fix this inconsistency because it converts + // the normal back to a byte-based format, which then re-applies Forge's own bug when piping it + // to the AO lighter, thus fixing our problem. + BakedQuad packedQuad = new BakedQuad(unpackedQuad.getVertexData(), quad.getTintIndex(), unpackedQuad.getFace(), quad.getSprite(), quad + .shouldApplyDiffuseLighting(), quad.getFormat()); + rotated.add(packedQuad); + } + return rotated; + } - @Override - public boolean isAmbientOcclusion() - { - return this.parent.isAmbientOcclusion(); - } + @Override + public boolean isAmbientOcclusion() { + return this.parent.isAmbientOcclusion(); + } - @Override - public boolean isGui3d() - { - return this.parent.isGui3d(); - } + @Override + public boolean isGui3d() { + return this.parent.isGui3d(); + } - @Override - public boolean isBuiltInRenderer() - { - return this.parent.isBuiltInRenderer(); - } + @Override + public boolean isBuiltInRenderer() { + return this.parent.isBuiltInRenderer(); + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.parent.getParticleTexture(); - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.parent.getParticleTexture(); + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return this.parent.getItemCameraTransforms(); - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return this.parent.getItemCameraTransforms(); + } - @Override - public ItemOverrideList getOverrides() - { - return this.parent.getOverrides(); - } + @Override + public ItemOverrideList getOverrides() { + return this.parent.getOverrides(); + } - @Override - public List getQuads( IBlockState state, EnumFacing side, long rand ) - { - if( !( state instanceof IExtendedBlockState ) ) - { - return this.parent.getQuads( state, side, rand ); - } + @Override + public List getQuads(IBlockState state, EnumFacing side, long rand) { + if (!(state instanceof IExtendedBlockState)) { + return this.parent.getQuads(state, side, rand); + } - IExtendedBlockState extState = (IExtendedBlockState) state; + IExtendedBlockState extState = (IExtendedBlockState) state; - EnumFacing forward = extState.getValue( AEBaseTileBlock.FORWARD ); - EnumFacing up = extState.getValue( AEBaseTileBlock.UP ); + EnumFacing forward = extState.getValue(AEBaseTileBlock.FORWARD); + EnumFacing up = extState.getValue(AEBaseTileBlock.UP); - if( forward == null || up == null ) - { - return this.parent.getQuads( state, side, rand ); - } + if (forward == null || up == null) { + return this.parent.getQuads(state, side, rand); + } - // The model has other properties than just forward/up, so it would cause our cache to inadvertendly also cache - // these - // additional states, possibly leading to huge isseus if the other extended state properties do not implement - // equals/hashCode correctly - if( extState.getUnlistedProperties().size() != 2 ) - { - return this.getRotatedModel( extState, side, forward, up ); - } + // The model has other properties than just forward/up, so it would cause our cache to inadvertendly also cache + // these + // additional states, possibly leading to huge isseus if the other extended state properties do not implement + // equals/hashCode correctly + if (extState.getUnlistedProperties().size() != 2) { + return this.getRotatedModel(extState, side, forward, up); + } - AutoRotatingCacheKey key = new AutoRotatingCacheKey( extState.getClean(), forward, up, side ); + AutoRotatingCacheKey key = new AutoRotatingCacheKey(extState.getClean(), forward, up, side); - return this.quadCache.getUnchecked( key ); - } + return this.quadCache.getUnchecked(key); + } - public static class VertexRotator extends QuadGatheringTransformer - { - private final FacingToRotation f2r; - private final EnumFacing face; + public static class VertexRotator extends QuadGatheringTransformer { + private final FacingToRotation f2r; + private final EnumFacing face; - public VertexRotator( FacingToRotation f2r, EnumFacing face ) - { - this.f2r = f2r; - this.face = face; - } + public VertexRotator(FacingToRotation f2r, EnumFacing face) { + this.f2r = f2r; + this.face = face; + } - @Override - public void setParent( IVertexConsumer parent ) - { - super.setParent( parent ); - if( Objects.equal( this.getVertexFormat(), parent.getVertexFormat() ) ) - { - return; - } - this.setVertexFormat( parent.getVertexFormat() ); - } + @Override + public void setParent(IVertexConsumer parent) { + super.setParent(parent); + if (Objects.equal(this.getVertexFormat(), parent.getVertexFormat())) { + return; + } + this.setVertexFormat(parent.getVertexFormat()); + } - @Override - protected void processQuad() - { - VertexFormat format = this.parent.getVertexFormat(); - int count = format.getElementCount(); + @Override + protected void processQuad() { + VertexFormat format = this.parent.getVertexFormat(); + int count = format.getElementCount(); - for( int v = 0; v < 4; v++ ) - { - for( int e = 0; e < count; e++ ) - { - VertexFormatElement element = format.getElement( e ); - if( element.getUsage() == VertexFormatElement.EnumUsage.POSITION ) - { - this.parent.put( e, this.transform( this.quadData[e][v] ) ); - } - else if( element.getUsage() == VertexFormatElement.EnumUsage.NORMAL ) - { - this.parent.put( e, this.transformNormal( this.quadData[e][v] ) ); - } - else - { - this.parent.put( e, this.quadData[e][v] ); - } - } - } - } + for (int v = 0; v < 4; v++) { + for (int e = 0; e < count; e++) { + VertexFormatElement element = format.getElement(e); + if (element.getUsage() == VertexFormatElement.EnumUsage.POSITION) { + this.parent.put(e, this.transform(this.quadData[e][v])); + } else if (element.getUsage() == VertexFormatElement.EnumUsage.NORMAL) { + this.parent.put(e, this.transformNormal(this.quadData[e][v])); + } else { + this.parent.put(e, this.quadData[e][v]); + } + } + } + } - private float[] transform( float[] fs ) - { - switch( fs.length ) - { - case 3: - Vector3f vec = new Vector3f( fs[0], fs[1], fs[2] ); - vec.x -= 0.5f; - vec.y -= 0.5f; - vec.z -= 0.5f; - this.f2r.getMat().transform( vec ); - vec.x += 0.5f; - vec.y += 0.5f; - vec.z += 0.5f; - return new float[] { vec.x, vec.y, vec.z - }; - case 4: - Vector4f vecc = new Vector4f( fs[0], fs[1], fs[2], fs[3] ); - vecc.x -= 0.5f; - vecc.y -= 0.5f; - vecc.z -= 0.5f; - this.f2r.getMat().transform( vecc ); - vecc.x += 0.5f; - vecc.y += 0.5f; - vecc.z += 0.5f; - return new float[] { vecc.x, vecc.y, vecc.z, vecc.w - }; + private float[] transform(float[] fs) { + switch (fs.length) { + case 3: + Vector3f vec = new Vector3f(fs[0], fs[1], fs[2]); + vec.x -= 0.5f; + vec.y -= 0.5f; + vec.z -= 0.5f; + this.f2r.getMat().transform(vec); + vec.x += 0.5f; + vec.y += 0.5f; + vec.z += 0.5f; + return new float[]{vec.x, vec.y, vec.z + }; + case 4: + Vector4f vecc = new Vector4f(fs[0], fs[1], fs[2], fs[3]); + vecc.x -= 0.5f; + vecc.y -= 0.5f; + vecc.z -= 0.5f; + this.f2r.getMat().transform(vecc); + vecc.x += 0.5f; + vecc.y += 0.5f; + vecc.z += 0.5f; + return new float[]{vecc.x, vecc.y, vecc.z, vecc.w + }; - default: - return fs; - } - } + default: + return fs; + } + } - private float[] transformNormal( float[] fs ) - { - if( this.face == null ) - { - switch( fs.length ) - { - case 3: - Vector3f vec = new Vector3f( fs ); - this.f2r.getMat().transform( vec ); - return new float[] { - vec.getX(), - vec.getY(), - vec.getZ() - }; - case 4: - Vector4f vec4 = new Vector4f( fs ); - this.f2r.getMat().transform( vec4 ); - return new float[] { - vec4.getX(), - vec4.getY(), - vec4.getZ(), - 0 - }; + private float[] transformNormal(float[] fs) { + if (this.face == null) { + switch (fs.length) { + case 3: + Vector3f vec = new Vector3f(fs); + this.f2r.getMat().transform(vec); + return new float[]{ + vec.getX(), + vec.getY(), + vec.getZ() + }; + case 4: + Vector4f vec4 = new Vector4f(fs); + this.f2r.getMat().transform(vec4); + return new float[]{ + vec4.getX(), + vec4.getY(), + vec4.getZ(), + 0 + }; - default: - return fs; - } - } - else - { - switch( fs.length ) - { - case 3: - Vec3i vec = this.f2r.rotate( this.face ).getDirectionVec(); - return new float[] { - vec.getX(), - vec.getY(), - vec.getZ() - }; - case 4: - Vector4f veccc = new Vector4f( fs[0], fs[1], fs[2], fs[3] ); - Vec3i vecc = this.f2r.rotate( this.face ).getDirectionVec(); - return new float[] { - vecc.getX(), - vecc.getY(), - vecc.getZ(), - veccc.w - }; + default: + return fs; + } + } else { + switch (fs.length) { + case 3: + Vec3i vec = this.f2r.rotate(this.face).getDirectionVec(); + return new float[]{ + vec.getX(), + vec.getY(), + vec.getZ() + }; + case 4: + Vector4f veccc = new Vector4f(fs[0], fs[1], fs[2], fs[3]); + Vec3i vecc = this.f2r.rotate(this.face).getDirectionVec(); + return new float[]{ + vecc.getX(), + vecc.getY(), + vecc.getZ(), + veccc.w + }; - default: - return fs; - } - } - } + default: + return fs; + } + } + } - @Override - public void setQuadTint( int tint ) - { - this.parent.setQuadTint( tint ); - } + @Override + public void setQuadTint(int tint) { + this.parent.setQuadTint(tint); + } - @Override - public void setQuadOrientation( EnumFacing orientation ) - { - this.parent.setQuadOrientation( orientation ); - } + @Override + public void setQuadOrientation(EnumFacing orientation) { + this.parent.setQuadOrientation(orientation); + } - @Override - public void setApplyDiffuseLighting( boolean diffuse ) - { - this.parent.setApplyDiffuseLighting( diffuse ); - } + @Override + public void setApplyDiffuseLighting(boolean diffuse) { + this.parent.setApplyDiffuseLighting(diffuse); + } - @Override - public void setTexture( TextureAtlasSprite texture ) - { - this.parent.setTexture( texture ); - } - } + @Override + public void setTexture(TextureAtlasSprite texture) { + this.parent.setTexture(texture); + } + } } diff --git a/src/main/java/appeng/client/render/model/BiometricCardBakedModel.java b/src/main/java/appeng/client/render/model/BiometricCardBakedModel.java index b9e4a1979..3d4c78000 100644 --- a/src/main/java/appeng/client/render/model/BiometricCardBakedModel.java +++ b/src/main/java/appeng/client/render/model/BiometricCardBakedModel.java @@ -1,22 +1,14 @@ - package appeng.client.render.model; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ExecutionException; - -import javax.annotation.Nullable; -import javax.vecmath.Matrix4f; - +import appeng.api.implementations.items.IBiometricCard; +import appeng.api.util.AEColor; +import appeng.client.render.cablebus.CubeBuilder; +import appeng.core.AELog; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableList; import com.mojang.authlib.GameProfile; - -import org.apache.commons.lang3.tuple.Pair; - import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -29,198 +21,166 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; import net.minecraftforge.common.model.TRSRTransformation; +import org.apache.commons.lang3.tuple.Pair; -import appeng.api.implementations.items.IBiometricCard; -import appeng.api.util.AEColor; -import appeng.client.render.cablebus.CubeBuilder; -import appeng.core.AELog; +import javax.annotation.Nullable; +import javax.vecmath.Matrix4f; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ExecutionException; -class BiometricCardBakedModel implements IBakedModel -{ +class BiometricCardBakedModel implements IBakedModel { - private final VertexFormat format; + private final VertexFormat format; - private final IBakedModel baseModel; + private final IBakedModel baseModel; - private final TextureAtlasSprite texture; + private final TextureAtlasSprite texture; - private final int hash; + private final int hash; - private final Cache modelCache; + private final Cache modelCache; - private final ImmutableList generalQuads; + private final ImmutableList generalQuads; - BiometricCardBakedModel( VertexFormat format, IBakedModel baseModel, TextureAtlasSprite texture ) - { - this( format, baseModel, texture, 0, createCache() ); - } + BiometricCardBakedModel(VertexFormat format, IBakedModel baseModel, TextureAtlasSprite texture) { + this(format, baseModel, texture, 0, createCache()); + } - private BiometricCardBakedModel( VertexFormat format, IBakedModel baseModel, TextureAtlasSprite texture, int hash, Cache modelCache ) - { - this.format = format; - this.baseModel = baseModel; - this.texture = texture; - this.hash = hash; - this.generalQuads = ImmutableList.copyOf( this.buildGeneralQuads() ); - this.modelCache = modelCache; - } + private BiometricCardBakedModel(VertexFormat format, IBakedModel baseModel, TextureAtlasSprite texture, int hash, Cache modelCache) { + this.format = format; + this.baseModel = baseModel; + this.texture = texture; + this.hash = hash; + this.generalQuads = ImmutableList.copyOf(this.buildGeneralQuads()); + this.modelCache = modelCache; + } - private static Cache createCache() - { - return CacheBuilder.newBuilder() - .maximumSize( 100 ) - .build(); - } + private static Cache createCache() { + return CacheBuilder.newBuilder() + .maximumSize(100) + .build(); + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { - List quads = this.baseModel.getQuads( state, side, rand ); + List quads = this.baseModel.getQuads(state, side, rand); - if( side != null ) - { - return quads; - } + if (side != null) { + return quads; + } - List result = new ArrayList<>( quads.size() + this.generalQuads.size() ); - result.addAll( quads ); - result.addAll( this.generalQuads ); - return result; - } + List result = new ArrayList<>(quads.size() + this.generalQuads.size()); + result.addAll(quads); + result.addAll(this.generalQuads); + return result; + } - private List buildGeneralQuads() - { - CubeBuilder builder = new CubeBuilder( this.format ); + private List buildGeneralQuads() { + CubeBuilder builder = new CubeBuilder(this.format); - builder.setTexture( this.texture ); + builder.setTexture(this.texture); - AEColor col = AEColor.values()[Math.abs( 3 + this.hash ) % AEColor.values().length]; - if( this.hash == 0 ) - { - col = AEColor.BLACK; - } + AEColor col = AEColor.values()[Math.abs(3 + this.hash) % AEColor.values().length]; + if (this.hash == 0) { + col = AEColor.BLACK; + } - for( int x = 0; x < 8; x++ ) - { - for( int y = 0; y < 6; y++ ) - { - final boolean isLit; + for (int x = 0; x < 8; x++) { + for (int y = 0; y < 6; y++) { + final boolean isLit; - // This makes the border always use the darker color - if( x == 0 || y == 0 || x == 7 || y == 5 ) - { - isLit = false; - } - else - { - isLit = ( this.hash & ( 1 << x ) ) != 0 || ( this.hash & ( 1 << y ) ) != 0; - } + // This makes the border always use the darker color + if (x == 0 || y == 0 || x == 7 || y == 5) { + isLit = false; + } else { + isLit = (this.hash & (1 << x)) != 0 || (this.hash & (1 << y)) != 0; + } - if( isLit ) - { - builder.setColorRGB( col.mediumVariant ); - } - else - { - final float scale = 0.3f / 255.0f; - builder.setColorRGB( ( ( col.blackVariant >> 16 ) & 0xff ) * scale, ( ( col.blackVariant >> 8 ) & 0xff ) * scale, - ( col.blackVariant & 0xff ) * scale ); - } + if (isLit) { + builder.setColorRGB(col.mediumVariant); + } else { + final float scale = 0.3f / 255.0f; + builder.setColorRGB(((col.blackVariant >> 16) & 0xff) * scale, ((col.blackVariant >> 8) & 0xff) * scale, + (col.blackVariant & 0xff) * scale); + } - builder.addCube( 4 + x, 6 + y, 7.5f, 4 + x + 1, 6 + y + 1, 8.5f ); - } - } - return builder.getOutput(); - } + builder.addCube(4 + x, 6 + y, 7.5f, 4 + x + 1, 6 + y + 1, 8.5f); + } + } + return builder.getOutput(); + } - @Override - public boolean isAmbientOcclusion() - { - return this.baseModel.isAmbientOcclusion(); - } + @Override + public boolean isAmbientOcclusion() { + return this.baseModel.isAmbientOcclusion(); + } - @Override - public boolean isGui3d() - { - return this.baseModel.isGui3d(); - } + @Override + public boolean isGui3d() { + return this.baseModel.isGui3d(); + } - @Override - public boolean isBuiltInRenderer() - { - return this.baseModel.isBuiltInRenderer(); - } + @Override + public boolean isBuiltInRenderer() { + return this.baseModel.isBuiltInRenderer(); + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.baseModel.getParticleTexture(); - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.baseModel.getParticleTexture(); + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return this.baseModel.getItemCameraTransforms(); - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return this.baseModel.getItemCameraTransforms(); + } - @Override - public ItemOverrideList getOverrides() - { - return new ItemOverrideList( Collections.emptyList() ) - { - @Override - public IBakedModel handleItemState( IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity ) - { - String username = ""; - if( stack.getItem() instanceof IBiometricCard ) - { - final GameProfile gp = ( (IBiometricCard) stack.getItem() ).getProfile( stack ); - if( gp != null ) - { - if( gp.getId() != null ) - { - username = gp.getId().toString(); - } - else - { - username = gp.getName(); - } - } - } - final int hash = !username.isEmpty() ? username.hashCode() : 0; + @Override + public ItemOverrideList getOverrides() { + return new ItemOverrideList(Collections.emptyList()) { + @Override + public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity) { + String username = ""; + if (stack.getItem() instanceof IBiometricCard) { + final GameProfile gp = ((IBiometricCard) stack.getItem()).getProfile(stack); + if (gp != null) { + if (gp.getId() != null) { + username = gp.getId().toString(); + } else { + username = gp.getName(); + } + } + } + final int hash = !username.isEmpty() ? username.hashCode() : 0; - // Get hash - if( hash == 0 ) - { - return BiometricCardBakedModel.this; - } + // Get hash + if (hash == 0) { + return BiometricCardBakedModel.this; + } - try - { - return BiometricCardBakedModel.this.modelCache.get( hash, - () -> new BiometricCardBakedModel( BiometricCardBakedModel.this.format, BiometricCardBakedModel.this.baseModel, BiometricCardBakedModel.this.texture, hash, BiometricCardBakedModel.this.modelCache ) ); - } - catch( ExecutionException e ) - { - AELog.error( e ); - return BiometricCardBakedModel.this; - } - } - }; - } + try { + return BiometricCardBakedModel.this.modelCache.get(hash, + () -> new BiometricCardBakedModel(BiometricCardBakedModel.this.format, BiometricCardBakedModel.this.baseModel, BiometricCardBakedModel.this.texture, hash, BiometricCardBakedModel.this.modelCache)); + } catch (ExecutionException e) { + AELog.error(e); + return BiometricCardBakedModel.this; + } + } + }; + } - @Override - public Pair handlePerspective( ItemCameraTransforms.TransformType type ) - { - // Delegate to the base model if possible - if( this.baseModel instanceof IBakedModel ) - { - IBakedModel pam = this.baseModel; - Pair pair = pam.handlePerspective( type ); - return Pair.of( this, pair.getValue() ); - } - return Pair.of( this, TRSRTransformation.identity().getMatrix() ); - } + @Override + public Pair handlePerspective(ItemCameraTransforms.TransformType type) { + // Delegate to the base model if possible + if (this.baseModel instanceof IBakedModel) { + IBakedModel pam = this.baseModel; + Pair pair = pam.handlePerspective(type); + return Pair.of(this, pair.getValue()); + } + return Pair.of(this, TRSRTransformation.identity().getMatrix()); + } } diff --git a/src/main/java/appeng/client/render/model/BiometricCardModel.java b/src/main/java/appeng/client/render/model/BiometricCardModel.java index 9ebf4c879..b305492ad 100644 --- a/src/main/java/appeng/client/render/model/BiometricCardModel.java +++ b/src/main/java/appeng/client/render/model/BiometricCardModel.java @@ -1,11 +1,7 @@ - package appeng.client.render.model; -import java.util.Collection; -import java.util.Collections; -import java.util.function.Function; - +import appeng.core.AppEng; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -15,57 +11,50 @@ import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; -import appeng.core.AppEng; +import java.util.Collection; +import java.util.Collections; +import java.util.function.Function; /** * Model wrapper for the biometric card item model, which combines a base card layer with a "visual hash" of the player * name */ -public class BiometricCardModel implements IModel -{ +public class BiometricCardModel implements IModel { - private static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "item/biometric_card" ); - private static final ResourceLocation TEXTURE = new ResourceLocation( AppEng.MOD_ID, "items/biometric_card_hash" ); + private static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "item/biometric_card"); + private static final ResourceLocation TEXTURE = new ResourceLocation(AppEng.MOD_ID, "items/biometric_card_hash"); - @Override - public Collection getDependencies() - { - return Collections.singletonList( MODEL_BASE ); - } + @Override + public Collection getDependencies() { + return Collections.singletonList(MODEL_BASE); + } - @Override - public Collection getTextures() - { - return Collections.singletonList( TEXTURE ); - } + @Override + public Collection getTextures() { + return Collections.singletonList(TEXTURE); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - TextureAtlasSprite texture = bakedTextureGetter.apply( TEXTURE ); + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + TextureAtlasSprite texture = bakedTextureGetter.apply(TEXTURE); - IBakedModel baseModel = this.getBaseModel( state, format, bakedTextureGetter ); + IBakedModel baseModel = this.getBaseModel(state, format, bakedTextureGetter); - return new BiometricCardBakedModel( format, baseModel, texture ); - } + return new BiometricCardBakedModel(format, baseModel, texture); + } - private IBakedModel getBaseModel( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - // Load the base model - try - { - return ModelLoaderRegistry.getModel( MODEL_BASE ).bake( state, format, bakedTextureGetter ); - } - catch( Exception e ) - { - throw new RuntimeException( e ); - } - } + private IBakedModel getBaseModel(IModelState state, VertexFormat format, Function bakedTextureGetter) { + // Load the base model + try { + return ModelLoaderRegistry.getModel(MODEL_BASE).bake(state, format, bakedTextureGetter); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - @Override - public IModelState getDefaultState() - { - return TRSRTransformation.identity(); - } + @Override + public IModelState getDefaultState() { + return TRSRTransformation.identity(); + } } diff --git a/src/main/java/appeng/client/render/model/BuiltInModelLoader.java b/src/main/java/appeng/client/render/model/BuiltInModelLoader.java index 1dc76da83..e547d53ca 100644 --- a/src/main/java/appeng/client/render/model/BuiltInModelLoader.java +++ b/src/main/java/appeng/client/render/model/BuiltInModelLoader.java @@ -19,58 +19,48 @@ package appeng.client.render.model; -import java.util.Map; - +import appeng.core.AppEng; import com.google.common.collect.ImmutableMap; - import net.minecraft.client.resources.IResourceManager; import net.minecraft.client.resources.IResourceManagerReloadListener; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.ICustomModelLoader; import net.minecraftforge.client.model.IModel; -import appeng.core.AppEng; +import java.util.Map; /** * Manages built-in models. */ -public class BuiltInModelLoader implements ICustomModelLoader -{ +public class BuiltInModelLoader implements ICustomModelLoader { - private final Map builtInModels; + private final Map builtInModels; - public BuiltInModelLoader( Map builtInModels ) - { - this.builtInModels = ImmutableMap.copyOf( builtInModels ); - } + public BuiltInModelLoader(Map builtInModels) { + this.builtInModels = ImmutableMap.copyOf(builtInModels); + } - @Override - public boolean accepts( ResourceLocation modelLocation ) - { - if( !modelLocation.getResourceDomain().equals( AppEng.MOD_ID ) ) - { - return false; - } + @Override + public boolean accepts(ResourceLocation modelLocation) { + if (!modelLocation.getResourceDomain().equals(AppEng.MOD_ID)) { + return false; + } - return this.builtInModels.containsKey( modelLocation.getResourcePath() ); - } + return this.builtInModels.containsKey(modelLocation.getResourcePath()); + } - @Override - public IModel loadModel( ResourceLocation modelLocation ) throws Exception - { - return this.builtInModels.get( modelLocation.getResourcePath() ); - } + @Override + public IModel loadModel(ResourceLocation modelLocation) throws Exception { + return this.builtInModels.get(modelLocation.getResourcePath()); + } - @Override - public void onResourceManagerReload( IResourceManager resourceManager ) - { - for( IModel model : this.builtInModels.values() ) - { - if( model instanceof IResourceManagerReloadListener ) - { - ( (IResourceManagerReloadListener) model ).onResourceManagerReload( resourceManager ); - } - } - } + @Override + public void onResourceManagerReload(IResourceManager resourceManager) { + for (IModel model : this.builtInModels.values()) { + if (model instanceof IResourceManagerReloadListener) { + ((IResourceManagerReloadListener) model).onResourceManagerReload(resourceManager); + } + } + } } diff --git a/src/main/java/appeng/client/render/model/ColorApplicatorBakedModel.java b/src/main/java/appeng/client/render/model/ColorApplicatorBakedModel.java index 3657a9025..90011994b 100644 --- a/src/main/java/appeng/client/render/model/ColorApplicatorBakedModel.java +++ b/src/main/java/appeng/client/render/model/ColorApplicatorBakedModel.java @@ -1,18 +1,7 @@ - package appeng.client.render.model; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; - -import javax.annotation.Nullable; -import javax.vecmath.Matrix4f; - import com.google.common.collect.ImmutableMap; - -import org.apache.commons.lang3.tuple.Pair; - import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -22,116 +11,102 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.util.EnumFacing; import net.minecraftforge.client.model.PerspectiveMapWrapper; import net.minecraftforge.common.model.TRSRTransformation; +import org.apache.commons.lang3.tuple.Pair; + +import javax.annotation.Nullable; +import javax.vecmath.Matrix4f; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; -class ColorApplicatorBakedModel implements IBakedModel -{ +class ColorApplicatorBakedModel implements IBakedModel { - private final IBakedModel baseModel; + private final IBakedModel baseModel; - private final ImmutableMap transforms; + private final ImmutableMap transforms; - private final EnumMap> quadsBySide; + private final EnumMap> quadsBySide; - private final List generalQuads; + private final List generalQuads; - ColorApplicatorBakedModel( IBakedModel baseModel, ImmutableMap map, TextureAtlasSprite texDark, TextureAtlasSprite texMedium, TextureAtlasSprite texBright ) - { - this.baseModel = baseModel; - this.transforms = map; + ColorApplicatorBakedModel(IBakedModel baseModel, ImmutableMap map, TextureAtlasSprite texDark, TextureAtlasSprite texMedium, TextureAtlasSprite texBright) { + this.baseModel = baseModel; + this.transforms = map; - // Put the tint indices in... Since this is an item model, we are ignoring rand - this.generalQuads = this.fixQuadTint( null, texDark, texMedium, texBright ); - this.quadsBySide = new EnumMap<>( EnumFacing.class ); - for( EnumFacing facing : EnumFacing.values() ) - { - this.quadsBySide.put( facing, this.fixQuadTint( facing, texDark, texMedium, texBright ) ); - } - } + // Put the tint indices in... Since this is an item model, we are ignoring rand + this.generalQuads = this.fixQuadTint(null, texDark, texMedium, texBright); + this.quadsBySide = new EnumMap<>(EnumFacing.class); + for (EnumFacing facing : EnumFacing.values()) { + this.quadsBySide.put(facing, this.fixQuadTint(facing, texDark, texMedium, texBright)); + } + } - private List fixQuadTint( EnumFacing facing, TextureAtlasSprite texDark, TextureAtlasSprite texMedium, TextureAtlasSprite texBright ) - { - List quads = this.baseModel.getQuads( null, facing, 0 ); - List result = new ArrayList<>( quads.size() ); - for( BakedQuad quad : quads ) - { - int tint; + private List fixQuadTint(EnumFacing facing, TextureAtlasSprite texDark, TextureAtlasSprite texMedium, TextureAtlasSprite texBright) { + List quads = this.baseModel.getQuads(null, facing, 0); + List result = new ArrayList<>(quads.size()); + for (BakedQuad quad : quads) { + int tint; - if( quad.getSprite() == texDark ) - { - tint = 1; - } - else if( quad.getSprite() == texMedium ) - { - tint = 2; - } - else if( quad.getSprite() == texBright ) - { - tint = 3; - } - else - { - result.add( quad ); - continue; - } + if (quad.getSprite() == texDark) { + tint = 1; + } else if (quad.getSprite() == texMedium) { + tint = 2; + } else if (quad.getSprite() == texBright) { + tint = 3; + } else { + result.add(quad); + continue; + } - BakedQuad newQuad = new BakedQuad( quad.getVertexData(), tint, quad.getFace(), quad.getSprite(), quad.shouldApplyDiffuseLighting(), quad - .getFormat() ); - result.add( newQuad ); - } + BakedQuad newQuad = new BakedQuad(quad.getVertexData(), tint, quad.getFace(), quad.getSprite(), quad.shouldApplyDiffuseLighting(), quad + .getFormat()); + result.add(newQuad); + } - return result; - } + return result; + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - if( side == null ) - { - return this.generalQuads; - } - return this.quadsBySide.get( side ); - } + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + if (side == null) { + return this.generalQuads; + } + return this.quadsBySide.get(side); + } - @Override - public boolean isAmbientOcclusion() - { - return this.baseModel.isAmbientOcclusion(); - } + @Override + public boolean isAmbientOcclusion() { + return this.baseModel.isAmbientOcclusion(); + } - @Override - public boolean isGui3d() - { - return this.baseModel.isGui3d(); - } + @Override + public boolean isGui3d() { + return this.baseModel.isGui3d(); + } - @Override - public boolean isBuiltInRenderer() - { - return this.baseModel.isBuiltInRenderer(); - } + @Override + public boolean isBuiltInRenderer() { + return this.baseModel.isBuiltInRenderer(); + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.baseModel.getParticleTexture(); - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.baseModel.getParticleTexture(); + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return this.baseModel.getItemCameraTransforms(); - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return this.baseModel.getItemCameraTransforms(); + } - @Override - public ItemOverrideList getOverrides() - { - return this.baseModel.getOverrides(); - } + @Override + public ItemOverrideList getOverrides() { + return this.baseModel.getOverrides(); + } - @Override - public Pair handlePerspective( ItemCameraTransforms.TransformType type ) - { - return PerspectiveMapWrapper.handlePerspective( this, this.transforms, type ); - } + @Override + public Pair handlePerspective(ItemCameraTransforms.TransformType type) { + return PerspectiveMapWrapper.handlePerspective(this, this.transforms, type); + } } diff --git a/src/main/java/appeng/client/render/model/ColorApplicatorModel.java b/src/main/java/appeng/client/render/model/ColorApplicatorModel.java index 23a5fa9d9..1926c46b0 100644 --- a/src/main/java/appeng/client/render/model/ColorApplicatorModel.java +++ b/src/main/java/appeng/client/render/model/ColorApplicatorModel.java @@ -1,14 +1,9 @@ - package appeng.client.render.model; -import java.util.Collection; -import java.util.Collections; -import java.util.function.Function; - +import appeng.core.AppEng; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; - import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -20,67 +15,60 @@ import net.minecraftforge.client.model.PerspectiveMapWrapper; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; -import appeng.core.AppEng; +import java.util.Collection; +import java.util.Collections; +import java.util.function.Function; /** * A color applicator uses the base model, and extends it with additional layers that are colored according to the * selected color of the applicator. */ -public class ColorApplicatorModel implements IModel -{ +public class ColorApplicatorModel implements IModel { - private static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "item/color_applicator_colored" ); + private static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "item/color_applicator_colored"); - private static final ResourceLocation TEXTURE_DARK = new ResourceLocation( AppEng.MOD_ID, "items/color_applicator_tip_dark" ); - private static final ResourceLocation TEXTURE_MEDIUM = new ResourceLocation( AppEng.MOD_ID, "items/color_applicator_tip_medium" ); - private static final ResourceLocation TEXTURE_BRIGHT = new ResourceLocation( AppEng.MOD_ID, "items/color_applicator_tip_bright" ); + private static final ResourceLocation TEXTURE_DARK = new ResourceLocation(AppEng.MOD_ID, "items/color_applicator_tip_dark"); + private static final ResourceLocation TEXTURE_MEDIUM = new ResourceLocation(AppEng.MOD_ID, "items/color_applicator_tip_medium"); + private static final ResourceLocation TEXTURE_BRIGHT = new ResourceLocation(AppEng.MOD_ID, "items/color_applicator_tip_bright"); - @Override - public Collection getDependencies() - { - return Collections.singletonList( MODEL_BASE ); - } + @Override + public Collection getDependencies() { + return Collections.singletonList(MODEL_BASE); + } - @Override - public Collection getTextures() - { - return ImmutableList.of( - TEXTURE_DARK, - TEXTURE_MEDIUM, - TEXTURE_BRIGHT ); - } + @Override + public Collection getTextures() { + return ImmutableList.of( + TEXTURE_DARK, + TEXTURE_MEDIUM, + TEXTURE_BRIGHT); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - IBakedModel baseModel = this.getBaseModel( state, format, bakedTextureGetter ); + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + IBakedModel baseModel = this.getBaseModel(state, format, bakedTextureGetter); - TextureAtlasSprite texDark = bakedTextureGetter.apply( TEXTURE_DARK ); - TextureAtlasSprite texMedium = bakedTextureGetter.apply( TEXTURE_MEDIUM ); - TextureAtlasSprite texBright = bakedTextureGetter.apply( TEXTURE_BRIGHT ); + TextureAtlasSprite texDark = bakedTextureGetter.apply(TEXTURE_DARK); + TextureAtlasSprite texMedium = bakedTextureGetter.apply(TEXTURE_MEDIUM); + TextureAtlasSprite texBright = bakedTextureGetter.apply(TEXTURE_BRIGHT); - ImmutableMap map = PerspectiveMapWrapper.getTransforms( state ); + ImmutableMap map = PerspectiveMapWrapper.getTransforms(state); - return new ColorApplicatorBakedModel( baseModel, map, texDark, texMedium, texBright ); - } + return new ColorApplicatorBakedModel(baseModel, map, texDark, texMedium, texBright); + } - private IBakedModel getBaseModel( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - // Load the base model - try - { - return ModelLoaderRegistry.getModel( MODEL_BASE ).bake( state, format, bakedTextureGetter ); - } - catch( Exception e ) - { - throw new RuntimeException( e ); - } - } + private IBakedModel getBaseModel(IModelState state, VertexFormat format, Function bakedTextureGetter) { + // Load the base model + try { + return ModelLoaderRegistry.getModel(MODEL_BASE).bake(state, format, bakedTextureGetter); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - @Override - public IModelState getDefaultState() - { - return TRSRTransformation.identity(); - } + @Override + public IModelState getDefaultState() { + return TRSRTransformation.identity(); + } } diff --git a/src/main/java/appeng/client/render/model/DriveBakedModel.java b/src/main/java/appeng/client/render/model/DriveBakedModel.java index 7835b9c5b..0d88dc8e5 100644 --- a/src/main/java/appeng/client/render/model/DriveBakedModel.java +++ b/src/main/java/appeng/client/render/model/DriveBakedModel.java @@ -40,101 +40,87 @@ import java.util.List; import java.util.Map; -public class DriveBakedModel implements IBakedModel -{ - private final IBakedModel bakedBase; - private final Map bakedCells; +public class DriveBakedModel implements IBakedModel { + private final IBakedModel bakedBase; + private final Map bakedCells; - public DriveBakedModel( IBakedModel bakedBase, Map bakedCells ) - { - this.bakedBase = bakedBase; - this.bakedCells = bakedCells; - } + public DriveBakedModel(IBakedModel bakedBase, Map bakedCells) { + this.bakedBase = bakedBase; + this.bakedCells = bakedCells; + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { - List result = new ArrayList<>( this.bakedBase.getQuads( state, side, rand ) ); + List result = new ArrayList<>(this.bakedBase.getQuads(state, side, rand)); - if( side == null && state instanceof IExtendedBlockState ) - { - IExtendedBlockState extState = (IExtendedBlockState) state; + if (side == null && state instanceof IExtendedBlockState) { + IExtendedBlockState extState = (IExtendedBlockState) state; - if (!extState.getUnlistedNames().contains( BlockDrive.SLOTS_STATE )) - { - return result; - } + if (!extState.getUnlistedNames().contains(BlockDrive.SLOTS_STATE)) { + return result; + } - DriveSlotsState slotsState = extState.getValue( BlockDrive.SLOTS_STATE ); + DriveSlotsState slotsState = extState.getValue(BlockDrive.SLOTS_STATE); - for( int row = 0; row < 5; row++ ) - { - for( int col = 0; col < 2; col++ ) - { - DriveSlotState slotState = slotsState.getState( row * 2 + col ); + for (int row = 0; row < 5; row++) { + for (int col = 0; col < 2; col++) { + DriveSlotState slotState = slotsState.getState(row * 2 + col); - IBakedModel bakedCell = this.bakedCells.get( slotState ); + IBakedModel bakedCell = this.bakedCells.get(slotState); - Matrix4f transform = new Matrix4f(); - transform.setIdentity(); + Matrix4f transform = new Matrix4f(); + transform.setIdentity(); - // Position this drive model copy at the correct slot. The transform is based on the - // cell-model being in slot 0,0 at the top left of the drive. - float xOffset = -col * 7 / 16.0f; - float yOffset = -row * 3 / 16.0f; + // Position this drive model copy at the correct slot. The transform is based on the + // cell-model being in slot 0,0 at the top left of the drive. + float xOffset = -col * 7 / 16.0f; + float yOffset = -row * 3 / 16.0f; - transform.setTranslation( new Vector3f( xOffset, yOffset, 0 ) ); + transform.setTranslation(new Vector3f(xOffset, yOffset, 0)); - MatrixVertexTransformer transformer = new MatrixVertexTransformer( transform ); - for( BakedQuad bakedQuad : bakedCell.getQuads( state, null, rand ) ) - { - UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder( bakedQuad.getFormat() ); - transformer.setParent( builder ); - transformer.setVertexFormat( builder.getVertexFormat() ); - bakedQuad.pipe( transformer ); - result.add( builder.build() ); - } - } - } - } + MatrixVertexTransformer transformer = new MatrixVertexTransformer(transform); + for (BakedQuad bakedQuad : bakedCell.getQuads(state, null, rand)) { + UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder(bakedQuad.getFormat()); + transformer.setParent(builder); + transformer.setVertexFormat(builder.getVertexFormat()); + bakedQuad.pipe(transformer); + result.add(builder.build()); + } + } + } + } - return result; - } + return result; + } - @Override - public boolean isAmbientOcclusion() - { - return this.bakedBase.isAmbientOcclusion(); - } + @Override + public boolean isAmbientOcclusion() { + return this.bakedBase.isAmbientOcclusion(); + } - @Override - public boolean isGui3d() - { - return this.bakedBase.isGui3d(); - } + @Override + public boolean isGui3d() { + return this.bakedBase.isGui3d(); + } - @Override - public boolean isBuiltInRenderer() - { - return this.bakedBase.isGui3d(); - } + @Override + public boolean isBuiltInRenderer() { + return this.bakedBase.isGui3d(); + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.bakedBase.getParticleTexture(); - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.bakedBase.getParticleTexture(); + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return this.bakedBase.getItemCameraTransforms(); - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return this.bakedBase.getItemCameraTransforms(); + } - @Override - public ItemOverrideList getOverrides() - { - return this.bakedBase.getOverrides(); - } + @Override + public ItemOverrideList getOverrides() { + return this.bakedBase.getOverrides(); + } } diff --git a/src/main/java/appeng/client/render/model/DriveModel.java b/src/main/java/appeng/client/render/model/DriveModel.java index b9a253505..4cd20df46 100644 --- a/src/main/java/appeng/client/render/model/DriveModel.java +++ b/src/main/java/appeng/client/render/model/DriveModel.java @@ -19,15 +19,9 @@ package appeng.client.render.model; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumMap; -import java.util.Map; -import java.util.function.Function; - +import appeng.block.storage.DriveSlotState; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; - import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -37,61 +31,56 @@ import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; -import appeng.block.storage.DriveSlotState; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumMap; +import java.util.Map; +import java.util.function.Function; -public class DriveModel implements IModel -{ +public class DriveModel implements IModel { - private static final ResourceLocation MODEL_BASE = new ResourceLocation( "appliedenergistics2:block/drive_base" ); + private static final ResourceLocation MODEL_BASE = new ResourceLocation("appliedenergistics2:block/drive_base"); - private static final Map MODELS_CELLS = ImmutableMap.of( - DriveSlotState.EMPTY, new ResourceLocation( "appliedenergistics2:block/drive_cell_empty" ), - DriveSlotState.OFFLINE, new ResourceLocation( "appliedenergistics2:block/drive_cell_off" ), - DriveSlotState.ONLINE, new ResourceLocation( "appliedenergistics2:block/drive_cell_on" ), - DriveSlotState.TYPES_FULL, new ResourceLocation( "appliedenergistics2:block/drive_cell_types_full" ), - DriveSlotState.FULL, new ResourceLocation( "appliedenergistics2:block/drive_cell_full" ) ); + private static final Map MODELS_CELLS = ImmutableMap.of( + DriveSlotState.EMPTY, new ResourceLocation("appliedenergistics2:block/drive_cell_empty"), + DriveSlotState.OFFLINE, new ResourceLocation("appliedenergistics2:block/drive_cell_off"), + DriveSlotState.ONLINE, new ResourceLocation("appliedenergistics2:block/drive_cell_on"), + DriveSlotState.TYPES_FULL, new ResourceLocation("appliedenergistics2:block/drive_cell_types_full"), + DriveSlotState.FULL, new ResourceLocation("appliedenergistics2:block/drive_cell_full")); - @Override - public Collection getDependencies() - { - return ImmutableList.builder().add( MODEL_BASE ).addAll( MODELS_CELLS.values() ).build(); - } + @Override + public Collection getDependencies() { + return ImmutableList.builder().add(MODEL_BASE).addAll(MODELS_CELLS.values()).build(); + } - @Override - public Collection getTextures() - { - return Collections.emptyList(); - } + @Override + public Collection getTextures() { + return Collections.emptyList(); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - EnumMap cellModels = new EnumMap<>( DriveSlotState.class ); + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + EnumMap cellModels = new EnumMap<>(DriveSlotState.class); - // Load the base model and the model for each cell state. - IModel baseModel; - try - { - baseModel = ModelLoaderRegistry.getModel( MODEL_BASE ); - for( DriveSlotState slotState : MODELS_CELLS.keySet() ) - { - IModel model = ModelLoaderRegistry.getModel( MODELS_CELLS.get( slotState ) ); - cellModels.put( slotState, model.bake( state, format, bakedTextureGetter ) ); - } - } - catch( Exception e ) - { - throw new RuntimeException( e ); - } + // Load the base model and the model for each cell state. + IModel baseModel; + try { + baseModel = ModelLoaderRegistry.getModel(MODEL_BASE); + for (DriveSlotState slotState : MODELS_CELLS.keySet()) { + IModel model = ModelLoaderRegistry.getModel(MODELS_CELLS.get(slotState)); + cellModels.put(slotState, model.bake(state, format, bakedTextureGetter)); + } + } catch (Exception e) { + throw new RuntimeException(e); + } - IBakedModel bakedBase = baseModel.bake( state, format, bakedTextureGetter ); - return new DriveBakedModel( bakedBase, cellModels ); - } + IBakedModel bakedBase = baseModel.bake(state, format, bakedTextureGetter); + return new DriveBakedModel(bakedBase, cellModels); + } - @Override - public IModelState getDefaultState() - { - return TRSRTransformation.identity(); - } + @Override + public IModelState getDefaultState() { + return TRSRTransformation.identity(); + } } diff --git a/src/main/java/appeng/client/render/model/GlassBakedModel.java b/src/main/java/appeng/client/render/model/GlassBakedModel.java index 72b0fdcbc..621a6fc5c 100644 --- a/src/main/java/appeng/client/render/model/GlassBakedModel.java +++ b/src/main/java/appeng/client/render/model/GlassBakedModel.java @@ -19,17 +19,9 @@ package appeng.client.render.model; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Random; -import java.util.function.Function; -import java.util.stream.IntStream; - -import javax.annotation.Nullable; - +import appeng.decorative.solid.BlockQuartzGlass; +import appeng.decorative.solid.GlassState; import com.google.common.base.Strings; - import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -44,276 +36,250 @@ import net.minecraft.util.math.Vec3d; import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad; import net.minecraftforge.common.property.IExtendedBlockState; -import appeng.decorative.solid.BlockQuartzGlass; -import appeng.decorative.solid.GlassState; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.function.Function; +import java.util.stream.IntStream; -class GlassBakedModel implements IBakedModel -{ +class GlassBakedModel implements IBakedModel { - private static final byte[][][] OFFSETS = generateOffsets(); + private static final byte[][][] OFFSETS = generateOffsets(); - // Alternating textures based on position - static final ResourceLocation TEXTURE_A = new ResourceLocation( "appliedenergistics2:blocks/glass/quartz_glass_a" ); - static final ResourceLocation TEXTURE_B = new ResourceLocation( "appliedenergistics2:blocks/glass/quartz_glass_b" ); - static final ResourceLocation TEXTURE_C = new ResourceLocation( "appliedenergistics2:blocks/glass/quartz_glass_c" ); - static final ResourceLocation TEXTURE_D = new ResourceLocation( "appliedenergistics2:blocks/glass/quartz_glass_d" ); + // Alternating textures based on position + static final ResourceLocation TEXTURE_A = new ResourceLocation("appliedenergistics2:blocks/glass/quartz_glass_a"); + static final ResourceLocation TEXTURE_B = new ResourceLocation("appliedenergistics2:blocks/glass/quartz_glass_b"); + static final ResourceLocation TEXTURE_C = new ResourceLocation("appliedenergistics2:blocks/glass/quartz_glass_c"); + static final ResourceLocation TEXTURE_D = new ResourceLocation("appliedenergistics2:blocks/glass/quartz_glass_d"); - // Frame texture - static final ResourceLocation[] TEXTURES_FRAME = generateTexturesFrame(); + // Frame texture + static final ResourceLocation[] TEXTURES_FRAME = generateTexturesFrame(); - // Generates the required textures for the frame - private static ResourceLocation[] generateTexturesFrame() - { - return IntStream.range( 1, 16 ) - .mapToObj( Integer::toBinaryString ) - .map( s -> Strings.padStart( s, 4, '0' ) ) - .map( s -> new ResourceLocation( "appliedenergistics2:blocks/glass/quartz_glass_frame" + s ) ) - .toArray( ResourceLocation[]::new ); - } + // Generates the required textures for the frame + private static ResourceLocation[] generateTexturesFrame() { + return IntStream.range(1, 16) + .mapToObj(Integer::toBinaryString) + .map(s -> Strings.padStart(s, 4, '0')) + .map(s -> new ResourceLocation("appliedenergistics2:blocks/glass/quartz_glass_frame" + s)) + .toArray(ResourceLocation[]::new); + } - private final TextureAtlasSprite[] glassTextures; + private final TextureAtlasSprite[] glassTextures; - private final TextureAtlasSprite[] frameTextures; + private final TextureAtlasSprite[] frameTextures; - private final VertexFormat vertexFormat; + private final VertexFormat vertexFormat; - public GlassBakedModel( VertexFormat format, Function bakedTextureGetter ) - { - this.glassTextures = new TextureAtlasSprite[] { - bakedTextureGetter.apply( TEXTURE_A ), - bakedTextureGetter.apply( TEXTURE_B ), - bakedTextureGetter.apply( TEXTURE_C ), - bakedTextureGetter.apply( TEXTURE_D ) - }; + public GlassBakedModel(VertexFormat format, Function bakedTextureGetter) { + this.glassTextures = new TextureAtlasSprite[]{ + bakedTextureGetter.apply(TEXTURE_A), + bakedTextureGetter.apply(TEXTURE_B), + bakedTextureGetter.apply(TEXTURE_C), + bakedTextureGetter.apply(TEXTURE_D) + }; - this.vertexFormat = format; + this.vertexFormat = format; - // The first frame texture would be empty, so we simply leave it set to null here - this.frameTextures = new TextureAtlasSprite[16]; - for( int i = 0; i < TEXTURES_FRAME.length; i++ ) - { - this.frameTextures[1 + i] = bakedTextureGetter.apply( TEXTURES_FRAME[i] ); - } - } + // The first frame texture would be empty, so we simply leave it set to null here + this.frameTextures = new TextureAtlasSprite[16]; + for (int i = 0; i < TEXTURES_FRAME.length; i++) { + this.frameTextures[1 + i] = bakedTextureGetter.apply(TEXTURES_FRAME[i]); + } + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - if( !( state instanceof IExtendedBlockState ) || side == null ) - { - return Collections.emptyList(); - } + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + if (!(state instanceof IExtendedBlockState) || side == null) { + return Collections.emptyList(); + } - final IExtendedBlockState extState = (IExtendedBlockState) state; - final GlassState glassState = extState.getValue( BlockQuartzGlass.GLASS_STATE ); + final IExtendedBlockState extState = (IExtendedBlockState) state; + final GlassState glassState = extState.getValue(BlockQuartzGlass.GLASS_STATE); - if( glassState == null ) - { - return Collections.emptyList(); - } + if (glassState == null) { + return Collections.emptyList(); + } - final int cx = Math.abs( glassState.getX() % 10 ); - final int cy = Math.abs( glassState.getY() % 10 ); - final int cz = Math.abs( glassState.getZ() % 10 ); + final int cx = Math.abs(glassState.getX() % 10); + final int cy = Math.abs(glassState.getY() % 10); + final int cz = Math.abs(glassState.getZ() % 10); - int u = OFFSETS[cx][cy][cz] % 4; - int v = OFFSETS[9 - cx][9 - cy][9 - cz] % 4; + int u = OFFSETS[cx][cy][cz] % 4; + int v = OFFSETS[9 - cx][9 - cy][9 - cz] % 4; - int texIdx = Math.abs( ( OFFSETS[cx][cy][cz] + ( glassState.getX() + glassState.getY() + glassState.getZ() ) ) % 4 ); + int texIdx = Math.abs((OFFSETS[cx][cy][cz] + (glassState.getX() + glassState.getY() + glassState.getZ())) % 4); - if( texIdx < 2 ) - { - u /= 2; - v /= 2; - } + if (texIdx < 2) { + u /= 2; + v /= 2; + } - final TextureAtlasSprite glassTexture = this.glassTextures[texIdx]; + final TextureAtlasSprite glassTexture = this.glassTextures[texIdx]; - // Render the glass side - final List quads = new ArrayList<>( 5 ); // At most 5 + // Render the glass side + final List quads = new ArrayList<>(5); // At most 5 - final List corners = RenderHelper.getFaceCorners( side ); - quads.add( this.createQuad( side, corners, glassTexture, u, v ) ); + final List corners = RenderHelper.getFaceCorners(side); + quads.add(this.createQuad(side, corners, glassTexture, u, v)); - /* - * This needs some explanation: - * The bit-field contains 4-bits, one for each direction that a frame may be drawn. - * Converted to a number, the bit-field is then used as an index into the list of - * frame textures, which have been created in such a way that their filenames - * indicate, in which directions they contain borders. - * i.e. bitmask = 0101 means a border should be drawn up and down (in terms of u,v space). - * Converted to a number, this bitmask is 5. So the texture at index 5 is used. - * That texture had "0101" in its filename to indicate this. - */ - final int edgeBitmask = makeBitmask( glassState, side ); - final TextureAtlasSprite sideSprite = this.frameTextures[edgeBitmask]; + /* + * This needs some explanation: + * The bit-field contains 4-bits, one for each direction that a frame may be drawn. + * Converted to a number, the bit-field is then used as an index into the list of + * frame textures, which have been created in such a way that their filenames + * indicate, in which directions they contain borders. + * i.e. bitmask = 0101 means a border should be drawn up and down (in terms of u,v space). + * Converted to a number, this bitmask is 5. So the texture at index 5 is used. + * That texture had "0101" in its filename to indicate this. + */ + final int edgeBitmask = makeBitmask(glassState, side); + final TextureAtlasSprite sideSprite = this.frameTextures[edgeBitmask]; - if( sideSprite != null ) - { - quads.add( this.createQuad( side, corners, sideSprite, 0, 0 ) ); - } + if (sideSprite != null) { + quads.add(this.createQuad(side, corners, sideSprite, 0, 0)); + } - return quads; - } + return quads; + } - /** - * Creates the bitmask that indicates, in which directions (in terms of u,v space) a border should be drawn. - */ - private static int makeBitmask( GlassState state, EnumFacing side ) - { - switch( side ) - { - case DOWN: - return makeBitmask( state, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.NORTH, EnumFacing.WEST ); - case UP: - return makeBitmask( state, EnumFacing.SOUTH, EnumFacing.WEST, EnumFacing.NORTH, EnumFacing.EAST ); - case NORTH: - return makeBitmask( state, EnumFacing.UP, EnumFacing.WEST, EnumFacing.DOWN, EnumFacing.EAST ); - case SOUTH: - return makeBitmask( state, EnumFacing.UP, EnumFacing.EAST, EnumFacing.DOWN, EnumFacing.WEST ); - case WEST: - return makeBitmask( state, EnumFacing.UP, EnumFacing.SOUTH, EnumFacing.DOWN, EnumFacing.NORTH ); - case EAST: - return makeBitmask( state, EnumFacing.UP, EnumFacing.NORTH, EnumFacing.DOWN, EnumFacing.SOUTH ); - default: - throw new IllegalArgumentException( "Unsupported side!" ); - } - } + /** + * Creates the bitmask that indicates, in which directions (in terms of u,v space) a border should be drawn. + */ + private static int makeBitmask(GlassState state, EnumFacing side) { + switch (side) { + case DOWN: + return makeBitmask(state, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.NORTH, EnumFacing.WEST); + case UP: + return makeBitmask(state, EnumFacing.SOUTH, EnumFacing.WEST, EnumFacing.NORTH, EnumFacing.EAST); + case NORTH: + return makeBitmask(state, EnumFacing.UP, EnumFacing.WEST, EnumFacing.DOWN, EnumFacing.EAST); + case SOUTH: + return makeBitmask(state, EnumFacing.UP, EnumFacing.EAST, EnumFacing.DOWN, EnumFacing.WEST); + case WEST: + return makeBitmask(state, EnumFacing.UP, EnumFacing.SOUTH, EnumFacing.DOWN, EnumFacing.NORTH); + case EAST: + return makeBitmask(state, EnumFacing.UP, EnumFacing.NORTH, EnumFacing.DOWN, EnumFacing.SOUTH); + default: + throw new IllegalArgumentException("Unsupported side!"); + } + } - private static int makeBitmask( GlassState state, EnumFacing up, EnumFacing right, EnumFacing down, EnumFacing left ) - { + private static int makeBitmask(GlassState state, EnumFacing up, EnumFacing right, EnumFacing down, EnumFacing left) { - int bitmask = 0; + int bitmask = 0; - if( !state.isFlushWith( up ) ) - { - bitmask |= 1; - } - if( !state.isFlushWith( right ) ) - { - bitmask |= 2; - } - if( !state.isFlushWith( down ) ) - { - bitmask |= 4; - } - if( !state.isFlushWith( left ) ) - { - bitmask |= 8; - } - return bitmask; - } + if (!state.isFlushWith(up)) { + bitmask |= 1; + } + if (!state.isFlushWith(right)) { + bitmask |= 2; + } + if (!state.isFlushWith(down)) { + bitmask |= 4; + } + if (!state.isFlushWith(left)) { + bitmask |= 8; + } + return bitmask; + } - private BakedQuad createQuad( EnumFacing side, List corners, TextureAtlasSprite sprite, float uOffset, float vOffset ) - { - return this.createQuad( side, corners.get( 0 ), corners.get( 1 ), corners.get( 2 ), corners.get( 3 ), sprite, uOffset, vOffset ); - } + private BakedQuad createQuad(EnumFacing side, List corners, TextureAtlasSprite sprite, float uOffset, float vOffset) { + return this.createQuad(side, corners.get(0), corners.get(1), corners.get(2), corners.get(3), sprite, uOffset, vOffset); + } - private BakedQuad createQuad( EnumFacing side, Vec3d c1, Vec3d c2, Vec3d c3, Vec3d c4, TextureAtlasSprite sprite, float uOffset, float vOffset ) - { - Vec3d normal = new Vec3d( side.getDirectionVec() ); + private BakedQuad createQuad(EnumFacing side, Vec3d c1, Vec3d c2, Vec3d c3, Vec3d c4, TextureAtlasSprite sprite, float uOffset, float vOffset) { + Vec3d normal = new Vec3d(side.getDirectionVec()); - // Apply the u,v shift. - // This mirrors the logic from OffsetIcon from 1.7 - float u1 = MathHelper.clamp( 0 - uOffset, 0, 16 ); - float u2 = MathHelper.clamp( 16 - uOffset, 0, 16 ); - float v1 = MathHelper.clamp( 0 - vOffset, 0, 16 ); - float v2 = MathHelper.clamp( 16 - vOffset, 0, 16 ); + // Apply the u,v shift. + // This mirrors the logic from OffsetIcon from 1.7 + float u1 = MathHelper.clamp(0 - uOffset, 0, 16); + float u2 = MathHelper.clamp(16 - uOffset, 0, 16); + float v1 = MathHelper.clamp(0 - vOffset, 0, 16); + float v2 = MathHelper.clamp(16 - vOffset, 0, 16); - UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder( this.vertexFormat ); - builder.setTexture( sprite ); - this.putVertex( builder, normal, c1.x, c1.y, c1.z, sprite, u1, v1 ); - this.putVertex( builder, normal, c2.x, c2.y, c2.z, sprite, u1, v2 ); - this.putVertex( builder, normal, c3.x, c3.y, c3.z, sprite, u2, v2 ); - this.putVertex( builder, normal, c4.x, c4.y, c4.z, sprite, u2, v1 ); - return builder.build(); - } + UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder(this.vertexFormat); + builder.setTexture(sprite); + this.putVertex(builder, normal, c1.x, c1.y, c1.z, sprite, u1, v1); + this.putVertex(builder, normal, c2.x, c2.y, c2.z, sprite, u1, v2); + this.putVertex(builder, normal, c3.x, c3.y, c3.z, sprite, u2, v2); + this.putVertex(builder, normal, c4.x, c4.y, c4.z, sprite, u2, v1); + return builder.build(); + } - /* - * This method is as complicated as it is, because the order in which we push data into the vertexbuffer actually - * has to be precisely the order - * in which the vertex elements had been declared in the vertex format. - */ - private void putVertex( UnpackedBakedQuad.Builder builder, Vec3d normal, double x, double y, double z, TextureAtlasSprite sprite, float u, float v ) - { - for( int e = 0; e < this.vertexFormat.getElementCount(); e++ ) - { - switch( this.vertexFormat.getElement( e ).getUsage() ) - { - case POSITION: - builder.put( e, (float) x, (float) y, (float) z, 1.0f ); - break; - case COLOR: - builder.put( e, 1.0f, 1.0f, 1.0f, 1.0f ); - break; - case UV: - if( this.vertexFormat.getElement( e ).getIndex() == 0 ) - { - u = sprite.getInterpolatedU( u ); - v = sprite.getInterpolatedV( v ); - builder.put( e, u, v, 0f, 1f ); - break; - } - case NORMAL: - builder.put( e, (float) normal.x, (float) normal.y, (float) normal.z, 0f ); - break; - default: - builder.put( e ); - break; - } - } - } + /* + * This method is as complicated as it is, because the order in which we push data into the vertexbuffer actually + * has to be precisely the order + * in which the vertex elements had been declared in the vertex format. + */ + private void putVertex(UnpackedBakedQuad.Builder builder, Vec3d normal, double x, double y, double z, TextureAtlasSprite sprite, float u, float v) { + for (int e = 0; e < this.vertexFormat.getElementCount(); e++) { + switch (this.vertexFormat.getElement(e).getUsage()) { + case POSITION: + builder.put(e, (float) x, (float) y, (float) z, 1.0f); + break; + case COLOR: + builder.put(e, 1.0f, 1.0f, 1.0f, 1.0f); + break; + case UV: + if (this.vertexFormat.getElement(e).getIndex() == 0) { + u = sprite.getInterpolatedU(u); + v = sprite.getInterpolatedV(v); + builder.put(e, u, v, 0f, 1f); + break; + } + case NORMAL: + builder.put(e, (float) normal.x, (float) normal.y, (float) normal.z, 0f); + break; + default: + builder.put(e); + break; + } + } + } - @Override - public ItemOverrideList getOverrides() - { - return ItemOverrideList.NONE; - } + @Override + public ItemOverrideList getOverrides() { + return ItemOverrideList.NONE; + } - @Override - public boolean isAmbientOcclusion() - { - return false; - } + @Override + public boolean isAmbientOcclusion() { + return false; + } - @Override - public boolean isGui3d() - { - return false; - } + @Override + public boolean isGui3d() { + return false; + } - @Override - public boolean isBuiltInRenderer() - { - return false; - } + @Override + public boolean isBuiltInRenderer() { + return false; + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.frameTextures[this.frameTextures.length - 1]; - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.frameTextures[this.frameTextures.length - 1]; + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return ItemCameraTransforms.DEFAULT; - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return ItemCameraTransforms.DEFAULT; + } - private static byte[][][] generateOffsets() - { - final Random r = new Random( 924 ); - final byte[][][] offset = new byte[10][10][10]; + private static byte[][][] generateOffsets() { + final Random r = new Random(924); + final byte[][][] offset = new byte[10][10][10]; - for( int x = 0; x < 10; x++ ) - { - for( int y = 0; y < 10; y++ ) - { - r.nextBytes( offset[x][y] ); - } - } + for (int x = 0; x < 10; x++) { + for (int y = 0; y < 10; y++) { + r.nextBytes(offset[x][y]); + } + } - return offset; - } + return offset; + } } diff --git a/src/main/java/appeng/client/render/model/GlassModel.java b/src/main/java/appeng/client/render/model/GlassModel.java index 6ccae53da..7070df089 100644 --- a/src/main/java/appeng/client/render/model/GlassModel.java +++ b/src/main/java/appeng/client/render/model/GlassModel.java @@ -19,12 +19,7 @@ package appeng.client.render.model; -import java.util.Collection; -import java.util.Collections; -import java.util.function.Function; - import com.google.common.collect.ImmutableSet; - import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -33,38 +28,37 @@ import net.minecraftforge.client.model.IModel; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; +import java.util.Collection; +import java.util.Collections; +import java.util.function.Function; + /** * Model class for the connected texture glass model. */ -public class GlassModel implements IModel -{ +public class GlassModel implements IModel { - @Override - public Collection getDependencies() - { - return Collections.emptySet(); - } + @Override + public Collection getDependencies() { + return Collections.emptySet(); + } - @Override - public Collection getTextures() - { - return ImmutableSet.builder() - .add( GlassBakedModel.TEXTURE_A, GlassBakedModel.TEXTURE_B, GlassBakedModel.TEXTURE_C, GlassBakedModel.TEXTURE_D ) - .add( GlassBakedModel.TEXTURES_FRAME ) - .build(); - } + @Override + public Collection getTextures() { + return ImmutableSet.builder() + .add(GlassBakedModel.TEXTURE_A, GlassBakedModel.TEXTURE_B, GlassBakedModel.TEXTURE_C, GlassBakedModel.TEXTURE_D) + .add(GlassBakedModel.TEXTURES_FRAME) + .build(); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - return new GlassBakedModel( format, bakedTextureGetter ); - } + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + return new GlassBakedModel(format, bakedTextureGetter); + } - @Override - public IModelState getDefaultState() - { - return TRSRTransformation.identity(); - } + @Override + public IModelState getDefaultState() { + return TRSRTransformation.identity(); + } } diff --git a/src/main/java/appeng/client/render/model/MatrixVertexTransformer.java b/src/main/java/appeng/client/render/model/MatrixVertexTransformer.java index 961b3c103..af466d1a8 100644 --- a/src/main/java/appeng/client/render/model/MatrixVertexTransformer.java +++ b/src/main/java/appeng/client/render/model/MatrixVertexTransformer.java @@ -19,153 +19,134 @@ package appeng.client.render.model; -import javax.vecmath.Matrix4f; -import javax.vecmath.Vector4f; - import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.client.renderer.vertex.VertexFormatElement; import net.minecraft.util.EnumFacing; import net.minecraftforge.client.model.pipeline.QuadGatheringTransformer; +import javax.vecmath.Matrix4f; +import javax.vecmath.Vector4f; + /** * Applies an arbitrary transformation matrix to the vertices of a quad. */ -final class MatrixVertexTransformer extends QuadGatheringTransformer -{ +final class MatrixVertexTransformer extends QuadGatheringTransformer { - private final Matrix4f transform; + private final Matrix4f transform; - public MatrixVertexTransformer( Matrix4f transform ) - { - this.transform = transform; - } + public MatrixVertexTransformer(Matrix4f transform) { + this.transform = transform; + } - @Override - protected void processQuad() - { - VertexFormat format = this.parent.getVertexFormat(); - int count = format.getElementCount(); + @Override + protected void processQuad() { + VertexFormat format = this.parent.getVertexFormat(); + int count = format.getElementCount(); - for( int v = 0; v < 4; v++ ) - { - for( int e = 0; e < count; e++ ) - { - VertexFormatElement element = format.getElement( e ); - if( element.getUsage() == VertexFormatElement.EnumUsage.POSITION ) - { - this.parent.put( e, this.transform( this.quadData[e][v], element.getElementCount() ) ); - } - else if( element.getUsage() == VertexFormatElement.EnumUsage.NORMAL ) - { - this.parent.put( e, this.transformNormal( this.quadData[e][v] ) ); - } - else - { - this.parent.put( e, this.quadData[e][v] ); - } - } - } - } + for (int v = 0; v < 4; v++) { + for (int e = 0; e < count; e++) { + VertexFormatElement element = format.getElement(e); + if (element.getUsage() == VertexFormatElement.EnumUsage.POSITION) { + this.parent.put(e, this.transform(this.quadData[e][v], element.getElementCount())); + } else if (element.getUsage() == VertexFormatElement.EnumUsage.NORMAL) { + this.parent.put(e, this.transformNormal(this.quadData[e][v])); + } else { + this.parent.put(e, this.quadData[e][v]); + } + } + } + } - @Override - public void setQuadTint( int tint ) - { - this.parent.setQuadTint( tint ); - } + @Override + public void setQuadTint(int tint) { + this.parent.setQuadTint(tint); + } - @Override - public void setQuadOrientation( EnumFacing orientation ) - { - this.parent.setQuadOrientation( orientation ); - } + @Override + public void setQuadOrientation(EnumFacing orientation) { + this.parent.setQuadOrientation(orientation); + } - @Override - public void setApplyDiffuseLighting( boolean diffuse ) - { - this.parent.setApplyDiffuseLighting( diffuse ); - } + @Override + public void setApplyDiffuseLighting(boolean diffuse) { + this.parent.setApplyDiffuseLighting(diffuse); + } - @Override - public void setTexture( TextureAtlasSprite texture ) - { - this.parent.setTexture( texture ); - } + @Override + public void setTexture(TextureAtlasSprite texture) { + this.parent.setTexture(texture); + } - private float[] transform( float[] fs, int elemCount ) - { - switch( fs.length ) - { - case 3: - javax.vecmath.Vector3f vec = new javax.vecmath.Vector3f( fs[0], fs[1], fs[2] ); - vec.x -= 0.5f; - vec.y -= 0.5f; - vec.z -= 0.5f; - this.transform.transform( vec ); - vec.x += 0.5f; - vec.y += 0.5f; - vec.z += 0.5f; - return new float[] { - vec.x, - vec.y, - vec.z - }; - case 4: - Vector4f vecc = new Vector4f( fs[0], fs[1], fs[2], fs[3] ); - // Otherwise all translation is lost - if( elemCount == 3 ) - { - vecc.w = 1; - } - vecc.x -= 0.5f; - vecc.y -= 0.5f; - vecc.z -= 0.5f; - this.transform.transform( vecc ); - vecc.x += 0.5f; - vecc.y += 0.5f; - vecc.z += 0.5f; - return new float[] { - vecc.x, - vecc.y, - vecc.z, - vecc.w - }; + private float[] transform(float[] fs, int elemCount) { + switch (fs.length) { + case 3: + javax.vecmath.Vector3f vec = new javax.vecmath.Vector3f(fs[0], fs[1], fs[2]); + vec.x -= 0.5f; + vec.y -= 0.5f; + vec.z -= 0.5f; + this.transform.transform(vec); + vec.x += 0.5f; + vec.y += 0.5f; + vec.z += 0.5f; + return new float[]{ + vec.x, + vec.y, + vec.z + }; + case 4: + Vector4f vecc = new Vector4f(fs[0], fs[1], fs[2], fs[3]); + // Otherwise all translation is lost + if (elemCount == 3) { + vecc.w = 1; + } + vecc.x -= 0.5f; + vecc.y -= 0.5f; + vecc.z -= 0.5f; + this.transform.transform(vecc); + vecc.x += 0.5f; + vecc.y += 0.5f; + vecc.z += 0.5f; + return new float[]{ + vecc.x, + vecc.y, + vecc.z, + vecc.w + }; - default: - return fs; - } - } + default: + return fs; + } + } - private float[] transformNormal( float[] fs ) - { - Vector4f normal; + private float[] transformNormal(float[] fs) { + Vector4f normal; - switch( fs.length ) - { - case 3: - normal = new Vector4f( fs[0], fs[1], fs[2], 0 ); - this.transform.transform( normal ); - normal.normalize(); - return new float[] { - normal.x, - normal.y, - normal.z - }; + switch (fs.length) { + case 3: + normal = new Vector4f(fs[0], fs[1], fs[2], 0); + this.transform.transform(normal); + normal.normalize(); + return new float[]{ + normal.x, + normal.y, + normal.z + }; - case 4: - normal = new Vector4f( fs[0], fs[1], fs[2], fs[3] ); - this.transform.transform( normal ); - normal.normalize(); - return new float[] { - normal.x, - normal.y, - normal.z, - normal.w - }; + case 4: + normal = new Vector4f(fs[0], fs[1], fs[2], fs[3]); + this.transform.transform(normal); + normal.normalize(); + return new float[]{ + normal.x, + normal.y, + normal.z, + normal.w + }; - default: - return fs; - } - } + default: + return fs; + } + } } diff --git a/src/main/java/appeng/client/render/model/MemoryCardBakedModel.java b/src/main/java/appeng/client/render/model/MemoryCardBakedModel.java index ebe8cbed5..a291504fd 100644 --- a/src/main/java/appeng/client/render/model/MemoryCardBakedModel.java +++ b/src/main/java/appeng/client/render/model/MemoryCardBakedModel.java @@ -1,22 +1,13 @@ - package appeng.client.render.model; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ExecutionException; - -import javax.annotation.Nullable; -import javax.vecmath.Matrix4f; - +import appeng.api.implementations.items.IMemoryCard; +import appeng.api.util.AEColor; +import appeng.client.render.cablebus.CubeBuilder; +import appeng.core.AELog; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableList; - -import org.apache.commons.lang3.tuple.Pair; - import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -29,200 +20,174 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; import net.minecraftforge.common.model.TRSRTransformation; +import org.apache.commons.lang3.tuple.Pair; -import appeng.api.implementations.items.IMemoryCard; -import appeng.api.util.AEColor; -import appeng.client.render.cablebus.CubeBuilder; -import appeng.core.AELog; +import javax.annotation.Nullable; +import javax.vecmath.Matrix4f; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ExecutionException; -class MemoryCardBakedModel implements IBakedModel -{ - private static final AEColor[] DEFAULT_COLOR_CODE = new AEColor[] { - AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, - AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, - }; +class MemoryCardBakedModel implements IBakedModel { + private static final AEColor[] DEFAULT_COLOR_CODE = new AEColor[]{ + AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, + AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, + }; - private final VertexFormat format; + private final VertexFormat format; - private final IBakedModel baseModel; + private final IBakedModel baseModel; - private final TextureAtlasSprite texture; + private final TextureAtlasSprite texture; - private final AEColor[] colorCode; + private final AEColor[] colorCode; - private final Cache modelCache; + private final Cache modelCache; - private final ImmutableList generalQuads; + private final ImmutableList generalQuads; - MemoryCardBakedModel( VertexFormat format, IBakedModel baseModel, TextureAtlasSprite texture ) - { - this( format, baseModel, texture, DEFAULT_COLOR_CODE, createCache() ); - } + MemoryCardBakedModel(VertexFormat format, IBakedModel baseModel, TextureAtlasSprite texture) { + this(format, baseModel, texture, DEFAULT_COLOR_CODE, createCache()); + } - private MemoryCardBakedModel( VertexFormat format, IBakedModel baseModel, TextureAtlasSprite texture, AEColor[] hash, Cache modelCache ) - { - this.format = format; - this.baseModel = baseModel; - this.texture = texture; - this.colorCode = hash; - this.generalQuads = ImmutableList.copyOf( this.buildGeneralQuads() ); - this.modelCache = modelCache; - } + private MemoryCardBakedModel(VertexFormat format, IBakedModel baseModel, TextureAtlasSprite texture, AEColor[] hash, Cache modelCache) { + this.format = format; + this.baseModel = baseModel; + this.texture = texture; + this.colorCode = hash; + this.generalQuads = ImmutableList.copyOf(this.buildGeneralQuads()); + this.modelCache = modelCache; + } - private static Cache createCache() - { - return CacheBuilder.newBuilder() - .maximumSize( 100 ) - .build(); - } + private static Cache createCache() { + return CacheBuilder.newBuilder() + .maximumSize(100) + .build(); + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { - List quads = this.baseModel.getQuads( state, side, rand ); + List quads = this.baseModel.getQuads(state, side, rand); - if( side != null ) - { - return quads; - } + if (side != null) { + return quads; + } - List result = new ArrayList<>( quads.size() + this.generalQuads.size() ); - result.addAll( quads ); - result.addAll( this.generalQuads ); - return result; - } + List result = new ArrayList<>(quads.size() + this.generalQuads.size()); + result.addAll(quads); + result.addAll(this.generalQuads); + return result; + } - private List buildGeneralQuads() - { - CubeBuilder builder = new CubeBuilder( this.format ); + private List buildGeneralQuads() { + CubeBuilder builder = new CubeBuilder(this.format); - builder.setTexture( this.texture ); + builder.setTexture(this.texture); - for( int x = 0; x < 4; x++ ) - { - for( int y = 0; y < 2; y++ ) - { - final AEColor color = this.colorCode[x + y * 4]; + for (int x = 0; x < 4; x++) { + for (int y = 0; y < 2; y++) { + final AEColor color = this.colorCode[x + y * 4]; - builder.setColorRGB( color.mediumVariant ); - builder.addCube( 7 + x, 8 + ( 1 - y ), 7.5f, 7 + x + 1, 8 + ( 1 - y ) + 1, 8.5f ); - } - } + builder.setColorRGB(color.mediumVariant); + builder.addCube(7 + x, 8 + (1 - y), 7.5f, 7 + x + 1, 8 + (1 - y) + 1, 8.5f); + } + } - return builder.getOutput(); - } + return builder.getOutput(); + } - @Override - public boolean isAmbientOcclusion() - { - return this.baseModel.isAmbientOcclusion(); - } + @Override + public boolean isAmbientOcclusion() { + return this.baseModel.isAmbientOcclusion(); + } - @Override - public boolean isGui3d() - { - return this.baseModel.isGui3d(); - } + @Override + public boolean isGui3d() { + return this.baseModel.isGui3d(); + } - @Override - public boolean isBuiltInRenderer() - { - return this.baseModel.isBuiltInRenderer(); - } + @Override + public boolean isBuiltInRenderer() { + return this.baseModel.isBuiltInRenderer(); + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.baseModel.getParticleTexture(); - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.baseModel.getParticleTexture(); + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return this.baseModel.getItemCameraTransforms(); - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return this.baseModel.getItemCameraTransforms(); + } - @Override - public ItemOverrideList getOverrides() - { - return new ItemOverrideList( Collections.emptyList() ) - { - @Override - public IBakedModel handleItemState( IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity ) - { - try - { - if( stack.getItem() instanceof IMemoryCard ) - { - final IMemoryCard memoryCard = (IMemoryCard) stack.getItem(); - final AEColor[] colors = memoryCard.getColorCode( stack ); + @Override + public ItemOverrideList getOverrides() { + return new ItemOverrideList(Collections.emptyList()) { + @Override + public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity) { + try { + if (stack.getItem() instanceof IMemoryCard) { + final IMemoryCard memoryCard = (IMemoryCard) stack.getItem(); + final AEColor[] colors = memoryCard.getColorCode(stack); - return MemoryCardBakedModel.this.modelCache.get( new CacheKey( colors ), - () -> new MemoryCardBakedModel( MemoryCardBakedModel.this.format, MemoryCardBakedModel.this.baseModel, MemoryCardBakedModel.this.texture, colors, MemoryCardBakedModel.this.modelCache ) ); - } - } - catch( ExecutionException e ) - { - AELog.error( e ); - } + return MemoryCardBakedModel.this.modelCache.get(new CacheKey(colors), + () -> new MemoryCardBakedModel(MemoryCardBakedModel.this.format, MemoryCardBakedModel.this.baseModel, MemoryCardBakedModel.this.texture, colors, MemoryCardBakedModel.this.modelCache)); + } + } catch (ExecutionException e) { + AELog.error(e); + } - return MemoryCardBakedModel.this; - } - }; + return MemoryCardBakedModel.this; + } + }; - } + } - @Override - public Pair handlePerspective( ItemCameraTransforms.TransformType type ) - { - // Delegate to the base model if possible - if( this.baseModel instanceof IBakedModel ) - { - IBakedModel pam = this.baseModel; - Pair pair = pam.handlePerspective( type ); - return Pair.of( this, pair.getValue() ); - } - return Pair.of( this, TRSRTransformation.identity().getMatrix() ); - } + @Override + public Pair handlePerspective(ItemCameraTransforms.TransformType type) { + // Delegate to the base model if possible + if (this.baseModel instanceof IBakedModel) { + IBakedModel pam = this.baseModel; + Pair pair = pam.handlePerspective(type); + return Pair.of(this, pair.getValue()); + } + return Pair.of(this, TRSRTransformation.identity().getMatrix()); + } - private static class CacheKey - { - private final AEColor[] key; + private static class CacheKey { + private final AEColor[] key; - CacheKey( AEColor[] key ) - { - this.key = key; - } + CacheKey(AEColor[] key) { + this.key = key; + } - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode( this.key ); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + Arrays.hashCode(this.key); + return result; + } - @Override - public boolean equals( Object obj ) - { - if( this == obj ) - { - return true; - } - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - CacheKey other = (CacheKey) obj; - return Arrays.equals( this.key, other.key ); - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + CacheKey other = (CacheKey) obj; + return Arrays.equals(this.key, other.key); + } - } + } } diff --git a/src/main/java/appeng/client/render/model/MemoryCardModel.java b/src/main/java/appeng/client/render/model/MemoryCardModel.java index da2af481a..dc4a60f6b 100644 --- a/src/main/java/appeng/client/render/model/MemoryCardModel.java +++ b/src/main/java/appeng/client/render/model/MemoryCardModel.java @@ -1,11 +1,7 @@ - package appeng.client.render.model; -import java.util.Collection; -import java.util.Collections; -import java.util.function.Function; - +import appeng.core.AppEng; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -15,56 +11,49 @@ import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; -import appeng.core.AppEng; +import java.util.Collection; +import java.util.Collections; +import java.util.function.Function; /** * Model wrapper for the memory card item model, which combines a base card layer with a "visual hash" of the part/tile. */ -public class MemoryCardModel implements IModel -{ +public class MemoryCardModel implements IModel { - private static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "item/memory_card" ); - private static final ResourceLocation TEXTURE = new ResourceLocation( AppEng.MOD_ID, "items/memory_card_hash" ); + private static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "item/memory_card"); + private static final ResourceLocation TEXTURE = new ResourceLocation(AppEng.MOD_ID, "items/memory_card_hash"); - @Override - public Collection getDependencies() - { - return Collections.singletonList( MODEL_BASE ); - } + @Override + public Collection getDependencies() { + return Collections.singletonList(MODEL_BASE); + } - @Override - public Collection getTextures() - { - return Collections.singletonList( TEXTURE ); - } + @Override + public Collection getTextures() { + return Collections.singletonList(TEXTURE); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - TextureAtlasSprite texture = bakedTextureGetter.apply( TEXTURE ); + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + TextureAtlasSprite texture = bakedTextureGetter.apply(TEXTURE); - IBakedModel baseModel = this.getBaseModel( state, format, bakedTextureGetter ); + IBakedModel baseModel = this.getBaseModel(state, format, bakedTextureGetter); - return new MemoryCardBakedModel( format, baseModel, texture ); - } + return new MemoryCardBakedModel(format, baseModel, texture); + } - private IBakedModel getBaseModel( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - // Load the base model - try - { - return ModelLoaderRegistry.getModel( MODEL_BASE ).bake( state, format, bakedTextureGetter ); - } - catch( Exception e ) - { - throw new RuntimeException( e ); - } - } + private IBakedModel getBaseModel(IModelState state, VertexFormat format, Function bakedTextureGetter) { + // Load the base model + try { + return ModelLoaderRegistry.getModel(MODEL_BASE).bake(state, format, bakedTextureGetter); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - @Override - public IModelState getDefaultState() - { - return TRSRTransformation.identity().toItemTransform(); - } + @Override + public IModelState getDefaultState() { + return TRSRTransformation.identity().toItemTransform(); + } } diff --git a/src/main/java/appeng/client/render/model/RenderHelper.java b/src/main/java/appeng/client/render/model/RenderHelper.java index dd40e77e2..e6d841ccf 100644 --- a/src/main/java/appeng/client/render/model/RenderHelper.java +++ b/src/main/java/appeng/client/render/model/RenderHelper.java @@ -19,78 +19,68 @@ package appeng.client.render.model; -import java.util.EnumMap; -import java.util.List; - import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; - import net.minecraft.util.EnumFacing; import net.minecraft.util.math.Vec3d; +import java.util.EnumMap; +import java.util.List; + // TODO: Investigate use of CubeBuilder instead -final class RenderHelper -{ +final class RenderHelper { - private static EnumMap> cornersForFacing = generateCornersForFacings(); + private static final EnumMap> cornersForFacing = generateCornersForFacings(); - private RenderHelper() - { + private RenderHelper() { - } + } - static List getFaceCorners( EnumFacing side ) - { - return cornersForFacing.get( side ); - } + static List getFaceCorners(EnumFacing side) { + return cornersForFacing.get(side); + } - private static EnumMap> generateCornersForFacings() - { - EnumMap> result = new EnumMap<>( EnumFacing.class ); + private static EnumMap> generateCornersForFacings() { + EnumMap> result = new EnumMap<>(EnumFacing.class); - for( EnumFacing facing : EnumFacing.values() ) - { - List corners; + for (EnumFacing facing : EnumFacing.values()) { + List corners; - float offset = ( facing.getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE ) ? 0 : 1; + float offset = (facing.getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE) ? 0 : 1; - switch( facing.getAxis() ) - { - default: - case X: - corners = Lists.newArrayList( new Vec3d( offset, 1, 1 ), new Vec3d( offset, 0, 1 ), new Vec3d( offset, 0, 0 ), new Vec3d( offset, 1, 0 ) ); - break; - case Y: - corners = Lists.newArrayList( new Vec3d( 1, offset, 1 ), new Vec3d( 1, offset, 0 ), new Vec3d( 0, offset, 0 ), new Vec3d( 0, offset, 1 ) ); - break; - case Z: - corners = Lists.newArrayList( new Vec3d( 0, 1, offset ), new Vec3d( 0, 0, offset ), new Vec3d( 1, 0, offset ), new Vec3d( 1, 1, offset ) ); - break; - } + switch (facing.getAxis()) { + default: + case X: + corners = Lists.newArrayList(new Vec3d(offset, 1, 1), new Vec3d(offset, 0, 1), new Vec3d(offset, 0, 0), new Vec3d(offset, 1, 0)); + break; + case Y: + corners = Lists.newArrayList(new Vec3d(1, offset, 1), new Vec3d(1, offset, 0), new Vec3d(0, offset, 0), new Vec3d(0, offset, 1)); + break; + case Z: + corners = Lists.newArrayList(new Vec3d(0, 1, offset), new Vec3d(0, 0, offset), new Vec3d(1, 0, offset), new Vec3d(1, 1, offset)); + break; + } - if( facing.getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE ) - { - corners = Lists.reverse( corners ); - } + if (facing.getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE) { + corners = Lists.reverse(corners); + } - result.put( facing, ImmutableList.copyOf( corners ) ); - } + result.put(facing, ImmutableList.copyOf(corners)); + } - return result; - } + return result; + } - private static Vec3d adjust( Vec3d vec, EnumFacing.Axis axis, double delta ) - { - switch( axis ) - { - default: - case X: - return new Vec3d( vec.x + delta, vec.y, vec.z ); - case Y: - return new Vec3d( vec.x, vec.y + delta, vec.z ); - case Z: - return new Vec3d( vec.x, vec.y, vec.z + delta ); - } - } + private static Vec3d adjust(Vec3d vec, EnumFacing.Axis axis, double delta) { + switch (axis) { + default: + case X: + return new Vec3d(vec.x + delta, vec.y, vec.z); + case Y: + return new Vec3d(vec.x, vec.y + delta, vec.z); + case Z: + return new Vec3d(vec.x, vec.y, vec.z + delta); + } + } } diff --git a/src/main/java/appeng/client/render/model/SkyCompassBakedModel.java b/src/main/java/appeng/client/render/model/SkyCompassBakedModel.java index 04676c512..c71c5b762 100644 --- a/src/main/java/appeng/client/render/model/SkyCompassBakedModel.java +++ b/src/main/java/appeng/client/render/model/SkyCompassBakedModel.java @@ -19,14 +19,9 @@ package appeng.client.render.model; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nullable; -import javax.vecmath.AxisAngle4f; -import javax.vecmath.Matrix4f; - +import appeng.block.misc.BlockSkyCompass; +import appeng.hooks.CompassManager; +import appeng.hooks.CompassResult; import net.minecraft.block.state.IBlockState; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.renderer.block.model.BakedQuad; @@ -43,185 +38,159 @@ import net.minecraft.world.World; import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad; import net.minecraftforge.common.property.IExtendedBlockState; -import appeng.block.misc.BlockSkyCompass; -import appeng.hooks.CompassManager; -import appeng.hooks.CompassResult; +import javax.annotation.Nullable; +import javax.vecmath.AxisAngle4f; +import javax.vecmath.Matrix4f; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; /** * This baked model combines the quads of a compass base and the quads of a compass pointer, which will be rotated * around the Y-axis to get the compass to point in the right direction. */ -public class SkyCompassBakedModel implements IBakedModel -{ +public class SkyCompassBakedModel implements IBakedModel { - private final IBakedModel base; + private final IBakedModel base; - private final IBakedModel pointer; + private final IBakedModel pointer; - private float fallbackRotation = 0; + private float fallbackRotation = 0; - public SkyCompassBakedModel( IBakedModel base, IBakedModel pointer ) - { - this.base = base; - this.pointer = pointer; - } + public SkyCompassBakedModel(IBakedModel base, IBakedModel pointer) { + this.base = base; + this.pointer = pointer; + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - float rotation = 0; - // Get rotation from the special block state - if( state instanceof IExtendedBlockState ) - { - Float rotationOpt = ( (IExtendedBlockState) state ).getValue( BlockSkyCompass.ROTATION ); - if( rotationOpt != null ) - { - rotation = rotationOpt; - } - } - else if( state == null ) - { - // This is used to render a compass pointing in a specific direction when being held in hand - rotation = this.fallbackRotation; - } + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + float rotation = 0; + // Get rotation from the special block state + if (state instanceof IExtendedBlockState) { + Float rotationOpt = ((IExtendedBlockState) state).getValue(BlockSkyCompass.ROTATION); + if (rotationOpt != null) { + rotation = rotationOpt; + } + } else if (state == null) { + // This is used to render a compass pointing in a specific direction when being held in hand + rotation = this.fallbackRotation; + } - // Pre-compute the quad count to avoid list resizes - List quads = new ArrayList<>(); + // Pre-compute the quad count to avoid list resizes + List quads = new ArrayList<>(); - quads.addAll( this.base.getQuads( state, side, rand ) ); + quads.addAll(this.base.getQuads(state, side, rand)); - // We'll add the pointer as "sideless" - if( side == null ) - { - // Set up the rotation around the Y-axis for the pointer - Matrix4f matrix = new Matrix4f(); - matrix.setIdentity(); - matrix.setRotation( new AxisAngle4f( 0, 1, 0, rotation ) ); + // We'll add the pointer as "sideless" + if (side == null) { + // Set up the rotation around the Y-axis for the pointer + Matrix4f matrix = new Matrix4f(); + matrix.setIdentity(); + matrix.setRotation(new AxisAngle4f(0, 1, 0, rotation)); - MatrixVertexTransformer transformer = new MatrixVertexTransformer( matrix ); - for( BakedQuad bakedQuad : this.pointer.getQuads( state, side, rand ) ) - { - UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder( bakedQuad.getFormat() ); + MatrixVertexTransformer transformer = new MatrixVertexTransformer(matrix); + for (BakedQuad bakedQuad : this.pointer.getQuads(state, side, rand)) { + UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder(bakedQuad.getFormat()); - transformer.setParent( builder ); - transformer.setVertexFormat( builder.getVertexFormat() ); - bakedQuad.pipe( transformer ); - builder.setQuadOrientation( null ); // After rotation, facing a specific side cannot be guaranteed - // anymore - BakedQuad q = builder.build(); - quads.add( q ); - } - } + transformer.setParent(builder); + transformer.setVertexFormat(builder.getVertexFormat()); + bakedQuad.pipe(transformer); + builder.setQuadOrientation(null); // After rotation, facing a specific side cannot be guaranteed + // anymore + BakedQuad q = builder.build(); + quads.add(q); + } + } - return quads; - } + return quads; + } - @Override - public boolean isAmbientOcclusion() - { - return this.base.isAmbientOcclusion(); - } + @Override + public boolean isAmbientOcclusion() { + return this.base.isAmbientOcclusion(); + } - @Override - public boolean isGui3d() - { - return true; - } + @Override + public boolean isGui3d() { + return true; + } - @Override - public boolean isBuiltInRenderer() - { - return false; - } + @Override + public boolean isBuiltInRenderer() { + return false; + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.base.getParticleTexture(); - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.base.getParticleTexture(); + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return this.base.getItemCameraTransforms(); - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return this.base.getItemCameraTransforms(); + } - @Override - public ItemOverrideList getOverrides() - { - /* - * This handles setting the rotation of the compass when being held in hand. If it's not held in hand, it'll - * animate using the - * spinning animation. - */ - return new ItemOverrideList( Collections.emptyList() ) - { + @Override + public ItemOverrideList getOverrides() { + /* + * This handles setting the rotation of the compass when being held in hand. If it's not held in hand, it'll + * animate using the + * spinning animation. + */ + return new ItemOverrideList(Collections.emptyList()) { - @Override - public IBakedModel handleItemState( IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity ) - { - if( world != null && entity instanceof EntityPlayerSP ) - { - EntityPlayer player = (EntityPlayer) entity; + @Override + public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity) { + if (world != null && entity instanceof EntityPlayerSP) { + EntityPlayer player = (EntityPlayer) entity; - float offRads = (float) ( player.rotationYaw / 180.0f * (float) Math.PI + Math.PI ); + float offRads = (float) (player.rotationYaw / 180.0f * (float) Math.PI + Math.PI); - SkyCompassBakedModel.this.fallbackRotation = offRads + getAnimatedRotation( player.getPosition(), true ); - } - else - { - SkyCompassBakedModel.this.fallbackRotation = getAnimatedRotation( null, false ); - } + SkyCompassBakedModel.this.fallbackRotation = offRads + getAnimatedRotation(player.getPosition(), true); + } else { + SkyCompassBakedModel.this.fallbackRotation = getAnimatedRotation(null, false); + } - return originalModel; - } - }; - } + return originalModel; + } + }; + } - /** - * Gets the effective, animated rotation for the compass given the current position of the compass. - */ - public static float getAnimatedRotation( @Nullable BlockPos pos, boolean prefetch ) - { + /** + * Gets the effective, animated rotation for the compass given the current position of the compass. + */ + public static float getAnimatedRotation(@Nullable BlockPos pos, boolean prefetch) { - // Only query for a meteor position if we know our own position - if( pos != null ) - { - CompassResult cr = CompassManager.INSTANCE.getCompassDirection( 0, pos.getX(), pos.getY(), pos.getZ() ); + // Only query for a meteor position if we know our own position + if (pos != null) { + CompassResult cr = CompassManager.INSTANCE.getCompassDirection(0, pos.getX(), pos.getY(), pos.getZ()); - // Prefetch meteor positions from the server for adjacent blocks so they are available more quickly when - // we're moving - if( prefetch ) - { - for( int i = 0; i < 3; i++ ) - { - for( int j = 0; j < 3; j++ ) - { - CompassManager.INSTANCE.getCompassDirection( 0, pos.getX() + i - 1, pos.getY(), pos.getZ() + j - 1 ); - } - } - } + // Prefetch meteor positions from the server for adjacent blocks so they are available more quickly when + // we're moving + if (prefetch) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + CompassManager.INSTANCE.getCompassDirection(0, pos.getX() + i - 1, pos.getY(), pos.getZ() + j - 1); + } + } + } - if( cr.isValidResult() ) - { - if( cr.isSpin() ) - { - long timeMillis = System.currentTimeMillis(); - // .5 seconds per full rotation - timeMillis %= 500; - return timeMillis / 500.f * (float) Math.PI * 2; - } - else - { - return (float) cr.getRad(); - } - } - } + if (cr.isValidResult()) { + if (cr.isSpin()) { + long timeMillis = System.currentTimeMillis(); + // .5 seconds per full rotation + timeMillis %= 500; + return timeMillis / 500.f * (float) Math.PI * 2; + } else { + return (float) cr.getRad(); + } + } + } - long timeMillis = System.currentTimeMillis(); - // 3 seconds per full rotation - timeMillis %= 3000; - return timeMillis / 3000.f * (float) Math.PI * 2; - } + long timeMillis = System.currentTimeMillis(); + // 3 seconds per full rotation + timeMillis %= 3000; + return timeMillis / 3000.f * (float) Math.PI * 2; + } } diff --git a/src/main/java/appeng/client/render/model/SkyCompassModel.java b/src/main/java/appeng/client/render/model/SkyCompassModel.java index 69e7c711a..9ec32e0d1 100644 --- a/src/main/java/appeng/client/render/model/SkyCompassModel.java +++ b/src/main/java/appeng/client/render/model/SkyCompassModel.java @@ -19,13 +19,7 @@ package appeng.client.render.model; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.function.Function; - import com.google.common.collect.ImmutableList; - import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -35,53 +29,50 @@ import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; + /** * The parent model for the compass baked model. Declares the dependencies for the base and pointer submodels mostly. */ -public class SkyCompassModel implements IModel -{ +public class SkyCompassModel implements IModel { - private static final ResourceLocation MODEL_BASE = new ResourceLocation( "appliedenergistics2:block/sky_compass_base" ); + private static final ResourceLocation MODEL_BASE = new ResourceLocation("appliedenergistics2:block/sky_compass_base"); - private static final ResourceLocation MODEL_POINTER = new ResourceLocation( "appliedenergistics2:block/sky_compass_pointer" ); + private static final ResourceLocation MODEL_POINTER = new ResourceLocation("appliedenergistics2:block/sky_compass_pointer"); - private static final List DEPENDENCIES = ImmutableList.of( MODEL_BASE, MODEL_POINTER ); + private static final List DEPENDENCIES = ImmutableList.of(MODEL_BASE, MODEL_POINTER); - @Override - public Collection getDependencies() - { - return DEPENDENCIES; - } + @Override + public Collection getDependencies() { + return DEPENDENCIES; + } - @Override - public Collection getTextures() - { - return Collections.emptyList(); - } + @Override + public Collection getTextures() { + return Collections.emptyList(); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - IModel baseModel, pointerModel; - try - { - baseModel = ModelLoaderRegistry.getModel( MODEL_BASE ); - pointerModel = ModelLoaderRegistry.getModel( MODEL_POINTER ); - } - catch( Exception e ) - { - throw new RuntimeException( e ); - } + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + IModel baseModel, pointerModel; + try { + baseModel = ModelLoaderRegistry.getModel(MODEL_BASE); + pointerModel = ModelLoaderRegistry.getModel(MODEL_POINTER); + } catch (Exception e) { + throw new RuntimeException(e); + } - IBakedModel bakedBase = baseModel.bake( state, format, bakedTextureGetter ); - IBakedModel bakedPointer = pointerModel.bake( state, format, bakedTextureGetter ); - return new SkyCompassBakedModel( bakedBase, bakedPointer ); - } + IBakedModel bakedBase = baseModel.bake(state, format, bakedTextureGetter); + IBakedModel bakedPointer = pointerModel.bake(state, format, bakedTextureGetter); + return new SkyCompassBakedModel(bakedBase, bakedPointer); + } - @Override - public IModelState getDefaultState() - { - return TRSRTransformation.identity(); - } + @Override + public IModelState getDefaultState() { + return TRSRTransformation.identity(); + } } diff --git a/src/main/java/appeng/client/render/model/UVLModelLoader.java b/src/main/java/appeng/client/render/model/UVLModelLoader.java index f9f8397a4..d5fbe3e4e 100644 --- a/src/main/java/appeng/client/render/model/UVLModelLoader.java +++ b/src/main/java/appeng/client/render/model/UVLModelLoader.java @@ -19,50 +19,12 @@ package appeng.client.render.model; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.lang.reflect.Type; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - -import javax.annotation.Nullable; - +import appeng.client.render.VertexFormats; import com.google.common.base.Charsets; import com.google.common.base.Throwables; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.lwjgl.util.vector.Vector3f; - +import com.google.gson.*; import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.BlockFaceUV; -import net.minecraft.client.renderer.block.model.BlockPart; -import net.minecraft.client.renderer.block.model.BlockPartFace; -import net.minecraft.client.renderer.block.model.BlockPartRotation; -import net.minecraft.client.renderer.block.model.FaceBakery; -import net.minecraft.client.renderer.block.model.IBakedModel; -import net.minecraft.client.renderer.block.model.ItemCameraTransforms; -import net.minecraft.client.renderer.block.model.ItemOverride; -import net.minecraft.client.renderer.block.model.ItemTransformVec3f; -import net.minecraft.client.renderer.block.model.ModelBakery; -import net.minecraft.client.renderer.block.model.ModelBlock; +import net.minecraft.client.renderer.block.model.*; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.client.resources.IResource; @@ -79,318 +41,279 @@ import net.minecraftforge.client.model.pipeline.VertexLighterFlat; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.ITransformation; import net.minecraftforge.fml.relauncher.ReflectionHelper; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.lwjgl.util.vector.Vector3f; -import appeng.client.render.VertexFormats; +import javax.annotation.Nullable; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; -public enum UVLModelLoader implements ICustomModelLoader -{ - INSTANCE; +public enum UVLModelLoader implements ICustomModelLoader { + INSTANCE; - private static final Gson gson = new Gson(); + private static final Gson gson = new Gson(); - private static final Constructor vanillaModelWrapper; - private static final Field faceBakery; - private static final Object vanillaLoader; - private static final MethodHandle loaderGetter; + private static final Constructor vanillaModelWrapper; + private static final Field faceBakery; + private static final Object vanillaLoader; + private static final MethodHandle loaderGetter; - static - { - try - { - Field modifiers = Field.class.getDeclaredField( "modifiers" ); - modifiers.setAccessible( true ); + static { + try { + Field modifiers = Field.class.getDeclaredField("modifiers"); + modifiers.setAccessible(true); - faceBakery = ReflectionHelper.findField( ModelBakery.class, "faceBakery", "field_177607_l" ); - modifiers.set( faceBakery, faceBakery.getModifiers() & ( ~Modifier.FINAL ) ); + faceBakery = ReflectionHelper.findField(ModelBakery.class, "faceBakery", "field_177607_l"); + modifiers.set(faceBakery, faceBakery.getModifiers() & (~Modifier.FINAL)); - Class clas = Class.forName( ModelLoader.class.getName() + "$VanillaModelWrapper" ); - vanillaModelWrapper = clas.getDeclaredConstructor( ModelLoader.class, ResourceLocation.class, ModelBlock.class, boolean.class, - ModelBlockAnimation.class ); - vanillaModelWrapper.setAccessible( true ); + Class clas = Class.forName(ModelLoader.class.getName() + "$VanillaModelWrapper"); + vanillaModelWrapper = clas.getDeclaredConstructor(ModelLoader.class, ResourceLocation.class, ModelBlock.class, boolean.class, + ModelBlockAnimation.class); + vanillaModelWrapper.setAccessible(true); - Class vanillaLoaderClass = Class.forName( ModelLoader.class.getName() + "$VanillaLoader" ); - Field instanceField = vanillaLoaderClass.getField( "INSTANCE" ); - // Static field - vanillaLoader = instanceField.get( null ); - Field loaderField = vanillaLoaderClass.getDeclaredField( "loader" ); - loaderField.setAccessible( true ); - loaderGetter = MethodHandles.lookup().unreflectGetter( loaderField ); - } - catch( Exception e ) - { - throw Throwables.propagate( e ); - } - } + Class vanillaLoaderClass = Class.forName(ModelLoader.class.getName() + "$VanillaLoader"); + Field instanceField = vanillaLoaderClass.getField("INSTANCE"); + // Static field + vanillaLoader = instanceField.get(null); + Field loaderField = vanillaLoaderClass.getDeclaredField("loader"); + loaderField.setAccessible(true); + loaderGetter = MethodHandles.lookup().unreflectGetter(loaderField); + } catch (Exception e) { + throw Throwables.propagate(e); + } + } - private static Object deserializer( Class clas ) - { - try - { - clas = Class.forName( clas.getName() + "$Deserializer" ); - Constructor constr = clas.getDeclaredConstructor(); - constr.setAccessible( true ); - return constr.newInstance(); - } - catch( Exception e ) - { - throw Throwables.propagate( e ); - } - } + private static Object deserializer(Class clas) { + try { + clas = Class.forName(clas.getName() + "$Deserializer"); + Constructor constr = clas.getDeclaredConstructor(); + constr.setAccessible(true); + return constr.newInstance(); + } catch (Exception e) { + throw Throwables.propagate(e); + } + } - private static M vanillaModelWrapper( ModelLoader loader, ResourceLocation location, ModelBlock model, boolean uvlock, ModelBlockAnimation animation ) - { - try - { - return (M) vanillaModelWrapper.newInstance( loader, location, model, uvlock, animation ); - } - catch( Exception e ) - { - throw Throwables.propagate( e ); - } - } + private static M vanillaModelWrapper(ModelLoader loader, ResourceLocation location, ModelBlock model, boolean uvlock, ModelBlockAnimation animation) { + try { + return (M) vanillaModelWrapper.newInstance(loader, location, model, uvlock, animation); + } catch (Exception e) { + throw Throwables.propagate(e); + } + } - private static void setFaceBakery( ModelBakery modelBakery, FaceBakery faceBakery ) - { - try - { - UVLModelLoader.faceBakery.set( modelBakery, faceBakery ); - } - catch( Exception e ) - { - throw Throwables.propagate( e ); - } - } + private static void setFaceBakery(ModelBakery modelBakery, FaceBakery faceBakery) { + try { + UVLModelLoader.faceBakery.set(modelBakery, faceBakery); + } catch (Exception e) { + throw Throwables.propagate(e); + } + } - private IResourceManager resourceManager; + private IResourceManager resourceManager; - public ModelLoader getLoader() - { - try - { - return (ModelLoader) loaderGetter.invoke( vanillaLoader ); - } - catch( Throwable throwable ) - { - throw new RuntimeException( throwable ); - } - } + public ModelLoader getLoader() { + try { + return (ModelLoader) loaderGetter.invoke(vanillaLoader); + } catch (Throwable throwable) { + throw new RuntimeException(throwable); + } + } - @Override - public void onResourceManagerReload( IResourceManager resourceManager ) - { - this.resourceManager = resourceManager; - } + @Override + public void onResourceManagerReload(IResourceManager resourceManager) { + this.resourceManager = resourceManager; + } - @Override - public boolean accepts( ResourceLocation modelLocation ) - { - String modelPath = modelLocation.getResourcePath(); - if( modelLocation.getResourcePath().startsWith( "models/" ) ) - { - modelPath = modelPath.substring( "models/".length() ); - } + @Override + public boolean accepts(ResourceLocation modelLocation) { + String modelPath = modelLocation.getResourcePath(); + if (modelLocation.getResourcePath().startsWith("models/")) { + modelPath = modelPath.substring("models/".length()); + } - try( InputStreamReader io = new InputStreamReader( Minecraft.getMinecraft() - .getResourceManager() - .getResource( new ResourceLocation( modelLocation.getResourceDomain(), "models/" + modelPath + ".json" ) ) - .getInputStream() ) ) - { - return gson.fromJson( io, UVLMarker.class ).ae2_uvl_marker; - } - catch( Exception e ) - { - // Catch-all in case of any JSON parser issues. - } + try (InputStreamReader io = new InputStreamReader(Minecraft.getMinecraft() + .getResourceManager() + .getResource(new ResourceLocation(modelLocation.getResourceDomain(), "models/" + modelPath + ".json")) + .getInputStream())) { + return gson.fromJson(io, UVLMarker.class).ae2_uvl_marker; + } catch (Exception e) { + // Catch-all in case of any JSON parser issues. + } - return false; - } + return false; + } - @Override - public IModel loadModel( ResourceLocation modelLocation ) throws Exception - { - return new UVLModelWrapper( modelLocation ); - } + @Override + public IModel loadModel(ResourceLocation modelLocation) throws Exception { + return new UVLModelWrapper(modelLocation); + } - public class UVLModelWrapper implements IModel - { - final Gson UVLSERIALIZER = ( new GsonBuilder() ).registerTypeAdapter( ModelBlock.class, deserializer( ModelBlock.class ) ) - .registerTypeAdapter( BlockPart.class, deserializer( BlockPart.class ) ) - .registerTypeAdapter( BlockPartFace.class, new BlockPartFaceOverrideSerializer() ) - .registerTypeAdapter( BlockFaceUV.class, deserializer( BlockFaceUV.class ) ) - .registerTypeAdapter( ItemTransformVec3f.class, deserializer( ItemTransformVec3f.class ) ) - .registerTypeAdapter( ItemCameraTransforms.class, deserializer( ItemCameraTransforms.class ) ) - .registerTypeAdapter( ItemOverride.class, deserializer( ItemOverride.class ) ) - .create(); + public class UVLModelWrapper implements IModel { + final Gson UVLSERIALIZER = (new GsonBuilder()).registerTypeAdapter(ModelBlock.class, deserializer(ModelBlock.class)) + .registerTypeAdapter(BlockPart.class, deserializer(BlockPart.class)) + .registerTypeAdapter(BlockPartFace.class, new BlockPartFaceOverrideSerializer()) + .registerTypeAdapter(BlockFaceUV.class, deserializer(BlockFaceUV.class)) + .registerTypeAdapter(ItemTransformVec3f.class, deserializer(ItemTransformVec3f.class)) + .registerTypeAdapter(ItemCameraTransforms.class, deserializer(ItemCameraTransforms.class)) + .registerTypeAdapter(ItemOverride.class, deserializer(ItemOverride.class)) + .create(); - private Map> uvlightmap = new HashMap<>(); + private final Map> uvlightmap = new HashMap<>(); - private final IModel parent; + private final IModel parent; - public UVLModelWrapper( ResourceLocation modelLocation ) - { - String modelPath = modelLocation.getResourcePath(); - if( modelLocation.getResourcePath().startsWith( "models/" ) ) - { - modelPath = modelPath.substring( "models/".length() ); - } - ResourceLocation armatureLocation = new ResourceLocation( modelLocation.getResourceDomain(), "armatures/" + modelPath + ".json" ); - ModelBlockAnimation animation = ModelBlockAnimation.loadVanillaAnimation( UVLModelLoader.this.resourceManager, armatureLocation ); - ModelBlock model; - { - Reader reader = null; - IResource iresource = null; - ModelBlock lvt_5_1_ = null; + public UVLModelWrapper(ResourceLocation modelLocation) { + String modelPath = modelLocation.getResourcePath(); + if (modelLocation.getResourcePath().startsWith("models/")) { + modelPath = modelPath.substring("models/".length()); + } + ResourceLocation armatureLocation = new ResourceLocation(modelLocation.getResourceDomain(), "armatures/" + modelPath + ".json"); + ModelBlockAnimation animation = ModelBlockAnimation.loadVanillaAnimation(UVLModelLoader.this.resourceManager, armatureLocation); + ModelBlock model; + { + Reader reader = null; + IResource iresource = null; + ModelBlock lvt_5_1_ = null; - try - { - String s = modelLocation.getResourcePath(); + try { + String s = modelLocation.getResourcePath(); - iresource = Minecraft.getMinecraft() - .getResourceManager() - .getResource( - new ResourceLocation( modelLocation.getResourceDomain(), "models/" + modelPath + ".json" ) ); - reader = new InputStreamReader( iresource.getInputStream(), Charsets.UTF_8 ); + iresource = Minecraft.getMinecraft() + .getResourceManager() + .getResource( + new ResourceLocation(modelLocation.getResourceDomain(), "models/" + modelPath + ".json")); + reader = new InputStreamReader(iresource.getInputStream(), Charsets.UTF_8); - lvt_5_1_ = JsonUtils.gsonDeserialize( this.UVLSERIALIZER, reader, ModelBlock.class, false ); - lvt_5_1_.name = modelLocation.toString(); - } - catch( IOException e ) - { - e.printStackTrace(); - } - finally - { - IOUtils.closeQuietly( reader ); - IOUtils.closeQuietly( iresource ); - } + lvt_5_1_ = JsonUtils.gsonDeserialize(this.UVLSERIALIZER, reader, ModelBlock.class, false); + lvt_5_1_.name = modelLocation.toString(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + IOUtils.closeQuietly(reader); + IOUtils.closeQuietly(iresource); + } - model = lvt_5_1_; - } + model = lvt_5_1_; + } - this.parent = vanillaModelWrapper( UVLModelLoader.this.getLoader(), modelLocation, model, false, animation ); - } + this.parent = vanillaModelWrapper(UVLModelLoader.this.getLoader(), modelLocation, model, false, animation); + } - @Override - public Collection getDependencies() - { - return this.parent.getDependencies(); - } + @Override + public Collection getDependencies() { + return this.parent.getDependencies(); + } - @Override - public Collection getTextures() - { - return this.parent.getTextures(); - } + @Override + public Collection getTextures() { + return this.parent.getTextures(); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - setFaceBakery( UVLModelLoader.this.getLoader(), new FaceBakeryOverride() ); - IBakedModel model = this.parent.bake( state, format, bakedTextureGetter ); - setFaceBakery( UVLModelLoader.this.getLoader(), new FaceBakery() ); - return model; - } + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + setFaceBakery(UVLModelLoader.this.getLoader(), new FaceBakeryOverride()); + IBakedModel model = this.parent.bake(state, format, bakedTextureGetter); + setFaceBakery(UVLModelLoader.this.getLoader(), new FaceBakery()); + return model; + } - @Override - public IModelState getDefaultState() - { - return this.parent.getDefaultState(); - } + @Override + public IModelState getDefaultState() { + return this.parent.getDefaultState(); + } - public class BlockPartFaceOverrideSerializer implements JsonDeserializer - { - @Override - public BlockPartFace deserialize( JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_ ) throws JsonParseException - { - JsonObject jsonobject = p_deserialize_1_.getAsJsonObject(); - EnumFacing enumfacing = this.parseCullFace( jsonobject ); - int i = this.parseTintIndex( jsonobject ); - String s = this.parseTexture( jsonobject ); - BlockFaceUV blockfaceuv = (BlockFaceUV) p_deserialize_3_.deserialize( jsonobject, BlockFaceUV.class ); - BlockPartFace blockFace = new BlockPartFace( enumfacing, i, s, blockfaceuv ); - UVLModelWrapper.this.uvlightmap.put( blockFace, this.parseUVL( jsonobject ) ); - return blockFace; - } + public class BlockPartFaceOverrideSerializer implements JsonDeserializer { + @Override + public BlockPartFace deserialize(JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_) throws JsonParseException { + JsonObject jsonobject = p_deserialize_1_.getAsJsonObject(); + EnumFacing enumfacing = this.parseCullFace(jsonobject); + int i = this.parseTintIndex(jsonobject); + String s = this.parseTexture(jsonobject); + BlockFaceUV blockfaceuv = p_deserialize_3_.deserialize(jsonobject, BlockFaceUV.class); + BlockPartFace blockFace = new BlockPartFace(enumfacing, i, s, blockfaceuv); + UVLModelWrapper.this.uvlightmap.put(blockFace, this.parseUVL(jsonobject)); + return blockFace; + } - protected int parseTintIndex( JsonObject object ) - { - return JsonUtils.getInt( object, "tintindex", -1 ); - } + protected int parseTintIndex(JsonObject object) { + return JsonUtils.getInt(object, "tintindex", -1); + } - private String parseTexture( JsonObject object ) - { - return JsonUtils.getString( object, "texture" ); - } + private String parseTexture(JsonObject object) { + return JsonUtils.getString(object, "texture"); + } - @Nullable - private EnumFacing parseCullFace( JsonObject object ) - { - String s = JsonUtils.getString( object, "cullface", "" ); - return EnumFacing.byName( s ); - } + @Nullable + private EnumFacing parseCullFace(JsonObject object) { + String s = JsonUtils.getString(object, "cullface", ""); + return EnumFacing.byName(s); + } - protected Pair parseUVL( JsonObject object ) - { - if( !object.has( "uvlightmap" ) ) - { - return null; - } - object = object.get( "uvlightmap" ).getAsJsonObject(); - return new ImmutablePair<>( JsonUtils.getFloat( object, "sky", 0 ), JsonUtils.getFloat( object, "block", 0 ) ); - } - } + protected Pair parseUVL(JsonObject object) { + if (!object.has("uvlightmap")) { + return null; + } + object = object.get("uvlightmap").getAsJsonObject(); + return new ImmutablePair<>(JsonUtils.getFloat(object, "sky", 0), JsonUtils.getFloat(object, "block", 0)); + } + } - public class FaceBakeryOverride extends FaceBakery - { + public class FaceBakeryOverride extends FaceBakery { - @Override - public BakedQuad makeBakedQuad( Vector3f posFrom, Vector3f posTo, BlockPartFace face, TextureAtlasSprite sprite, EnumFacing facing, ITransformation modelRotationIn, BlockPartRotation partRotation, boolean uvLocked, boolean shade ) - { - BakedQuad quad = super.makeBakedQuad( posFrom, posTo, face, sprite, facing, modelRotationIn, partRotation, uvLocked, shade ); + @Override + public BakedQuad makeBakedQuad(Vector3f posFrom, Vector3f posTo, BlockPartFace face, TextureAtlasSprite sprite, EnumFacing facing, ITransformation modelRotationIn, BlockPartRotation partRotation, boolean uvLocked, boolean shade) { + BakedQuad quad = super.makeBakedQuad(posFrom, posTo, face, sprite, facing, modelRotationIn, partRotation, uvLocked, shade); - Pair brightness = UVLModelWrapper.this.uvlightmap.get( face ); - if( brightness != null ) - { - VertexFormat newFormat = VertexFormats.getFormatWithLightMap( quad.getFormat() ); - UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder( newFormat ); - VertexLighterFlat trans = new VertexLighterFlat( Minecraft.getMinecraft().getBlockColors() ) - { + Pair brightness = UVLModelWrapper.this.uvlightmap.get(face); + if (brightness != null) { + VertexFormat newFormat = VertexFormats.getFormatWithLightMap(quad.getFormat()); + UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder(newFormat); + VertexLighterFlat trans = new VertexLighterFlat(Minecraft.getMinecraft().getBlockColors()) { - @Override - protected void updateLightmap( float[] normal, float[] lightmap, float x, float y, float z ) - { - lightmap[0] = brightness.getRight(); - lightmap[1] = brightness.getLeft(); - } + @Override + protected void updateLightmap(float[] normal, float[] lightmap, float x, float y, float z) { + lightmap[0] = brightness.getRight(); + lightmap[1] = brightness.getLeft(); + } - @Override - public void setQuadTint( int tint ) - { - // Tint requires a block state which we don't have at this point - } - }; - trans.setParent( builder ); - quad.pipe( trans ); - builder.setQuadTint( quad.getTintIndex() ); - builder.setQuadOrientation( quad.getFace() ); - builder.setTexture( quad.getSprite() ); - builder.setApplyDiffuseLighting( false ); - return builder.build(); - } - else - { - return quad; - } - } + @Override + public void setQuadTint(int tint) { + // Tint requires a block state which we don't have at this point + } + }; + trans.setParent(builder); + quad.pipe(trans); + builder.setQuadTint(quad.getTintIndex()); + builder.setQuadOrientation(quad.getFace()); + builder.setTexture(quad.getSprite()); + builder.setApplyDiffuseLighting(false); + return builder.build(); + } else { + return quad; + } + } - } + } - } + } - class UVLMarker - { - boolean ae2_uvl_marker = false; - } + class UVLMarker { + boolean ae2_uvl_marker = false; + } } \ No newline at end of file diff --git a/src/main/java/appeng/client/render/renderable/ItemRenderable.java b/src/main/java/appeng/client/render/renderable/ItemRenderable.java index 6a0ffa2b0..1d6e9d192 100644 --- a/src/main/java/appeng/client/render/renderable/ItemRenderable.java +++ b/src/main/java/appeng/client/render/renderable/ItemRenderable.java @@ -19,54 +19,47 @@ package appeng.client.render.renderable; -import java.nio.FloatBuffer; -import java.util.function.Function; - -import org.apache.commons.lang3.tuple.Pair; -import org.lwjgl.BufferUtils; -import org.lwjgl.util.vector.Matrix4f; - import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +import org.apache.commons.lang3.tuple.Pair; +import org.lwjgl.BufferUtils; +import org.lwjgl.util.vector.Matrix4f; + +import java.nio.FloatBuffer; +import java.util.function.Function; -public class ItemRenderable implements Renderable -{ +public class ItemRenderable implements Renderable { - private final Function> f; + private final Function> f; - public ItemRenderable( Function> f ) - { - this.f = f; - } + public ItemRenderable(Function> f) { + this.f = f; + } - @Override - public void renderTileEntityAt( T te, double x, double y, double z, float partialTicks, int destroyStage ) - { - Pair pair = this.f.apply( te ); - if( pair != null && pair.getLeft() != null ) - { - GlStateManager.pushMatrix(); - if( pair.getRight() != null ) - { - FloatBuffer matrix = BufferUtils.createFloatBuffer( 16 ); - pair.getRight().store( matrix ); - matrix.flip(); - GlStateManager.multMatrix( matrix ); - } - Minecraft.getMinecraft().getRenderItem().renderItem( pair.getLeft(), TransformType.GROUND ); - GlStateManager.popMatrix(); - } - } + @Override + public void renderTileEntityAt(T te, double x, double y, double z, float partialTicks, int destroyStage) { + Pair pair = this.f.apply(te); + if (pair != null && pair.getLeft() != null) { + GlStateManager.pushMatrix(); + if (pair.getRight() != null) { + FloatBuffer matrix = BufferUtils.createFloatBuffer(16); + pair.getRight().store(matrix); + matrix.flip(); + GlStateManager.multMatrix(matrix); + } + Minecraft.getMinecraft().getRenderItem().renderItem(pair.getLeft(), TransformType.GROUND); + GlStateManager.popMatrix(); + } + } - @Override - public void renderTileEntityFast( T te, double x, double y, double z, float partialTicks, int destroyStage, BufferBuilder buffer ) - { + @Override + public void renderTileEntityFast(T te, double x, double y, double z, float partialTicks, int destroyStage, BufferBuilder buffer) { - } + } } diff --git a/src/main/java/appeng/client/render/renderable/Renderable.java b/src/main/java/appeng/client/render/renderable/Renderable.java index 98ef927dd..3636c95d9 100644 --- a/src/main/java/appeng/client/render/renderable/Renderable.java +++ b/src/main/java/appeng/client/render/renderable/Renderable.java @@ -23,11 +23,10 @@ import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.tileentity.TileEntity; -public interface Renderable -{ +public interface Renderable { - public void renderTileEntityAt( T te, double x, double y, double z, float partialTicks, int destroyStage ); + void renderTileEntityAt(T te, double x, double y, double z, float partialTicks, int destroyStage); - public void renderTileEntityFast( T te, double x, double y, double z, float partialTicks, int destroyStage, BufferBuilder buffer ); + void renderTileEntityFast(T te, double x, double y, double z, float partialTicks, int destroyStage, BufferBuilder buffer); } diff --git a/src/main/java/appeng/client/render/spatial/SpatialPylonBakedModel.java b/src/main/java/appeng/client/render/spatial/SpatialPylonBakedModel.java index 8f37f299e..62b294950 100644 --- a/src/main/java/appeng/client/render/spatial/SpatialPylonBakedModel.java +++ b/src/main/java/appeng/client/render/spatial/SpatialPylonBakedModel.java @@ -19,13 +19,10 @@ package appeng.client.render.spatial; -import java.util.List; -import java.util.Map; - -import javax.annotation.Nullable; - +import appeng.block.spatial.BlockSpatialPylon; +import appeng.client.render.cablebus.CubeBuilder; +import appeng.tile.spatial.TileSpatialPylon; import com.google.common.collect.ImmutableMap; - import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -36,225 +33,178 @@ import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.property.IExtendedBlockState; -import appeng.block.spatial.BlockSpatialPylon; -import appeng.client.render.cablebus.CubeBuilder; -import appeng.tile.spatial.TileSpatialPylon; +import javax.annotation.Nullable; +import java.util.List; +import java.util.Map; /** * The baked model that will be used for rendering the spatial pylon. */ -class SpatialPylonBakedModel implements IBakedModel -{ +class SpatialPylonBakedModel implements IBakedModel { - private final Map textures; + private final Map textures; - private final VertexFormat format; + private final VertexFormat format; - SpatialPylonBakedModel( VertexFormat format, Map textures ) - { - this.textures = ImmutableMap.copyOf( textures ); - this.format = format; - } + SpatialPylonBakedModel(VertexFormat format, Map textures) { + this.textures = ImmutableMap.copyOf(textures); + this.format = format; + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - int flags = this.getFlags( state ); + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + int flags = this.getFlags(state); - CubeBuilder builder = new CubeBuilder( this.format ); + CubeBuilder builder = new CubeBuilder(this.format); - if( flags != 0 ) - { - EnumFacing ori = null; - int displayAxis = flags & TileSpatialPylon.DISPLAY_Z; - if( displayAxis == TileSpatialPylon.DISPLAY_X ) - { - ori = EnumFacing.EAST; + if (flags != 0) { + EnumFacing ori = null; + int displayAxis = flags & TileSpatialPylon.DISPLAY_Z; + if (displayAxis == TileSpatialPylon.DISPLAY_X) { + ori = EnumFacing.EAST; - if( ( flags & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - builder.setUvRotation( EnumFacing.SOUTH, 1 ); - builder.setUvRotation( EnumFacing.NORTH, 1 ); - builder.setUvRotation( EnumFacing.UP, 2 ); - builder.setUvRotation( EnumFacing.DOWN, 2 ); - } - else if( ( flags & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MIN ) - { - builder.setUvRotation( EnumFacing.SOUTH, 2 ); - builder.setUvRotation( EnumFacing.NORTH, 2 ); - builder.setUvRotation( EnumFacing.UP, 1 ); - builder.setUvRotation( EnumFacing.DOWN, 1 ); - } - else - { - builder.setUvRotation( EnumFacing.SOUTH, 1 ); - builder.setUvRotation( EnumFacing.NORTH, 1 ); - builder.setUvRotation( EnumFacing.UP, 1 ); - builder.setUvRotation( EnumFacing.DOWN, 1 ); - } - } + if ((flags & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MAX) { + builder.setUvRotation(EnumFacing.SOUTH, 1); + builder.setUvRotation(EnumFacing.NORTH, 1); + builder.setUvRotation(EnumFacing.UP, 2); + builder.setUvRotation(EnumFacing.DOWN, 2); + } else if ((flags & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MIN) { + builder.setUvRotation(EnumFacing.SOUTH, 2); + builder.setUvRotation(EnumFacing.NORTH, 2); + builder.setUvRotation(EnumFacing.UP, 1); + builder.setUvRotation(EnumFacing.DOWN, 1); + } else { + builder.setUvRotation(EnumFacing.SOUTH, 1); + builder.setUvRotation(EnumFacing.NORTH, 1); + builder.setUvRotation(EnumFacing.UP, 1); + builder.setUvRotation(EnumFacing.DOWN, 1); + } + } else if (displayAxis == TileSpatialPylon.DISPLAY_Y) { + ori = EnumFacing.UP; + if ((flags & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MAX) { + builder.setUvRotation(EnumFacing.NORTH, 3); + builder.setUvRotation(EnumFacing.SOUTH, 3); + builder.setUvRotation(EnumFacing.EAST, 3); + builder.setUvRotation(EnumFacing.WEST, 3); + } + } else if (displayAxis == TileSpatialPylon.DISPLAY_Z) { + ori = EnumFacing.NORTH; + if ((flags & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MAX) { + builder.setUvRotation(EnumFacing.EAST, 2); + builder.setUvRotation(EnumFacing.WEST, 1); + } else if ((flags & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MIN) { + builder.setUvRotation(EnumFacing.EAST, 1); + builder.setUvRotation(EnumFacing.WEST, 2); + builder.setUvRotation(EnumFacing.UP, 3); + builder.setUvRotation(EnumFacing.DOWN, 3); + } else { + builder.setUvRotation(EnumFacing.EAST, 1); + builder.setUvRotation(EnumFacing.WEST, 2); + } + } - else if( displayAxis == TileSpatialPylon.DISPLAY_Y ) - { - ori = EnumFacing.UP; - if( ( flags & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - builder.setUvRotation( EnumFacing.NORTH, 3 ); - builder.setUvRotation( EnumFacing.SOUTH, 3 ); - builder.setUvRotation( EnumFacing.EAST, 3 ); - builder.setUvRotation( EnumFacing.WEST, 3 ); - } - } + builder.setTextures(this.textures.get(getTextureTypeFromSideOutside(flags, ori, EnumFacing.UP)), + this.textures.get(getTextureTypeFromSideOutside(flags, ori, EnumFacing.DOWN)), + this.textures.get(getTextureTypeFromSideOutside(flags, ori, EnumFacing.NORTH)), + this.textures.get(getTextureTypeFromSideOutside(flags, ori, EnumFacing.SOUTH)), + this.textures.get(getTextureTypeFromSideOutside(flags, ori, EnumFacing.EAST)), + this.textures.get(getTextureTypeFromSideOutside(flags, ori, EnumFacing.WEST))); + builder.addCube(0, 0, 0, 16, 16, 16); - else if( displayAxis == TileSpatialPylon.DISPLAY_Z ) - { - ori = EnumFacing.NORTH; - if( ( flags & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - builder.setUvRotation( EnumFacing.EAST, 2 ); - builder.setUvRotation( EnumFacing.WEST, 1 ); - } - else if( ( flags & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MIN ) - { - builder.setUvRotation( EnumFacing.EAST, 1 ); - builder.setUvRotation( EnumFacing.WEST, 2 ); - builder.setUvRotation( EnumFacing.UP, 3 ); - builder.setUvRotation( EnumFacing.DOWN, 3 ); - } - else - { - builder.setUvRotation( EnumFacing.EAST, 1 ); - builder.setUvRotation( EnumFacing.WEST, 2 ); - } - } + if ((flags & TileSpatialPylon.DISPLAY_POWERED_ENABLED) == TileSpatialPylon.DISPLAY_POWERED_ENABLED) { + builder.setRenderFullBright(true); + } - builder.setTextures( this.textures.get( getTextureTypeFromSideOutside( flags, ori, EnumFacing.UP ) ), - this.textures.get( getTextureTypeFromSideOutside( flags, ori, EnumFacing.DOWN ) ), - this.textures.get( getTextureTypeFromSideOutside( flags, ori, EnumFacing.NORTH ) ), - this.textures.get( getTextureTypeFromSideOutside( flags, ori, EnumFacing.SOUTH ) ), - this.textures.get( getTextureTypeFromSideOutside( flags, ori, EnumFacing.EAST ) ), - this.textures.get( getTextureTypeFromSideOutside( flags, ori, EnumFacing.WEST ) ) ); - builder.addCube( 0, 0, 0, 16, 16, 16 ); + builder.setTextures(this.textures.get(getTextureTypeFromSideInside(flags, ori, EnumFacing.UP)), + this.textures.get(getTextureTypeFromSideInside(flags, ori, EnumFacing.DOWN)), + this.textures.get(getTextureTypeFromSideInside(flags, ori, EnumFacing.NORTH)), + this.textures.get(getTextureTypeFromSideInside(flags, ori, EnumFacing.SOUTH)), + this.textures.get(getTextureTypeFromSideInside(flags, ori, EnumFacing.EAST)), + this.textures.get(getTextureTypeFromSideInside(flags, ori, EnumFacing.WEST))); + builder.addCube(0, 0, 0, 16, 16, 16); + } else { + builder.setTexture(this.textures.get(SpatialPylonTextureType.BASE)); + builder.addCube(0, 0, 0, 16, 16, 16); - if( ( flags & TileSpatialPylon.DISPLAY_POWERED_ENABLED ) == TileSpatialPylon.DISPLAY_POWERED_ENABLED ) - { - builder.setRenderFullBright( true ); - } + builder.setTexture(this.textures.get(SpatialPylonTextureType.DIM)); + builder.addCube(0, 0, 0, 16, 16, 16); + } - builder.setTextures( this.textures.get( getTextureTypeFromSideInside( flags, ori, EnumFacing.UP ) ), - this.textures.get( getTextureTypeFromSideInside( flags, ori, EnumFacing.DOWN ) ), - this.textures.get( getTextureTypeFromSideInside( flags, ori, EnumFacing.NORTH ) ), - this.textures.get( getTextureTypeFromSideInside( flags, ori, EnumFacing.SOUTH ) ), - this.textures.get( getTextureTypeFromSideInside( flags, ori, EnumFacing.EAST ) ), - this.textures.get( getTextureTypeFromSideInside( flags, ori, EnumFacing.WEST ) ) ); - builder.addCube( 0, 0, 0, 16, 16, 16 ); - } - else - { - builder.setTexture( this.textures.get( SpatialPylonTextureType.BASE ) ); - builder.addCube( 0, 0, 0, 16, 16, 16 ); + return builder.getOutput(); + } - builder.setTexture( this.textures.get( SpatialPylonTextureType.DIM ) ); - builder.addCube( 0, 0, 0, 16, 16, 16 ); - } + private int getFlags(IBlockState state) { + if (!(state instanceof IExtendedBlockState)) { + return 0; + } - return builder.getOutput(); - } + IExtendedBlockState extState = (IExtendedBlockState) state; - private int getFlags( IBlockState state ) - { - if( !( state instanceof IExtendedBlockState ) ) - { - return 0; - } + return extState.getValue(BlockSpatialPylon.STATE); + } - IExtendedBlockState extState = (IExtendedBlockState) state; + private static SpatialPylonTextureType getTextureTypeFromSideOutside(int flags, EnumFacing ori, EnumFacing dir) { + if (ori == dir || ori.getOpposite() == dir) { + return SpatialPylonTextureType.BASE; + } - return extState.getValue( BlockSpatialPylon.STATE ); - } + if ((flags & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_MIDDLE) { + return SpatialPylonTextureType.BASE_SPANNED; + } else if ((flags & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MIN) { + return SpatialPylonTextureType.BASE_END; + } else if ((flags & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MAX) { + return SpatialPylonTextureType.BASE_END; + } - private static SpatialPylonTextureType getTextureTypeFromSideOutside( int flags, EnumFacing ori, EnumFacing dir ) - { - if( ori == dir || ori.getOpposite() == dir ) - { - return SpatialPylonTextureType.BASE; - } + return SpatialPylonTextureType.BASE; + } - if( ( flags & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_MIDDLE ) - { - return SpatialPylonTextureType.BASE_SPANNED; - } - else if( ( flags & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MIN ) - { - return SpatialPylonTextureType.BASE_END; - } - else if( ( flags & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - return SpatialPylonTextureType.BASE_END; - } + private static SpatialPylonTextureType getTextureTypeFromSideInside(int flags, EnumFacing ori, EnumFacing dir) { + final boolean good = (flags & TileSpatialPylon.DISPLAY_ENABLED) == TileSpatialPylon.DISPLAY_ENABLED; - return SpatialPylonTextureType.BASE; - } + if (ori == dir || ori.getOpposite() == dir) { + return good ? SpatialPylonTextureType.DIM : SpatialPylonTextureType.RED; + } - private static SpatialPylonTextureType getTextureTypeFromSideInside( int flags, EnumFacing ori, EnumFacing dir ) - { - final boolean good = ( flags & TileSpatialPylon.DISPLAY_ENABLED ) == TileSpatialPylon.DISPLAY_ENABLED; + if ((flags & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_MIDDLE) { + return good ? SpatialPylonTextureType.DIM_SPANNED : SpatialPylonTextureType.RED_SPANNED; + } else if ((flags & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MIN) { + return good ? SpatialPylonTextureType.DIM_END : SpatialPylonTextureType.RED_END; + } else if ((flags & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MAX) { + return good ? SpatialPylonTextureType.DIM_END : SpatialPylonTextureType.RED_END; + } - if( ori == dir || ori.getOpposite() == dir ) - { - return good ? SpatialPylonTextureType.DIM : SpatialPylonTextureType.RED; - } + return SpatialPylonTextureType.BASE; + } - if( ( flags & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_MIDDLE ) - { - return good ? SpatialPylonTextureType.DIM_SPANNED : SpatialPylonTextureType.RED_SPANNED; - } - else if( ( flags & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MIN ) - { - return good ? SpatialPylonTextureType.DIM_END : SpatialPylonTextureType.RED_END; - } - else if( ( flags & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - return good ? SpatialPylonTextureType.DIM_END : SpatialPylonTextureType.RED_END; - } + @Override + public boolean isAmbientOcclusion() { + return true; + } - return SpatialPylonTextureType.BASE; - } + @Override + public boolean isGui3d() { + return false; + } - @Override - public boolean isAmbientOcclusion() - { - return true; - } + @Override + public boolean isBuiltInRenderer() { + return false; + } - @Override - public boolean isGui3d() - { - return false; - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.textures.get(SpatialPylonTextureType.DIM); + } - @Override - public boolean isBuiltInRenderer() - { - return false; - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return ItemCameraTransforms.DEFAULT; + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.textures.get( SpatialPylonTextureType.DIM ); - } - - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return ItemCameraTransforms.DEFAULT; - } - - @Override - public ItemOverrideList getOverrides() - { - return ItemOverrideList.NONE; - } + @Override + public ItemOverrideList getOverrides() { + return ItemOverrideList.NONE; + } } diff --git a/src/main/java/appeng/client/render/spatial/SpatialPylonModel.java b/src/main/java/appeng/client/render/spatial/SpatialPylonModel.java index b60432c13..861f51bf9 100644 --- a/src/main/java/appeng/client/render/spatial/SpatialPylonModel.java +++ b/src/main/java/appeng/client/render/spatial/SpatialPylonModel.java @@ -19,14 +19,7 @@ package appeng.client.render.spatial; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumMap; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; - +import appeng.core.AppEng; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -35,46 +28,41 @@ import net.minecraftforge.client.model.IModel; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; -import appeng.core.AppEng; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; -class SpatialPylonModel implements IModel -{ +class SpatialPylonModel implements IModel { - @Override - public Collection getDependencies() - { - return Collections.emptyList(); - } + @Override + public Collection getDependencies() { + return Collections.emptyList(); + } - @Override - public Collection getTextures() - { - return Arrays.stream( SpatialPylonTextureType.values() ).map( SpatialPylonModel::getTexturePath ).collect( Collectors.toList() ); - } + @Override + public Collection getTextures() { + return Arrays.stream(SpatialPylonTextureType.values()).map(SpatialPylonModel::getTexturePath).collect(Collectors.toList()); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - Map textures = new EnumMap<>( SpatialPylonTextureType.class ); + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + Map textures = new EnumMap<>(SpatialPylonTextureType.class); - for( SpatialPylonTextureType type : SpatialPylonTextureType.values() ) - { - ResourceLocation loc = getTexturePath( type ); - textures.put( type, bakedTextureGetter.apply( loc ) ); - } + for (SpatialPylonTextureType type : SpatialPylonTextureType.values()) { + ResourceLocation loc = getTexturePath(type); + textures.put(type, bakedTextureGetter.apply(loc)); + } - return new SpatialPylonBakedModel( format, textures ); - } + return new SpatialPylonBakedModel(format, textures); + } - @Override - public IModelState getDefaultState() - { - return TRSRTransformation.identity(); - } + @Override + public IModelState getDefaultState() { + return TRSRTransformation.identity(); + } - private static ResourceLocation getTexturePath( SpatialPylonTextureType type ) - { - return new ResourceLocation( AppEng.MOD_ID, "blocks/spatial_pylon/" + type.name().toLowerCase() ); - } + private static ResourceLocation getTexturePath(SpatialPylonTextureType type) { + return new ResourceLocation(AppEng.MOD_ID, "blocks/spatial_pylon/" + type.name().toLowerCase()); + } } diff --git a/src/main/java/appeng/client/render/spatial/SpatialPylonRendering.java b/src/main/java/appeng/client/render/spatial/SpatialPylonRendering.java index 9a417eb9f..153040b46 100644 --- a/src/main/java/appeng/client/render/spatial/SpatialPylonRendering.java +++ b/src/main/java/appeng/client/render/spatial/SpatialPylonRendering.java @@ -19,10 +19,11 @@ package appeng.client.render.spatial; -import java.util.Map; - +import appeng.bootstrap.BlockRenderingCustomizer; +import appeng.bootstrap.IBlockRendering; +import appeng.bootstrap.IItemRendering; +import appeng.core.AppEng; import com.google.common.collect.ImmutableMap; - import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.ModelResourceLocation; @@ -30,28 +31,22 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.bootstrap.BlockRenderingCustomizer; -import appeng.bootstrap.IBlockRendering; -import appeng.bootstrap.IItemRendering; -import appeng.core.AppEng; +import java.util.Map; -public class SpatialPylonRendering extends BlockRenderingCustomizer -{ +public class SpatialPylonRendering extends BlockRenderingCustomizer { - private static final ResourceLocation MODEL_ID = new ResourceLocation( AppEng.MOD_ID, "models/blocks/spatial_pylon/builtin" ); + private static final ResourceLocation MODEL_ID = new ResourceLocation(AppEng.MOD_ID, "models/blocks/spatial_pylon/builtin"); - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - rendering.builtInModel( MODEL_ID.getResourcePath(), new SpatialPylonModel() ); - rendering.stateMapper( this::mapState ); - } + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + rendering.builtInModel(MODEL_ID.getResourcePath(), new SpatialPylonModel()); + rendering.stateMapper(this::mapState); + } - private Map mapState( Block block ) - { - return ImmutableMap.of( block.getDefaultState(), new ModelResourceLocation( MODEL_ID, "normal" ) ); - } + private Map mapState(Block block) { + return ImmutableMap.of(block.getDefaultState(), new ModelResourceLocation(MODEL_ID, "normal")); + } } diff --git a/src/main/java/appeng/client/render/spatial/SpatialPylonStateProperty.java b/src/main/java/appeng/client/render/spatial/SpatialPylonStateProperty.java index 47b50c7d6..f78482a3c 100644 --- a/src/main/java/appeng/client/render/spatial/SpatialPylonStateProperty.java +++ b/src/main/java/appeng/client/render/spatial/SpatialPylonStateProperty.java @@ -25,32 +25,27 @@ import net.minecraftforge.common.property.IUnlistedProperty; /** * Models the rendering state of the spatial pylon, which is largely determined by the state of neighboring tiles. */ -public class SpatialPylonStateProperty implements IUnlistedProperty -{ +public class SpatialPylonStateProperty implements IUnlistedProperty { - @Override - public String getName() - { - return "spatial_state"; - } + @Override + public String getName() { + return "spatial_state"; + } - @Override - public boolean isValid( Integer value ) - { - int val = value; - // The lower 6 bits are used - return ( val & ~0x3F ) == 0; - } + @Override + public boolean isValid(Integer value) { + int val = value; + // The lower 6 bits are used + return (val & ~0x3F) == 0; + } - @Override - public Class getType() - { - return Integer.class; - } + @Override + public Class getType() { + return Integer.class; + } - @Override - public String valueToString( Integer value ) - { - return value.toString(); - } + @Override + public String valueToString(Integer value) { + return value.toString(); + } } diff --git a/src/main/java/appeng/client/render/spatial/SpatialPylonTextureType.java b/src/main/java/appeng/client/render/spatial/SpatialPylonTextureType.java index 47390f53e..87e73214e 100644 --- a/src/main/java/appeng/client/render/spatial/SpatialPylonTextureType.java +++ b/src/main/java/appeng/client/render/spatial/SpatialPylonTextureType.java @@ -19,7 +19,6 @@ package appeng.client.render.spatial; -enum SpatialPylonTextureType -{ - BASE, BASE_END, BASE_SPANNED, DIM, DIM_END, DIM_SPANNED, RED, RED_END, RED_SPANNED +enum SpatialPylonTextureType { + BASE, BASE_END, BASE_SPANNED, DIM, DIM_END, DIM_SPANNED, RED, RED_END, RED_SPANNED } diff --git a/src/main/java/appeng/client/render/tesr/CrankTESR.java b/src/main/java/appeng/client/render/tesr/CrankTESR.java index aa1f3c337..5bb9605e0 100644 --- a/src/main/java/appeng/client/render/tesr/CrankTESR.java +++ b/src/main/java/appeng/client/render/tesr/CrankTESR.java @@ -19,82 +19,71 @@ package appeng.client.render.tesr; -import org.lwjgl.opengl.GL11; - +import appeng.client.render.FacingToRotation; +import appeng.tile.grindstone.TileCrank; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.BlockRendererDispatcher; -import net.minecraft.client.renderer.BufferBuilder; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.*; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; - -import appeng.client.render.FacingToRotation; -import appeng.tile.grindstone.TileCrank; +import org.lwjgl.opengl.GL11; /** * This FastTESR only handles the animated model of the turning crank. When the crank is at rest, it is rendered using a * normal model. */ -@SideOnly( Side.CLIENT ) -public class CrankTESR extends TileEntitySpecialRenderer -{ +@SideOnly(Side.CLIENT) +public class CrankTESR extends TileEntitySpecialRenderer { - @Override - public void render( TileCrank te, double x, double y, double z, float partialTicks, int destroyStage, float p_render_10_ ) - { - // Most of this is blatantly copied from FastTESR - Tessellator tessellator = Tessellator.getInstance(); - this.bindTexture( TextureMap.LOCATION_BLOCKS_TEXTURE ); - RenderHelper.disableStandardItemLighting(); - GlStateManager.blendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); - GlStateManager.enableBlend(); - GlStateManager.disableCull(); + @Override + public void render(TileCrank te, double x, double y, double z, float partialTicks, int destroyStage, float p_render_10_) { + // Most of this is blatantly copied from FastTESR + Tessellator tessellator = Tessellator.getInstance(); + this.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); + RenderHelper.disableStandardItemLighting(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GlStateManager.enableBlend(); + GlStateManager.disableCull(); - if( Minecraft.isAmbientOcclusionEnabled() ) - { - GlStateManager.shadeModel( GL11.GL_SMOOTH ); - } - else - { - GlStateManager.shadeModel( GL11.GL_FLAT ); - } + if (Minecraft.isAmbientOcclusionEnabled()) { + GlStateManager.shadeModel(GL11.GL_SMOOTH); + } else { + GlStateManager.shadeModel(GL11.GL_FLAT); + } - IBlockState blockState = te.getWorld().getBlockState( te.getPos() ); + IBlockState blockState = te.getWorld().getBlockState(te.getPos()); - BlockRendererDispatcher dispatcher = Minecraft.getMinecraft().getBlockRendererDispatcher(); - IBakedModel model = dispatcher.getModelForState( blockState ); + BlockRendererDispatcher dispatcher = Minecraft.getMinecraft().getBlockRendererDispatcher(); + IBakedModel model = dispatcher.getModelForState(blockState); - BufferBuilder buffer = tessellator.getBuffer(); - buffer.begin( GL11.GL_QUADS, DefaultVertexFormats.BLOCK ); + BufferBuilder buffer = tessellator.getBuffer(); + buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.BLOCK); - // The translation ensures the vertex buffer positions are relative to 0,0,0 instead of the block pos - // This makes the translations that follow much easier - buffer.setTranslation( -te.getPos().getX(), -te.getPos().getY(), -te.getPos().getZ() ); - dispatcher.getBlockModelRenderer().renderModel( te.getWorld(), model, blockState, te.getPos(), buffer, false ); - buffer.setTranslation( 0, 0, 0 ); + // The translation ensures the vertex buffer positions are relative to 0,0,0 instead of the block pos + // This makes the translations that follow much easier + buffer.setTranslation(-te.getPos().getX(), -te.getPos().getY(), -te.getPos().getZ()); + dispatcher.getBlockModelRenderer().renderModel(te.getWorld(), model, blockState, te.getPos(), buffer, false); + buffer.setTranslation(0, 0, 0); - GlStateManager.pushMatrix(); - GlStateManager.translate( x, y, z ); + GlStateManager.pushMatrix(); + GlStateManager.translate(x, y, z); - // Apply GL transformations relative to the center of the block: 1) TE rotation and 2) crank rotation - GlStateManager.translate( 0.5, 0.5, 0.5 ); - FacingToRotation.get( te.getForward(), te.getUp() ).glRotateCurrentMat(); - GlStateManager.rotate( te.getVisibleRotation(), 0, 1, 0 ); - GlStateManager.translate( -0.5, -0.5, -0.5 ); + // Apply GL transformations relative to the center of the block: 1) TE rotation and 2) crank rotation + GlStateManager.translate(0.5, 0.5, 0.5); + FacingToRotation.get(te.getForward(), te.getUp()).glRotateCurrentMat(); + GlStateManager.rotate(te.getVisibleRotation(), 0, 1, 0); + GlStateManager.translate(-0.5, -0.5, -0.5); - tessellator.draw(); + tessellator.draw(); - GlStateManager.popMatrix(); + GlStateManager.popMatrix(); - RenderHelper.enableStandardItemLighting(); - } + RenderHelper.enableStandardItemLighting(); + } } diff --git a/src/main/java/appeng/client/render/tesr/InscriberTESR.java b/src/main/java/appeng/client/render/tesr/InscriberTESR.java index a3dec5998..52538ed10 100644 --- a/src/main/java/appeng/client/render/tesr/InscriberTESR.java +++ b/src/main/java/appeng/client/render/tesr/InscriberTESR.java @@ -1,9 +1,11 @@ - package appeng.client.render.tesr; -import org.lwjgl.opengl.GL11; - +import appeng.api.features.IInscriberRecipe; +import appeng.client.render.FacingToRotation; +import appeng.core.AppEng; +import appeng.tile.AEBaseTile; +import appeng.tile.misc.TileInscriber; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; @@ -19,186 +21,163 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.items.IItemHandler; - -import appeng.api.features.IInscriberRecipe; -import appeng.client.render.FacingToRotation; -import appeng.core.AppEng; -import appeng.tile.AEBaseTile; -import appeng.tile.misc.TileInscriber; +import org.lwjgl.opengl.GL11; /** * Renders the dynamic parts of an inscriber (the presses, the animation and the item being smashed) */ -public final class InscriberTESR extends TileEntitySpecialRenderer -{ +public final class InscriberTESR extends TileEntitySpecialRenderer { - private static final float ITEM_RENDER_SCALE = 1.0f / 1.2f; + private static final float ITEM_RENDER_SCALE = 1.0f / 1.2f; - private static final ResourceLocation TEXTURE_INSIDE = new ResourceLocation( AppEng.MOD_ID, "blocks/inscriber_inside" ); + private static final ResourceLocation TEXTURE_INSIDE = new ResourceLocation(AppEng.MOD_ID, "blocks/inscriber_inside"); - private static TextureAtlasSprite textureInside; + private static TextureAtlasSprite textureInside; - @Override - public void render( final TileInscriber tile, final double x, final double y, final double z, final float partialTicks, final int destroyStage, final float p_render_10_ ) - { - // render inscriber + @Override + public void render(final TileInscriber tile, final double x, final double y, final double z, final float partialTicks, final int destroyStage, final float p_render_10_) { + // render inscriber - GlStateManager.pushMatrix(); - GlStateManager.translate( x, y, z ); - GlStateManager.translate( 0.5F, 0.5F, 0.5F ); - FacingToRotation.get( tile.getForward(), tile.getUp() ).glRotateCurrentMat(); - GlStateManager.translate( -0.5F, -0.5F, -0.5F ); + GlStateManager.pushMatrix(); + GlStateManager.translate(x, y, z); + GlStateManager.translate(0.5F, 0.5F, 0.5F); + FacingToRotation.get(tile.getForward(), tile.getUp()).glRotateCurrentMat(); + GlStateManager.translate(-0.5F, -0.5F, -0.5F); - GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); - GlStateManager.disableLighting(); - GlStateManager.disableRescaleNormal(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.disableLighting(); + GlStateManager.disableRescaleNormal(); - // render sides of stamps + // render sides of stamps - Minecraft mc = Minecraft.getMinecraft(); - mc.renderEngine.bindTexture( TextureMap.LOCATION_BLOCKS_TEXTURE ); + Minecraft mc = Minecraft.getMinecraft(); + mc.renderEngine.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); - // << 20 | light << 4; - final int br = tile.getWorld().getCombinedLight( tile.getPos(), 0 ); - final int var11 = br % 65536; - final int var12 = br / 65536; + // << 20 | light << 4; + final int br = tile.getWorld().getCombinedLight(tile.getPos(), 0); + final int var11 = br % 65536; + final int var12 = br / 65536; - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, var11, var12 ); + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, var11, var12); - long absoluteProgress = 0; + long absoluteProgress = 0; - if( tile.isSmash() ) - { - final long currentTime = System.currentTimeMillis(); - absoluteProgress = currentTime - tile.getClientStart(); - if( absoluteProgress > 800 ) - { - tile.setSmash( false ); - } - } + if (tile.isSmash()) { + final long currentTime = System.currentTimeMillis(); + absoluteProgress = currentTime - tile.getClientStart(); + if (absoluteProgress > 800) { + tile.setSmash(false); + } + } - final float relativeProgress = absoluteProgress % 800 / 400.0f; - float progress = relativeProgress; + final float relativeProgress = absoluteProgress % 800 / 400.0f; + float progress = relativeProgress; - if( progress > 1.0f ) - { - progress = 1.0f - ( progress - 1.0f ); - } - float press = 0.2f; - press -= progress / 5.0f; + if (progress > 1.0f) { + progress = 1.0f - (progress - 1.0f); + } + float press = 0.2f; + press -= progress / 5.0f; - final BufferBuilder buffer = Tessellator.getInstance().getBuffer(); - buffer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX ); + final BufferBuilder buffer = Tessellator.getInstance().getBuffer(); + buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX); - float middle = 0.5f; - middle += 0.02f; - final float TwoPx = 2.0f / 16.0f; - final float base = 0.4f; + float middle = 0.5f; + middle += 0.02f; + final float TwoPx = 2.0f / 16.0f; + final float base = 0.4f; - final TextureAtlasSprite tas = textureInside; - if( tas != null ) - { - // Bottom of Top Stamp - buffer.pos( TwoPx, middle + press, TwoPx ).tex( tas.getInterpolatedU( 2 ), tas.getInterpolatedV( 13 ) ).endVertex(); - buffer.pos( 1.0 - TwoPx, middle + press, TwoPx ).tex( tas.getInterpolatedU( 14 ), tas.getInterpolatedV( 13 ) ).endVertex(); - buffer.pos( 1.0 - TwoPx, middle + press, 1.0 - TwoPx ).tex( tas.getInterpolatedU( 14 ), tas.getInterpolatedV( 2 ) ).endVertex(); - buffer.pos( TwoPx, middle + press, 1.0 - TwoPx ).tex( tas.getInterpolatedU( 2 ), tas.getInterpolatedV( 2 ) ).endVertex(); + final TextureAtlasSprite tas = textureInside; + if (tas != null) { + // Bottom of Top Stamp + buffer.pos(TwoPx, middle + press, TwoPx).tex(tas.getInterpolatedU(2), tas.getInterpolatedV(13)).endVertex(); + buffer.pos(1.0 - TwoPx, middle + press, TwoPx).tex(tas.getInterpolatedU(14), tas.getInterpolatedV(13)).endVertex(); + buffer.pos(1.0 - TwoPx, middle + press, 1.0 - TwoPx).tex(tas.getInterpolatedU(14), tas.getInterpolatedV(2)).endVertex(); + buffer.pos(TwoPx, middle + press, 1.0 - TwoPx).tex(tas.getInterpolatedU(2), tas.getInterpolatedV(2)).endVertex(); - // Front of Top Stamp - buffer.pos( TwoPx, middle + base, TwoPx ).tex( tas.getInterpolatedU( 2 ), tas.getInterpolatedV( 3 - 16 * ( press - base ) ) ).endVertex(); - buffer.pos( 1.0 - TwoPx, middle + base, TwoPx ).tex( tas.getInterpolatedU( 14 ), tas.getInterpolatedV( 3 - 16 * ( press - base ) ) ).endVertex(); - buffer.pos( 1.0 - TwoPx, middle + press, TwoPx ).tex( tas.getInterpolatedU( 14 ), tas.getInterpolatedV( 3 ) ).endVertex(); - buffer.pos( TwoPx, middle + press, TwoPx ).tex( tas.getInterpolatedU( 2 ), tas.getInterpolatedV( 3 ) ).endVertex(); + // Front of Top Stamp + buffer.pos(TwoPx, middle + base, TwoPx).tex(tas.getInterpolatedU(2), tas.getInterpolatedV(3 - 16 * (press - base))).endVertex(); + buffer.pos(1.0 - TwoPx, middle + base, TwoPx).tex(tas.getInterpolatedU(14), tas.getInterpolatedV(3 - 16 * (press - base))).endVertex(); + buffer.pos(1.0 - TwoPx, middle + press, TwoPx).tex(tas.getInterpolatedU(14), tas.getInterpolatedV(3)).endVertex(); + buffer.pos(TwoPx, middle + press, TwoPx).tex(tas.getInterpolatedU(2), tas.getInterpolatedV(3)).endVertex(); - // Top of Bottom Stamp - middle -= 2.0f * 0.02f; - buffer.pos( 1.0 - TwoPx, middle - press, TwoPx ).tex( tas.getInterpolatedU( 2 ), tas.getInterpolatedV( 13 ) ).endVertex(); - buffer.pos( TwoPx, middle - press, TwoPx ).tex( tas.getInterpolatedU( 14 ), tas.getInterpolatedV( 13 ) ).endVertex(); - buffer.pos( TwoPx, middle - press, 1.0 - TwoPx ).tex( tas.getInterpolatedU( 14 ), tas.getInterpolatedV( 2 ) ).endVertex(); - buffer.pos( 1.0 - TwoPx, middle - press, 1.0 - TwoPx ).tex( tas.getInterpolatedU( 2 ), tas.getInterpolatedV( 2 ) ).endVertex(); + // Top of Bottom Stamp + middle -= 2.0f * 0.02f; + buffer.pos(1.0 - TwoPx, middle - press, TwoPx).tex(tas.getInterpolatedU(2), tas.getInterpolatedV(13)).endVertex(); + buffer.pos(TwoPx, middle - press, TwoPx).tex(tas.getInterpolatedU(14), tas.getInterpolatedV(13)).endVertex(); + buffer.pos(TwoPx, middle - press, 1.0 - TwoPx).tex(tas.getInterpolatedU(14), tas.getInterpolatedV(2)).endVertex(); + buffer.pos(1.0 - TwoPx, middle - press, 1.0 - TwoPx).tex(tas.getInterpolatedU(2), tas.getInterpolatedV(2)).endVertex(); - // Front of Bottom Stamp - buffer.pos( 1.0 - TwoPx, middle + -base, TwoPx ).tex( tas.getInterpolatedU( 2 ), tas.getInterpolatedV( 3 - 16 * ( press - base ) ) ).endVertex(); - buffer.pos( TwoPx, middle - base, TwoPx ).tex( tas.getInterpolatedU( 14 ), tas.getInterpolatedV( 3 - 16 * ( press - base ) ) ).endVertex(); - buffer.pos( TwoPx, middle - press, TwoPx ).tex( tas.getInterpolatedU( 14 ), tas.getInterpolatedV( 3 ) ).endVertex(); - buffer.pos( 1.0 - TwoPx, middle - press, TwoPx ).tex( tas.getInterpolatedU( 2 ), tas.getInterpolatedV( 3 ) ).endVertex(); - } + // Front of Bottom Stamp + buffer.pos(1.0 - TwoPx, middle + -base, TwoPx).tex(tas.getInterpolatedU(2), tas.getInterpolatedV(3 - 16 * (press - base))).endVertex(); + buffer.pos(TwoPx, middle - base, TwoPx).tex(tas.getInterpolatedU(14), tas.getInterpolatedV(3 - 16 * (press - base))).endVertex(); + buffer.pos(TwoPx, middle - press, TwoPx).tex(tas.getInterpolatedU(14), tas.getInterpolatedV(3)).endVertex(); + buffer.pos(1.0 - TwoPx, middle - press, TwoPx).tex(tas.getInterpolatedU(2), tas.getInterpolatedV(3)).endVertex(); + } - Tessellator.getInstance().draw(); + Tessellator.getInstance().draw(); - // render items. - GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); + // render items. + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - IItemHandler tileInv = tile.getInternalInventory(); + IItemHandler tileInv = tile.getInternalInventory(); - int items = 0; - if( !tileInv.getStackInSlot( 0 ).isEmpty() ) - { - items++; - } - if( !tileInv.getStackInSlot( 1 ).isEmpty() ) - { - items++; - } - if( !tileInv.getStackInSlot( 2 ).isEmpty() ) - { - items++; - } + int items = 0; + if (!tileInv.getStackInSlot(0).isEmpty()) { + items++; + } + if (!tileInv.getStackInSlot(1).isEmpty()) { + items++; + } + if (!tileInv.getStackInSlot(2).isEmpty()) { + items++; + } - if( relativeProgress > 1.0f || items == 0 ) - { - ItemStack is = tileInv.getStackInSlot( 3 ); + if (relativeProgress > 1.0f || items == 0) { + ItemStack is = tileInv.getStackInSlot(3); - if( is.isEmpty() ) - { - final IInscriberRecipe ir = tile.getTask(); - if( ir != null ) - { - is = ir.getOutput().copy(); - } - } + if (is.isEmpty()) { + final IInscriberRecipe ir = tile.getTask(); + if (ir != null) { + is = ir.getOutput().copy(); + } + } - this.renderItem( is, 0.0f, tile, x, y, z ); - } - else - { - this.renderItem( tileInv.getStackInSlot( 0 ), press, tile, x, y, z ); - this.renderItem( tileInv.getStackInSlot( 1 ), -press, tile, x, y, z ); - this.renderItem( tileInv.getStackInSlot( 2 ), 0.0f, tile, x, y, z ); - } + this.renderItem(is, 0.0f, tile, x, y, z); + } else { + this.renderItem(tileInv.getStackInSlot(0), press, tile, x, y, z); + this.renderItem(tileInv.getStackInSlot(1), -press, tile, x, y, z); + this.renderItem(tileInv.getStackInSlot(2), 0.0f, tile, x, y, z); + } - GlStateManager.popMatrix(); - GlStateManager.enableLighting(); - GlStateManager.enableRescaleNormal(); - } + GlStateManager.popMatrix(); + GlStateManager.enableLighting(); + GlStateManager.enableRescaleNormal(); + } - private void renderItem( final ItemStack stack, final float o, final AEBaseTile tile, final double x, final double y, final double z ) - { - if( !stack.isEmpty() ) - { - final ItemStack sis = stack.copy(); + private void renderItem(final ItemStack stack, final float o, final AEBaseTile tile, final double x, final double y, final double z) { + if (!stack.isEmpty()) { + final ItemStack sis = stack.copy(); - GlStateManager.pushMatrix(); - // move to center - GlStateManager.translate( 0.5f, 0.5f + o, 0.5f ); - GlStateManager.rotate( 90, 1, 0, 0 ); - // set scale - GlStateManager.scale( ITEM_RENDER_SCALE, ITEM_RENDER_SCALE, ITEM_RENDER_SCALE ); + GlStateManager.pushMatrix(); + // move to center + GlStateManager.translate(0.5f, 0.5f + o, 0.5f); + GlStateManager.rotate(90, 1, 0, 0); + // set scale + GlStateManager.scale(ITEM_RENDER_SCALE, ITEM_RENDER_SCALE, ITEM_RENDER_SCALE); - // heuristic to scale items down much further than blocks - if( !( sis.getItem() instanceof ItemBlock ) ) - { - GlStateManager.scale( 0.5, 0.5, 0.5 ); - } + // heuristic to scale items down much further than blocks + if (!(sis.getItem() instanceof ItemBlock)) { + GlStateManager.scale(0.5, 0.5, 0.5); + } - Minecraft.getMinecraft().getRenderItem().renderItem( sis, ItemCameraTransforms.TransformType.FIXED ); - GlStateManager.popMatrix(); - } - } + Minecraft.getMinecraft().getRenderItem().renderItem(sis, ItemCameraTransforms.TransformType.FIXED); + GlStateManager.popMatrix(); + } + } - public static void registerTexture( TextureStitchEvent.Pre event ) - { - textureInside = event.getMap().registerSprite( TEXTURE_INSIDE ); - } + public static void registerTexture(TextureStitchEvent.Pre event) { + textureInside = event.getMap().registerSprite(TEXTURE_INSIDE); + } } diff --git a/src/main/java/appeng/client/render/tesr/ModularTESR.java b/src/main/java/appeng/client/render/tesr/ModularTESR.java index 972ce8dda..b2d7812e2 100644 --- a/src/main/java/appeng/client/render/tesr/ModularTESR.java +++ b/src/main/java/appeng/client/render/tesr/ModularTESR.java @@ -19,56 +19,49 @@ package appeng.client.render.tesr; +import appeng.client.render.FacingToRotation; +import appeng.client.render.renderable.Renderable; +import appeng.tile.AEBaseTile; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.client.render.FacingToRotation; -import appeng.client.render.renderable.Renderable; -import appeng.tile.AEBaseTile; +@SideOnly(Side.CLIENT) +public class ModularTESR extends TileEntitySpecialRenderer { -@SideOnly( Side.CLIENT ) -public class ModularTESR extends TileEntitySpecialRenderer -{ + private final Renderable[] renderables; - private final Renderable[] renderables; + public ModularTESR(Renderable... renderables) { + this.renderables = renderables; + } - public ModularTESR( Renderable... renderables ) - { - this.renderables = renderables; - } + @Override + public void render(T te, double x, double y, double z, float partialTicks, int destroyStage, float p_render_10_) { + GlStateManager.pushMatrix(); + GlStateManager.translate(x, y, z); + GlStateManager.translate(0.5, 0.5, 0.5); + FacingToRotation.get(te.getForward(), te.getUp()).glRotateCurrentMat(); + GlStateManager.translate(-0.5, -0.5, -0.5); + for (Renderable renderable : this.renderables) { + renderable.renderTileEntityAt(te, x, y, z, partialTicks, destroyStage); + } + GlStateManager.popMatrix(); + } - @Override - public void render( T te, double x, double y, double z, float partialTicks, int destroyStage, float p_render_10_ ) - { - GlStateManager.pushMatrix(); - GlStateManager.translate( x, y, z ); - GlStateManager.translate( 0.5, 0.5, 0.5 ); - FacingToRotation.get( te.getForward(), te.getUp() ).glRotateCurrentMat(); - GlStateManager.translate( -0.5, -0.5, -0.5 ); - for( Renderable renderable : this.renderables ) - { - renderable.renderTileEntityAt( te, x, y, z, partialTicks, destroyStage ); - } - GlStateManager.popMatrix(); - } - - @Override - public void renderTileEntityFast( T te, double x, double y, double z, float partialTicks, int destroyStage, float p_render_10_, BufferBuilder buffer ) - { - GlStateManager.pushMatrix(); - GlStateManager.translate( x, y, z ); - GlStateManager.translate( 0.5, 0.5, 0.5 ); - FacingToRotation.get( te.getForward(), te.getUp() ).glRotateCurrentMat(); - GlStateManager.translate( -0.5, -0.5, -0.5 ); - for( Renderable renderable : this.renderables ) - { - renderable.renderTileEntityFast( te, x, y, z, partialTicks, destroyStage, buffer ); - } - GlStateManager.popMatrix(); - } + @Override + public void renderTileEntityFast(T te, double x, double y, double z, float partialTicks, int destroyStage, float p_render_10_, BufferBuilder buffer) { + GlStateManager.pushMatrix(); + GlStateManager.translate(x, y, z); + GlStateManager.translate(0.5, 0.5, 0.5); + FacingToRotation.get(te.getForward(), te.getUp()).glRotateCurrentMat(); + GlStateManager.translate(-0.5, -0.5, -0.5); + for (Renderable renderable : this.renderables) { + renderable.renderTileEntityFast(te, x, y, z, partialTicks, destroyStage, buffer); + } + GlStateManager.popMatrix(); + } } \ No newline at end of file diff --git a/src/main/java/appeng/client/render/tesr/SkyChestTESR.java b/src/main/java/appeng/client/render/tesr/SkyChestTESR.java index 616e2475b..adaf2c6fd 100644 --- a/src/main/java/appeng/client/render/tesr/SkyChestTESR.java +++ b/src/main/java/appeng/client/render/tesr/SkyChestTESR.java @@ -19,6 +19,11 @@ package appeng.client.render.tesr; +import appeng.block.storage.BlockSkyChest; +import appeng.block.storage.BlockSkyChest.SkyChestType; +import appeng.client.render.FacingToRotation; +import appeng.core.AppEng; +import appeng.tile.storage.TileSkyChest; import net.minecraft.block.Block; import net.minecraft.client.model.ModelChest; import net.minecraft.client.renderer.GlStateManager; @@ -28,115 +33,92 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.block.storage.BlockSkyChest; -import appeng.block.storage.BlockSkyChest.SkyChestType; -import appeng.client.render.FacingToRotation; -import appeng.core.AppEng; -import appeng.tile.storage.TileSkyChest; +@SideOnly(Side.CLIENT) +public class SkyChestTESR extends TileEntitySpecialRenderer { -@SideOnly( Side.CLIENT ) -public class SkyChestTESR extends TileEntitySpecialRenderer -{ + private static final ResourceLocation TEXTURE_STONE = new ResourceLocation(AppEng.MOD_ID, "textures/models/skychest.png"); + private static final ResourceLocation TEXTURE_BLOCK = new ResourceLocation(AppEng.MOD_ID, "textures/models/skyblockchest.png"); - private static final ResourceLocation TEXTURE_STONE = new ResourceLocation( AppEng.MOD_ID, "textures/models/skychest.png" ); - private static final ResourceLocation TEXTURE_BLOCK = new ResourceLocation( AppEng.MOD_ID, "textures/models/skyblockchest.png" ); + private final ModelChest simpleChest = new ModelChest(); - private final ModelChest simpleChest = new ModelChest(); + public SkyChestTESR() { - public SkyChestTESR() - { + } - } + @Override + public void render(TileSkyChest te, double x, double y, double z, float partialTicks, int destroyStage, float p_render_10_) { + GlStateManager.enableDepth(); + GlStateManager.depthFunc(515); + GlStateManager.depthMask(true); - @Override - public void render( TileSkyChest te, double x, double y, double z, float partialTicks, int destroyStage, float p_render_10_ ) - { - GlStateManager.enableDepth(); - GlStateManager.depthFunc( 515 ); - GlStateManager.depthMask( true ); + ModelChest modelchest; - ModelChest modelchest; + modelchest = this.simpleChest; - modelchest = this.simpleChest; + if (destroyStage >= 0) { + this.bindTexture(DESTROY_STAGES[destroyStage]); + GlStateManager.matrixMode(5890); + GlStateManager.pushMatrix(); + GlStateManager.scale(4.0F, 4.0F, 1.0F); + GlStateManager.translate(0.0625F, 0.0625F, 0.0625F); + GlStateManager.matrixMode(5888); + } else { + SkyChestType chestType = getChestType(te); + this.bindTexture(chestType == SkyChestType.STONE ? TEXTURE_STONE : TEXTURE_BLOCK); + } - if( destroyStage >= 0 ) - { - this.bindTexture( DESTROY_STAGES[destroyStage] ); - GlStateManager.matrixMode( 5890 ); - GlStateManager.pushMatrix(); - GlStateManager.scale( 4.0F, 4.0F, 1.0F ); - GlStateManager.translate( 0.0625F, 0.0625F, 0.0625F ); - GlStateManager.matrixMode( 5888 ); - } - else - { - SkyChestType chestType = getChestType( te ); - this.bindTexture( chestType == SkyChestType.STONE ? TEXTURE_STONE : TEXTURE_BLOCK ); - } + GlStateManager.pushMatrix(); + GlStateManager.enableRescaleNormal(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.translate((float) x, (float) y + 1.0F, (float) z + 1.0F); + GlStateManager.scale(1.0F, -1.0F, -1.0F); + if (te != null) { + GlStateManager.translate(0.5F, 0.5F, 0.5F); + // In the vanilla chest model, north and south are flipped + EnumFacing forward = te.getForward(); + EnumFacing up = te.getUp(); + if (forward == EnumFacing.SOUTH) { + forward = EnumFacing.NORTH; + } else if (forward == EnumFacing.NORTH) { + forward = EnumFacing.SOUTH; + } + if (up == EnumFacing.SOUTH) { + up = EnumFacing.NORTH; + } else if (up == EnumFacing.NORTH) { + up = EnumFacing.SOUTH; + } + FacingToRotation.get(forward, up).glRotateCurrentMat(); + GlStateManager.translate(-0.5F, -0.5F, -0.5F); + } + float f = te != null ? te.getPrevLidAngle() + (te.getLidAngle() - te.getPrevLidAngle()) * partialTicks : 0; - GlStateManager.pushMatrix(); - GlStateManager.enableRescaleNormal(); - GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); - GlStateManager.translate( (float) x, (float) y + 1.0F, (float) z + 1.0F ); - GlStateManager.scale( 1.0F, -1.0F, -1.0F ); - if( te != null ) - { - GlStateManager.translate( 0.5F, 0.5F, 0.5F ); - // In the vanilla chest model, north and south are flipped - EnumFacing forward = te.getForward(); - EnumFacing up = te.getUp(); - if( forward == EnumFacing.SOUTH ) - { - forward = EnumFacing.NORTH; - } - else if( forward == EnumFacing.NORTH ) - { - forward = EnumFacing.SOUTH; - } - if( up == EnumFacing.SOUTH ) - { - up = EnumFacing.NORTH; - } - else if( up == EnumFacing.NORTH ) - { - up = EnumFacing.SOUTH; - } - FacingToRotation.get( forward, up ).glRotateCurrentMat(); - GlStateManager.translate( -0.5F, -0.5F, -0.5F ); - } - float f = te != null ? te.getPrevLidAngle() + ( te.getLidAngle() - te.getPrevLidAngle() ) * partialTicks : 0; + f = 1.0F - f; + f = 1.0F - f * f * f; + modelchest.chestLid.rotateAngleX = -(f * ((float) Math.PI / 2F)); + modelchest.renderAll(); + GlStateManager.disableRescaleNormal(); + GlStateManager.popMatrix(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - f = 1.0F - f; - f = 1.0F - f * f * f; - modelchest.chestLid.rotateAngleX = -( f * ( (float) Math.PI / 2F ) ); - modelchest.renderAll(); - GlStateManager.disableRescaleNormal(); - GlStateManager.popMatrix(); - GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); + if (destroyStage >= 0) { + GlStateManager.matrixMode(5890); + GlStateManager.popMatrix(); + GlStateManager.matrixMode(5888); + } + } - if( destroyStage >= 0 ) - { - GlStateManager.matrixMode( 5890 ); - GlStateManager.popMatrix(); - GlStateManager.matrixMode( 5888 ); - } - } + // Defensively determine the sky chest type + private static SkyChestType getChestType(TileSkyChest te) { + if (te == null) { + return SkyChestType.BLOCK; + } - // Defensively determine the sky chest type - private static SkyChestType getChestType( TileSkyChest te ) - { - if( te == null ) - { - return SkyChestType.BLOCK; - } - - Block blockType = te.getBlockType(); - if( blockType instanceof BlockSkyChest ) - { - return ( (BlockSkyChest) blockType ).type; - } - return SkyChestType.BLOCK; - } + Block blockType = te.getBlockType(); + if (blockType instanceof BlockSkyChest) { + return ((BlockSkyChest) blockType).type; + } + return SkyChestType.BLOCK; + } } diff --git a/src/main/java/appeng/client/render/tesr/SkyCompassTESR.java b/src/main/java/appeng/client/render/tesr/SkyCompassTESR.java index e2a45cade..e8fc31766 100644 --- a/src/main/java/appeng/client/render/tesr/SkyCompassTESR.java +++ b/src/main/java/appeng/client/render/tesr/SkyCompassTESR.java @@ -19,6 +19,10 @@ package appeng.client.render.tesr; +import appeng.block.AEBaseTileBlock; +import appeng.block.misc.BlockSkyCompass; +import appeng.client.render.model.SkyCompassBakedModel; +import appeng.tile.misc.TileSkyCompass; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BlockRendererDispatcher; @@ -34,90 +38,72 @@ import net.minecraftforge.common.property.Properties; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.block.AEBaseTileBlock; -import appeng.block.misc.BlockSkyCompass; -import appeng.client.render.model.SkyCompassBakedModel; -import appeng.tile.misc.TileSkyCompass; +@SideOnly(Side.CLIENT) +public class SkyCompassTESR extends FastTESR { -@SideOnly( Side.CLIENT ) -public class SkyCompassTESR extends FastTESR -{ + private static BlockRendererDispatcher blockRenderer; - private static BlockRendererDispatcher blockRenderer; + @Override + public void renderTileEntityFast(TileSkyCompass te, double x, double y, double z, float partialTicks, int destroyStage, float var10, BufferBuilder buffer) { - @Override - public void renderTileEntityFast( TileSkyCompass te, double x, double y, double z, float partialTicks, int destroyStage, float var10, BufferBuilder buffer ) - { + if (!te.hasWorld()) { + return; + } - if( !te.hasWorld() ) - { - return; - } + if (blockRenderer == null) { + blockRenderer = Minecraft.getMinecraft().getBlockRendererDispatcher(); + } - if( blockRenderer == null ) - { - blockRenderer = Minecraft.getMinecraft().getBlockRendererDispatcher(); - } + BlockPos pos = te.getPos(); + IBlockAccess world = MinecraftForgeClient.getRegionRenderCache(te.getWorld(), pos); + IBlockState state = world.getBlockState(pos); + if (state.getPropertyKeys().contains(Properties.StaticProperty)) { + state = state.withProperty(Properties.StaticProperty, false); + } - BlockPos pos = te.getPos(); - IBlockAccess world = MinecraftForgeClient.getRegionRenderCache( te.getWorld(), pos ); - IBlockState state = world.getBlockState( pos ); - if( state.getPropertyKeys().contains( Properties.StaticProperty ) ) - { - state = state.withProperty( Properties.StaticProperty, false ); - } + if (state instanceof IExtendedBlockState) { + IExtendedBlockState exState = (IExtendedBlockState) state.getBlock().getExtendedState(state, world, pos); - if( state instanceof IExtendedBlockState ) - { - IExtendedBlockState exState = (IExtendedBlockState) state.getBlock().getExtendedState( state, world, pos ); + IBakedModel model = blockRenderer.getBlockModelShapes().getModelForState(exState.getClean()); + exState = exState.withProperty(BlockSkyCompass.ROTATION, getRotation(te)); - IBakedModel model = blockRenderer.getBlockModelShapes().getModelForState( exState.getClean() ); - exState = exState.withProperty( BlockSkyCompass.ROTATION, getRotation( te ) ); + // Flip forward/up for rendering, the base model is facing up without any rotation + EnumFacing forward = exState.getValue(AEBaseTileBlock.FORWARD); + EnumFacing up = exState.getValue(AEBaseTileBlock.UP); + // This ensures the needle isn't flipped by the model rotator. Since the model is symmetrical, this should + // not affect the appearance + if (forward == EnumFacing.UP || forward == EnumFacing.DOWN) { + up = EnumFacing.NORTH; + } + exState = exState.withProperty(AEBaseTileBlock.FORWARD, up) + .withProperty(AEBaseTileBlock.UP, forward); - // Flip forward/up for rendering, the base model is facing up without any rotation - EnumFacing forward = exState.getValue( AEBaseTileBlock.FORWARD ); - EnumFacing up = exState.getValue( AEBaseTileBlock.UP ); - // This ensures the needle isn't flipped by the model rotator. Since the model is symmetrical, this should - // not affect the appearance - if( forward == EnumFacing.UP || forward == EnumFacing.DOWN ) - { - up = EnumFacing.NORTH; - } - exState = exState.withProperty( AEBaseTileBlock.FORWARD, up ) - .withProperty( AEBaseTileBlock.UP, forward ); + buffer.setTranslation(x - pos.getX(), y - pos.getY(), z - pos.getZ()); - buffer.setTranslation( x - pos.getX(), y - pos.getY(), z - pos.getZ() ); + blockRenderer.getBlockModelRenderer().renderModel(world, model, exState, pos, buffer, false); + } + } - blockRenderer.getBlockModelRenderer().renderModel( world, model, exState, pos, buffer, false ); - } - } + private static float getRotation(TileSkyCompass skyCompass) { + float rotation; - private static float getRotation( TileSkyCompass skyCompass ) - { - float rotation; + if (skyCompass.getForward() == EnumFacing.UP || skyCompass.getForward() == EnumFacing.DOWN) { + rotation = SkyCompassBakedModel.getAnimatedRotation(skyCompass.getPos(), false); + } else { + rotation = SkyCompassBakedModel.getAnimatedRotation(null, false); + } - if( skyCompass.getForward() == EnumFacing.UP || skyCompass.getForward() == EnumFacing.DOWN ) - { - rotation = SkyCompassBakedModel.getAnimatedRotation( skyCompass.getPos(), false ); - } - else - { - rotation = SkyCompassBakedModel.getAnimatedRotation( null, false ); - } + if (skyCompass.getForward() == EnumFacing.DOWN) { + rotation = flipidiy(rotation); + } - if( skyCompass.getForward() == EnumFacing.DOWN ) - { - rotation = flipidiy( rotation ); - } + return rotation; + } - return rotation; - } - - private static float flipidiy( float rad ) - { - float x = (float) Math.cos( rad ); - float y = (float) Math.sin( rad ); - return (float) Math.atan2( -y, x ); - } + private static float flipidiy(float rad) { + float x = (float) Math.cos(rad); + float y = (float) Math.sin(rad); + return (float) Math.atan2(-y, x); + } } diff --git a/src/main/java/appeng/client/render/textures/ParticleTextures.java b/src/main/java/appeng/client/render/textures/ParticleTextures.java index 255a31dc4..0f5ff3554 100644 --- a/src/main/java/appeng/client/render/textures/ParticleTextures.java +++ b/src/main/java/appeng/client/render/textures/ParticleTextures.java @@ -24,14 +24,12 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.TextureStitchEvent; -public class ParticleTextures -{ - public static TextureAtlasSprite BlockEnergyParticle; - public static TextureAtlasSprite BlockMatterCannonParticle; +public class ParticleTextures { + public static TextureAtlasSprite BlockEnergyParticle; + public static TextureAtlasSprite BlockMatterCannonParticle; - public static void registerSprite( TextureStitchEvent.Pre event ) - { - BlockEnergyParticle = event.getMap().registerSprite( new ResourceLocation( "appliedenergistics2:particles/energy" ) ); - BlockMatterCannonParticle = event.getMap().registerSprite( new ResourceLocation( "appliedenergistics2:particles/matter_cannon" ) ); - } + public static void registerSprite(TextureStitchEvent.Pre event) { + BlockEnergyParticle = event.getMap().registerSprite(new ResourceLocation("appliedenergistics2:particles/energy")); + BlockMatterCannonParticle = event.getMap().registerSprite(new ResourceLocation("appliedenergistics2:particles/matter_cannon")); + } } diff --git a/src/main/java/appeng/container/AEBaseContainer.java b/src/main/java/appeng/container/AEBaseContainer.java index cdf4d97a4..3b8887c02 100644 --- a/src/main/java/appeng/container/AEBaseContainer.java +++ b/src/main/java/appeng/container/AEBaseContainer.java @@ -19,25 +19,6 @@ package appeng.container; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.IContainerListener; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.wrapper.PlayerInvWrapper; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; @@ -56,14 +37,7 @@ import appeng.api.storage.data.IAEItemStack; import appeng.client.me.SlotME; import appeng.container.guisync.GuiSync; import appeng.container.guisync.SyncData; -import appeng.container.slot.AppEngSlot; -import appeng.container.slot.SlotCraftingMatrix; -import appeng.container.slot.SlotCraftingTerm; -import appeng.container.slot.SlotDisabled; -import appeng.container.slot.SlotFake; -import appeng.container.slot.SlotInaccessible; -import appeng.container.slot.SlotPlayerHotBar; -import appeng.container.slot.SlotPlayerInv; +import appeng.container.slot.*; import appeng.core.AELog; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketInventoryAction; @@ -77,1202 +51,979 @@ import appeng.util.Platform; import appeng.util.inv.AdaptorItemHandler; import appeng.util.inv.WrapperCursorItemHandler; import appeng.util.item.AEItemStack; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IContainerListener; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.wrapper.PlayerInvWrapper; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; + + +public abstract class AEBaseContainer extends Container { + private final InventoryPlayer invPlayer; + private final IActionSource mySrc; + private final HashSet locked = new HashSet<>(); + private final TileEntity tileEntity; + private final IPart part; + private final IGuiItemObject obj; + private final HashMap syncData = new HashMap<>(); + private boolean isContainerValid = true; + private String customName; + private ContainerOpenContext openContext; + private IMEInventoryHandler cellInv; + private IEnergySource powerSrc; + private boolean sentCustomName; + private int ticksSinceCheck = 900; + private IAEItemStack clientRequestedTargetItem = null; + + public AEBaseContainer(final InventoryPlayer ip, final TileEntity myTile, final IPart myPart) { + this(ip, myTile, myPart, null); + } + + public AEBaseContainer(final InventoryPlayer ip, final TileEntity myTile, final IPart myPart, final IGuiItemObject gio) { + this.invPlayer = ip; + this.tileEntity = myTile; + this.part = myPart; + this.obj = gio; + this.mySrc = new PlayerSource(ip.player, this.getActionHost()); + this.prepareSync(); + } + + protected IActionHost getActionHost() { + if (this.obj instanceof IActionHost) { + return (IActionHost) this.obj; + } + + if (this.tileEntity instanceof IActionHost) { + return (IActionHost) this.tileEntity; + } + + if (this.part instanceof IActionHost) { + return (IActionHost) this.part; + } + + return null; + } + + private void prepareSync() { + for (final Field f : this.getClass().getFields()) { + if (f.isAnnotationPresent(GuiSync.class)) { + final GuiSync annotation = f.getAnnotation(GuiSync.class); + if (this.syncData.containsKey(annotation.value())) { + AELog.warn("Channel already in use: " + annotation.value() + " for " + f.getName()); + } else { + this.syncData.put(annotation.value(), new SyncData(this, f, annotation)); + } + } + } + } + + public AEBaseContainer(final InventoryPlayer ip, final Object anchor) { + this.invPlayer = ip; + this.tileEntity = anchor instanceof TileEntity ? (TileEntity) anchor : null; + this.part = anchor instanceof IPart ? (IPart) anchor : null; + this.obj = anchor instanceof IGuiItemObject ? (IGuiItemObject) anchor : null; + + if (this.tileEntity == null && this.part == null && this.obj == null) { + throw new IllegalArgumentException("Must have a valid anchor, instead " + anchor + " in " + ip); + } + + this.mySrc = new PlayerSource(ip.player, this.getActionHost()); + + this.prepareSync(); + } + + public IAEItemStack getTargetStack() { + return this.clientRequestedTargetItem; + } + + public void setTargetStack(final IAEItemStack stack) { + // client doesn't need to re-send, makes for lower overhead rapid packets. + if (Platform.isClient()) { + if (stack == null && this.clientRequestedTargetItem == null) { + return; + } + if (stack != null && stack.isSameType(this.clientRequestedTargetItem)) { + return; + } + + NetworkHandler.instance().sendToServer(new PacketTargetItemStack((AEItemStack) stack)); + } + + this.clientRequestedTargetItem = stack == null ? null : stack.copy(); + } + + public IActionSource getActionSource() { + return this.mySrc; + } + + public void verifyPermissions(final SecurityPermissions security, final boolean requirePower) { + if (Platform.isClient()) { + return; + } + + this.ticksSinceCheck++; + if (this.ticksSinceCheck < 20) { + return; + } + + this.ticksSinceCheck = 0; + this.setValidContainer(this.isValidContainer() && this.hasAccess(security, requirePower)); + } + + protected boolean hasAccess(final SecurityPermissions perm, final boolean requirePower) { + final IActionHost host = this.getActionHost(); + + if (host != null) { + final IGridNode gn = host.getActionableNode(); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + if (requirePower) { + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + if (!eg.isNetworkPowered()) { + return false; + } + } + + final ISecurityGrid sg = g.getCache(ISecurityGrid.class); + return sg.hasPermission(this.getInventoryPlayer().player, perm); + } + } + } + + return false; + } + + public void lockPlayerInventorySlot(final int idx) { + this.locked.add(idx); + } + + public Object getTarget() { + if (this.tileEntity != null) { + return this.tileEntity; + } + if (this.part != null) { + return this.part; + } + return this.obj; + } + + public InventoryPlayer getPlayerInv() { + return this.getInventoryPlayer(); + } + + public TileEntity getTileEntity() { + return this.tileEntity; + } + + public final void updateFullProgressBar(final int idx, final long value) { + if (this.syncData.containsKey(idx)) { + this.syncData.get(idx).update(value); + return; + } + + this.updateProgressBar(idx, (int) value); + } + + public void stringSync(final int idx, final String value) { + if (this.syncData.containsKey(idx)) { + this.syncData.get(idx).update(value); + } + } + + protected void bindPlayerInventory(final InventoryPlayer inventoryPlayer, final int offsetX, final int offsetY) { + IItemHandler ih = new PlayerInvWrapper(inventoryPlayer); + + // bind player inventory + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + if (this.locked.contains(j + i * 9 + 9)) { + this.addSlotToContainer(new SlotDisabled(ih, j + i * 9 + 9, 8 + j * 18 + offsetX, offsetY + i * 18)); + } else { + this.addSlotToContainer(new SlotPlayerInv(ih, j + i * 9 + 9, 8 + j * 18 + offsetX, offsetY + i * 18)); + } + } + } + + // bind player hotbar + for (int i = 0; i < 9; i++) { + if (this.locked.contains(i)) { + this.addSlotToContainer(new SlotDisabled(ih, i, 8 + i * 18 + offsetX, 58 + offsetY)); + } else { + this.addSlotToContainer(new SlotPlayerHotBar(ih, i, 8 + i * 18 + offsetX, 58 + offsetY)); + } + } + } + + @Override + protected Slot addSlotToContainer(final Slot newSlot) { + if (newSlot instanceof AppEngSlot) { + final AppEngSlot s = (AppEngSlot) newSlot; + s.setContainer(this); + return super.addSlotToContainer(newSlot); + } else { + throw new IllegalArgumentException("Invalid Slot [" + newSlot + "] for AE Container instead of AppEngSlot."); + } + } + + @Override + public void detectAndSendChanges() { + this.sendCustomName(); + + if (Platform.isServer()) { + if (this.tileEntity != null && this.tileEntity.getWorld().getTileEntity(this.tileEntity.getPos()) != this.tileEntity) { + this.setValidContainer(false); + } + + for (final IContainerListener listener : this.listeners) { + for (final SyncData sd : this.syncData.values()) { + sd.tick(listener); + } + } + } + + super.detectAndSendChanges(); + } + + @Override + public ItemStack transferStackInSlot(final EntityPlayer p, final int idx) { + if (Platform.isClient()) { + return ItemStack.EMPTY; + } + + final AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get(idx); // require AE SLots! + + if (clickSlot instanceof SlotDisabled || clickSlot instanceof SlotInaccessible) { + return ItemStack.EMPTY; + } + if (clickSlot != null && clickSlot.getHasStack()) { + ItemStack tis = clickSlot.getStack(); + + if (tis.isEmpty()) { + return ItemStack.EMPTY; + } + + final List selectedSlots = new ArrayList<>(); + + /** + * Gather a list of valid destinations. + */ + if (clickSlot.isPlayerSide()) { + tis = this.transferStackToContainer(tis); + + if (!tis.isEmpty()) { + // target slots in the container... + for (final Object inventorySlot : this.inventorySlots) { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + + if (!(cs.isPlayerSide()) && !(cs instanceof SlotFake) && !(cs instanceof SlotCraftingMatrix)) { + if (cs.isItemValid(tis)) { + selectedSlots.add(cs); + } + } + } + } + } else { + tis = tis.copy(); + + // target slots in the container... + for (final Object inventorySlot : this.inventorySlots) { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + + if ((cs.isPlayerSide()) && !(cs instanceof SlotFake) && !(cs instanceof SlotCraftingMatrix)) { + if (cs.isItemValid(tis)) { + selectedSlots.add(cs); + } + } + } + } + + /** + * Handle Fake Slot Shift clicking. + */ + if (selectedSlots.isEmpty() && clickSlot.isPlayerSide()) { + if (!tis.isEmpty()) { + // target slots in the container... + for (final Object inventorySlot : this.inventorySlots) { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + final ItemStack destination = cs.getStack(); + + if (!(cs.isPlayerSide()) && cs instanceof SlotFake) { + if (Platform.itemComparisons().isSameItem(destination, tis)) { + break; + } else if (destination.isEmpty()) { + cs.putStack(tis.copy()); + this.updateSlot(cs); + break; + } + } + } + } + } + + if (!tis.isEmpty()) { + // find partials.. + for (final Slot d : selectedSlots) { + if (d instanceof SlotDisabled || d instanceof SlotME) { + continue; + } + + if (d.isItemValid(tis)) { + if (d.getHasStack()) { + final ItemStack t = d.getStack().copy(); + + if (Platform.itemComparisons().isSameItem(tis, t)) // t.isItemEqual(tis)) + { + int maxSize = t.getMaxStackSize(); + if (maxSize > d.getSlotStackLimit()) { + maxSize = d.getSlotStackLimit(); + } + + int placeAble = maxSize - t.getCount(); + + if (tis.getCount() < placeAble) { + placeAble = tis.getCount(); + } + + t.setCount(t.getCount() + placeAble); + tis.setCount(tis.getCount() - placeAble); + + d.putStack(t); + + if (tis.getCount() <= 0) { + clickSlot.putStack(ItemStack.EMPTY); + d.onSlotChanged(); + + // if ( hasMETiles ) updateClient(); + + this.updateSlot(clickSlot); + this.updateSlot(d); + return ItemStack.EMPTY; + } else { + this.updateSlot(d); + } + } + } + } + } + + // any match.. + for (final Slot d : selectedSlots) { + if (d instanceof SlotDisabled || d instanceof SlotME) { + continue; + } + + if (d.isItemValid(tis)) { + if (d.getHasStack()) { + final ItemStack t = d.getStack().copy(); + + if (Platform.itemComparisons().isSameItem(t, tis)) { + int maxSize = t.getMaxStackSize(); + if (d.getSlotStackLimit() < maxSize) { + maxSize = d.getSlotStackLimit(); + } + + int placeAble = maxSize - t.getCount(); + + if (tis.getCount() < placeAble) { + placeAble = tis.getCount(); + } + + t.setCount(t.getCount() + placeAble); + tis.setCount(tis.getCount() - placeAble); + + d.putStack(t); + + if (tis.getCount() <= 0) { + clickSlot.putStack(ItemStack.EMPTY); + d.onSlotChanged(); + + // if ( worldEntity != null ) + // worldEntity.markDirty(); + // if ( hasMETiles ) updateClient(); + + this.updateSlot(clickSlot); + this.updateSlot(d); + return ItemStack.EMPTY; + } else { + this.updateSlot(d); + } + } + } else { + int maxSize = tis.getMaxStackSize(); + if (maxSize > d.getSlotStackLimit()) { + maxSize = d.getSlotStackLimit(); + } + + final ItemStack tmp = tis.copy(); + if (tmp.getCount() > maxSize) { + tmp.setCount(maxSize); + } + + tis.setCount(tis.getCount() - tmp.getCount()); + d.putStack(tmp); + + if (tis.getCount() <= 0) { + clickSlot.putStack(ItemStack.EMPTY); + d.onSlotChanged(); + + // if ( worldEntity != null ) + // worldEntity.markDirty(); + // if ( hasMETiles ) updateClient(); + + this.updateSlot(clickSlot); + this.updateSlot(d); + return ItemStack.EMPTY; + } else { + this.updateSlot(d); + } + } + } + } + } + + clickSlot.putStack(!tis.isEmpty() ? tis : ItemStack.EMPTY); + } + + this.updateSlot(clickSlot); + return ItemStack.EMPTY; + } + + @Override + public final void updateProgressBar(final int idx, final int value) { + if (this.syncData.containsKey(idx)) { + this.syncData.get(idx).update((long) value); + } + } + + @Override + public boolean canInteractWith(final EntityPlayer entityplayer) { + if (this.isValidContainer()) { + if (this.tileEntity instanceof IInventory) { + return ((IInventory) this.tileEntity).isUsableByPlayer(entityplayer); + } + return true; + } + return false; + } + + @Override + public boolean canDragIntoSlot(final Slot s) { + return ((AppEngSlot) s).isDraggable(); + } + + public void doAction(final EntityPlayerMP player, final InventoryAction action, final int slot, final long id) { + if (slot >= 0 && slot < this.inventorySlots.size()) { + final Slot s = this.getSlot(slot); + + if (s instanceof SlotCraftingTerm) { + switch (action) { + case CRAFT_SHIFT: + case CRAFT_ITEM: + case CRAFT_STACK: + ((SlotCraftingTerm) s).doClick(action, player); + this.updateHeld(player); + default: + } + } + + if (s instanceof SlotFake) { + final ItemStack hand = player.inventory.getItemStack(); + + switch (action) { + case PICKUP_OR_SET_DOWN: + + if (hand.isEmpty()) { + s.putStack(ItemStack.EMPTY); + } else { + s.putStack(hand.copy()); + } + + break; + case PLACE_SINGLE: + + if (!hand.isEmpty()) { + final ItemStack is = hand.copy(); + is.setCount(1); + s.putStack(is); + } else { + final ItemStack is = s.getStack().copy(); + if (is.getCount() < is.getMaxStackSize()) + is.grow(1); + s.putStack(is); + } + break; + case PICKUP_SINGLE: + if (hand.isEmpty()) { + final ItemStack is = s.getStack().copy(); + if (is.getCount() > 1) + is.shrink(1); + s.putStack(is); + } + break; + case SPLIT_OR_PLACE_SINGLE: + + ItemStack is = s.getStack(); + if (!is.isEmpty()) { + if (hand.isEmpty()) { + is.setCount(Math.max(1, is.getCount() - 1)); + } else if (hand.isItemEqual(is)) { + is.setCount(Math.min(is.getMaxStackSize(), is.getCount() + 1)); + } else { + is = hand.copy(); + is.setCount(1); + } + + s.putStack(is); + } else if (!hand.isEmpty()) { + is = hand.copy(); + is.setCount(1); + s.putStack(is); + } + + break; + case CREATIVE_DUPLICATE: + case MOVE_REGION: + case SHIFT_CLICK: + default: + break; + } + } + + if (action == InventoryAction.MOVE_REGION) { + final List from = new ArrayList<>(); + + for (final Object j : this.inventorySlots) { + if (j instanceof Slot && j.getClass() == s.getClass() && !(j instanceof SlotCraftingTerm)) { + from.add((Slot) j); + } + } + + for (final Slot fr : from) { + this.transferStackInSlot(player, fr.slotNumber); + } + } + + return; + } + + // get target item. + final IAEItemStack slotItem = this.clientRequestedTargetItem; + + switch (action) { + case SHIFT_CLICK: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (slotItem != null) { + IAEItemStack ais = slotItem.copy(); + ItemStack myItem = ais.createItemStack(); + + ais.setStackSize(myItem.getMaxStackSize()); + + final InventoryAdaptor adp = InventoryAdaptor.getAdaptor(player); + myItem.setCount((int) ais.getStackSize()); + myItem = adp.simulateAdd(myItem); + + if (!myItem.isEmpty()) { + ais.setStackSize(ais.getStackSize() - myItem.getCount()); + } + + ais = Platform.poweredExtraction(this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais != null) { + adp.addItems(ais.createItemStack()); + } + } + break; + case ROLL_DOWN: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + final int releaseQty = 1; + final ItemStack isg = player.inventory.getItemStack(); + + if (!isg.isEmpty() && releaseQty > 0) { + IAEItemStack ais = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(isg); + ais.setStackSize(1); + final IAEItemStack extracted = ais.copy(); + + ais = Platform.poweredInsert(this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais == null) { + final InventoryAdaptor ia = new AdaptorItemHandler(new WrapperCursorItemHandler(player.inventory)); + + final ItemStack fail = ia.removeItems(1, extracted.getDefinition(), null); + if (fail.isEmpty()) { + this.getCellInventory().extractItems(extracted, Actionable.MODULATE, this.getActionSource()); + } + + this.updateHeld(player); + } + } + + break; + case ROLL_UP: + case PICKUP_SINGLE: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (slotItem != null) { + int liftQty = 1; + final ItemStack item = player.inventory.getItemStack(); + + if (!item.isEmpty()) { + if (item.getCount() >= item.getMaxStackSize()) { + liftQty = 0; + } + if (!Platform.itemComparisons().isSameItem(slotItem.getDefinition(), item)) { + liftQty = 0; + } + } + + if (liftQty > 0) { + IAEItemStack ais = slotItem.copy(); + ais.setStackSize(1); + ais = Platform.poweredExtraction(this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais != null) { + final InventoryAdaptor ia = new AdaptorItemHandler(new WrapperCursorItemHandler(player.inventory)); + + final ItemStack fail = ia.addItems(ais.createItemStack()); + if (!fail.isEmpty()) { + this.getCellInventory().injectItems(ais, Actionable.MODULATE, this.getActionSource()); + } + + this.updateHeld(player); + } + } + } + break; + case PICKUP_OR_SET_DOWN: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (player.inventory.getItemStack().isEmpty()) { + if (slotItem != null) { + IAEItemStack ais = slotItem.copy(); + ais.setStackSize(ais.getDefinition().getMaxStackSize()); + ais = Platform.poweredExtraction(this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais != null) { + player.inventory.setItemStack(ais.createItemStack()); + } else { + player.inventory.setItemStack(ItemStack.EMPTY); + } + this.updateHeld(player); + } + } else { + IAEItemStack ais = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(player.inventory.getItemStack()); + ais = Platform.poweredInsert(this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais != null) { + player.inventory.setItemStack(ais.createItemStack()); + } else { + player.inventory.setItemStack(ItemStack.EMPTY); + } + this.updateHeld(player); + } + + break; + case SPLIT_OR_PLACE_SINGLE: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (player.inventory.getItemStack().isEmpty()) { + if (slotItem != null) { + IAEItemStack ais = slotItem.copy(); + final long maxSize = ais.getDefinition().getMaxStackSize(); + ais.setStackSize(maxSize); + ais = this.getCellInventory().extractItems(ais, Actionable.SIMULATE, this.getActionSource()); + + if (ais != null) { + final long stackSize = Math.min(maxSize, ais.getStackSize()); + ais.setStackSize((stackSize + 1) >> 1); + ais = Platform.poweredExtraction(this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + } + + if (ais != null) { + player.inventory.setItemStack(ais.createItemStack()); + } else { + player.inventory.setItemStack(ItemStack.EMPTY); + } + this.updateHeld(player); + } + } else { + IAEItemStack ais = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(player.inventory.getItemStack()); + ais.setStackSize(1); + ais = Platform.poweredInsert(this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais == null) { + final ItemStack is = player.inventory.getItemStack(); + is.setCount(is.getCount() - 1); + if (is.getCount() <= 0) { + player.inventory.setItemStack(ItemStack.EMPTY); + } + this.updateHeld(player); + } + } + + break; + case CREATIVE_DUPLICATE: + if (player.capabilities.isCreativeMode && slotItem != null) { + final ItemStack is = slotItem.createItemStack(); + is.setCount(is.getMaxStackSize()); + player.inventory.setItemStack(is); + this.updateHeld(player); + } + break; + case MOVE_REGION: + + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (slotItem != null) { + final int playerInv = 9 * 4; + for (int slotNum = 0; slotNum < playerInv; slotNum++) { + IAEItemStack ais = slotItem.copy(); + ItemStack myItem = ais.createItemStack(); + + ais.setStackSize(myItem.getMaxStackSize()); + + final InventoryAdaptor adp = InventoryAdaptor.getAdaptor(player); + myItem.setCount((int) ais.getStackSize()); + myItem = adp.simulateAdd(myItem); + + if (!myItem.isEmpty()) { + ais.setStackSize(ais.getStackSize() - myItem.getCount()); + } + + ais = Platform.poweredExtraction(this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais != null) { + adp.addItems(ais.createItemStack()); + } else { + return; + } + } + } + + break; + default: + break; + } + } + + protected void updateHeld(final EntityPlayerMP p) { + if (Platform.isServer()) { + try { + NetworkHandler.instance() + .sendTo( + new PacketInventoryAction(InventoryAction.UPDATE_HAND, 0, AEItemStack.fromItemStack(p.inventory.getItemStack())), + p); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + + protected ItemStack transferStackToContainer(final ItemStack input) { + return this.shiftStoreItem(input); + } + + private ItemStack shiftStoreItem(final ItemStack input) { + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return input; + } + final IAEItemStack ais = Platform.poweredInsert(this.getPowerSource(), this.getCellInventory(), + AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(input), + this.getActionSource()); + if (ais == null) { + return ItemStack.EMPTY; + } + return ais.createItemStack(); + } + + private void updateSlot(final Slot clickSlot) { + // ??? + this.detectAndSendChanges(); + } + + private void sendCustomName() { + if (!this.sentCustomName) { + this.sentCustomName = true; + if (Platform.isServer()) { + ICustomNameObject name = null; + + if (this.part instanceof ICustomNameObject) { + name = (ICustomNameObject) this.part; + } + + if (this.tileEntity instanceof ICustomNameObject) { + name = (ICustomNameObject) this.tileEntity; + } + + if (this.obj instanceof ICustomNameObject) { + name = (ICustomNameObject) this.obj; + } + + if (this instanceof ICustomNameObject) { + name = (ICustomNameObject) this; + } + + if (name != null) { + if (name.hasCustomInventoryName()) { + this.setCustomName(name.getCustomInventoryName()); + } + + if (this.getCustomName() != null) { + try { + NetworkHandler.instance() + .sendTo(new PacketValueConfig("CustomName", this.getCustomName()), + (EntityPlayerMP) this.getInventoryPlayer().player); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } + } + } + + public void swapSlotContents(final int slotA, final int slotB) { + final Slot a = this.getSlot(slotA); + final Slot b = this.getSlot(slotB); + + // NPE protection... + if (a == null || b == null) { + return; + } + + final ItemStack isA = a.getStack(); + final ItemStack isB = b.getStack(); + + // something to do? + if (isA.isEmpty() && isB.isEmpty()) { + return; + } + + // can take? + + if (!isA.isEmpty() && !a.canTakeStack(this.getInventoryPlayer().player)) { + return; + } + + if (!isB.isEmpty() && !b.canTakeStack(this.getInventoryPlayer().player)) { + return; + } + + // swap valid? + + if (!isB.isEmpty() && !a.isItemValid(isB)) { + return; + } + + if (!isA.isEmpty() && !b.isItemValid(isA)) { + return; + } + + ItemStack testA = isB.isEmpty() ? ItemStack.EMPTY : isB.copy(); + ItemStack testB = isA.isEmpty() ? ItemStack.EMPTY : isA.copy(); + + // can put some back? + if (!testA.isEmpty() && testA.getCount() > a.getSlotStackLimit()) { + if (!testB.isEmpty()) { + return; + } + + final int totalA = testA.getCount(); + testA.setCount(a.getSlotStackLimit()); + testB = testA.copy(); + + testB.setCount(totalA - testA.getCount()); + } + + if (!testB.isEmpty() && testB.getCount() > b.getSlotStackLimit()) { + if (!testA.isEmpty()) { + return; + } + final int totalB = testB.getCount(); + testB.setCount(b.getSlotStackLimit()); + testA = testB.copy(); -public abstract class AEBaseContainer extends Container -{ - private final InventoryPlayer invPlayer; - private final IActionSource mySrc; - private final HashSet locked = new HashSet<>(); - private final TileEntity tileEntity; - private final IPart part; - private final IGuiItemObject obj; - private final HashMap syncData = new HashMap<>(); - private boolean isContainerValid = true; - private String customName; - private ContainerOpenContext openContext; - private IMEInventoryHandler cellInv; - private IEnergySource powerSrc; - private boolean sentCustomName; - private int ticksSinceCheck = 900; - private IAEItemStack clientRequestedTargetItem = null; - - public AEBaseContainer( final InventoryPlayer ip, final TileEntity myTile, final IPart myPart ) - { - this( ip, myTile, myPart, null ); - } - - public AEBaseContainer( final InventoryPlayer ip, final TileEntity myTile, final IPart myPart, final IGuiItemObject gio ) - { - this.invPlayer = ip; - this.tileEntity = myTile; - this.part = myPart; - this.obj = gio; - this.mySrc = new PlayerSource( ip.player, this.getActionHost() ); - this.prepareSync(); - } - - protected IActionHost getActionHost() - { - if( this.obj instanceof IActionHost ) - { - return (IActionHost) this.obj; - } - - if( this.tileEntity instanceof IActionHost ) - { - return (IActionHost) this.tileEntity; - } - - if( this.part instanceof IActionHost ) - { - return (IActionHost) this.part; - } - - return null; - } - - private void prepareSync() - { - for( final Field f : this.getClass().getFields() ) - { - if( f.isAnnotationPresent( GuiSync.class ) ) - { - final GuiSync annotation = f.getAnnotation( GuiSync.class ); - if( this.syncData.containsKey( annotation.value() ) ) - { - AELog.warn( "Channel already in use: " + annotation.value() + " for " + f.getName() ); - } - else - { - this.syncData.put( annotation.value(), new SyncData( this, f, annotation ) ); - } - } - } - } - - public AEBaseContainer( final InventoryPlayer ip, final Object anchor ) - { - this.invPlayer = ip; - this.tileEntity = anchor instanceof TileEntity ? (TileEntity) anchor : null; - this.part = anchor instanceof IPart ? (IPart) anchor : null; - this.obj = anchor instanceof IGuiItemObject ? (IGuiItemObject) anchor : null; - - if( this.tileEntity == null && this.part == null && this.obj == null ) - { - throw new IllegalArgumentException( "Must have a valid anchor, instead " + anchor + " in " + ip ); - } - - this.mySrc = new PlayerSource( ip.player, this.getActionHost() ); - - this.prepareSync(); - } - - public IAEItemStack getTargetStack() - { - return this.clientRequestedTargetItem; - } - - public void setTargetStack( final IAEItemStack stack ) - { - // client doesn't need to re-send, makes for lower overhead rapid packets. - if( Platform.isClient() ) - { - if( stack == null && this.clientRequestedTargetItem == null ) - { - return; - } - if( stack != null && stack.isSameType( this.clientRequestedTargetItem ) ) - { - return; - } - - NetworkHandler.instance().sendToServer( new PacketTargetItemStack( (AEItemStack) stack ) ); - } - - this.clientRequestedTargetItem = stack == null ? null : stack.copy(); - } - - public IActionSource getActionSource() - { - return this.mySrc; - } - - public void verifyPermissions( final SecurityPermissions security, final boolean requirePower ) - { - if( Platform.isClient() ) - { - return; - } - - this.ticksSinceCheck++; - if( this.ticksSinceCheck < 20 ) - { - return; - } - - this.ticksSinceCheck = 0; - this.setValidContainer( this.isValidContainer() && this.hasAccess( security, requirePower ) ); - } - - protected boolean hasAccess( final SecurityPermissions perm, final boolean requirePower ) - { - final IActionHost host = this.getActionHost(); - - if( host != null ) - { - final IGridNode gn = host.getActionableNode(); - if( gn != null ) - { - final IGrid g = gn.getGrid(); - if( g != null ) - { - if( requirePower ) - { - final IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - if( !eg.isNetworkPowered() ) - { - return false; - } - } - - final ISecurityGrid sg = g.getCache( ISecurityGrid.class ); - if( sg.hasPermission( this.getInventoryPlayer().player, perm ) ) - { - return true; - } - } - } - } - - return false; - } - - public void lockPlayerInventorySlot( final int idx ) - { - this.locked.add( idx ); - } - - public Object getTarget() - { - if( this.tileEntity != null ) - { - return this.tileEntity; - } - if( this.part != null ) - { - return this.part; - } - if( this.obj != null ) - { - return this.obj; - } - return null; - } - - public InventoryPlayer getPlayerInv() - { - return this.getInventoryPlayer(); - } - - public TileEntity getTileEntity() - { - return this.tileEntity; - } - - public final void updateFullProgressBar( final int idx, final long value ) - { - if( this.syncData.containsKey( idx ) ) - { - this.syncData.get( idx ).update( value ); - return; - } - - this.updateProgressBar( idx, (int) value ); - } - - public void stringSync( final int idx, final String value ) - { - if( this.syncData.containsKey( idx ) ) - { - this.syncData.get( idx ).update( value ); - } - } - - protected void bindPlayerInventory( final InventoryPlayer inventoryPlayer, final int offsetX, final int offsetY ) - { - IItemHandler ih = new PlayerInvWrapper( inventoryPlayer ); - - // bind player inventory - for( int i = 0; i < 3; i++ ) - { - for( int j = 0; j < 9; j++ ) - { - if( this.locked.contains( j + i * 9 + 9 ) ) - { - this.addSlotToContainer( new SlotDisabled( ih, j + i * 9 + 9, 8 + j * 18 + offsetX, offsetY + i * 18 ) ); - } - else - { - this.addSlotToContainer( new SlotPlayerInv( ih, j + i * 9 + 9, 8 + j * 18 + offsetX, offsetY + i * 18 ) ); - } - } - } - - // bind player hotbar - for( int i = 0; i < 9; i++ ) - { - if( this.locked.contains( i ) ) - { - this.addSlotToContainer( new SlotDisabled( ih, i, 8 + i * 18 + offsetX, 58 + offsetY ) ); - } - else - { - this.addSlotToContainer( new SlotPlayerHotBar( ih, i, 8 + i * 18 + offsetX, 58 + offsetY ) ); - } - } - } - - @Override - protected Slot addSlotToContainer( final Slot newSlot ) - { - if( newSlot instanceof AppEngSlot ) - { - final AppEngSlot s = (AppEngSlot) newSlot; - s.setContainer( this ); - return super.addSlotToContainer( newSlot ); - } - else - { - throw new IllegalArgumentException( "Invalid Slot [" + newSlot + "] for AE Container instead of AppEngSlot." ); - } - } - - @Override - public void detectAndSendChanges() - { - this.sendCustomName(); - - if( Platform.isServer() ) - { - if( this.tileEntity != null && this.tileEntity.getWorld().getTileEntity( this.tileEntity.getPos() ) != this.tileEntity ) - { - this.setValidContainer( false ); - } - - for( final IContainerListener listener : this.listeners ) - { - for( final SyncData sd : this.syncData.values() ) - { - sd.tick( listener ); - } - } - } - - super.detectAndSendChanges(); - } - - @Override - public ItemStack transferStackInSlot( final EntityPlayer p, final int idx ) - { - if( Platform.isClient() ) - { - return ItemStack.EMPTY; - } - - final AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get( idx ); // require AE SLots! - - if( clickSlot instanceof SlotDisabled || clickSlot instanceof SlotInaccessible ) - { - return ItemStack.EMPTY; - } - if( clickSlot != null && clickSlot.getHasStack() ) - { - ItemStack tis = clickSlot.getStack(); - - if( tis.isEmpty() ) - { - return ItemStack.EMPTY; - } - - final List selectedSlots = new ArrayList<>(); - - /** - * Gather a list of valid destinations. - */ - if( clickSlot.isPlayerSide() ) - { - tis = this.transferStackToContainer( tis ); - - if( !tis.isEmpty() ) - { - // target slots in the container... - for( final Object inventorySlot : this.inventorySlots ) - { - final AppEngSlot cs = (AppEngSlot) inventorySlot; - - if( !( cs.isPlayerSide() ) && !( cs instanceof SlotFake ) && !( cs instanceof SlotCraftingMatrix ) ) - { - if( cs.isItemValid( tis ) ) - { - selectedSlots.add( cs ); - } - } - } - } - } - else - { - tis = tis.copy(); - - // target slots in the container... - for( final Object inventorySlot : this.inventorySlots ) - { - final AppEngSlot cs = (AppEngSlot) inventorySlot; - - if( ( cs.isPlayerSide() ) && !( cs instanceof SlotFake ) && !( cs instanceof SlotCraftingMatrix ) ) - { - if( cs.isItemValid( tis ) ) - { - selectedSlots.add( cs ); - } - } - } - } - - /** - * Handle Fake Slot Shift clicking. - */ - if( selectedSlots.isEmpty() && clickSlot.isPlayerSide() ) - { - if( !tis.isEmpty() ) - { - // target slots in the container... - for( final Object inventorySlot : this.inventorySlots ) - { - final AppEngSlot cs = (AppEngSlot) inventorySlot; - final ItemStack destination = cs.getStack(); - - if( !( cs.isPlayerSide() ) && cs instanceof SlotFake ) - { - if( Platform.itemComparisons().isSameItem( destination, tis ) ) - { - break; - } - else if( destination.isEmpty() ) - { - cs.putStack( tis.copy() ); - this.updateSlot( cs ); - break; - } - } - } - } - } - - if( !tis.isEmpty() ) - { - // find partials.. - for( final Slot d : selectedSlots ) - { - if( d instanceof SlotDisabled || d instanceof SlotME ) - { - continue; - } - - if( d.isItemValid( tis ) ) - { - if( d.getHasStack() ) - { - final ItemStack t = d.getStack().copy(); - - if( Platform.itemComparisons().isSameItem( tis, t ) ) // t.isItemEqual(tis)) - { - int maxSize = t.getMaxStackSize(); - if( maxSize > d.getSlotStackLimit() ) - { - maxSize = d.getSlotStackLimit(); - } - - int placeAble = maxSize - t.getCount(); - - if( tis.getCount() < placeAble ) - { - placeAble = tis.getCount(); - } - - t.setCount( t.getCount() + placeAble ); - tis.setCount( tis.getCount() - placeAble ); - - d.putStack( t ); - - if( tis.getCount() <= 0 ) - { - clickSlot.putStack( ItemStack.EMPTY ); - d.onSlotChanged(); - - // if ( hasMETiles ) updateClient(); - - this.updateSlot( clickSlot ); - this.updateSlot( d ); - return ItemStack.EMPTY; - } - else - { - this.updateSlot( d ); - } - } - } - } - } - - // any match.. - for( final Slot d : selectedSlots ) - { - if( d instanceof SlotDisabled || d instanceof SlotME ) - { - continue; - } - - if( d.isItemValid( tis ) ) - { - if( d.getHasStack() ) - { - final ItemStack t = d.getStack().copy(); - - if( Platform.itemComparisons().isSameItem( t, tis ) ) - { - int maxSize = t.getMaxStackSize(); - if( d.getSlotStackLimit() < maxSize ) - { - maxSize = d.getSlotStackLimit(); - } - - int placeAble = maxSize - t.getCount(); - - if( tis.getCount() < placeAble ) - { - placeAble = tis.getCount(); - } - - t.setCount( t.getCount() + placeAble ); - tis.setCount( tis.getCount() - placeAble ); - - d.putStack( t ); - - if( tis.getCount() <= 0 ) - { - clickSlot.putStack( ItemStack.EMPTY ); - d.onSlotChanged(); - - // if ( worldEntity != null ) - // worldEntity.markDirty(); - // if ( hasMETiles ) updateClient(); - - this.updateSlot( clickSlot ); - this.updateSlot( d ); - return ItemStack.EMPTY; - } - else - { - this.updateSlot( d ); - } - } - } - else - { - int maxSize = tis.getMaxStackSize(); - if( maxSize > d.getSlotStackLimit() ) - { - maxSize = d.getSlotStackLimit(); - } - - final ItemStack tmp = tis.copy(); - if( tmp.getCount() > maxSize ) - { - tmp.setCount( maxSize ); - } - - tis.setCount( tis.getCount() - tmp.getCount() ); - d.putStack( tmp ); - - if( tis.getCount() <= 0 ) - { - clickSlot.putStack( ItemStack.EMPTY ); - d.onSlotChanged(); - - // if ( worldEntity != null ) - // worldEntity.markDirty(); - // if ( hasMETiles ) updateClient(); - - this.updateSlot( clickSlot ); - this.updateSlot( d ); - return ItemStack.EMPTY; - } - else - { - this.updateSlot( d ); - } - } - } - } - } - - clickSlot.putStack( !tis.isEmpty() ? tis : ItemStack.EMPTY ); - } - - this.updateSlot( clickSlot ); - return ItemStack.EMPTY; - } - - @Override - public final void updateProgressBar( final int idx, final int value ) - { - if( this.syncData.containsKey( idx ) ) - { - this.syncData.get( idx ).update( (long) value ); - } - } - - @Override - public boolean canInteractWith( final EntityPlayer entityplayer ) - { - if( this.isValidContainer() ) - { - if( this.tileEntity instanceof IInventory ) - { - return ( (IInventory) this.tileEntity ).isUsableByPlayer( entityplayer ); - } - return true; - } - return false; - } - - @Override - public boolean canDragIntoSlot( final Slot s ) - { - return ( (AppEngSlot) s ).isDraggable(); - } - - public void doAction( final EntityPlayerMP player, final InventoryAction action, final int slot, final long id ) - { - if( slot >= 0 && slot < this.inventorySlots.size() ) - { - final Slot s = this.getSlot( slot ); - - if( s instanceof SlotCraftingTerm ) - { - switch( action ) - { - case CRAFT_SHIFT: - case CRAFT_ITEM: - case CRAFT_STACK: - ( (SlotCraftingTerm) s ).doClick( action, player ); - this.updateHeld( player ); - default: - } - } - - if( s instanceof SlotFake ) - { - final ItemStack hand = player.inventory.getItemStack(); - - switch( action ) - { - case PICKUP_OR_SET_DOWN: - - if( hand.isEmpty() ) - { - s.putStack( ItemStack.EMPTY ); - } - else - { - s.putStack( hand.copy() ); - } - - break; - case PLACE_SINGLE: - - if( !hand.isEmpty() ) - { - final ItemStack is = hand.copy(); - is.setCount( 1 ); - s.putStack( is ); - } - else - { - final ItemStack is = s.getStack().copy(); - if (is.getCount() < is.getMaxStackSize()) - is.grow( 1 ); - s.putStack( is ); - } - break; - case PICKUP_SINGLE: - if( hand.isEmpty() ) - { - final ItemStack is = s.getStack().copy(); - if (is.getCount() > 1) - is.shrink( 1 ); - s.putStack( is ); - } - break; - case SPLIT_OR_PLACE_SINGLE: - - ItemStack is = s.getStack(); - if( !is.isEmpty() ) - { - if( hand.isEmpty() ) - { - is.setCount( Math.max( 1, is.getCount() - 1 ) ); - } - else if( hand.isItemEqual( is ) ) - { - is.setCount( Math.min( is.getMaxStackSize(), is.getCount() + 1 ) ); - } - else - { - is = hand.copy(); - is.setCount( 1 ); - } - - s.putStack( is ); - } - else if( !hand.isEmpty() ) - { - is = hand.copy(); - is.setCount( 1 ); - s.putStack( is ); - } - - break; - case CREATIVE_DUPLICATE: - case MOVE_REGION: - case SHIFT_CLICK: - default: - break; - } - } - - if( action == InventoryAction.MOVE_REGION ) - { - final List from = new ArrayList<>(); - - for( final Object j : this.inventorySlots ) - { - if( j instanceof Slot && j.getClass() == s.getClass() && !( j instanceof SlotCraftingTerm ) ) - { - from.add( (Slot) j ); - } - } - - for( final Slot fr : from ) - { - this.transferStackInSlot( player, fr.slotNumber ); - } - } - - return; - } - - // get target item. - final IAEItemStack slotItem = this.clientRequestedTargetItem; - - switch( action ) - { - case SHIFT_CLICK: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( slotItem != null ) - { - IAEItemStack ais = slotItem.copy(); - ItemStack myItem = ais.createItemStack(); - - ais.setStackSize( myItem.getMaxStackSize() ); - - final InventoryAdaptor adp = InventoryAdaptor.getAdaptor( player ); - myItem.setCount( (int) ais.getStackSize() ); - myItem = adp.simulateAdd( myItem ); - - if( !myItem.isEmpty() ) - { - ais.setStackSize( ais.getStackSize() - myItem.getCount() ); - } - - ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - adp.addItems( ais.createItemStack() ); - } - } - break; - case ROLL_DOWN: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - final int releaseQty = 1; - final ItemStack isg = player.inventory.getItemStack(); - - if( !isg.isEmpty() && releaseQty > 0 ) - { - IAEItemStack ais = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( isg ); - ais.setStackSize( 1 ); - final IAEItemStack extracted = ais.copy(); - - ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais == null ) - { - final InventoryAdaptor ia = new AdaptorItemHandler( new WrapperCursorItemHandler( player.inventory ) ); - - final ItemStack fail = ia.removeItems( 1, extracted.getDefinition(), null ); - if( fail.isEmpty() ) - { - this.getCellInventory().extractItems( extracted, Actionable.MODULATE, this.getActionSource() ); - } - - this.updateHeld( player ); - } - } - - break; - case ROLL_UP: - case PICKUP_SINGLE: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( slotItem != null ) - { - int liftQty = 1; - final ItemStack item = player.inventory.getItemStack(); - - if( !item.isEmpty() ) - { - if( item.getCount() >= item.getMaxStackSize() ) - { - liftQty = 0; - } - if( !Platform.itemComparisons().isSameItem( slotItem.getDefinition(), item ) ) - { - liftQty = 0; - } - } - - if( liftQty > 0 ) - { - IAEItemStack ais = slotItem.copy(); - ais.setStackSize( 1 ); - ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - final InventoryAdaptor ia = new AdaptorItemHandler( new WrapperCursorItemHandler( player.inventory ) ); - - final ItemStack fail = ia.addItems( ais.createItemStack() ); - if( !fail.isEmpty() ) - { - this.getCellInventory().injectItems( ais, Actionable.MODULATE, this.getActionSource() ); - } - - this.updateHeld( player ); - } - } - } - break; - case PICKUP_OR_SET_DOWN: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( player.inventory.getItemStack().isEmpty() ) - { - if( slotItem != null ) - { - IAEItemStack ais = slotItem.copy(); - ais.setStackSize( ais.getDefinition().getMaxStackSize() ); - ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - player.inventory.setItemStack( ais.createItemStack() ); - } - else - { - player.inventory.setItemStack( ItemStack.EMPTY ); - } - this.updateHeld( player ); - } - } - else - { - IAEItemStack ais = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( player.inventory.getItemStack() ); - ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - player.inventory.setItemStack( ais.createItemStack() ); - } - else - { - player.inventory.setItemStack( ItemStack.EMPTY ); - } - this.updateHeld( player ); - } - - break; - case SPLIT_OR_PLACE_SINGLE: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( player.inventory.getItemStack().isEmpty() ) - { - if( slotItem != null ) - { - IAEItemStack ais = slotItem.copy(); - final long maxSize = ais.getDefinition().getMaxStackSize(); - ais.setStackSize( maxSize ); - ais = this.getCellInventory().extractItems( ais, Actionable.SIMULATE, this.getActionSource() ); - - if( ais != null ) - { - final long stackSize = Math.min( maxSize, ais.getStackSize() ); - ais.setStackSize( ( stackSize + 1 ) >> 1 ); - ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - } - - if( ais != null ) - { - player.inventory.setItemStack( ais.createItemStack() ); - } - else - { - player.inventory.setItemStack( ItemStack.EMPTY ); - } - this.updateHeld( player ); - } - } - else - { - IAEItemStack ais = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( player.inventory.getItemStack() ); - ais.setStackSize( 1 ); - ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais == null ) - { - final ItemStack is = player.inventory.getItemStack(); - is.setCount( is.getCount() - 1 ); - if( is.getCount() <= 0 ) - { - player.inventory.setItemStack( ItemStack.EMPTY ); - } - this.updateHeld( player ); - } - } - - break; - case CREATIVE_DUPLICATE: - if( player.capabilities.isCreativeMode && slotItem != null ) - { - final ItemStack is = slotItem.createItemStack(); - is.setCount( is.getMaxStackSize() ); - player.inventory.setItemStack( is ); - this.updateHeld( player ); - } - break; - case MOVE_REGION: - - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( slotItem != null ) - { - final int playerInv = 9 * 4; - for( int slotNum = 0; slotNum < playerInv; slotNum++ ) - { - IAEItemStack ais = slotItem.copy(); - ItemStack myItem = ais.createItemStack(); - - ais.setStackSize( myItem.getMaxStackSize() ); - - final InventoryAdaptor adp = InventoryAdaptor.getAdaptor( player ); - myItem.setCount( (int) ais.getStackSize() ); - myItem = adp.simulateAdd( myItem ); - - if( !myItem.isEmpty() ) - { - ais.setStackSize( ais.getStackSize() - myItem.getCount() ); - } - - ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - adp.addItems( ais.createItemStack() ); - } - else - { - return; - } - } - } - - break; - default: - break; - } - } - - protected void updateHeld( final EntityPlayerMP p ) - { - if( Platform.isServer() ) - { - try - { - NetworkHandler.instance() - .sendTo( - new PacketInventoryAction( InventoryAction.UPDATE_HAND, 0, AEItemStack.fromItemStack( p.inventory.getItemStack() ) ), - p ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - - protected ItemStack transferStackToContainer( final ItemStack input ) - { - return this.shiftStoreItem( input ); - } - - private ItemStack shiftStoreItem( final ItemStack input ) - { - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return input; - } - final IAEItemStack ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), - AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( input ), - this.getActionSource() ); - if( ais == null ) - { - return ItemStack.EMPTY; - } - return ais.createItemStack(); - } - - private void updateSlot( final Slot clickSlot ) - { - // ??? - this.detectAndSendChanges(); - } - - private void sendCustomName() - { - if( !this.sentCustomName ) - { - this.sentCustomName = true; - if( Platform.isServer() ) - { - ICustomNameObject name = null; - - if( this.part instanceof ICustomNameObject ) - { - name = (ICustomNameObject) this.part; - } - - if( this.tileEntity instanceof ICustomNameObject ) - { - name = (ICustomNameObject) this.tileEntity; - } - - if( this.obj instanceof ICustomNameObject ) - { - name = (ICustomNameObject) this.obj; - } - - if( this instanceof ICustomNameObject ) - { - name = (ICustomNameObject) this; - } - - if( name != null ) - { - if( name.hasCustomInventoryName() ) - { - this.setCustomName( name.getCustomInventoryName() ); - } - - if( this.getCustomName() != null ) - { - try - { - NetworkHandler.instance() - .sendTo( new PacketValueConfig( "CustomName", this.getCustomName() ), - (EntityPlayerMP) this.getInventoryPlayer().player ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } - } - } - - public void swapSlotContents( final int slotA, final int slotB ) - { - final Slot a = this.getSlot( slotA ); - final Slot b = this.getSlot( slotB ); - - // NPE protection... - if( a == null || b == null ) - { - return; - } - - final ItemStack isA = a.getStack(); - final ItemStack isB = b.getStack(); - - // something to do? - if( isA.isEmpty() && isB.isEmpty() ) - { - return; - } - - // can take? - - if( !isA.isEmpty() && !a.canTakeStack( this.getInventoryPlayer().player ) ) - { - return; - } - - if( !isB.isEmpty() && !b.canTakeStack( this.getInventoryPlayer().player ) ) - { - return; - } - - // swap valid? - - if( !isB.isEmpty() && !a.isItemValid( isB ) ) - { - return; - } - - if( !isA.isEmpty() && !b.isItemValid( isA ) ) - { - return; - } - - ItemStack testA = isB.isEmpty() ? ItemStack.EMPTY : isB.copy(); - ItemStack testB = isA.isEmpty() ? ItemStack.EMPTY : isA.copy(); - - // can put some back? - if( !testA.isEmpty() && testA.getCount() > a.getSlotStackLimit() ) - { - if( !testB.isEmpty() ) - { - return; - } - - final int totalA = testA.getCount(); - testA.setCount( a.getSlotStackLimit() ); - testB = testA.copy(); - - testB.setCount( totalA - testA.getCount() ); - } - - if( !testB.isEmpty() && testB.getCount() > b.getSlotStackLimit() ) - { - if( !testA.isEmpty() ) - { - return; - } - - final int totalB = testB.getCount(); - testB.setCount( b.getSlotStackLimit() ); - testA = testB.copy(); - - testA.setCount( totalB - testA.getCount() ); - } - - a.putStack( testA ); - b.putStack( testB ); - } - - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - - } - - public void onSlotChange( final Slot s ) - { - - } - - public boolean isValidForSlot( final Slot s, final ItemStack i ) - { - return true; - } - - public IMEInventoryHandler getCellInventory() - { - return this.cellInv; - } - - public void setCellInventory( final IMEInventoryHandler cellInv ) - { - this.cellInv = cellInv; - } - - public String getCustomName() - { - return this.customName; - } - - public void setCustomName( final String customName ) - { - this.customName = customName; - } - - public InventoryPlayer getInventoryPlayer() - { - return this.invPlayer; - } - - public boolean isValidContainer() - { - return this.isContainerValid; - } - - public void setValidContainer( final boolean isContainerValid ) - { - this.isContainerValid = isContainerValid; - } - - public ContainerOpenContext getOpenContext() - { - return this.openContext; - } - - public void setOpenContext( final ContainerOpenContext openContext ) - { - this.openContext = openContext; - } - - public IEnergySource getPowerSource() - { - return this.powerSrc; - } - - public void setPowerSource( final IEnergySource powerSrc ) - { - this.powerSrc = powerSrc; - } + testA.setCount(totalB - testA.getCount()); + } + + a.putStack(testA); + b.putStack(testB); + } + + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + + } + + public void onSlotChange(final Slot s) { + + } + + public boolean isValidForSlot(final Slot s, final ItemStack i) { + return true; + } + + public IMEInventoryHandler getCellInventory() { + return this.cellInv; + } + + public void setCellInventory(final IMEInventoryHandler cellInv) { + this.cellInv = cellInv; + } + + public String getCustomName() { + return this.customName; + } + + public void setCustomName(final String customName) { + this.customName = customName; + } + + public InventoryPlayer getInventoryPlayer() { + return this.invPlayer; + } + + public boolean isValidContainer() { + return this.isContainerValid; + } + + public void setValidContainer(final boolean isContainerValid) { + this.isContainerValid = isContainerValid; + } + + public ContainerOpenContext getOpenContext() { + return this.openContext; + } + + public void setOpenContext(final ContainerOpenContext openContext) { + this.openContext = openContext; + } + + public IEnergySource getPowerSource() { + return this.powerSrc; + } + + public void setPowerSource(final IEnergySource powerSrc) { + this.powerSrc = powerSrc; + } } diff --git a/src/main/java/appeng/container/ContainerNull.java b/src/main/java/appeng/container/ContainerNull.java index 8e94d3caf..c3198144c 100644 --- a/src/main/java/appeng/container/ContainerNull.java +++ b/src/main/java/appeng/container/ContainerNull.java @@ -26,12 +26,10 @@ import net.minecraft.inventory.Container; /* * Totally useless container that does nothing. */ -public class ContainerNull extends Container -{ +public class ContainerNull extends Container { - @Override - public boolean canInteractWith( final EntityPlayer entityplayer ) - { - return false; - } + @Override + public boolean canInteractWith(final EntityPlayer entityplayer) { + return false; + } } diff --git a/src/main/java/appeng/container/ContainerOpenContext.java b/src/main/java/appeng/container/ContainerOpenContext.java index 6f7ed7248..4617a5eb3 100644 --- a/src/main/java/appeng/container/ContainerOpenContext.java +++ b/src/main/java/appeng/container/ContainerOpenContext.java @@ -19,86 +19,71 @@ package appeng.container; +import appeng.api.parts.IPart; +import appeng.api.util.AEPartLocation; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.api.parts.IPart; -import appeng.api.util.AEPartLocation; +public class ContainerOpenContext { -public class ContainerOpenContext -{ + private final boolean isItem; + private World w; + private int x; + private int y; + private int z; + private AEPartLocation side; - private final boolean isItem; - private World w; - private int x; - private int y; - private int z; - private AEPartLocation side; + public ContainerOpenContext(final Object myItem) { + final boolean isWorld = myItem instanceof IPart || myItem instanceof TileEntity; + this.isItem = !isWorld; + } - public ContainerOpenContext( final Object myItem ) - { - final boolean isWorld = myItem instanceof IPart || myItem instanceof TileEntity; - this.isItem = !isWorld; - } + public TileEntity getTile() { + if (this.isItem) { + return null; + } + return this.w.getTileEntity(new BlockPos(this.x, this.y, this.z)); + } - public TileEntity getTile() - { - if( this.isItem ) - { - return null; - } - return this.w.getTileEntity( new BlockPos( this.x, this.y, this.z ) ); - } + public AEPartLocation getSide() { + return this.side; + } - public AEPartLocation getSide() - { - return this.side; - } + public void setSide(final AEPartLocation side) { + this.side = side; + } - public void setSide( final AEPartLocation side ) - { - this.side = side; - } + private int getZ() { + return this.z; + } - private int getZ() - { - return this.z; - } + public void setZ(final int z) { + this.z = z; + } - public void setZ( final int z ) - { - this.z = z; - } + private int getY() { + return this.y; + } - private int getY() - { - return this.y; - } + public void setY(final int y) { + this.y = y; + } - public void setY( final int y ) - { - this.y = y; - } + private int getX() { + return this.x; + } - private int getX() - { - return this.x; - } + public void setX(final int x) { + this.x = x; + } - public void setX( final int x ) - { - this.x = x; - } + private World getWorld() { + return this.w; + } - private World getWorld() - { - return this.w; - } - - public void setWorld( final World w ) - { - this.w = w; - } + public void setWorld(final World w) { + this.w = w; + } } diff --git a/src/main/java/appeng/container/guisync/GuiSync.java b/src/main/java/appeng/container/guisync/GuiSync.java index 14d6e922f..ab1d5266d 100644 --- a/src/main/java/appeng/container/guisync/GuiSync.java +++ b/src/main/java/appeng/container/guisync/GuiSync.java @@ -29,10 +29,9 @@ import java.lang.annotation.Target; * Annotates that this field should be synchronized between the server and client. * Requires the field to be public. */ -@Retention( RetentionPolicy.RUNTIME ) -@Target( ElementType.FIELD ) -public @interface GuiSync -{ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface GuiSync { - int value(); + int value(); } diff --git a/src/main/java/appeng/container/guisync/SyncData.java b/src/main/java/appeng/container/guisync/SyncData.java index 13b903f72..8b5e55708 100644 --- a/src/main/java/appeng/container/guisync/SyncData.java +++ b/src/main/java/appeng/container/guisync/SyncData.java @@ -19,194 +19,130 @@ package appeng.container.guisync; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.EnumSet; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.inventory.IContainerListener; - import appeng.container.AEBaseContainer; import appeng.core.AELog; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketProgressBar; import appeng.core.sync.packets.PacketValueConfig; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.IContainerListener; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.EnumSet; -public class SyncData -{ +public class SyncData { - private final AEBaseContainer source; - private final Field field; - private final int channel; - private Object clientVersion; + private final AEBaseContainer source; + private final Field field; + private final int channel; + private Object clientVersion; - public SyncData( final AEBaseContainer container, final Field field, final GuiSync annotation ) - { - this.clientVersion = null; - this.source = container; - this.field = field; - this.channel = annotation.value(); - } + public SyncData(final AEBaseContainer container, final Field field, final GuiSync annotation) { + this.clientVersion = null; + this.source = container; + this.field = field; + this.channel = annotation.value(); + } - public int getChannel() - { - return this.channel; - } + public int getChannel() { + return this.channel; + } - public void tick( final IContainerListener c ) - { - try - { - final Object val = this.field.get( this.source ); - if( val != null && this.clientVersion == null ) - { - this.send( c, val ); - } - else if( !val.equals( this.clientVersion ) ) - { - this.send( c, val ); - } - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + public void tick(final IContainerListener c) { + try { + final Object val = this.field.get(this.source); + if (val != null && this.clientVersion == null) { + this.send(c, val); + } else if (!val.equals(this.clientVersion)) { + this.send(c, val); + } + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } catch (final IOException e) { + AELog.debug(e); + } + } - private void send( final IContainerListener o, final Object val ) throws IOException - { - if( val instanceof String ) - { - if( o instanceof EntityPlayerMP ) - { - NetworkHandler.instance().sendTo( new PacketValueConfig( "SyncDat." + this.channel, (String) val ), (EntityPlayerMP) o ); - } - } - else if( this.field.getType().isEnum() ) - { - o.sendWindowProperty( this.source, this.channel, ( (Enum) val ).ordinal() ); - } - else if( val instanceof Long || val.getClass() == long.class ) - { - if( o instanceof EntityPlayerMP ) - { - NetworkHandler.instance().sendTo( new PacketProgressBar( this.channel, (Long) val ), (EntityPlayerMP) o ); - } - } - else if( val instanceof Boolean || val.getClass() == boolean.class ) - { - o.sendWindowProperty( this.source, this.channel, ( (Boolean) val ) ? 1 : 0 ); - } - else - { - o.sendWindowProperty( this.source, this.channel, (Integer) val ); - } + private void send(final IContainerListener o, final Object val) throws IOException { + if (val instanceof String) { + if (o instanceof EntityPlayerMP) { + NetworkHandler.instance().sendTo(new PacketValueConfig("SyncDat." + this.channel, (String) val), (EntityPlayerMP) o); + } + } else if (this.field.getType().isEnum()) { + o.sendWindowProperty(this.source, this.channel, ((Enum) val).ordinal()); + } else if (val instanceof Long || val.getClass() == long.class) { + if (o instanceof EntityPlayerMP) { + NetworkHandler.instance().sendTo(new PacketProgressBar(this.channel, (Long) val), (EntityPlayerMP) o); + } + } else if (val instanceof Boolean || val.getClass() == boolean.class) { + o.sendWindowProperty(this.source, this.channel, ((Boolean) val) ? 1 : 0); + } else { + o.sendWindowProperty(this.source, this.channel, (Integer) val); + } - this.clientVersion = val; - } + this.clientVersion = val; + } - public void update( final Object val ) - { - try - { - final Object oldValue = this.field.get( this.source ); - if( val instanceof String ) - { - this.updateString( oldValue, (String) val ); - } - else - { - this.updateValue( oldValue, (Long) val ); - } - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - } + public void update(final Object val) { + try { + final Object oldValue = this.field.get(this.source); + if (val instanceof String) { + this.updateString(oldValue, (String) val); + } else { + this.updateValue(oldValue, (Long) val); + } + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } + } - private void updateString( final Object oldValue, final String val ) - { - try - { - this.field.set( this.source, val ); - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - } + private void updateString(final Object oldValue, final String val) { + try { + this.field.set(this.source, val); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } + } - private void updateValue( final Object oldValue, final long val ) - { - try - { - if( this.field.getType().isEnum() ) - { - final EnumSet valList = EnumSet.allOf( (Class) this.field.getType() ); - for( final Enum e : valList ) - { - if( e.ordinal() == val ) - { - this.field.set( this.source, e ); - break; - } - } - } - else - { - if( this.field.getType().equals( int.class ) ) - { - this.field.set( this.source, (int) val ); - } - else if( this.field.getType().equals( long.class ) ) - { - this.field.set( this.source, val ); - } - else if( this.field.getType().equals( boolean.class ) ) - { - this.field.set( this.source, val == 1 ); - } - else if( this.field.getType().equals( Integer.class ) ) - { - this.field.set( this.source, (int) val ); - } - else if( this.field.getType().equals( Long.class ) ) - { - this.field.set( this.source, val ); - } - else if( this.field.getType().equals( Boolean.class ) ) - { - this.field.set( this.source, val == 1 ); - } - } + private void updateValue(final Object oldValue, final long val) { + try { + if (this.field.getType().isEnum()) { + final EnumSet valList = EnumSet.allOf((Class) this.field.getType()); + for (final Enum e : valList) { + if (e.ordinal() == val) { + this.field.set(this.source, e); + break; + } + } + } else { + if (this.field.getType().equals(int.class)) { + this.field.set(this.source, (int) val); + } else if (this.field.getType().equals(long.class)) { + this.field.set(this.source, val); + } else if (this.field.getType().equals(boolean.class)) { + this.field.set(this.source, val == 1); + } else if (this.field.getType().equals(Integer.class)) { + this.field.set(this.source, (int) val); + } else if (this.field.getType().equals(Long.class)) { + this.field.set(this.source, val); + } else if (this.field.getType().equals(Boolean.class)) { + this.field.set(this.source, val == 1); + } + } - this.source.onUpdate( this.field.getName(), oldValue, this.field.get( this.source ) ); - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - } + this.source.onUpdate(this.field.getName(), oldValue, this.field.get(this.source)); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java b/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java index dbc45bff8..b126cf03b 100644 --- a/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java +++ b/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java @@ -19,16 +19,6 @@ package appeng.container.implementations; -import java.util.Iterator; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IContainerListener; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.wrapper.EmptyHandler; - import appeng.api.AEApi; import appeng.api.config.CopyMode; import appeng.api.config.FuzzyMode; @@ -49,219 +39,192 @@ import appeng.util.Platform; import appeng.util.helpers.ItemHandlerUtil; import appeng.util.inv.WrapperSupplierItemHandler; import appeng.util.iterators.NullIterator; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IContainerListener; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.wrapper.EmptyHandler; + +import java.util.Iterator; -public class ContainerCellWorkbench extends ContainerUpgradeable -{ - private final TileCellWorkbench workBench; - @GuiSync( 2 ) - public CopyMode copyMode = CopyMode.CLEAR_ON_REMOVE; - private ItemStack prevStack = ItemStack.EMPTY; - private int lastUpgrades = 0; +public class ContainerCellWorkbench extends ContainerUpgradeable { + private final TileCellWorkbench workBench; + @GuiSync(2) + public CopyMode copyMode = CopyMode.CLEAR_ON_REMOVE; + private ItemStack prevStack = ItemStack.EMPTY; + private int lastUpgrades = 0; - public ContainerCellWorkbench( final InventoryPlayer ip, final TileCellWorkbench te ) - { - super( ip, te ); - this.workBench = te; - } + public ContainerCellWorkbench(final InventoryPlayer ip, final TileCellWorkbench te) { + super(ip, te); + this.workBench = te; + } - public void setFuzzy( final FuzzyMode valueOf ) - { - final ICellWorkbenchItem cwi = this.workBench.getCell(); - if( cwi != null ) - { - cwi.setFuzzyMode( this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ), valueOf ); - } - } + public void setFuzzy(final FuzzyMode valueOf) { + final ICellWorkbenchItem cwi = this.workBench.getCell(); + if (cwi != null) { + cwi.setFuzzyMode(this.workBench.getInventoryByName("cell").getStackInSlot(0), valueOf); + } + } - public void nextWorkBenchCopyMode() - { - this.workBench.getConfigManager().putSetting( Settings.COPY_MODE, Platform.nextEnum( this.getWorkBenchCopyMode() ) ); - } + public void nextWorkBenchCopyMode() { + this.workBench.getConfigManager().putSetting(Settings.COPY_MODE, Platform.nextEnum(this.getWorkBenchCopyMode())); + } - private CopyMode getWorkBenchCopyMode() - { - return (CopyMode) this.workBench.getConfigManager().getSetting( Settings.COPY_MODE ); - } + private CopyMode getWorkBenchCopyMode() { + return (CopyMode) this.workBench.getConfigManager().getSetting(Settings.COPY_MODE); + } - @Override - protected int getHeight() - { - return 251; - } + @Override + protected int getHeight() { + return 251; + } - @Override - protected void setupConfig() - { - final IItemHandler cell = this.getUpgradeable().getInventoryByName( "cell" ); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.WORKBENCH_CELL, cell, 0, 152, 8, this.getPlayerInv() ) ); + @Override + protected void setupConfig() { + final IItemHandler cell = this.getUpgradeable().getInventoryByName("cell"); + this.addSlotToContainer(new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.WORKBENCH_CELL, cell, 0, 152, 8, this.getPlayerInv())); - final IItemHandler inv = this.getUpgradeable().getInventoryByName( "config" ); - final WrapperSupplierItemHandler upgradeInventory = new WrapperSupplierItemHandler( this::getCellUpgradeInventory ); - // null, 3 * 8 ); + final IItemHandler inv = this.getUpgradeable().getInventoryByName("config"); + final WrapperSupplierItemHandler upgradeInventory = new WrapperSupplierItemHandler(this::getCellUpgradeInventory); + // null, 3 * 8 ); - int offset = 0; - final int y = 29; - final int x = 8; - for( int w = 0; w < 7; w++ ) - { - for( int z = 0; z < 9; z++ ) - { - this.addSlotToContainer( new SlotFakeTypeOnly( inv, offset, x + z * 18, y + w * 18 ) ); - offset++; - } - } + int offset = 0; + final int y = 29; + final int x = 8; + for (int w = 0; w < 7; w++) { + for (int z = 0; z < 9; z++) { + this.addSlotToContainer(new SlotFakeTypeOnly(inv, offset, x + z * 18, y + w * 18)); + offset++; + } + } - for( int zz = 0; zz < 3; zz++ ) - { - for( int z = 0; z < 8; z++ ) - { - final int iSLot = zz * 8 + z; - this.addSlotToContainer( - new OptionalSlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgradeInventory, this, iSLot, 187 + zz * 18, 8 + 18 * z, iSLot, this - .getInventoryPlayer() ) ); - } - } - /* - * if ( supportCapacity() ) { for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new - * OptionalSlotFakeTypeOnly( inv, this, offset++, x, y, z, w, 1 ) ); - * for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new OptionalSlotFakeTypeOnly( - * inv, this, offset++, x, y, z, w + 2, 2 ) ); - * for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new OptionalSlotFakeTypeOnly( - * inv, this, offset++, x, y, z, w + 4, 3 ) ); } - */ - } + for (int zz = 0; zz < 3; zz++) { + for (int z = 0; z < 8; z++) { + final int iSLot = zz * 8 + z; + this.addSlotToContainer( + new OptionalSlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgradeInventory, this, iSLot, 187 + zz * 18, 8 + 18 * z, iSLot, this + .getInventoryPlayer())); + } + } + /* + * if ( supportCapacity() ) { for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new + * OptionalSlotFakeTypeOnly( inv, this, offset++, x, y, z, w, 1 ) ); + * for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new OptionalSlotFakeTypeOnly( + * inv, this, offset++, x, y, z, w + 2, 2 ) ); + * for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new OptionalSlotFakeTypeOnly( + * inv, this, offset++, x, y, z, w + 4, 3 ) ); } + */ + } - @Override - public int availableUpgrades() - { - final ItemStack is = this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ); - if( this.prevStack != is ) - { - this.prevStack = is; - this.lastUpgrades = this.getCellUpgradeInventory().getSlots(); - } - return this.lastUpgrades; - } + @Override + public int availableUpgrades() { + final ItemStack is = this.workBench.getInventoryByName("cell").getStackInSlot(0); + if (this.prevStack != is) { + this.prevStack = is; + this.lastUpgrades = this.getCellUpgradeInventory().getSlots(); + } + return this.lastUpgrades; + } - @Override - public void detectAndSendChanges() - { - final ItemStack is = this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ); - if( Platform.isServer() ) - { - for( final IContainerListener listener : this.listeners ) - { - if( this.prevStack != is ) - { - // if the bars changed an item was probably made, so just send shit! - for( final Slot s : this.inventorySlots ) - { - if( s instanceof OptionalSlotRestrictedInput ) - { - final OptionalSlotRestrictedInput sri = (OptionalSlotRestrictedInput) s; - listener.sendSlotContents( this, sri.slotNumber, sri.getStack() ); - } - } + @Override + public void detectAndSendChanges() { + final ItemStack is = this.workBench.getInventoryByName("cell").getStackInSlot(0); + if (Platform.isServer()) { + for (final IContainerListener listener : this.listeners) { + if (this.prevStack != is) { + // if the bars changed an item was probably made, so just send shit! + for (final Slot s : this.inventorySlots) { + if (s instanceof OptionalSlotRestrictedInput) { + final OptionalSlotRestrictedInput sri = (OptionalSlotRestrictedInput) s; + listener.sendSlotContents(this, sri.slotNumber, sri.getStack()); + } + } - if( listener instanceof EntityPlayerMP ) - { - ( (EntityPlayerMP) listener ).isChangingQuantityOnly = false; - } - } - } + if (listener instanceof EntityPlayerMP) { + ((EntityPlayerMP) listener).isChangingQuantityOnly = false; + } + } + } - this.setCopyMode( this.getWorkBenchCopyMode() ); - this.setFuzzyMode( this.getWorkBenchFuzzyMode() ); - } + this.setCopyMode(this.getWorkBenchCopyMode()); + this.setFuzzyMode(this.getWorkBenchFuzzyMode()); + } - this.prevStack = is; - this.standardDetectAndSendChanges(); - } + this.prevStack = is; + this.standardDetectAndSendChanges(); + } - @Override - public boolean isSlotEnabled( final int idx ) - { - return idx < this.availableUpgrades(); - } + @Override + public boolean isSlotEnabled(final int idx) { + return idx < this.availableUpgrades(); + } - public IItemHandler getCellUpgradeInventory() - { - final IItemHandler upgradeInventory = this.workBench.getCellUpgradeInventory(); + public IItemHandler getCellUpgradeInventory() { + final IItemHandler upgradeInventory = this.workBench.getCellUpgradeInventory(); - return upgradeInventory == null ? EmptyHandler.INSTANCE : upgradeInventory; - } + return upgradeInventory == null ? EmptyHandler.INSTANCE : upgradeInventory; + } - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if( field.equals( "copyMode" ) ) - { - this.workBench.getConfigManager().putSetting( Settings.COPY_MODE, this.getCopyMode() ); - } + @Override + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("copyMode")) { + this.workBench.getConfigManager().putSetting(Settings.COPY_MODE, this.getCopyMode()); + } - super.onUpdate( field, oldValue, newValue ); - } + super.onUpdate(field, oldValue, newValue); + } - public void clear() - { - ItemHandlerUtil.clear( this.getUpgradeable().getInventoryByName( "config" ) ); - this.detectAndSendChanges(); - } + public void clear() { + ItemHandlerUtil.clear(this.getUpgradeable().getInventoryByName("config")); + this.detectAndSendChanges(); + } - private FuzzyMode getWorkBenchFuzzyMode() - { - final ICellWorkbenchItem cwi = this.workBench.getCell(); - if( cwi != null ) - { - return cwi.getFuzzyMode( this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ) ); - } - return FuzzyMode.IGNORE_ALL; - } + private FuzzyMode getWorkBenchFuzzyMode() { + final ICellWorkbenchItem cwi = this.workBench.getCell(); + if (cwi != null) { + return cwi.getFuzzyMode(this.workBench.getInventoryByName("cell").getStackInSlot(0)); + } + return FuzzyMode.IGNORE_ALL; + } - public void partition() - { + public void partition() { - final IItemHandler inv = this.getUpgradeable().getInventoryByName( "config" ); + final IItemHandler inv = this.getUpgradeable().getInventoryByName("config"); - final ItemStack is = this.getUpgradeable().getInventoryByName( "cell" ).getStackInSlot( 0 ); - final IStorageChannel channel = is.getItem() instanceof IStorageCell ? ( (IStorageCell) is.getItem() ).getChannel() : AEApi.instance() - .storage() - .getStorageChannel( IItemStorageChannel.class ); + final ItemStack is = this.getUpgradeable().getInventoryByName("cell").getStackInSlot(0); + final IStorageChannel channel = is.getItem() instanceof IStorageCell ? ((IStorageCell) is.getItem()).getChannel() : AEApi.instance() + .storage() + .getStorageChannel(IItemStorageChannel.class); - final IMEInventory cellInv = AEApi.instance().registries().cell().getCellInventory( is, null, channel ); + final IMEInventory cellInv = AEApi.instance().registries().cell().getCellInventory(is, null, channel); - Iterator i = new NullIterator<>(); - if( cellInv != null ) - { - final IItemList list = cellInv.getAvailableItems( channel.createList() ); - i = list.iterator(); - } + Iterator i = new NullIterator<>(); + if (cellInv != null) { + final IItemList list = cellInv.getAvailableItems(channel.createList()); + i = list.iterator(); + } - for( int x = 0; x < inv.getSlots(); x++ ) - { - if( i.hasNext() ) - { - // TODO: check if ok - final ItemStack g = i.next().asItemStackRepresentation(); - ItemHandlerUtil.setStackInSlot( inv, x, g ); - } - else - { - ItemHandlerUtil.setStackInSlot( inv, x, ItemStack.EMPTY ); - } - } + for (int x = 0; x < inv.getSlots(); x++) { + if (i.hasNext()) { + // TODO: check if ok + final ItemStack g = i.next().asItemStackRepresentation(); + ItemHandlerUtil.setStackInSlot(inv, x, g); + } else { + ItemHandlerUtil.setStackInSlot(inv, x, ItemStack.EMPTY); + } + } - this.detectAndSendChanges(); - } + this.detectAndSendChanges(); + } - public CopyMode getCopyMode() - { - return this.copyMode; - } + public CopyMode getCopyMode() { + return this.copyMode; + } - private void setCopyMode( final CopyMode copyMode ) - { - this.copyMode = copyMode; - } + private void setCopyMode(final CopyMode copyMode) { + this.copyMode = copyMode; + } } \ No newline at end of file diff --git a/src/main/java/appeng/container/implementations/ContainerChest.java b/src/main/java/appeng/container/implementations/ContainerChest.java index 5659071da..ac8209f7b 100644 --- a/src/main/java/appeng/container/implementations/ContainerChest.java +++ b/src/main/java/appeng/container/implementations/ContainerChest.java @@ -19,26 +19,23 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.storage.TileChest; +import net.minecraft.entity.player.InventoryPlayer; -public class ContainerChest extends AEBaseContainer -{ +public class ContainerChest extends AEBaseContainer { - private final TileChest chest; + private final TileChest chest; - public ContainerChest( final InventoryPlayer ip, final TileChest chest ) - { - super( ip, chest, null ); - this.chest = chest; + public ContainerChest(final InventoryPlayer ip, final TileChest chest) { + super(ip, chest, null); + this.chest = chest; - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, this.chest.getInternalInventory(), 1, 80, 37, this - .getInventoryPlayer() ) ); + this.addSlotToContainer(new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, this.chest.getInternalInventory(), 1, 80, 37, this + .getInventoryPlayer())); - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 166 - /* height of player inventory */82); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCondenser.java b/src/main/java/appeng/container/implementations/ContainerCondenser.java index 519f2ea93..87a4a6ed1 100644 --- a/src/main/java/appeng/container/implementations/ContainerCondenser.java +++ b/src/main/java/appeng/container/implementations/ContainerCondenser.java @@ -19,11 +19,6 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IContainerListener; -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.CondenserOutput; import appeng.api.config.Settings; import appeng.container.AEBaseContainer; @@ -33,79 +28,73 @@ import appeng.container.slot.SlotOutput; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.misc.TileCondenser; import appeng.util.Platform; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IContainerListener; +import net.minecraft.item.ItemStack; +import net.minecraftforge.items.IItemHandler; -public class ContainerCondenser extends AEBaseContainer implements IProgressProvider -{ +public class ContainerCondenser extends AEBaseContainer implements IProgressProvider { - private final TileCondenser condenser; - @GuiSync( 0 ) - public long requiredEnergy = 0; - @GuiSync( 1 ) - public long storedPower = 0; - @GuiSync( 2 ) - public CondenserOutput output = CondenserOutput.TRASH; - private ItemStack prevStack = ItemStack.EMPTY; + private final TileCondenser condenser; + @GuiSync(0) + public long requiredEnergy = 0; + @GuiSync(1) + public long storedPower = 0; + @GuiSync(2) + public CondenserOutput output = CondenserOutput.TRASH; + private final ItemStack prevStack = ItemStack.EMPTY; - public ContainerCondenser( final InventoryPlayer ip, final TileCondenser condenser ) - { - super( ip, condenser, null ); - this.condenser = condenser; + public ContainerCondenser(final InventoryPlayer ip, final TileCondenser condenser) { + super(ip, condenser, null); + this.condenser = condenser; - IItemHandler inv = condenser.getInternalInventory(); + IItemHandler inv = condenser.getInternalInventory(); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.TRASH, inv, 0, 51, 52, ip ) ); - this.addSlotToContainer( new SlotOutput( inv, 1, 105, 52, -1 ) ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.STORAGE_COMPONENT, inv, 2, 101, 26, ip ) ).setStackLimit( 1 ) ); + this.addSlotToContainer(new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.TRASH, inv, 0, 51, 52, ip)); + this.addSlotToContainer(new SlotOutput(inv, 1, 105, 52, -1)); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.STORAGE_COMPONENT, inv, 2, 101, 26, ip)).setStackLimit(1)); - this.bindPlayerInventory( ip, 0, 197 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 197 - /* height of player inventory */82); + } - @Override - public void detectAndSendChanges() - { - final ItemStack is = this.condenser.getInternalInventory().getStackInSlot( 1 ); - if( Platform.isServer() ) - { - final double maxStorage = this.condenser.getStorage(); - final double requiredEnergy = this.condenser.getRequiredPower(); + @Override + public void detectAndSendChanges() { + final ItemStack is = this.condenser.getInternalInventory().getStackInSlot(1); + if (Platform.isServer()) { + final double maxStorage = this.condenser.getStorage(); + final double requiredEnergy = this.condenser.getRequiredPower(); - this.requiredEnergy = requiredEnergy == 0 ? (int) maxStorage : (int) Math.min( requiredEnergy, maxStorage ); - this.storedPower = (int) this.condenser.getStoredPower(); - this.setOutput( (CondenserOutput) this.condenser.getConfigManager().getSetting( Settings.CONDENSER_OUTPUT ) ); + this.requiredEnergy = requiredEnergy == 0 ? (int) maxStorage : (int) Math.min(requiredEnergy, maxStorage); + this.storedPower = (int) this.condenser.getStoredPower(); + this.setOutput((CondenserOutput) this.condenser.getConfigManager().getSetting(Settings.CONDENSER_OUTPUT)); - for( final IContainerListener listener : this.listeners ) - { - if( !ItemStack.areItemsEqual( is, prevStack ) ) - { - listener.sendSlotContents( this, 1, is ); - } - } - } + for (final IContainerListener listener : this.listeners) { + if (!ItemStack.areItemsEqual(is, prevStack)) { + listener.sendSlotContents(this, 1, is); + } + } + } - super.detectAndSendChanges(); - } + super.detectAndSendChanges(); + } - @Override - public int getCurrentProgress() - { - return (int) this.storedPower; - } + @Override + public int getCurrentProgress() { + return (int) this.storedPower; + } - @Override - public int getMaxProgress() - { - return (int) this.requiredEnergy; - } + @Override + public int getMaxProgress() { + return (int) this.requiredEnergy; + } - public CondenserOutput getOutput() - { - return this.output; - } + public CondenserOutput getOutput() { + return this.output; + } - private void setOutput( final CondenserOutput output ) - { - this.output = output; - } + private void setOutput(final CondenserOutput output) { + this.output = output; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftAmount.java b/src/main/java/appeng/container/implementations/ContainerCraftAmount.java index 7d91e1a04..3bad84170 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftAmount.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftAmount.java @@ -19,12 +19,6 @@ package appeng.container.implementations; -import javax.annotation.Nonnull; - -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Slot; -import net.minecraft.world.World; - import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; import appeng.api.networking.security.IActionHost; @@ -35,63 +29,58 @@ import appeng.container.AEBaseContainer; import appeng.container.slot.SlotInaccessible; import appeng.me.helpers.PlayerSource; import appeng.tile.inventory.AppEngInternalInventory; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.world.World; + +import javax.annotation.Nonnull; -public class ContainerCraftAmount extends AEBaseContainer -{ +public class ContainerCraftAmount extends AEBaseContainer { - private final Slot craftingItem; - private IAEItemStack itemToCreate; + private final Slot craftingItem; + private IAEItemStack itemToCreate; - public ContainerCraftAmount( final InventoryPlayer ip, final ITerminalHost te ) - { - super( ip, te ); + public ContainerCraftAmount(final InventoryPlayer ip, final ITerminalHost te) { + super(ip, te); - this.craftingItem = new SlotInaccessible( new AppEngInternalInventory( null, 1 ), 0, 34, 53 ); - this.addSlotToContainer( this.getCraftingItem() ); - } + this.craftingItem = new SlotInaccessible(new AppEngInternalInventory(null, 1), 0, 34, 53); + this.addSlotToContainer(this.getCraftingItem()); + } - @Override - public Slot getSlot( int slotId ) - { - return super.getSlot( 0 ); - } + @Override + public Slot getSlot(int slotId) { + return super.getSlot(0); + } - @Override - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - this.verifyPermissions( SecurityPermissions.CRAFT, false ); - } + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + this.verifyPermissions(SecurityPermissions.CRAFT, false); + } - public IGrid getGrid() - { - final IActionHost h = ( (IActionHost) this.getTarget() ); - return h.getActionableNode().getGrid(); - } + public IGrid getGrid() { + final IActionHost h = ((IActionHost) this.getTarget()); + return h.getActionableNode().getGrid(); + } - public World getWorld() - { - return this.getPlayerInv().player.world; - } + public World getWorld() { + return this.getPlayerInv().player.world; + } - public IActionSource getActionSrc() - { - return new PlayerSource( this.getPlayerInv().player, (IActionHost) this.getTarget() ); - } + public IActionSource getActionSrc() { + return new PlayerSource(this.getPlayerInv().player, (IActionHost) this.getTarget()); + } - public Slot getCraftingItem() - { - return this.craftingItem; - } + public Slot getCraftingItem() { + return this.craftingItem; + } - public IAEItemStack getItemToCraft() - { - return this.itemToCreate; - } + public IAEItemStack getItemToCraft() { + return this.itemToCreate; + } - public void setItemToCraft( @Nonnull final IAEItemStack itemToCreate ) - { - this.itemToCreate = itemToCreate; - } + public void setItemToCraft(@Nonnull final IAEItemStack itemToCreate) { + this.itemToCreate = itemToCreate; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java b/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java index 4593fdde8..7a9c9501c 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java @@ -19,24 +19,6 @@ package appeng.container.implementations; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.concurrent.Future; - -import javax.annotation.Nonnull; - -import appeng.parts.reporting.PartExpandedProcessingPatternTerminal; -import com.google.common.collect.ImmutableSet; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IContainerListener; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.world.World; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; @@ -62,428 +44,363 @@ import appeng.core.sync.packets.PacketMEInventoryUpdate; import appeng.helpers.WirelessTerminalGuiObject; import appeng.me.helpers.PlayerSource; import appeng.parts.reporting.PartCraftingTerminal; +import appeng.parts.reporting.PartExpandedProcessingPatternTerminal; import appeng.parts.reporting.PartPatternTerminal; import appeng.parts.reporting.PartTerminal; import appeng.util.Platform; - - -public class ContainerCraftConfirm extends AEBaseContainer -{ - - private final ArrayList cpus = new ArrayList<>(); - private Future job; - private ICraftingJob result; - @GuiSync( 0 ) - public long bytesUsed; - @GuiSync( 1 ) - public long cpuBytesAvail; - @GuiSync( 2 ) - public int cpuCoProcessors; - @GuiSync( 3 ) - public boolean autoStart = false; - @GuiSync( 4 ) - public boolean simulation = true; - @GuiSync( 5 ) - public int selectedCpu = -1; - @GuiSync( 6 ) - public boolean noCPU = true; - @GuiSync( 7 ) - public String myName = ""; - - public ContainerCraftConfirm( final InventoryPlayer ip, final ITerminalHost te ) - { - super( ip, te ); - } - - public void cycleCpu( final boolean next ) - { - if( next ) - { - this.setSelectedCpu( this.getSelectedCpu() + 1 ); - } - else - { - this.setSelectedCpu( this.getSelectedCpu() - 1 ); - } - - if( this.getSelectedCpu() < -1 ) - { - this.setSelectedCpu( this.cpus.size() - 1 ); - } - else if( this.getSelectedCpu() >= this.cpus.size() ) - { - this.setSelectedCpu( -1 ); - } - - if( this.getSelectedCpu() == -1 ) - { - this.setCpuAvailableBytes( 0 ); - this.setCpuCoProcessors( 0 ); - this.setName( "" ); - } - else - { - this.setName( this.cpus.get( this.getSelectedCpu() ).getName() ); - this.setCpuAvailableBytes( this.cpus.get( this.getSelectedCpu() ).getSize() ); - this.setCpuCoProcessors( this.cpus.get( this.getSelectedCpu() ).getProcessors() ); - } - } - - @Override - public void detectAndSendChanges() - { - if( Platform.isClient() ) - { - return; - } - - final ICraftingGrid cc = this.getGrid().getCache( ICraftingGrid.class ); - final ImmutableSet cpuSet = cc.getCpus(); - - int matches = 0; - boolean changed = false; - for( final ICraftingCPU c : cpuSet ) - { - boolean found = false; - for( final CraftingCPURecord ccr : this.cpus ) - { - if( ccr.getCpu() == c ) - { - found = true; - break; - } - } - - final boolean matched = this.cpuMatches( c ); - - if( matched ) - { - matches++; - } - - if( found == !matched ) - { - changed = true; - } - } - - if( changed || this.cpus.size() != matches ) - { - this.cpus.clear(); - for( final ICraftingCPU c : cpuSet ) - { - if( this.cpuMatches( c ) ) - { - this.cpus.add( new CraftingCPURecord( c.getAvailableStorage(), c.getCoProcessors(), c ) ); - } - } - - this.sendCPUs(); - } - - this.setNoCPU( this.cpus.isEmpty() ); - - super.detectAndSendChanges(); - - if( this.getJob() != null && this.getJob().isDone() ) - { - try - { - this.result = this.getJob().get(); - - if( !this.result.isSimulation() ) - { - this.setSimulation( false ); - if( this.isAutoStart() ) - { - this.startJob(); - return; - } - } - else - { - this.setSimulation( true ); - } - - try - { - final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate( (byte) 0 ); - final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 ); - final PacketMEInventoryUpdate c = this.result.isSimulation() ? new PacketMEInventoryUpdate( (byte) 2 ) : null; - - final IItemList plan = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - this.result.populatePlan( plan ); - - this.setUsedBytes( this.result.getByteTotal() ); - - for( final IAEItemStack out : plan ) - { - - IAEItemStack o = out.copy(); - o.reset(); - o.setStackSize( out.getStackSize() ); - - final IAEItemStack p = out.copy(); - p.reset(); - p.setStackSize( out.getCountRequestable() ); - - final IStorageGrid sg = this.getGrid().getCache( IStorageGrid.class ); - final IMEInventory items = sg.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - - IAEItemStack m = null; - if( c != null && this.result.isSimulation() ) - { - m = o.copy(); - o = items.extractItems( o, Actionable.SIMULATE, this.getActionSource() ); - - if( o == null ) - { - o = m.copy(); - o.setStackSize( 0 ); - } - - m.setStackSize( m.getStackSize() - o.getStackSize() ); - } - - if( o.getStackSize() > 0 ) - { - a.appendItem( o ); - } - - if( p.getStackSize() > 0 ) - { - b.appendItem( p ); - } - - if( c != null && m != null && m.getStackSize() > 0 ) - { - c.appendItem( m ); - } - } - - for( final Object g : this.listeners ) - { - if( g instanceof EntityPlayer ) - { - NetworkHandler.instance().sendTo( a, (EntityPlayerMP) g ); - NetworkHandler.instance().sendTo( b, (EntityPlayerMP) g ); - if( c != null ) - { - NetworkHandler.instance().sendTo( c, (EntityPlayerMP) g ); - } - } - } - } - catch( final IOException e ) - { - // :P - } - } - catch( final Throwable e ) - { - this.getPlayerInv().player.sendMessage( new TextComponentString( "Error: " + e.toString() ) ); - AELog.debug( e ); - this.setValidContainer( false ); - this.result = null; - } - - this.setJob( null ); - } - this.verifyPermissions( SecurityPermissions.CRAFT, false ); - } - - private IGrid getGrid() - { - final IActionHost h = ( (IActionHost) this.getTarget() ); - return h.getActionableNode().getGrid(); - } - - private boolean cpuMatches( final ICraftingCPU c ) - { - return c.getAvailableStorage() >= this.getUsedBytes() && !c.isBusy(); - } - - private void sendCPUs() - { - Collections.sort( this.cpus ); - - if( this.getSelectedCpu() >= this.cpus.size() ) - { - this.setSelectedCpu( -1 ); - this.setCpuAvailableBytes( 0 ); - this.setCpuCoProcessors( 0 ); - this.setName( "" ); - } - else if( this.getSelectedCpu() != -1 ) - { - this.setName( this.cpus.get( this.getSelectedCpu() ).getName() ); - this.setCpuAvailableBytes( this.cpus.get( this.getSelectedCpu() ).getSize() ); - this.setCpuCoProcessors( this.cpus.get( this.getSelectedCpu() ).getProcessors() ); - } - } - - public void startJob() - { - GuiBridge originalGui = null; - - final IActionHost ah = this.getActionHost(); - if( ah instanceof WirelessTerminalGuiObject ) - { - originalGui = GuiBridge.GUI_WIRELESS_TERM; - } - - if( ah instanceof PartTerminal ) - { - originalGui = GuiBridge.GUI_ME; - } - - if( ah instanceof PartCraftingTerminal ) - { - originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; - } - - if( ah instanceof PartPatternTerminal ) - { - originalGui = GuiBridge.GUI_PATTERN_TERMINAL; - } - - if( ah instanceof PartExpandedProcessingPatternTerminal ) - { - originalGui = GuiBridge.GUI_EXPANDED_PROCESSING_PATTERN_TERMINAL; - } - - if( this.result != null && !this.isSimulation() ) - { - final ICraftingGrid cc = this.getGrid().getCache( ICraftingGrid.class ); - final ICraftingLink g = cc.submitJob( this.result, null, this.getSelectedCpu() == -1 ? null : this.cpus.get( this.getSelectedCpu() ).getCpu(), true, this.getActionSrc() ); - this.setAutoStart( false ); - if( g != null && originalGui != null && this.getOpenContext() != null ) - { - final TileEntity te = this.getOpenContext().getTile(); - Platform.openGUI( this.getInventoryPlayer().player, te, this.getOpenContext().getSide(), originalGui ); - } - } - } - - private IActionSource getActionSrc() - { - return new PlayerSource( this.getPlayerInv().player, (IActionHost) this.getTarget() ); - } - - @Override - public void removeListener( final IContainerListener c ) - { - super.removeListener( c ); - if( this.getJob() != null ) - { - this.getJob().cancel( true ); - this.setJob( null ); - } - } - - @Override - public void onContainerClosed( final EntityPlayer par1EntityPlayer ) - { - super.onContainerClosed( par1EntityPlayer ); - if( this.getJob() != null ) - { - this.getJob().cancel( true ); - this.setJob( null ); - } - } - - public World getWorld() - { - return this.getPlayerInv().player.world; - } - - public boolean isAutoStart() - { - return this.autoStart; - } - - public void setAutoStart( final boolean autoStart ) - { - this.autoStart = autoStart; - } - - public long getUsedBytes() - { - return this.bytesUsed; - } - - private void setUsedBytes( final long bytesUsed ) - { - this.bytesUsed = bytesUsed; - } - - public long getCpuAvailableBytes() - { - return this.cpuBytesAvail; - } - - private void setCpuAvailableBytes( final long cpuBytesAvail ) - { - this.cpuBytesAvail = cpuBytesAvail; - } - - public int getCpuCoProcessors() - { - return this.cpuCoProcessors; - } - - private void setCpuCoProcessors( final int cpuCoProcessors ) - { - this.cpuCoProcessors = cpuCoProcessors; - } - - public int getSelectedCpu() - { - return this.selectedCpu; - } - - private void setSelectedCpu( final int selectedCpu ) - { - this.selectedCpu = selectedCpu; - } - - public String getName() - { - return this.myName; - } - - private void setName( @Nonnull final String myName ) - { - this.myName = myName; - } - - public boolean hasNoCPU() - { - return this.noCPU; - } - - private void setNoCPU( final boolean noCPU ) - { - this.noCPU = noCPU; - } - - public boolean isSimulation() - { - return this.simulation; - } - - private void setSimulation( final boolean simulation ) - { - this.simulation = simulation; - } - - private Future getJob() - { - return this.job; - } - - public void setJob( final Future job ) - { - this.job = job; - } +import com.google.common.collect.ImmutableSet; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IContainerListener; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.world.World; + +import javax.annotation.Nonnull; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.concurrent.Future; + + +public class ContainerCraftConfirm extends AEBaseContainer { + + private final ArrayList cpus = new ArrayList<>(); + private Future job; + private ICraftingJob result; + @GuiSync(0) + public long bytesUsed; + @GuiSync(1) + public long cpuBytesAvail; + @GuiSync(2) + public int cpuCoProcessors; + @GuiSync(3) + public boolean autoStart = false; + @GuiSync(4) + public boolean simulation = true; + @GuiSync(5) + public int selectedCpu = -1; + @GuiSync(6) + public boolean noCPU = true; + @GuiSync(7) + public String myName = ""; + + public ContainerCraftConfirm(final InventoryPlayer ip, final ITerminalHost te) { + super(ip, te); + } + + public void cycleCpu(final boolean next) { + if (next) { + this.setSelectedCpu(this.getSelectedCpu() + 1); + } else { + this.setSelectedCpu(this.getSelectedCpu() - 1); + } + + if (this.getSelectedCpu() < -1) { + this.setSelectedCpu(this.cpus.size() - 1); + } else if (this.getSelectedCpu() >= this.cpus.size()) { + this.setSelectedCpu(-1); + } + + if (this.getSelectedCpu() == -1) { + this.setCpuAvailableBytes(0); + this.setCpuCoProcessors(0); + this.setName(""); + } else { + this.setName(this.cpus.get(this.getSelectedCpu()).getName()); + this.setCpuAvailableBytes(this.cpus.get(this.getSelectedCpu()).getSize()); + this.setCpuCoProcessors(this.cpus.get(this.getSelectedCpu()).getProcessors()); + } + } + + @Override + public void detectAndSendChanges() { + if (Platform.isClient()) { + return; + } + + final ICraftingGrid cc = this.getGrid().getCache(ICraftingGrid.class); + final ImmutableSet cpuSet = cc.getCpus(); + + int matches = 0; + boolean changed = false; + for (final ICraftingCPU c : cpuSet) { + boolean found = false; + for (final CraftingCPURecord ccr : this.cpus) { + if (ccr.getCpu() == c) { + found = true; + break; + } + } + + final boolean matched = this.cpuMatches(c); + + if (matched) { + matches++; + } + + if (found == !matched) { + changed = true; + } + } + + if (changed || this.cpus.size() != matches) { + this.cpus.clear(); + for (final ICraftingCPU c : cpuSet) { + if (this.cpuMatches(c)) { + this.cpus.add(new CraftingCPURecord(c.getAvailableStorage(), c.getCoProcessors(), c)); + } + } + + this.sendCPUs(); + } + + this.setNoCPU(this.cpus.isEmpty()); + + super.detectAndSendChanges(); + + if (this.getJob() != null && this.getJob().isDone()) { + try { + this.result = this.getJob().get(); + + if (!this.result.isSimulation()) { + this.setSimulation(false); + if (this.isAutoStart()) { + this.startJob(); + return; + } + } else { + this.setSimulation(true); + } + + try { + final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate((byte) 0); + final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate((byte) 1); + final PacketMEInventoryUpdate c = this.result.isSimulation() ? new PacketMEInventoryUpdate((byte) 2) : null; + + final IItemList plan = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + this.result.populatePlan(plan); + + this.setUsedBytes(this.result.getByteTotal()); + + for (final IAEItemStack out : plan) { + + IAEItemStack o = out.copy(); + o.reset(); + o.setStackSize(out.getStackSize()); + + final IAEItemStack p = out.copy(); + p.reset(); + p.setStackSize(out.getCountRequestable()); + + final IStorageGrid sg = this.getGrid().getCache(IStorageGrid.class); + final IMEInventory items = sg.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + + IAEItemStack m = null; + if (c != null && this.result.isSimulation()) { + m = o.copy(); + o = items.extractItems(o, Actionable.SIMULATE, this.getActionSource()); + + if (o == null) { + o = m.copy(); + o.setStackSize(0); + } + + m.setStackSize(m.getStackSize() - o.getStackSize()); + } + + if (o.getStackSize() > 0) { + a.appendItem(o); + } + + if (p.getStackSize() > 0) { + b.appendItem(p); + } + + if (c != null && m != null && m.getStackSize() > 0) { + c.appendItem(m); + } + } + + for (final Object g : this.listeners) { + if (g instanceof EntityPlayer) { + NetworkHandler.instance().sendTo(a, (EntityPlayerMP) g); + NetworkHandler.instance().sendTo(b, (EntityPlayerMP) g); + if (c != null) { + NetworkHandler.instance().sendTo(c, (EntityPlayerMP) g); + } + } + } + } catch (final IOException e) { + // :P + } + } catch (final Throwable e) { + this.getPlayerInv().player.sendMessage(new TextComponentString("Error: " + e)); + AELog.debug(e); + this.setValidContainer(false); + this.result = null; + } + + this.setJob(null); + } + this.verifyPermissions(SecurityPermissions.CRAFT, false); + } + + private IGrid getGrid() { + final IActionHost h = ((IActionHost) this.getTarget()); + return h.getActionableNode().getGrid(); + } + + private boolean cpuMatches(final ICraftingCPU c) { + return c.getAvailableStorage() >= this.getUsedBytes() && !c.isBusy(); + } + + private void sendCPUs() { + Collections.sort(this.cpus); + + if (this.getSelectedCpu() >= this.cpus.size()) { + this.setSelectedCpu(-1); + this.setCpuAvailableBytes(0); + this.setCpuCoProcessors(0); + this.setName(""); + } else if (this.getSelectedCpu() != -1) { + this.setName(this.cpus.get(this.getSelectedCpu()).getName()); + this.setCpuAvailableBytes(this.cpus.get(this.getSelectedCpu()).getSize()); + this.setCpuCoProcessors(this.cpus.get(this.getSelectedCpu()).getProcessors()); + } + } + + public void startJob() { + GuiBridge originalGui = null; + + final IActionHost ah = this.getActionHost(); + if (ah instanceof WirelessTerminalGuiObject) { + originalGui = GuiBridge.GUI_WIRELESS_TERM; + } + + if (ah instanceof PartTerminal) { + originalGui = GuiBridge.GUI_ME; + } + + if (ah instanceof PartCraftingTerminal) { + originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; + } + + if (ah instanceof PartPatternTerminal) { + originalGui = GuiBridge.GUI_PATTERN_TERMINAL; + } + + if (ah instanceof PartExpandedProcessingPatternTerminal) { + originalGui = GuiBridge.GUI_EXPANDED_PROCESSING_PATTERN_TERMINAL; + } + + if (this.result != null && !this.isSimulation()) { + final ICraftingGrid cc = this.getGrid().getCache(ICraftingGrid.class); + final ICraftingLink g = cc.submitJob(this.result, null, this.getSelectedCpu() == -1 ? null : this.cpus.get(this.getSelectedCpu()).getCpu(), true, this.getActionSrc()); + this.setAutoStart(false); + if (g != null && originalGui != null && this.getOpenContext() != null) { + final TileEntity te = this.getOpenContext().getTile(); + Platform.openGUI(this.getInventoryPlayer().player, te, this.getOpenContext().getSide(), originalGui); + } + } + } + + private IActionSource getActionSrc() { + return new PlayerSource(this.getPlayerInv().player, (IActionHost) this.getTarget()); + } + + @Override + public void removeListener(final IContainerListener c) { + super.removeListener(c); + if (this.getJob() != null) { + this.getJob().cancel(true); + this.setJob(null); + } + } + + @Override + public void onContainerClosed(final EntityPlayer par1EntityPlayer) { + super.onContainerClosed(par1EntityPlayer); + if (this.getJob() != null) { + this.getJob().cancel(true); + this.setJob(null); + } + } + + public World getWorld() { + return this.getPlayerInv().player.world; + } + + public boolean isAutoStart() { + return this.autoStart; + } + + public void setAutoStart(final boolean autoStart) { + this.autoStart = autoStart; + } + + public long getUsedBytes() { + return this.bytesUsed; + } + + private void setUsedBytes(final long bytesUsed) { + this.bytesUsed = bytesUsed; + } + + public long getCpuAvailableBytes() { + return this.cpuBytesAvail; + } + + private void setCpuAvailableBytes(final long cpuBytesAvail) { + this.cpuBytesAvail = cpuBytesAvail; + } + + public int getCpuCoProcessors() { + return this.cpuCoProcessors; + } + + private void setCpuCoProcessors(final int cpuCoProcessors) { + this.cpuCoProcessors = cpuCoProcessors; + } + + public int getSelectedCpu() { + return this.selectedCpu; + } + + private void setSelectedCpu(final int selectedCpu) { + this.selectedCpu = selectedCpu; + } + + public String getName() { + return this.myName; + } + + private void setName(@Nonnull final String myName) { + this.myName = myName; + } + + public boolean hasNoCPU() { + return this.noCPU; + } + + private void setNoCPU(final boolean noCPU) { + this.noCPU = noCPU; + } + + public boolean isSimulation() { + return this.simulation; + } + + private void setSimulation(final boolean simulation) { + this.simulation = simulation; + } + + private Future getJob() { + return this.job; + } + + public void setJob(final Future job) { + this.job = job; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java b/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java index 230aeeca7..4954d7428 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java @@ -19,13 +19,6 @@ package appeng.container.implementations; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IContainerListener; - import appeng.api.AEApi; import appeng.api.networking.IGrid; import appeng.api.networking.crafting.CraftingItemList; @@ -48,236 +41,195 @@ import appeng.me.cluster.IAEMultiBlock; import appeng.me.cluster.implementations.CraftingCPUCluster; import appeng.tile.crafting.TileCraftingTile; import appeng.util.Platform; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IContainerListener; + +import java.io.IOException; -public class ContainerCraftingCPU extends AEBaseContainer implements IMEMonitorHandlerReceiver, ICustomNameObject -{ +public class ContainerCraftingCPU extends AEBaseContainer implements IMEMonitorHandlerReceiver, ICustomNameObject { - private final IItemList list = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - private IGrid network; - private CraftingCPUCluster monitor = null; - private String cpuName = null; + private final IItemList list = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + private IGrid network; + private CraftingCPUCluster monitor = null; + private String cpuName = null; - @GuiSync( 0 ) - public long eta = -1; + @GuiSync(0) + public long eta = -1; - public ContainerCraftingCPU( final InventoryPlayer ip, final Object te ) - { - super( ip, te ); - final IActionHost host = (IActionHost) ( te instanceof IActionHost ? te : null ); + public ContainerCraftingCPU(final InventoryPlayer ip, final Object te) { + super(ip, te); + final IActionHost host = (IActionHost) (te instanceof IActionHost ? te : null); - if( host != null && host.getActionableNode() != null ) - { - this.setNetwork( host.getActionableNode().getGrid() ); - } + if (host != null && host.getActionableNode() != null) { + this.setNetwork(host.getActionableNode().getGrid()); + } - if( te instanceof TileCraftingTile ) - { - this.setCPU( (ICraftingCPU) ( (IAEMultiBlock) te ).getCluster() ); - } + if (te instanceof TileCraftingTile) { + this.setCPU((ICraftingCPU) ((IAEMultiBlock) te).getCluster()); + } - if( this.getNetwork() == null && Platform.isServer() ) - { - this.setValidContainer( false ); - } - } + if (this.getNetwork() == null && Platform.isServer()) { + this.setValidContainer(false); + } + } - protected void setCPU( final ICraftingCPU c ) - { - if( c == this.getMonitor() ) - { - return; - } + protected void setCPU(final ICraftingCPU c) { + if (c == this.getMonitor()) { + return; + } - if( this.getMonitor() != null ) - { - this.getMonitor().removeListener( this ); - } + if (this.getMonitor() != null) { + this.getMonitor().removeListener(this); + } - for( final Object g : this.listeners ) - { - if( g instanceof EntityPlayer ) - { - try - { - NetworkHandler.instance().sendTo( new PacketValueConfig( "CraftingStatus", "Clear" ), (EntityPlayerMP) g ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } + for (final Object g : this.listeners) { + if (g instanceof EntityPlayer) { + try { + NetworkHandler.instance().sendTo(new PacketValueConfig("CraftingStatus", "Clear"), (EntityPlayerMP) g); + } catch (final IOException e) { + AELog.debug(e); + } + } + } - if( c instanceof CraftingCPUCluster ) - { - this.cpuName = c.getName(); - this.setMonitor( (CraftingCPUCluster) c ); - this.list.resetStatus(); - this.getMonitor().getListOfItem( this.list, CraftingItemList.ALL ); - this.getMonitor().addListener( this, null ); - this.setEstimatedTime( 0 ); - } - else - { - this.setMonitor( null ); - this.cpuName = ""; - this.setEstimatedTime( -1 ); - } - } + if (c instanceof CraftingCPUCluster) { + this.cpuName = c.getName(); + this.setMonitor((CraftingCPUCluster) c); + this.list.resetStatus(); + this.getMonitor().getListOfItem(this.list, CraftingItemList.ALL); + this.getMonitor().addListener(this, null); + this.setEstimatedTime(0); + } else { + this.setMonitor(null); + this.cpuName = ""; + this.setEstimatedTime(-1); + } + } - public void cancelCrafting() - { - if( this.getMonitor() != null ) - { - this.getMonitor().cancel(); - } - this.setEstimatedTime( -1 ); - } + public void cancelCrafting() { + if (this.getMonitor() != null) { + this.getMonitor().cancel(); + } + this.setEstimatedTime(-1); + } - @Override - public void removeListener( final IContainerListener c ) - { - super.removeListener( c ); + @Override + public void removeListener(final IContainerListener c) { + super.removeListener(c); - if( this.listeners.isEmpty() && this.getMonitor() != null ) - { - this.getMonitor().removeListener( this ); - } - } + if (this.listeners.isEmpty() && this.getMonitor() != null) { + this.getMonitor().removeListener(this); + } + } - @Override - public void onContainerClosed( final EntityPlayer player ) - { - super.onContainerClosed( player ); - if( this.getMonitor() != null ) - { - this.getMonitor().removeListener( this ); - } - } + @Override + public void onContainerClosed(final EntityPlayer player) { + super.onContainerClosed(player); + if (this.getMonitor() != null) { + this.getMonitor().removeListener(this); + } + } - @Override - public void detectAndSendChanges() - { - if( Platform.isServer() && this.getMonitor() != null ) - { - if( this.getEstimatedTime() >= 0 ) - { - final long elapsedTime = this.getMonitor().getElapsedTime(); - final double remainingItems = this.getMonitor().getRemainingItemCount(); - final double startItems = this.getMonitor().getStartItemCount(); - final long eta = (long) ( elapsedTime / Math.max( 1d, ( startItems - remainingItems ) ) * remainingItems ); - this.setEstimatedTime( eta ); - } - if( !this.list.isEmpty() ) - { - try - { - final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate( (byte) 0 ); - final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 ); - final PacketMEInventoryUpdate c = new PacketMEInventoryUpdate( (byte) 2 ); + @Override + public void detectAndSendChanges() { + if (Platform.isServer() && this.getMonitor() != null) { + if (this.getEstimatedTime() >= 0) { + final long elapsedTime = this.getMonitor().getElapsedTime(); + final double remainingItems = this.getMonitor().getRemainingItemCount(); + final double startItems = this.getMonitor().getStartItemCount(); + final long eta = (long) (elapsedTime / Math.max(1d, (startItems - remainingItems)) * remainingItems); + this.setEstimatedTime(eta); + } + if (!this.list.isEmpty()) { + try { + final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate((byte) 0); + final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate((byte) 1); + final PacketMEInventoryUpdate c = new PacketMEInventoryUpdate((byte) 2); - for( final IAEItemStack out : this.list ) - { - a.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.STORAGE ) ); - b.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.ACTIVE ) ); - c.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.PENDING ) ); - } + for (final IAEItemStack out : this.list) { + a.appendItem(this.getMonitor().getItemStack(out, CraftingItemList.STORAGE)); + b.appendItem(this.getMonitor().getItemStack(out, CraftingItemList.ACTIVE)); + c.appendItem(this.getMonitor().getItemStack(out, CraftingItemList.PENDING)); + } - this.list.resetStatus(); + this.list.resetStatus(); - for( final Object g : this.listeners ) - { - if( g instanceof EntityPlayer ) - { - if( !a.isEmpty() ) - { - NetworkHandler.instance().sendTo( a, (EntityPlayerMP) g ); - } + for (final Object g : this.listeners) { + if (g instanceof EntityPlayer) { + if (!a.isEmpty()) { + NetworkHandler.instance().sendTo(a, (EntityPlayerMP) g); + } - if( !b.isEmpty() ) - { - NetworkHandler.instance().sendTo( b, (EntityPlayerMP) g ); - } + if (!b.isEmpty()) { + NetworkHandler.instance().sendTo(b, (EntityPlayerMP) g); + } - if( !c.isEmpty() ) - { - NetworkHandler.instance().sendTo( c, (EntityPlayerMP) g ); - } - } - } - } - catch( final IOException e ) - { - // :P - } - } - } - super.detectAndSendChanges(); - } + if (!c.isEmpty()) { + NetworkHandler.instance().sendTo(c, (EntityPlayerMP) g); + } + } + } + } catch (final IOException e) { + // :P + } + } + } + super.detectAndSendChanges(); + } - @Override - public boolean isValid( final Object verificationToken ) - { - return true; - } + @Override + public boolean isValid(final Object verificationToken) { + return true; + } - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final IActionSource actionSource ) - { - for( IAEItemStack is : change ) - { - is = is.copy(); - is.setStackSize( 1 ); - this.list.add( is ); - } - } + @Override + public void postChange(final IBaseMonitor monitor, final Iterable change, final IActionSource actionSource) { + for (IAEItemStack is : change) { + is = is.copy(); + is.setStackSize(1); + this.list.add(is); + } + } - @Override - public void onListUpdate() - { + @Override + public void onListUpdate() { - } + } - @Override - public String getCustomInventoryName() - { - return this.cpuName; - } + @Override + public String getCustomInventoryName() { + return this.cpuName; + } - @Override - public boolean hasCustomInventoryName() - { - return this.cpuName != null && this.cpuName.length() > 0; - } + @Override + public boolean hasCustomInventoryName() { + return this.cpuName != null && this.cpuName.length() > 0; + } - public long getEstimatedTime() - { - return this.eta; - } + public long getEstimatedTime() { + return this.eta; + } - private void setEstimatedTime( final long eta ) - { - this.eta = eta; - } + private void setEstimatedTime(final long eta) { + this.eta = eta; + } - CraftingCPUCluster getMonitor() - { - return this.monitor; - } + CraftingCPUCluster getMonitor() { + return this.monitor; + } - private void setMonitor( final CraftingCPUCluster monitor ) - { - this.monitor = monitor; - } + private void setMonitor(final CraftingCPUCluster monitor) { + this.monitor = monitor; + } - IGrid getNetwork() - { - return this.network; - } + IGrid getNetwork() { + return this.network; + } - private void setNetwork( final IGrid network ) - { - this.network = network; - } + private void setNetwork(final IGrid network) { + this.network = network; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java b/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java index f3b3d0a85..a49d111ab 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java @@ -19,49 +19,43 @@ package appeng.container.implementations; -import java.io.IOException; -import java.util.*; - import appeng.api.networking.IGrid; -import appeng.core.AELog; -import appeng.core.sync.network.NetworkHandler; -import appeng.core.sync.packets.PacketCraftingCPUsUpdate; -import com.google.common.collect.ImmutableSet; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.networking.crafting.ICraftingCPU; import appeng.api.networking.crafting.ICraftingGrid; import appeng.api.storage.ITerminalHost; import appeng.container.guisync.GuiSync; +import appeng.core.AELog; +import appeng.core.sync.network.NetworkHandler; +import appeng.core.sync.packets.PacketCraftingCPUsUpdate; import appeng.util.Platform; +import com.google.common.collect.ImmutableSet; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; + +import java.io.IOException; +import java.util.*; -public class ContainerCraftingStatus extends ContainerCraftingCPU -{ +public class ContainerCraftingStatus extends ContainerCraftingCPU { - private ImmutableSet lastCpuSet = null; - private List cpus = new ArrayList(); - private final WeakHashMap cpuSerialMap = new WeakHashMap<>(); - private int nextCpuSerial = 1; - private int lastUpdate = 0; - @GuiSync(5) - public int selectedCpuSerial = -1; + private ImmutableSet lastCpuSet = null; + private List cpus = new ArrayList(); + private final WeakHashMap cpuSerialMap = new WeakHashMap<>(); + private int nextCpuSerial = 1; + private int lastUpdate = 0; + @GuiSync(5) + public int selectedCpuSerial = -1; - public ContainerCraftingStatus( final InventoryPlayer ip, final ITerminalHost te ) - { - super( ip, te ); - } + public ContainerCraftingStatus(final InventoryPlayer ip, final ITerminalHost te) { + super(ip, te); + } - @Override - public void detectAndSendChanges() - { - IGrid network = this.getNetwork(); - if( Platform.isServer() && network != null ) - { - final ICraftingGrid cc = network.getCache( ICraftingGrid.class ); - final ImmutableSet cpuSet = cc.getCpus(); + @Override + public void detectAndSendChanges() { + IGrid network = this.getNetwork(); + if (Platform.isServer() && network != null) { + final ICraftingGrid cc = network.getCache(ICraftingGrid.class); + final ImmutableSet cpuSet = cc.getCpus(); /*int matches = 0; boolean changed = false; @@ -105,131 +99,111 @@ public class ContainerCraftingStatus extends ContainerCraftingCPU this.noCPU = this.cpus.isEmpty(); */ - // Update at least once a second - ++lastUpdate; - if (!cpuSet.equals( lastCpuSet ) || lastUpdate > 20) { - lastUpdate = 0; - lastCpuSet = cpuSet; - updateCpuList(); - sendCPUs(); - } - } + // Update at least once a second + ++lastUpdate; + if (!cpuSet.equals(lastCpuSet) || lastUpdate > 20) { + lastUpdate = 0; + lastCpuSet = cpuSet; + updateCpuList(); + sendCPUs(); + } + } - // Clear selection if CPU is no longer in list - if (selectedCpuSerial != -1) { - if (cpus.stream().noneMatch(c -> c.getSerial() == selectedCpuSerial)) { - selectCPU(-1); - } - } + // Clear selection if CPU is no longer in list + if (selectedCpuSerial != -1) { + if (cpus.stream().noneMatch(c -> c.getSerial() == selectedCpuSerial)) { + selectCPU(-1); + } + } - // Select a suitable CPU if none is selected - if (selectedCpuSerial == -1) { - // Try busy CPUs first - for (CraftingCPUStatus cpu : cpus) { - if (cpu.getRemainingItems() > 0) { - selectCPU(cpu.getSerial()); - break; - } - } - // If we couldn't find a busy one, just select the first - if (selectedCpuSerial == -1 && !cpus.isEmpty()) { - selectCPU(cpus.get(0).getSerial()); - } - } + // Select a suitable CPU if none is selected + if (selectedCpuSerial == -1) { + // Try busy CPUs first + for (CraftingCPUStatus cpu : cpus) { + if (cpu.getRemainingItems() > 0) { + selectCPU(cpu.getSerial()); + break; + } + } + // If we couldn't find a busy one, just select the first + if (selectedCpuSerial == -1 && !cpus.isEmpty()) { + selectCPU(cpus.get(0).getSerial()); + } + } - super.detectAndSendChanges(); - } + super.detectAndSendChanges(); + } - private static final Comparator CPU_COMPARATOR = Comparator - .comparing((CraftingCPUStatus e) -> e.getName() == null || e.getName().isEmpty()) - .thenComparing(e -> e.getName() != null ? e.getName() : "") - .thenComparingInt(CraftingCPUStatus::getSerial); + private static final Comparator CPU_COMPARATOR = Comparator + .comparing((CraftingCPUStatus e) -> e.getName() == null || e.getName().isEmpty()) + .thenComparing(e -> e.getName() != null ? e.getName() : "") + .thenComparingInt(CraftingCPUStatus::getSerial); - private void updateCpuList() - { - this.cpus.clear(); - for (ICraftingCPU cpu : lastCpuSet) - { - int serial = getOrAssignCpuSerial(cpu); - this.cpus.add( new CraftingCPUStatus( cpu, serial ) ); - } - this.cpus.sort(CPU_COMPARATOR); - } + private void updateCpuList() { + this.cpus.clear(); + for (ICraftingCPU cpu : lastCpuSet) { + int serial = getOrAssignCpuSerial(cpu); + this.cpus.add(new CraftingCPUStatus(cpu, serial)); + } + this.cpus.sort(CPU_COMPARATOR); + } - private int getOrAssignCpuSerial( ICraftingCPU cpu ) - { - return cpuSerialMap.computeIfAbsent( cpu, unused -> nextCpuSerial++ ); - } + private int getOrAssignCpuSerial(ICraftingCPU cpu) { + return cpuSerialMap.computeIfAbsent(cpu, unused -> nextCpuSerial++); + } - private boolean cpuMatches( final ICraftingCPU c ) - { - return c.isBusy(); - } + private boolean cpuMatches(final ICraftingCPU c) { + return c.isBusy(); + } - private void sendCPUs() - { - final PacketCraftingCPUsUpdate update; - for( final Object player : this.listeners ) - { - if( player instanceof EntityPlayerMP) - { - try - { - NetworkHandler.instance.sendTo( new PacketCraftingCPUsUpdate( this.cpus ), (EntityPlayerMP) player ); - } - catch( IOException e ) - { - AELog.debug( e ); - } - } - } - } + private void sendCPUs() { + final PacketCraftingCPUsUpdate update; + for (final Object player : this.listeners) { + if (player instanceof EntityPlayerMP) { + try { + NetworkHandler.instance.sendTo(new PacketCraftingCPUsUpdate(this.cpus), (EntityPlayerMP) player); + } catch (IOException e) { + AELog.debug(e); + } + } + } + } - public void selectCPU( int serial ) - { - if (Platform.isServer()) - { - if( serial < -1 ) - { - serial = -1; - } + public void selectCPU(int serial) { + if (Platform.isServer()) { + if (serial < -1) { + serial = -1; + } - final int searchedSerial = serial; - if( serial > -1 && cpus.stream().noneMatch(c -> c.getSerial() == searchedSerial) ) - { - serial = -1; - } + final int searchedSerial = serial; + if (serial > -1 && cpus.stream().noneMatch(c -> c.getSerial() == searchedSerial)) { + serial = -1; + } - ICraftingCPU newSelectedCpu = null; - if( serial != -1 ) - { - for( ICraftingCPU cpu : lastCpuSet ) - { - if( cpuSerialMap.getOrDefault( cpu, -1 ) == serial ) - { - newSelectedCpu = cpu; - break; - } - } - } + ICraftingCPU newSelectedCpu = null; + if (serial != -1) { + for (ICraftingCPU cpu : lastCpuSet) { + if (cpuSerialMap.getOrDefault(cpu, -1) == serial) { + newSelectedCpu = cpu; + break; + } + } + } - if( newSelectedCpu != getMonitor() ) - { - this.selectedCpuSerial = serial; - setCPU( newSelectedCpu ); - } - } - } + if (newSelectedCpu != getMonitor()) { + this.selectedCpuSerial = serial; + setCPU(newSelectedCpu); + } + } + } - public List getCPUs() - { - return Collections.unmodifiableList( cpus ); - } + public List getCPUs() { + return Collections.unmodifiableList(cpus); + } - public void postCPUUpdate( CraftingCPUStatus[] cpus ) - { - this.cpus = Arrays.asList( cpus ); - } + public void postCPUUpdate(CraftingCPUStatus[] cpus) { + this.cpus = Arrays.asList(cpus); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java b/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java index 850aa9c1c..b55bbbba3 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java @@ -19,15 +19,6 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.CraftingManager; -import net.minecraft.item.crafting.IRecipe; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.wrapper.PlayerInvWrapper; - import appeng.api.storage.ITerminalHost; import appeng.container.ContainerNull; import appeng.container.slot.SlotCraftingMatrix; @@ -38,102 +29,94 @@ import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.inv.IAEAppEngInventory; import appeng.util.inv.InvOperation; import appeng.util.inv.WrapperInvItemHandler; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.item.crafting.IRecipe; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.wrapper.PlayerInvWrapper; -public class ContainerCraftingTerm extends ContainerMEMonitorable implements IAEAppEngInventory, IContainerCraftingPacket -{ +public class ContainerCraftingTerm extends ContainerMEMonitorable implements IAEAppEngInventory, IContainerCraftingPacket { - private final PartCraftingTerminal ct; - private final AppEngInternalInventory output = new AppEngInternalInventory( this, 1 ); - private final SlotCraftingMatrix[] craftingSlots = new SlotCraftingMatrix[9]; - private final SlotCraftingTerm outputSlot; - private IRecipe currentRecipe; + private final PartCraftingTerminal ct; + private final AppEngInternalInventory output = new AppEngInternalInventory(this, 1); + private final SlotCraftingMatrix[] craftingSlots = new SlotCraftingMatrix[9]; + private final SlotCraftingTerm outputSlot; + private IRecipe currentRecipe; - public ContainerCraftingTerm( final InventoryPlayer ip, final ITerminalHost monitorable ) - { - super( ip, monitorable, false ); - this.ct = (PartCraftingTerminal) monitorable; + public ContainerCraftingTerm(final InventoryPlayer ip, final ITerminalHost monitorable) { + super(ip, monitorable, false); + this.ct = (PartCraftingTerminal) monitorable; - final IItemHandler crafting = this.ct.getInventoryByName( "crafting" ); + final IItemHandler crafting = this.ct.getInventoryByName("crafting"); - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 3; x++ ) - { - this.addSlotToContainer( this.craftingSlots[x + y * 3] = new SlotCraftingMatrix( this, crafting, x + y * 3, 37 + x * 18, -72 + y * 18 ) ); - } - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + this.addSlotToContainer(this.craftingSlots[x + y * 3] = new SlotCraftingMatrix(this, crafting, x + y * 3, 37 + x * 18, -72 + y * 18)); + } + } - this.addSlotToContainer( this.outputSlot = new SlotCraftingTerm( this.getPlayerInv().player, this.getActionSource(), this - .getPowerSource(), monitorable, crafting, crafting, this.output, 131, -72 + 18, this ) ); + this.addSlotToContainer(this.outputSlot = new SlotCraftingTerm(this.getPlayerInv().player, this.getActionSource(), this + .getPowerSource(), monitorable, crafting, crafting, this.output, 131, -72 + 18, this)); - this.bindPlayerInventory( ip, 0, 0 ); + this.bindPlayerInventory(ip, 0, 0); - this.onCraftMatrixChanged( new WrapperInvItemHandler( crafting ) ); - } + this.onCraftMatrixChanged(new WrapperInvItemHandler(crafting)); + } - /** - * Callback for when the crafting matrix is changed. - */ + /** + * Callback for when the crafting matrix is changed. + */ - @Override - public void onCraftMatrixChanged( IInventory inventory ) - { - final ContainerNull cn = new ContainerNull(); - final InventoryCrafting ic = new InventoryCrafting( cn, 3, 3 ); + @Override + public void onCraftMatrixChanged(IInventory inventory) { + final ContainerNull cn = new ContainerNull(); + final InventoryCrafting ic = new InventoryCrafting(cn, 3, 3); - for( int x = 0; x < 9; x++ ) - { - ic.setInventorySlotContents( x, this.craftingSlots[x].getStack() ); - } + for (int x = 0; x < 9; x++) { + ic.setInventorySlotContents(x, this.craftingSlots[x].getStack()); + } - if( this.currentRecipe == null || !this.currentRecipe.matches( ic, this.getPlayerInv().player.world ) ) - { - this.currentRecipe = CraftingManager.findMatchingRecipe( ic, this.getPlayerInv().player.world ); - } + if (this.currentRecipe == null || !this.currentRecipe.matches(ic, this.getPlayerInv().player.world)) { + this.currentRecipe = CraftingManager.findMatchingRecipe(ic, this.getPlayerInv().player.world); + } - if( this.currentRecipe == null ) - { - this.outputSlot.putStack( ItemStack.EMPTY ); - } - else - { - final ItemStack craftingResult = this.currentRecipe.getCraftingResult( ic ); + if (this.currentRecipe == null) { + this.outputSlot.putStack(ItemStack.EMPTY); + } else { + final ItemStack craftingResult = this.currentRecipe.getCraftingResult(ic); - this.outputSlot.putStack( craftingResult ); - } - } + this.outputSlot.putStack(craftingResult); + } + } - @Override - public void saveChanges() - { + @Override + public void saveChanges() { - } + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { - } + } - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "player" ) ) - { - return new PlayerInvWrapper( this.getInventoryPlayer() ); - } - return this.ct.getInventoryByName( name ); - } + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("player")) { + return new PlayerInvWrapper(this.getInventoryPlayer()); + } + return this.ct.getInventoryByName(name); + } - @Override - public boolean useRealItems() - { - return true; - } + @Override + public boolean useRealItems() { + return true; + } - public IRecipe getCurrentRecipe() - { - return this.currentRecipe; - } + public IRecipe getCurrentRecipe() { + return this.currentRecipe; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerDrive.java b/src/main/java/appeng/container/implementations/ContainerDrive.java index d6d77f373..d78dd2fb5 100644 --- a/src/main/java/appeng/container/implementations/ContainerDrive.java +++ b/src/main/java/appeng/container/implementations/ContainerDrive.java @@ -19,29 +19,24 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.storage.TileDrive; +import net.minecraft.entity.player.InventoryPlayer; -public class ContainerDrive extends AEBaseContainer -{ +public class ContainerDrive extends AEBaseContainer { - public ContainerDrive( final InventoryPlayer ip, final TileDrive drive ) - { - super( ip, drive, null ); + public ContainerDrive(final InventoryPlayer ip, final TileDrive drive) { + super(ip, drive, null); - for( int y = 0; y < 5; y++ ) - { - for( int x = 0; x < 2; x++ ) - { - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, drive - .getInternalInventory(), x + y * 2, 71 + x * 18, 14 + y * 18, this.getInventoryPlayer() ) ); - } - } + for (int y = 0; y < 5; y++) { + for (int x = 0; x < 2; x++) { + this.addSlotToContainer(new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, drive + .getInternalInventory(), x + y * 2, 71 + x * 18, 14 + y * 18, this.getInventoryPlayer())); + } + } - this.bindPlayerInventory( ip, 0, 199 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 199 - /* height of player inventory */82); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerExpandedProcessingPatternTerm.java b/src/main/java/appeng/container/implementations/ContainerExpandedProcessingPatternTerm.java index bbcbc27ca..b3f6312b7 100644 --- a/src/main/java/appeng/container/implementations/ContainerExpandedProcessingPatternTerm.java +++ b/src/main/java/appeng/container/implementations/ContainerExpandedProcessingPatternTerm.java @@ -29,525 +29,424 @@ import static appeng.helpers.PatternHelper.PROCESSING_INPUT_LIMIT; import static appeng.helpers.PatternHelper.PROCESSING_OUTPUT_LIMIT; -public class ContainerExpandedProcessingPatternTerm extends ContainerMEMonitorable implements IAEAppEngInventory, IOptionalSlotHost, IContainerCraftingPacket -{ - private final IItemHandler crafting; - private final SlotFakeCraftingMatrix[] gridSlots = new SlotFakeCraftingMatrix[PROCESSING_INPUT_LIMIT]; - private final OptionalSlotFake[] outputSlots = new OptionalSlotFake[PROCESSING_OUTPUT_LIMIT]; - private final SlotRestrictedInput patternSlotIN; - private final SlotRestrictedInput patternSlotOUT; - private final PartExpandedProcessingPatternTerminal expandedProcessingPatternTerminal; +public class ContainerExpandedProcessingPatternTerm extends ContainerMEMonitorable implements IAEAppEngInventory, IOptionalSlotHost, IContainerCraftingPacket { + private final IItemHandler crafting; + private final SlotFakeCraftingMatrix[] gridSlots = new SlotFakeCraftingMatrix[PROCESSING_INPUT_LIMIT]; + private final OptionalSlotFake[] outputSlots = new OptionalSlotFake[PROCESSING_OUTPUT_LIMIT]; + private final SlotRestrictedInput patternSlotIN; + private final SlotRestrictedInput patternSlotOUT; + private final PartExpandedProcessingPatternTerminal expandedProcessingPatternTerminal; - public ContainerExpandedProcessingPatternTerm( InventoryPlayer ip, ITerminalHost monitorable ) - { - super( ip, monitorable, false ); + public ContainerExpandedProcessingPatternTerm(InventoryPlayer ip, ITerminalHost monitorable) { + super(ip, monitorable, false); - this.expandedProcessingPatternTerminal = (PartExpandedProcessingPatternTerminal) monitorable; + this.expandedProcessingPatternTerminal = (PartExpandedProcessingPatternTerminal) monitorable; - final IItemHandler patternInv = this.getExpandedPatternTerminal().getInventoryByName( "pattern" ); - final IItemHandler output = this.getExpandedPatternTerminal().getInventoryByName( "output" ); + final IItemHandler patternInv = this.getExpandedPatternTerminal().getInventoryByName("pattern"); + final IItemHandler output = this.getExpandedPatternTerminal().getInventoryByName("output"); - this.crafting = this.getExpandedPatternTerminal().getInventoryByName( "crafting" ); + this.crafting = this.getExpandedPatternTerminal().getInventoryByName("crafting"); - for( int y = 0; y < 4; y++ ) - { - for( int x = 0; x < 4; x++ ) - { - this.addSlotToContainer( this.gridSlots[x + y * 4] = new SlotFakeCraftingMatrix( this.crafting, x + y * 4, 4 + x * 18, -85 + y * 18 ) ); - } - } + for (int y = 0; y < 4; y++) { + for (int x = 0; x < 4; x++) { + this.addSlotToContainer(this.gridSlots[x + y * 4] = new SlotFakeCraftingMatrix(this.crafting, x + y * 4, 4 + x * 18, -85 + y * 18)); + } + } - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 2; x++ ) - { - this.addSlotToContainer( this.outputSlots[x + y * 2] = new SlotPatternOutputs( output, this, x + y * 2, 96 + x * 18, -76 + y * 18, 0, 0, 1 ) ); - this.outputSlots[x + y * 2].setRenderDisabled( false ); - this.outputSlots[x + y * 2].setIIcon( -1 ); - } - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 2; x++) { + this.addSlotToContainer(this.outputSlots[x + y * 2] = new SlotPatternOutputs(output, this, x + y * 2, 96 + x * 18, -76 + y * 18, 0, 0, 1)); + this.outputSlots[x + y * 2].setRenderDisabled(false); + this.outputSlots[x + y * 2].setIIcon(-1); + } + } - this.addSlotToContainer( this.patternSlotIN = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.BLANK_PATTERN, patternInv, 0, 147, -72 - 9, this.getInventoryPlayer() ) ); - this.addSlotToContainer( this.patternSlotOUT = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, patternInv, 1, 147, -72 + 34, this.getInventoryPlayer() ) ); + this.addSlotToContainer(this.patternSlotIN = new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.BLANK_PATTERN, patternInv, 0, 147, -72 - 9, this.getInventoryPlayer())); + this.addSlotToContainer(this.patternSlotOUT = new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, patternInv, 1, 147, -72 + 34, this.getInventoryPlayer())); - this.patternSlotOUT.setStackLimit( 1 ); + this.patternSlotOUT.setStackLimit(1); - this.bindPlayerInventory( ip, 0, 0 ); - } + this.bindPlayerInventory(ip, 0, 0); + } - @Override - public ItemStack transferStackInSlot( final EntityPlayer p, final int idx ) - { - if( Platform.isClient() ) - { - return ItemStack.EMPTY; - } - if( this.inventorySlots.get( idx ) instanceof SlotPlayerInv || this.inventorySlots.get( idx ) instanceof SlotPlayerHotBar ) - { - final AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get( idx ); // require AE SLots! - ItemStack itemStack = clickSlot.getStack(); - if( AEApi.instance().definitions().materials().blankPattern().isSameAs( itemStack ) ) - { - IItemHandler patternInv = this.getExpandedPatternTerminal().getInventoryByName( "pattern" ); - ItemStack remainder = patternInv.insertItem( 0, itemStack, false ); - clickSlot.putStack( remainder ); - } - } - return super.transferStackInSlot( p, idx ); - } + @Override + public ItemStack transferStackInSlot(final EntityPlayer p, final int idx) { + if (Platform.isClient()) { + return ItemStack.EMPTY; + } + if (this.inventorySlots.get(idx) instanceof SlotPlayerInv || this.inventorySlots.get(idx) instanceof SlotPlayerHotBar) { + final AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get(idx); // require AE SLots! + ItemStack itemStack = clickSlot.getStack(); + if (AEApi.instance().definitions().materials().blankPattern().isSameAs(itemStack)) { + IItemHandler patternInv = this.getExpandedPatternTerminal().getInventoryByName("pattern"); + ItemStack remainder = patternInv.insertItem(0, itemStack, false); + clickSlot.putStack(remainder); + } + } + return super.transferStackInSlot(p, idx); + } - @Override - public void saveChanges() - { + @Override + public void saveChanges() { - } + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { - } + } - public void encodeAndMoveToInventory() - { - encode(); - ItemStack output = this.patternSlotOUT.getStack(); - if( !output.isEmpty() ) - { - if( !getPlayerInv().addItemStackToInventory( output ) ) - { - getPlayerInv().player.dropItem( output, false ); - } - this.patternSlotOUT.putStack( ItemStack.EMPTY ); - } - } + public void encodeAndMoveToInventory() { + encode(); + ItemStack output = this.patternSlotOUT.getStack(); + if (!output.isEmpty()) { + if (!getPlayerInv().addItemStackToInventory(output)) { + getPlayerInv().player.dropItem(output, false); + } + this.patternSlotOUT.putStack(ItemStack.EMPTY); + } + } - public void encode() - { - ItemStack output = this.patternSlotOUT.getStack(); + public void encode() { + ItemStack output = this.patternSlotOUT.getStack(); - final ItemStack[] in = this.getInputs(); - final ItemStack[] out = this.getOutputs(); + final ItemStack[] in = this.getInputs(); + final ItemStack[] out = this.getOutputs(); - // if there is no input, this would be silly. - if( in == null || out == null ) - { - return; - } + // if there is no input, this would be silly. + if (in == null || out == null) { + return; + } - // first check the output slots, should either be null, or a pattern - if( !output.isEmpty() && !this.isPattern( output ) ) - { - return; - } // if nothing is there we should snag a new pattern. - else if( output.isEmpty() ) - { - output = this.patternSlotIN.getStack(); - if( output.isEmpty() || !this.isPattern( output ) ) - { - return; // no blanks. - } + // first check the output slots, should either be null, or a pattern + if (!output.isEmpty() && !this.isPattern(output)) { + return; + } // if nothing is there we should snag a new pattern. + else if (output.isEmpty()) { + output = this.patternSlotIN.getStack(); + if (output.isEmpty() || !this.isPattern(output)) { + return; // no blanks. + } - // remove one, and clear the input slot. - output.setCount( output.getCount() - 1 ); - if( output.getCount() == 0 ) - { - this.patternSlotIN.putStack( ItemStack.EMPTY ); - } + // remove one, and clear the input slot. + output.setCount(output.getCount() - 1); + if (output.getCount() == 0) { + this.patternSlotIN.putStack(ItemStack.EMPTY); + } - // add a new encoded pattern. - Optional maybePattern = AEApi.instance().definitions().items().encodedPattern().maybeStack( 1 ); - if( maybePattern.isPresent() ) - { - output = maybePattern.get(); - this.patternSlotOUT.putStack( output ); - } - } + // add a new encoded pattern. + Optional maybePattern = AEApi.instance().definitions().items().encodedPattern().maybeStack(1); + if (maybePattern.isPresent()) { + output = maybePattern.get(); + this.patternSlotOUT.putStack(output); + } + } - // encode the slot. - final NBTTagCompound encodedValue = new NBTTagCompound(); + // encode the slot. + final NBTTagCompound encodedValue = new NBTTagCompound(); - final NBTTagList tagIn = new NBTTagList(); - final NBTTagList tagOut = new NBTTagList(); + final NBTTagList tagIn = new NBTTagList(); + final NBTTagList tagOut = new NBTTagList(); - for( final ItemStack i : in ) - { - tagIn.appendTag( this.createItemTag( i ) ); - } + for (final ItemStack i : in) { + tagIn.appendTag(this.createItemTag(i)); + } - for( final ItemStack i : out ) - { - tagOut.appendTag( this.createItemTag( i ) ); - } + for (final ItemStack i : out) { + tagOut.appendTag(this.createItemTag(i)); + } - encodedValue.setTag( "in", tagIn ); - encodedValue.setTag( "out", tagOut ); - encodedValue.setBoolean( "crafting", false ); - encodedValue.setBoolean( "substitute", false ); + encodedValue.setTag("in", tagIn); + encodedValue.setTag("out", tagOut); + encodedValue.setBoolean("crafting", false); + encodedValue.setBoolean("substitute", false); - output.setTagCompound( encodedValue ); - } + output.setTagCompound(encodedValue); + } - boolean isPattern( final ItemStack output ) - { - if( output.isEmpty() ) - { - return false; - } + boolean isPattern(final ItemStack output) { + if (output.isEmpty()) { + return false; + } - final IDefinitions definitions = AEApi.instance().definitions(); + final IDefinitions definitions = AEApi.instance().definitions(); - boolean isPattern = definitions.items().encodedPattern().isSameAs( output ); - isPattern |= definitions.materials().blankPattern().isSameAs( output ); + boolean isPattern = definitions.items().encodedPattern().isSameAs(output); + isPattern |= definitions.materials().blankPattern().isSameAs(output); - return isPattern; - } + return isPattern; + } - NBTBase createItemTag( final ItemStack i ) - { - final NBTTagCompound c = new NBTTagCompound(); + NBTBase createItemTag(final ItemStack i) { + final NBTTagCompound c = new NBTTagCompound(); - if( !i.isEmpty() ) - { - i.writeToNBT( c ); - } + if (!i.isEmpty()) { + i.writeToNBT(c); + } - return c; - } + return c; + } - @Override - public boolean isSlotEnabled( final int idx ) - { - return true; - } + @Override + public boolean isSlotEnabled(final int idx) { + return true; + } - protected ItemStack[] getInputs() - { - final ItemStack[] input = new ItemStack[16]; - boolean hasValue = false; + protected ItemStack[] getInputs() { + final ItemStack[] input = new ItemStack[16]; + boolean hasValue = false; - for( int x = 0; x < this.gridSlots.length; x++ ) - { - input[x] = this.gridSlots[x].getStack(); - if( !input[x].isEmpty() ) - { - hasValue = true; - } - } + for (int x = 0; x < this.gridSlots.length; x++) { + input[x] = this.gridSlots[x].getStack(); + if (!input[x].isEmpty()) { + hasValue = true; + } + } - if( hasValue ) - { - return input; - } + if (hasValue) { + return input; + } - return null; - } + return null; + } - protected ItemStack[] getOutputs() - { - final List list = new ArrayList<>( 3 ); - boolean hasValue = false; + protected ItemStack[] getOutputs() { + final List list = new ArrayList<>(3); + boolean hasValue = false; - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); - if( !out.isEmpty() && out.getCount() > 0 ) - { - list.add( out ); - hasValue = true; - } - } + if (!out.isEmpty() && out.getCount() > 0) { + list.add(out); + hasValue = true; + } + } - if( hasValue ) - { - return list.toArray( new ItemStack[0] ); - } - return null; - } + if (hasValue) { + return list.toArray(new ItemStack[0]); + } + return null; + } - public void clear() - { - for( final Slot s : this.gridSlots ) - { - s.putStack( ItemStack.EMPTY ); - } + public void clear() { + for (final Slot s : this.gridSlots) { + s.putStack(ItemStack.EMPTY); + } - for( final Slot s : this.outputSlots ) - { - s.putStack( ItemStack.EMPTY ); - } + for (final Slot s : this.outputSlots) { + s.putStack(ItemStack.EMPTY); + } - this.detectAndSendChanges(); - } + this.detectAndSendChanges(); + } - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "player" ) ) - { - return new PlayerInvWrapper( this.getInventoryPlayer() ); - } - return this.getExpandedPatternTerminal().getInventoryByName( name ); - } + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("player")) { + return new PlayerInvWrapper(this.getInventoryPlayer()); + } + return this.getExpandedPatternTerminal().getInventoryByName(name); + } - @Override - public boolean useRealItems() - { - return false; - } + @Override + public boolean useRealItems() { + return false; + } - public PartExpandedProcessingPatternTerminal getExpandedPatternTerminal() - { - return this.expandedProcessingPatternTerminal; - } + public PartExpandedProcessingPatternTerminal getExpandedPatternTerminal() { + return this.expandedProcessingPatternTerminal; + } - public void multiply( int multiple ) - { - ItemStack[] input = new ItemStack[gridSlots.length]; - boolean canMultiplyInputs = true; - boolean canMultiplyOutputs = true; + public void multiply(int multiple) { + ItemStack[] input = new ItemStack[gridSlots.length]; + boolean canMultiplyInputs = true; + boolean canMultiplyOutputs = true; - for( int x = 0; x < this.gridSlots.length; x++ ) - { - input[x] = this.gridSlots[x].getStack(); - if( !input[x].isEmpty() && input[x].getCount() * multiple > input[x].getMaxStackSize() ) - { - canMultiplyInputs = false; - } - } - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); - if( !out.isEmpty() && out.getCount() * multiple > out.getMaxStackSize() ) - { - canMultiplyOutputs = false; - } - } - if( canMultiplyInputs && canMultiplyOutputs ) - { - for( SlotFakeCraftingMatrix craftingSlot : this.gridSlots ) - { - ItemStack stack = craftingSlot.getStack(); - if( !stack.isEmpty() ) - { - craftingSlot.getStack().setCount( stack.getCount() * multiple ); - } - } - for( OptionalSlotFake outputSlot : this.outputSlots ) - { - ItemStack stack = outputSlot.getStack(); - if( !stack.isEmpty() ) - { - outputSlot.getStack().setCount( stack.getCount() * multiple ); - } - } - } - } + for (int x = 0; x < this.gridSlots.length; x++) { + input[x] = this.gridSlots[x].getStack(); + if (!input[x].isEmpty() && input[x].getCount() * multiple > input[x].getMaxStackSize()) { + canMultiplyInputs = false; + } + } + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); + if (!out.isEmpty() && out.getCount() * multiple > out.getMaxStackSize()) { + canMultiplyOutputs = false; + } + } + if (canMultiplyInputs && canMultiplyOutputs) { + for (SlotFakeCraftingMatrix craftingSlot : this.gridSlots) { + ItemStack stack = craftingSlot.getStack(); + if (!stack.isEmpty()) { + craftingSlot.getStack().setCount(stack.getCount() * multiple); + } + } + for (OptionalSlotFake outputSlot : this.outputSlots) { + ItemStack stack = outputSlot.getStack(); + if (!stack.isEmpty()) { + outputSlot.getStack().setCount(stack.getCount() * multiple); + } + } + } + } - public void divide( int divide ) - { - ItemStack[] input = new ItemStack[gridSlots.length]; - boolean canDivideInputs = true; - boolean canDivideOutputs = true; + public void divide(int divide) { + ItemStack[] input = new ItemStack[gridSlots.length]; + boolean canDivideInputs = true; + boolean canDivideOutputs = true; - for( int x = 0; x < this.gridSlots.length; x++ ) - { - input[x] = this.gridSlots[x].getStack(); - if( !input[x].isEmpty() && input[x].getCount() % divide != 0 ) - { - canDivideInputs = false; - } - } - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); - if( !out.isEmpty() && out.getCount() % divide != 0 ) - { - canDivideOutputs = false; - } - } - if( canDivideInputs && canDivideOutputs ) - { - for( SlotFakeCraftingMatrix craftingSlot : this.gridSlots ) - { - ItemStack stack = craftingSlot.getStack(); - if( !stack.isEmpty() ) - { - craftingSlot.getStack().setCount( stack.getCount() / divide ); - } - } - for( OptionalSlotFake outputSlot : this.outputSlots ) - { - ItemStack stack = outputSlot.getStack(); - if( !stack.isEmpty() ) - { - outputSlot.getStack().setCount( stack.getCount() / divide ); - } - } - } - } + for (int x = 0; x < this.gridSlots.length; x++) { + input[x] = this.gridSlots[x].getStack(); + if (!input[x].isEmpty() && input[x].getCount() % divide != 0) { + canDivideInputs = false; + } + } + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); + if (!out.isEmpty() && out.getCount() % divide != 0) { + canDivideOutputs = false; + } + } + if (canDivideInputs && canDivideOutputs) { + for (SlotFakeCraftingMatrix craftingSlot : this.gridSlots) { + ItemStack stack = craftingSlot.getStack(); + if (!stack.isEmpty()) { + craftingSlot.getStack().setCount(stack.getCount() / divide); + } + } + for (OptionalSlotFake outputSlot : this.outputSlots) { + ItemStack stack = outputSlot.getStack(); + if (!stack.isEmpty()) { + outputSlot.getStack().setCount(stack.getCount() / divide); + } + } + } + } - public void increase( int increase ) - { - ItemStack[] input = new ItemStack[gridSlots.length]; - boolean canIncreaseInputs = true; - boolean canIncreaseOutputs = true; + public void increase(int increase) { + ItemStack[] input = new ItemStack[gridSlots.length]; + boolean canIncreaseInputs = true; + boolean canIncreaseOutputs = true; - for( int x = 0; x < this.gridSlots.length; x++ ) - { - input[x] = this.gridSlots[x].getStack(); - if( !input[x].isEmpty() && input[x].getCount() + increase > input[x].getMaxStackSize() ) - { - canIncreaseInputs = false; - } - } - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); - if( !out.isEmpty() && out.getCount() + increase > out.getMaxStackSize() ) - { - canIncreaseOutputs = false; - } - } - if( canIncreaseInputs && canIncreaseOutputs ) - { - for( SlotFakeCraftingMatrix craftingSlot : this.gridSlots ) - { - ItemStack stack = craftingSlot.getStack(); - if( !stack.isEmpty() ) - { - craftingSlot.getStack().setCount( stack.getCount() + increase ); - } - } - for( OptionalSlotFake outputSlot : this.outputSlots ) - { - ItemStack stack = outputSlot.getStack(); - if( !stack.isEmpty() ) - { - outputSlot.getStack().setCount( stack.getCount() + increase ); - } - } - } - } + for (int x = 0; x < this.gridSlots.length; x++) { + input[x] = this.gridSlots[x].getStack(); + if (!input[x].isEmpty() && input[x].getCount() + increase > input[x].getMaxStackSize()) { + canIncreaseInputs = false; + } + } + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); + if (!out.isEmpty() && out.getCount() + increase > out.getMaxStackSize()) { + canIncreaseOutputs = false; + } + } + if (canIncreaseInputs && canIncreaseOutputs) { + for (SlotFakeCraftingMatrix craftingSlot : this.gridSlots) { + ItemStack stack = craftingSlot.getStack(); + if (!stack.isEmpty()) { + craftingSlot.getStack().setCount(stack.getCount() + increase); + } + } + for (OptionalSlotFake outputSlot : this.outputSlots) { + ItemStack stack = outputSlot.getStack(); + if (!stack.isEmpty()) { + outputSlot.getStack().setCount(stack.getCount() + increase); + } + } + } + } - public void decrease( int decrease ) - { - ItemStack[] input = new ItemStack[gridSlots.length]; - boolean canDecreaseInputs = true; - boolean canDecreaseOutputs = true; + public void decrease(int decrease) { + ItemStack[] input = new ItemStack[gridSlots.length]; + boolean canDecreaseInputs = true; + boolean canDecreaseOutputs = true; - for( int x = 0; x < this.gridSlots.length; x++ ) - { - input[x] = this.gridSlots[x].getStack(); - if( !input[x].isEmpty() && input[x].getCount() - decrease < 1 ) - { - canDecreaseInputs = false; - } - } - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); - if( !out.isEmpty() && out.getCount() - decrease < 1 ) - { - canDecreaseOutputs = false; - } - } - if( canDecreaseInputs && canDecreaseOutputs ) - { - for( SlotFakeCraftingMatrix craftingSlot : this.gridSlots ) - { - ItemStack stack = craftingSlot.getStack(); - if( !stack.isEmpty() ) - { - craftingSlot.getStack().setCount( stack.getCount() - decrease ); - } - } - for( OptionalSlotFake outputSlot : this.outputSlots ) - { - ItemStack stack = outputSlot.getStack(); - if( !stack.isEmpty() ) - { - outputSlot.getStack().setCount( stack.getCount() - decrease ); - } - } - } - } + for (int x = 0; x < this.gridSlots.length; x++) { + input[x] = this.gridSlots[x].getStack(); + if (!input[x].isEmpty() && input[x].getCount() - decrease < 1) { + canDecreaseInputs = false; + } + } + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); + if (!out.isEmpty() && out.getCount() - decrease < 1) { + canDecreaseOutputs = false; + } + } + if (canDecreaseInputs && canDecreaseOutputs) { + for (SlotFakeCraftingMatrix craftingSlot : this.gridSlots) { + ItemStack stack = craftingSlot.getStack(); + if (!stack.isEmpty()) { + craftingSlot.getStack().setCount(stack.getCount() - decrease); + } + } + for (OptionalSlotFake outputSlot : this.outputSlots) { + ItemStack stack = outputSlot.getStack(); + if (!stack.isEmpty()) { + outputSlot.getStack().setCount(stack.getCount() - decrease); + } + } + } + } - public void maximizeCount() - { - ItemStack[] input = new ItemStack[gridSlots.length]; - boolean canGrowInputs = true; - boolean canGrowOutputs = true; - int maxInputStackGrowth = 0; - int maxOutputStackGrowth = 0; + public void maximizeCount() { + ItemStack[] input = new ItemStack[gridSlots.length]; + boolean canGrowInputs = true; + boolean canGrowOutputs = true; + int maxInputStackGrowth = 0; + int maxOutputStackGrowth = 0; - for( int x = 0; x < this.gridSlots.length; x++ ) - { - input[x] = this.gridSlots[x].getStack(); - if( !input[x].isEmpty() && input[x].getMaxStackSize() - input[x].getCount() > maxInputStackGrowth ) - { - maxInputStackGrowth = input[x].getMaxStackSize() - input[x].getCount(); - } - if( !input[x].isEmpty() && input[x].getCount() + maxInputStackGrowth > input[x].getMaxStackSize() ) - { - canGrowInputs = false; - } - } - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); - { - maxOutputStackGrowth = out.getMaxStackSize() - out.getCount(); - } - if( !out.isEmpty() && out.getCount() + maxOutputStackGrowth > out.getMaxStackSize() ) - { - canGrowOutputs = false; - } - } - if( canGrowInputs && canGrowOutputs ) - { - int maxStackGrowth = Math.min( maxInputStackGrowth, maxOutputStackGrowth ); - for( SlotFakeCraftingMatrix craftingSlot : this.gridSlots ) - { - ItemStack stack = craftingSlot.getStack(); - if( !stack.isEmpty() ) - { - craftingSlot.getStack().setCount( stack.getCount() + maxStackGrowth ); - } - } - for( OptionalSlotFake outputSlot : this.outputSlots ) - { - ItemStack stack = outputSlot.getStack(); - if( !stack.isEmpty() ) - { - outputSlot.getStack().setCount( stack.getCount() + maxStackGrowth ); - } - } - } - } + for (int x = 0; x < this.gridSlots.length; x++) { + input[x] = this.gridSlots[x].getStack(); + if (!input[x].isEmpty() && input[x].getMaxStackSize() - input[x].getCount() > maxInputStackGrowth) { + maxInputStackGrowth = input[x].getMaxStackSize() - input[x].getCount(); + } + if (!input[x].isEmpty() && input[x].getCount() + maxInputStackGrowth > input[x].getMaxStackSize()) { + canGrowInputs = false; + } + } + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); + { + maxOutputStackGrowth = out.getMaxStackSize() - out.getCount(); + } + if (!out.isEmpty() && out.getCount() + maxOutputStackGrowth > out.getMaxStackSize()) { + canGrowOutputs = false; + } + } + if (canGrowInputs && canGrowOutputs) { + int maxStackGrowth = Math.min(maxInputStackGrowth, maxOutputStackGrowth); + for (SlotFakeCraftingMatrix craftingSlot : this.gridSlots) { + ItemStack stack = craftingSlot.getStack(); + if (!stack.isEmpty()) { + craftingSlot.getStack().setCount(stack.getCount() + maxStackGrowth); + } + } + for (OptionalSlotFake outputSlot : this.outputSlots) { + ItemStack stack = outputSlot.getStack(); + if (!stack.isEmpty()) { + outputSlot.getStack().setCount(stack.getCount() + maxStackGrowth); + } + } + } + } - @Override - public void onSlotChange( final Slot s ) - { - if( s == this.patternSlotOUT && Platform.isServer() ) - { - for( final IContainerListener listener : this.listeners ) - { - for( final Slot slot : this.inventorySlots ) - { - if( slot instanceof OptionalSlotFake || slot instanceof SlotFakeCraftingMatrix ) - { - listener.sendSlotContents( this, slot.slotNumber, slot.getStack() ); - } - } - if( listener instanceof EntityPlayerMP ) - { - ( (EntityPlayerMP) listener ).isChangingQuantityOnly = false; - } - } - this.detectAndSendChanges(); - } - } + @Override + public void onSlotChange(final Slot s) { + if (s == this.patternSlotOUT && Platform.isServer()) { + for (final IContainerListener listener : this.listeners) { + for (final Slot slot : this.inventorySlots) { + if (slot instanceof OptionalSlotFake || slot instanceof SlotFakeCraftingMatrix) { + listener.sendSlotContents(this, slot.slotNumber, slot.getStack()); + } + } + if (listener instanceof EntityPlayerMP) { + ((EntityPlayerMP) listener).isChangingQuantityOnly = false; + } + } + this.detectAndSendChanges(); + } + } } diff --git a/src/main/java/appeng/container/implementations/ContainerFormationPlane.java b/src/main/java/appeng/container/implementations/ContainerFormationPlane.java index b884251b6..95b5d7f8d 100644 --- a/src/main/java/appeng/container/implementations/ContainerFormationPlane.java +++ b/src/main/java/appeng/container/implementations/ContainerFormationPlane.java @@ -19,119 +19,98 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraftforge.items.IItemHandler; - -import appeng.api.config.FuzzyMode; -import appeng.api.config.SecurityPermissions; -import appeng.api.config.Settings; -import appeng.api.config.Upgrades; -import appeng.api.config.YesNo; +import appeng.api.config.*; import appeng.container.guisync.GuiSync; import appeng.container.slot.OptionalSlotFakeTypeOnly; import appeng.container.slot.SlotFakeTypeOnly; import appeng.container.slot.SlotRestrictedInput; import appeng.parts.automation.PartFormationPlane; import appeng.util.Platform; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraftforge.items.IItemHandler; -public class ContainerFormationPlane extends ContainerUpgradeable -{ +public class ContainerFormationPlane extends ContainerUpgradeable { - @GuiSync( 6 ) - public YesNo placeMode; + @GuiSync(6) + public YesNo placeMode; - public ContainerFormationPlane( final InventoryPlayer ip, final PartFormationPlane te ) - { - super( ip, te ); - } + public ContainerFormationPlane(final InventoryPlayer ip, final PartFormationPlane te) { + super(ip, te); + } - @Override - protected int getHeight() - { - return 251; - } + @Override + protected int getHeight() { + return 251; + } - @Override - protected void setupConfig() - { - final int xo = 8; - final int yo = 23 + 6; + @Override + protected void setupConfig() { + final int xo = 8; + final int yo = 23 + 6; - final IItemHandler config = this.getUpgradeable().getInventoryByName( "config" ); - for( int y = 0; y < 7; y++ ) - { - for( int x = 0; x < 9; x++ ) - { - if( y < 2 ) - { - this.addSlotToContainer( new SlotFakeTypeOnly( config, y * 9 + x, xo + x * 18, yo + y * 18 ) ); - } - else - { - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( config, this, y * 9 + x, xo, yo, x, y, y - 2 ) ); - } - } - } + final IItemHandler config = this.getUpgradeable().getInventoryByName("config"); + for (int y = 0; y < 7; y++) { + for (int x = 0; x < 9; x++) { + if (y < 2) { + this.addSlotToContainer(new SlotFakeTypeOnly(config, y * 9 + x, xo + x * 18, yo + y * 18)); + } else { + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(config, this, y * 9 + x, xo, yo, x, y, y - 2)); + } + } + } - final IItemHandler upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } + final IItemHandler upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer())) + .setNotDraggable()); + } - @Override - protected boolean supportCapacity() - { - return true; - } + @Override + protected boolean supportCapacity() { + return true; + } - @Override - public int availableUpgrades() - { - return 5; - } + @Override + public int availableUpgrades() { + return 5; + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - if( Platform.isServer() ) - { - this.setFuzzyMode( (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting( Settings.FUZZY_MODE ) ); - this.setPlaceMode( (YesNo) this.getUpgradeable().getConfigManager().getSetting( Settings.PLACE_BLOCK ) ); - } + if (Platform.isServer()) { + this.setFuzzyMode((FuzzyMode) this.getUpgradeable().getConfigManager().getSetting(Settings.FUZZY_MODE)); + this.setPlaceMode((YesNo) this.getUpgradeable().getConfigManager().getSetting(Settings.PLACE_BLOCK)); + } - this.standardDetectAndSendChanges(); - } + this.standardDetectAndSendChanges(); + } - @Override - public boolean isSlotEnabled( final int idx ) - { - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); + @Override + public boolean isSlotEnabled(final int idx) { + final int upgrades = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); - return upgrades > idx; - } + return upgrades > idx; + } - public YesNo getPlaceMode() - { - return this.placeMode; - } + public YesNo getPlaceMode() { + return this.placeMode; + } - private void setPlaceMode( final YesNo placeMode ) - { - this.placeMode = placeMode; - } + private void setPlaceMode(final YesNo placeMode) { + this.placeMode = placeMode; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerGrinder.java b/src/main/java/appeng/container/implementations/ContainerGrinder.java index 051d19428..0adab5510 100644 --- a/src/main/java/appeng/container/implementations/ContainerGrinder.java +++ b/src/main/java/appeng/container/implementations/ContainerGrinder.java @@ -19,35 +19,32 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraftforge.items.IItemHandler; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotInaccessible; import appeng.container.slot.SlotOutput; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.grindstone.TileGrinder; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraftforge.items.IItemHandler; -public class ContainerGrinder extends AEBaseContainer -{ +public class ContainerGrinder extends AEBaseContainer { - public ContainerGrinder( final InventoryPlayer ip, final TileGrinder grinder ) - { - super( ip, grinder, null ); + public ContainerGrinder(final InventoryPlayer ip, final TileGrinder grinder) { + super(ip, grinder, null); - IItemHandler inv = grinder.getInternalInventory(); + IItemHandler inv = grinder.getInternalInventory(); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ORE, inv, 0, 12, 17, this.getInventoryPlayer() ) ); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ORE, inv, 1, 12 + 18, 17, this.getInventoryPlayer() ) ); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ORE, inv, 2, 12 + 36, 17, this.getInventoryPlayer() ) ); + this.addSlotToContainer(new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.ORE, inv, 0, 12, 17, this.getInventoryPlayer())); + this.addSlotToContainer(new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.ORE, inv, 1, 12 + 18, 17, this.getInventoryPlayer())); + this.addSlotToContainer(new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.ORE, inv, 2, 12 + 36, 17, this.getInventoryPlayer())); - this.addSlotToContainer( new SlotInaccessible( inv, 6, 80, 40 ) ); + this.addSlotToContainer(new SlotInaccessible(inv, 6, 80, 40)); - this.addSlotToContainer( new SlotOutput( inv, 3, 112, 63, 2 * 16 + 15 ) ); - this.addSlotToContainer( new SlotOutput( inv, 4, 112 + 18, 63, 2 * 16 + 15 ) ); - this.addSlotToContainer( new SlotOutput( inv, 5, 112 + 36, 63, 2 * 16 + 15 ) ); + this.addSlotToContainer(new SlotOutput(inv, 3, 112, 63, 2 * 16 + 15)); + this.addSlotToContainer(new SlotOutput(inv, 4, 112 + 18, 63, 2 * 16 + 15)); + this.addSlotToContainer(new SlotOutput(inv, 5, 112 + 36, 63, 2 * 16 + 15)); - this.bindPlayerInventory( ip, 0, 176 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 176 - /* height of player inventory */82); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerIOPort.java b/src/main/java/appeng/container/implementations/ContainerIOPort.java index f0a69e514..ab8b3ac1b 100644 --- a/src/main/java/appeng/container/implementations/ContainerIOPort.java +++ b/src/main/java/appeng/container/implementations/ContainerIOPort.java @@ -19,124 +19,103 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraftforge.items.IItemHandler; - -import appeng.api.config.FullnessMode; -import appeng.api.config.OperationMode; -import appeng.api.config.RedstoneMode; -import appeng.api.config.SecurityPermissions; -import appeng.api.config.Settings; +import appeng.api.config.*; import appeng.container.guisync.GuiSync; import appeng.container.slot.SlotOutput; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.storage.TileIOPort; import appeng.util.Platform; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraftforge.items.IItemHandler; -public class ContainerIOPort extends ContainerUpgradeable -{ +public class ContainerIOPort extends ContainerUpgradeable { - @GuiSync( 2 ) - public FullnessMode fMode = FullnessMode.EMPTY; - @GuiSync( 3 ) - public OperationMode opMode = OperationMode.EMPTY; + @GuiSync(2) + public FullnessMode fMode = FullnessMode.EMPTY; + @GuiSync(3) + public OperationMode opMode = OperationMode.EMPTY; - public ContainerIOPort( final InventoryPlayer ip, final TileIOPort te ) - { - super( ip, te ); - } + public ContainerIOPort(final InventoryPlayer ip, final TileIOPort te) { + super(ip, te); + } - @Override - protected int getHeight() - { - return 166; - } + @Override + protected int getHeight() { + return 166; + } - @Override - protected void setupConfig() - { - int offX = 19; - int offY = 17; + @Override + protected void setupConfig() { + int offX = 19; + int offY = 17; - final IItemHandler cells = this.getUpgradeable().getInventoryByName( "cells" ); + final IItemHandler cells = this.getUpgradeable().getInventoryByName("cells"); - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 2; x++ ) - { - this.addSlotToContainer( - new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, cells, x + y * 2, offX + x * 18, offY + y * 18, this - .getInventoryPlayer() ) ); - } - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 2; x++) { + this.addSlotToContainer( + new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, cells, x + y * 2, offX + x * 18, offY + y * 18, this + .getInventoryPlayer())); + } + } - offX = 122; - offY = 17; - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 2; x++ ) - { - this.addSlotToContainer( - new SlotOutput( cells, 6 + x + y * 2, offX + x * 18, offY + y * 18, SlotRestrictedInput.PlacableItemType.STORAGE_CELLS.IIcon ) ); - } - } + offX = 122; + offY = 17; + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 2; x++) { + this.addSlotToContainer( + new SlotOutput(cells, 6 + x + y * 2, offX + x * 18, offY + y * 18, SlotRestrictedInput.PlacableItemType.STORAGE_CELLS.IIcon)); + } + } - final IItemHandler upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } + final IItemHandler upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer())) + .setNotDraggable()); + } - @Override - protected boolean supportCapacity() - { - return false; - } + @Override + protected boolean supportCapacity() { + return false; + } - @Override - public int availableUpgrades() - { - return 3; - } + @Override + public int availableUpgrades() { + return 3; + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - if( Platform.isServer() ) - { - this.setOperationMode( (OperationMode) this.getUpgradeable().getConfigManager().getSetting( Settings.OPERATION_MODE ) ); - this.setFullMode( (FullnessMode) this.getUpgradeable().getConfigManager().getSetting( Settings.FULLNESS_MODE ) ); - this.setRedStoneMode( (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ) ); - } + if (Platform.isServer()) { + this.setOperationMode((OperationMode) this.getUpgradeable().getConfigManager().getSetting(Settings.OPERATION_MODE)); + this.setFullMode((FullnessMode) this.getUpgradeable().getConfigManager().getSetting(Settings.FULLNESS_MODE)); + this.setRedStoneMode((RedstoneMode) this.getUpgradeable().getConfigManager().getSetting(Settings.REDSTONE_CONTROLLED)); + } - this.standardDetectAndSendChanges(); - } + this.standardDetectAndSendChanges(); + } - public FullnessMode getFullMode() - { - return this.fMode; - } + public FullnessMode getFullMode() { + return this.fMode; + } - private void setFullMode( final FullnessMode fMode ) - { - this.fMode = fMode; - } + private void setFullMode(final FullnessMode fMode) { + this.fMode = fMode; + } - public OperationMode getOperationMode() - { - return this.opMode; - } + public OperationMode getOperationMode() { + return this.opMode; + } - private void setOperationMode( final OperationMode opMode ) - { - this.opMode = opMode; - } + private void setOperationMode(final OperationMode opMode) { + this.opMode = opMode; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerInscriber.java b/src/main/java/appeng/container/implementations/ContainerInscriber.java index 231ca2990..6a393e1bc 100644 --- a/src/main/java/appeng/container/implementations/ContainerInscriber.java +++ b/src/main/java/appeng/container/implementations/ContainerInscriber.java @@ -19,11 +19,6 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.definitions.IItemDefinition; import appeng.api.features.IInscriberRecipe; @@ -33,6 +28,10 @@ import appeng.container.slot.SlotOutput; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.misc.TileInscriber; import appeng.util.Platform; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraftforge.items.IItemHandler; /** @@ -41,172 +40,141 @@ import appeng.util.Platform; * @version rv2 * @since rv0 */ -public class ContainerInscriber extends ContainerUpgradeable implements IProgressProvider -{ +public class ContainerInscriber extends ContainerUpgradeable implements IProgressProvider { - private final TileInscriber ti; + private final TileInscriber ti; - private final Slot top; - private final Slot middle; - private final Slot bottom; + private final Slot top; + private final Slot middle; + private final Slot bottom; - @GuiSync( 2 ) - public int maxProcessingTime = -1; + @GuiSync(2) + public int maxProcessingTime = -1; - @GuiSync( 3 ) - public int processingTime = -1; + @GuiSync(3) + public int processingTime = -1; - public ContainerInscriber( final InventoryPlayer ip, final TileInscriber te ) - { - super( ip, te ); - this.ti = te; + public ContainerInscriber(final InventoryPlayer ip, final TileInscriber te) { + super(ip, te); + this.ti = te; - IItemHandler inv = te.getInternalInventory(); + IItemHandler inv = te.getInternalInventory(); - this.addSlotToContainer( - this.top = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.INSCRIBER_PLATE, inv, 0, 45, 16, this.getInventoryPlayer() ) ); - this.addSlotToContainer( - this.bottom = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.INSCRIBER_PLATE, inv, 1, 45, 62, this.getInventoryPlayer() ) ); - this.addSlotToContainer( - this.middle = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.INSCRIBER_INPUT, inv, 2, 63, 39, this.getInventoryPlayer() ) ); + this.addSlotToContainer( + this.top = new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.INSCRIBER_PLATE, inv, 0, 45, 16, this.getInventoryPlayer())); + this.addSlotToContainer( + this.bottom = new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.INSCRIBER_PLATE, inv, 1, 45, 62, this.getInventoryPlayer())); + this.addSlotToContainer( + this.middle = new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.INSCRIBER_INPUT, inv, 2, 63, 39, this.getInventoryPlayer())); - this.addSlotToContainer( new SlotOutput( inv, 3, 113, 40, -1 ) ); - } + this.addSlotToContainer(new SlotOutput(inv, 3, 113, 40, -1)); + } - @Override - protected int getHeight() - { - return 176; - } + @Override + protected int getHeight() { + return 176; + } - @Override - /** - * Overridden super.setupConfig to prevent setting up the fake slots - */ - protected void setupConfig() - { - this.setupUpgrades(); - } + @Override + /** + * Overridden super.setupConfig to prevent setting up the fake slots + */ + protected void setupConfig() { + this.setupUpgrades(); + } - @Override - protected boolean supportCapacity() - { - return false; - } + @Override + protected boolean supportCapacity() { + return false; + } - @Override - public int availableUpgrades() - { - return 3; - } + @Override + public int availableUpgrades() { + return 3; + } - @Override - public void detectAndSendChanges() - { - this.standardDetectAndSendChanges(); + @Override + public void detectAndSendChanges() { + this.standardDetectAndSendChanges(); - if( Platform.isServer() ) - { - this.maxProcessingTime = this.ti.getMaxProcessingTime(); - this.processingTime = this.ti.getProcessingTime(); - } - } + if (Platform.isServer()) { + this.maxProcessingTime = this.ti.getMaxProcessingTime(); + this.processingTime = this.ti.getProcessingTime(); + } + } - @Override - public boolean isValidForSlot( final Slot s, final ItemStack is ) - { - final ItemStack top = this.ti.getInternalInventory().getStackInSlot( 0 ); - final ItemStack bot = this.ti.getInternalInventory().getStackInSlot( 1 ); + @Override + public boolean isValidForSlot(final Slot s, final ItemStack is) { + final ItemStack top = this.ti.getInternalInventory().getStackInSlot(0); + final ItemStack bot = this.ti.getInternalInventory().getStackInSlot(1); - if( s == this.middle ) - { - IItemDefinition press = AEApi.instance().definitions().materials().namePress(); - if( press.isSameAs( top ) || press.isSameAs( bot ) ) - { - return !press.isSameAs( is ); - } + if (s == this.middle) { + IItemDefinition press = AEApi.instance().definitions().materials().namePress(); + if (press.isSameAs(top) || press.isSameAs(bot)) { + return !press.isSameAs(is); + } - boolean matches = false; - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - final boolean matchA = !top - .isEmpty() && ( Platform.itemComparisons().isSameItem( top, recipe.getTopOptional().orElse( ItemStack.EMPTY ) ) || Platform - .itemComparisons() - .isSameItem( top, recipe.getBottomOptional().orElse( ItemStack.EMPTY ) ) ); - final boolean matchB = !bot - .isEmpty() && ( Platform.itemComparisons().isSameItem( bot, recipe.getTopOptional().orElse( ItemStack.EMPTY ) ) || Platform - .itemComparisons() - .isSameItem( bot, recipe.getBottomOptional().orElse( ItemStack.EMPTY ) ) ); + boolean matches = false; + for (final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes()) { + final boolean matchA = !top + .isEmpty() && (Platform.itemComparisons().isSameItem(top, recipe.getTopOptional().orElse(ItemStack.EMPTY)) || Platform + .itemComparisons() + .isSameItem(top, recipe.getBottomOptional().orElse(ItemStack.EMPTY))); + final boolean matchB = !bot + .isEmpty() && (Platform.itemComparisons().isSameItem(bot, recipe.getTopOptional().orElse(ItemStack.EMPTY)) || Platform + .itemComparisons() + .isSameItem(bot, recipe.getBottomOptional().orElse(ItemStack.EMPTY))); - if( matchA || matchB ) - { - matches = true; - for( final ItemStack option : recipe.getInputs() ) - { - if( Platform.itemComparisons().isSameItem( is, option ) ) - { - return true; - } - } - } - } - if( matches ) - { - return false; - } - } - else if( ( s == this.top && !bot.isEmpty() ) || ( s == this.bottom && !top.isEmpty() ) ) - { - ItemStack otherSlot; - if( s == this.top ) - { - otherSlot = this.bottom.getStack(); - } - else - { - otherSlot = this.top.getStack(); - } + if (matchA || matchB) { + matches = true; + for (final ItemStack option : recipe.getInputs()) { + if (Platform.itemComparisons().isSameItem(is, option)) { + return true; + } + } + } + } + return !matches; + } else if ((s == this.top && !bot.isEmpty()) || (s == this.bottom && !top.isEmpty())) { + ItemStack otherSlot; + if (s == this.top) { + otherSlot = this.bottom.getStack(); + } else { + otherSlot = this.top.getStack(); + } - // name presses - final IItemDefinition namePress = AEApi.instance().definitions().materials().namePress(); - if( namePress.isSameAs( otherSlot ) ) - { - return namePress.isSameAs( is ); - } + // name presses + final IItemDefinition namePress = AEApi.instance().definitions().materials().namePress(); + if (namePress.isSameAs(otherSlot)) { + return namePress.isSameAs(is); + } - // everything else - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - boolean isValid = false; - if( Platform.itemComparisons().isSameItem( otherSlot, recipe.getTopOptional().orElse( ItemStack.EMPTY ) ) ) - { - isValid = Platform.itemComparisons().isSameItem( is, recipe.getBottomOptional().orElse( ItemStack.EMPTY ) ); - } - else if( Platform.itemComparisons().isSameItem( otherSlot, recipe.getBottomOptional().orElse( ItemStack.EMPTY ) ) ) - { - isValid = Platform.itemComparisons().isSameItem( is, recipe.getTopOptional().orElse( ItemStack.EMPTY ) ); - } + // everything else + for (final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes()) { + boolean isValid = false; + if (Platform.itemComparisons().isSameItem(otherSlot, recipe.getTopOptional().orElse(ItemStack.EMPTY))) { + isValid = Platform.itemComparisons().isSameItem(is, recipe.getBottomOptional().orElse(ItemStack.EMPTY)); + } else if (Platform.itemComparisons().isSameItem(otherSlot, recipe.getBottomOptional().orElse(ItemStack.EMPTY))) { + isValid = Platform.itemComparisons().isSameItem(is, recipe.getTopOptional().orElse(ItemStack.EMPTY)); + } - if( isValid ) - { - return true; - } - } - return false; - } + if (isValid) { + return true; + } + } + return false; + } - return true; - } + return true; + } - @Override - public int getCurrentProgress() - { - return this.processingTime; - } + @Override + public int getCurrentProgress() { + return this.processingTime; + } - @Override - public int getMaxProgress() - { - return this.maxProcessingTime; - } + @Override + public int getMaxProgress() { + return this.maxProcessingTime; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerInterface.java b/src/main/java/appeng/container/implementations/ContainerInterface.java index cb2c614c1..000b2ecc8 100644 --- a/src/main/java/appeng/container/implementations/ContainerInterface.java +++ b/src/main/java/appeng/container/implementations/ContainerInterface.java @@ -19,133 +19,114 @@ package appeng.container.implementations; -import appeng.api.config.Upgrades; -import appeng.container.slot.*; -import appeng.util.Platform; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.config.SecurityPermissions; import appeng.api.config.Settings; +import appeng.api.config.Upgrades; import appeng.api.config.YesNo; import appeng.api.util.IConfigManager; import appeng.container.guisync.GuiSync; +import appeng.container.slot.*; import appeng.helpers.DualityInterface; import appeng.helpers.IInterfaceHost; +import appeng.util.Platform; +import net.minecraft.entity.player.InventoryPlayer; -public class ContainerInterface extends ContainerUpgradeable implements IOptionalSlotHost -{ +public class ContainerInterface extends ContainerUpgradeable implements IOptionalSlotHost { - private final DualityInterface myDuality; + private final DualityInterface myDuality; - @GuiSync( 3 ) - public YesNo bMode = YesNo.NO; + @GuiSync(3) + public YesNo bMode = YesNo.NO; - @GuiSync( 4 ) - public YesNo iTermMode = YesNo.YES; + @GuiSync(4) + public YesNo iTermMode = YesNo.YES; - @GuiSync( 7 ) - public int patternExpansions = 0; + @GuiSync(7) + public int patternExpansions = 0; - public ContainerInterface( final InventoryPlayer ip, final IInterfaceHost te ) - { - super( ip, te.getInterfaceDuality().getHost() ); + public ContainerInterface(final InventoryPlayer ip, final IInterfaceHost te) { + super(ip, te.getInterfaceDuality().getHost()); - this.myDuality = te.getInterfaceDuality(); + this.myDuality = te.getInterfaceDuality(); - for (int row = 0 ; row < 4 ; ++row) - { - for( int x = 0; x < 9; x++ ) - { - this.addSlotToContainer( new OptionalSlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, this.myDuality - .getPatterns(), this, x + row * 9, 8 + 18 * x, 97 + ( 18 * row ), row, this.getInventoryPlayer() ).setStackLimit( 1 ) ); - } - } + for (int row = 0; row < 4; ++row) { + for (int x = 0; x < 9; x++) { + this.addSlotToContainer(new OptionalSlotRestrictedInput(SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, this.myDuality + .getPatterns(), this, x + row * 9, 8 + 18 * x, 97 + (18 * row), row, this.getInventoryPlayer()).setStackLimit(1)); + } + } - for( int x = 0; x < DualityInterface.NUMBER_OF_CONFIG_SLOTS; x++ ) - { - this.addSlotToContainer( new SlotFake( this.myDuality.getConfig(), x, 8 + 18 * x, 35 ) ); - } + for (int x = 0; x < DualityInterface.NUMBER_OF_CONFIG_SLOTS; x++) { + this.addSlotToContainer(new SlotFake(this.myDuality.getConfig(), x, 8 + 18 * x, 35)); + } - for( int x = 0; x < DualityInterface.NUMBER_OF_STORAGE_SLOTS; x++ ) - { - this.addSlotToContainer( new SlotNormal( this.myDuality.getStorage(), x, 8 + 18 * x, 35 + 18 ) ); - } - } + for (int x = 0; x < DualityInterface.NUMBER_OF_STORAGE_SLOTS; x++) { + this.addSlotToContainer(new SlotNormal(this.myDuality.getStorage(), x, 8 + 18 * x, 35 + 18)); + } + } - @Override - protected int getHeight() - { - return 256; - } + @Override + protected int getHeight() { + return 256; + } - @Override - protected void setupConfig() - { - this.setupUpgrades(); - } + @Override + protected void setupConfig() { + this.setupUpgrades(); + } - @Override - public int availableUpgrades() - { - return 4; - } + @Override + public int availableUpgrades() { + return 4; + } - @Override - public boolean isSlotEnabled( final int idx ) - { - return myDuality.getInstalledUpgrades(Upgrades.PATTERN_EXPANSION) >= idx; - } + @Override + public boolean isSlotEnabled(final int idx) { + return myDuality.getInstalledUpgrades(Upgrades.PATTERN_EXPANSION) >= idx; + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - if (patternExpansions != getPatternUpgrades()) - { - patternExpansions = getPatternUpgrades(); - this.myDuality.dropExcessPatterns(); - } - super.detectAndSendChanges(); - } + if (patternExpansions != getPatternUpgrades()) { + patternExpansions = getPatternUpgrades(); + this.myDuality.dropExcessPatterns(); + } + super.detectAndSendChanges(); + } - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) { - super.onUpdate(field, oldValue, newValue); - if ( Platform.isClient() && field.equals("patternExpansions")) - this.myDuality.dropExcessPatterns(); - } + @Override + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + super.onUpdate(field, oldValue, newValue); + if (Platform.isClient() && field.equals("patternExpansions")) + this.myDuality.dropExcessPatterns(); + } - @Override - protected void loadSettingsFromHost( final IConfigManager cm ) - { - this.setBlockingMode( (YesNo) cm.getSetting( Settings.BLOCK ) ); - this.setInterfaceTerminalMode( (YesNo) cm.getSetting( Settings.INTERFACE_TERMINAL ) ); - } + @Override + protected void loadSettingsFromHost(final IConfigManager cm) { + this.setBlockingMode((YesNo) cm.getSetting(Settings.BLOCK)); + this.setInterfaceTerminalMode((YesNo) cm.getSetting(Settings.INTERFACE_TERMINAL)); + } - public YesNo getBlockingMode() - { - return this.bMode; - } + public YesNo getBlockingMode() { + return this.bMode; + } - private void setBlockingMode( final YesNo bMode ) - { - this.bMode = bMode; - } + private void setBlockingMode(final YesNo bMode) { + this.bMode = bMode; + } - public YesNo getInterfaceTerminalMode() - { - return this.iTermMode; - } + public YesNo getInterfaceTerminalMode() { + return this.iTermMode; + } - private void setInterfaceTerminalMode( final YesNo iTermMode ) - { - this.iTermMode = iTermMode; - } + private void setInterfaceTerminalMode(final YesNo iTermMode) { + this.iTermMode = iTermMode; + } - public int getPatternUpgrades() - { - return this.myDuality.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION ); - } + public int getPatternUpgrades() { + return this.myDuality.getInstalledUpgrades(Upgrades.PATTERN_EXPANSION); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerInterfaceConfigurationTerminal.java b/src/main/java/appeng/container/implementations/ContainerInterfaceConfigurationTerminal.java index 3d58757ad..75addb848 100644 --- a/src/main/java/appeng/container/implementations/ContainerInterfaceConfigurationTerminal.java +++ b/src/main/java/appeng/container/implementations/ContainerInterfaceConfigurationTerminal.java @@ -19,20 +19,6 @@ package appeng.container.implementations; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -import appeng.parts.reporting.PartInterfaceConfigurationTerminal; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTUtil; -import net.minecraft.util.math.BlockPos; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.Settings; import appeng.api.config.YesNo; import appeng.api.networking.IGrid; @@ -45,356 +31,303 @@ import appeng.helpers.DualityInterface; import appeng.helpers.IInterfaceHost; import appeng.helpers.InventoryAction; import appeng.parts.misc.PartInterface; +import appeng.parts.reporting.PartInterfaceConfigurationTerminal; import appeng.tile.inventory.AppEngInternalInventory; import appeng.tile.misc.TileInterface; import appeng.util.Platform; import appeng.util.helpers.ItemHandlerUtil; import appeng.util.inv.WrapperRangeItemHandler; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTUtil; +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.items.IItemHandler; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; -public final class ContainerInterfaceConfigurationTerminal extends AEBaseContainer -{ +public final class ContainerInterfaceConfigurationTerminal extends AEBaseContainer { - /** - * this stuff is all server side.. - */ + /** + * this stuff is all server side.. + */ - private static long autoBase = Long.MIN_VALUE; - private final Map diList = new HashMap<>(); - private final Map byId = new HashMap<>(); - private IGrid grid; - private NBTTagCompound data = new NBTTagCompound(); + private static long autoBase = Long.MIN_VALUE; + private final Map diList = new HashMap<>(); + private final Map byId = new HashMap<>(); + private IGrid grid; + private NBTTagCompound data = new NBTTagCompound(); - public ContainerInterfaceConfigurationTerminal( final InventoryPlayer ip, final PartInterfaceConfigurationTerminal anchor ) - { - super( ip, anchor ); + public ContainerInterfaceConfigurationTerminal(final InventoryPlayer ip, final PartInterfaceConfigurationTerminal anchor) { + super(ip, anchor); - if( Platform.isServer() ) - { - this.grid = anchor.getActionableNode().getGrid(); - } + if (Platform.isServer()) { + this.grid = anchor.getActionableNode().getGrid(); + } - this.bindPlayerInventory( ip, 14, 235 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 14, 235 - /* height of player inventory */82); + } - @Override - public void detectAndSendChanges() - { - if( Platform.isClient() ) - { - return; - } + @Override + public void detectAndSendChanges() { + if (Platform.isClient()) { + return; + } - super.detectAndSendChanges(); + super.detectAndSendChanges(); - if( this.grid == null ) - { - return; - } + if (this.grid == null) { + return; + } - int total = 0; - boolean missing = false; + int total = 0; + boolean missing = false; - final IActionHost host = this.getActionHost(); - if( host != null ) - { - final IGridNode agn = host.getActionableNode(); - if( agn != null && agn.isActive() ) - { - for( final IGridNode gn : this.grid.getMachines( TileInterface.class ) ) - { - if( gn.isActive() ) - { - final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - if( ih.getInterfaceDuality().getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.NO ) - { - continue; - } + final IActionHost host = this.getActionHost(); + if (host != null) { + final IGridNode agn = host.getActionableNode(); + if (agn != null && agn.isActive()) { + for (final IGridNode gn : this.grid.getMachines(TileInterface.class)) { + if (gn.isActive()) { + final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + if (ih.getInterfaceDuality().getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) == YesNo.NO) { + continue; + } - final ConfigTracker t = this.diList.get( ih ); + final ConfigTracker t = this.diList.get(ih); - if( t == null ) - { - missing = true; - } - else - { - final DualityInterface dual = ih.getInterfaceDuality(); - if( !t.unlocalizedName.equals( dual.getTermName() ) ) - { - missing = true; - } - } + if (t == null) { + missing = true; + } else { + final DualityInterface dual = ih.getInterfaceDuality(); + if (!t.unlocalizedName.equals(dual.getTermName())) { + missing = true; + } + } - total++; - } - } + total++; + } + } - for( final IGridNode gn : this.grid.getMachines( PartInterface.class ) ) - { - if( gn.isActive() ) - { - final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - if( ih.getInterfaceDuality().getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.NO ) - { - continue; - } + for (final IGridNode gn : this.grid.getMachines(PartInterface.class)) { + if (gn.isActive()) { + final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + if (ih.getInterfaceDuality().getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) == YesNo.NO) { + continue; + } - final ConfigTracker t = this.diList.get( ih ); + final ConfigTracker t = this.diList.get(ih); - if( t == null ) - { - missing = true; - } - else - { - final DualityInterface dual = ih.getInterfaceDuality(); - if( !t.unlocalizedName.equals( dual.getTermName() ) ) - { - missing = true; - } - } + if (t == null) { + missing = true; + } else { + final DualityInterface dual = ih.getInterfaceDuality(); + if (!t.unlocalizedName.equals(dual.getTermName())) { + missing = true; + } + } - total++; - } - } - } - } + total++; + } + } + } + } - if( total != this.diList.size() || missing ) - { - this.regenList( this.data ); - } - else - { - for( final Entry en : this.diList.entrySet() ) - { - final ConfigTracker inv = en.getValue(); - for( int x = 0; x < inv.server.getSlots(); x++ ) - { - if( this.isDifferent( inv.server.getStackInSlot( x ), inv.client.getStackInSlot( x ) ) ) - { - this.addItems( this.data, inv, x, 1 ); - } - } - } - } + if (total != this.diList.size() || missing) { + this.regenList(this.data); + } else { + for (final Entry en : this.diList.entrySet()) { + final ConfigTracker inv = en.getValue(); + for (int x = 0; x < inv.server.getSlots(); x++) { + if (this.isDifferent(inv.server.getStackInSlot(x), inv.client.getStackInSlot(x))) { + this.addItems(this.data, inv, x, 1); + } + } + } + } - if( !this.data.hasNoTags() ) - { - try - { - NetworkHandler.instance().sendTo( new PacketCompressedNBT( this.data ), (EntityPlayerMP) this.getPlayerInv().player ); - } - catch( final IOException e ) - { - // :P - } + if (!this.data.hasNoTags()) { + try { + NetworkHandler.instance().sendTo(new PacketCompressedNBT(this.data), (EntityPlayerMP) this.getPlayerInv().player); + } catch (final IOException e) { + // :P + } - this.data = new NBTTagCompound(); - } - } + this.data = new NBTTagCompound(); + } + } - public ConfigTracker getSlotByID( long id ) - { - return this.byId.get( id ); - } + public ConfigTracker getSlotByID(long id) { + return this.byId.get(id); + } - @Override - public void doAction( final EntityPlayerMP player, final InventoryAction action, final int slot, final long id ) - { - final ConfigTracker inv = this.byId.get( id ); - if( inv != null ) - { - final boolean hasItemInHand = !player.inventory.getItemStack().isEmpty(); - final IItemHandler theSlot = new WrapperRangeItemHandler( inv.server, slot, slot + 1 ); + @Override + public void doAction(final EntityPlayerMP player, final InventoryAction action, final int slot, final long id) { + final ConfigTracker inv = this.byId.get(id); + if (inv != null) { + final boolean hasItemInHand = !player.inventory.getItemStack().isEmpty(); + final IItemHandler theSlot = new WrapperRangeItemHandler(inv.server, slot, slot + 1); - ItemStack inSlot = theSlot.getStackInSlot( 0 ); + ItemStack inSlot = theSlot.getStackInSlot(0); - switch ( action ) - { - case PICKUP_OR_SET_DOWN: - if( hasItemInHand ) - { - ItemHandlerUtil.setStackInSlot( theSlot, 0, player.inventory.getItemStack().copy() ); - } - else - { - ItemHandlerUtil.setStackInSlot( theSlot, 0, ItemStack.EMPTY ); - } - break; - case PLACE_SINGLE: - if( inSlot.getMaxStackSize() > inSlot.getCount() ) - { - inSlot.grow( 1 ); - ItemHandlerUtil.setStackInSlot( theSlot, 0, inSlot ); - } - break; - case PICKUP_SINGLE: - if( theSlot.getStackInSlot( 0 ).getCount() > 1 ) - { - inSlot.shrink( 1 ); - ItemHandlerUtil.setStackInSlot( theSlot, 0, inSlot ); - } - break; - case SPLIT_OR_PLACE_SINGLE: - if( hasItemInHand ) - { - if( ItemStack.areItemsEqual( inSlot, player.inventory.getItemStack() ) && ItemStack.areItemStackTagsEqual( inSlot, player.inventory.getItemStack() ) ) - { - inSlot.grow( 1 ); - ItemHandlerUtil.setStackInSlot( theSlot, 0, inSlot.copy() ); - } - else - { - ItemStack configuredStack = player.inventory.getItemStack().copy(); - configuredStack.setCount( 1 ); - ItemHandlerUtil.setStackInSlot( theSlot, 0, configuredStack ); - } + switch (action) { + case PICKUP_OR_SET_DOWN: + if (hasItemInHand) { + ItemHandlerUtil.setStackInSlot(theSlot, 0, player.inventory.getItemStack().copy()); + } else { + ItemHandlerUtil.setStackInSlot(theSlot, 0, ItemStack.EMPTY); + } + break; + case PLACE_SINGLE: + if (inSlot.getMaxStackSize() > inSlot.getCount()) { + inSlot.grow(1); + ItemHandlerUtil.setStackInSlot(theSlot, 0, inSlot); + } + break; + case PICKUP_SINGLE: + if (theSlot.getStackInSlot(0).getCount() > 1) { + inSlot.shrink(1); + ItemHandlerUtil.setStackInSlot(theSlot, 0, inSlot); + } + break; + case SPLIT_OR_PLACE_SINGLE: + if (hasItemInHand) { + if (ItemStack.areItemsEqual(inSlot, player.inventory.getItemStack()) && ItemStack.areItemStackTagsEqual(inSlot, player.inventory.getItemStack())) { + inSlot.grow(1); + ItemHandlerUtil.setStackInSlot(theSlot, 0, inSlot.copy()); + } else { + ItemStack configuredStack = player.inventory.getItemStack().copy(); + configuredStack.setCount(1); + ItemHandlerUtil.setStackInSlot(theSlot, 0, configuredStack); + } - } - else if( !inSlot.isEmpty() ) - { - inSlot.shrink( 1 ); - ItemHandlerUtil.setStackInSlot( theSlot, 0, inSlot.copy() ); - } + } else if (!inSlot.isEmpty()) { + inSlot.shrink(1); + ItemHandlerUtil.setStackInSlot(theSlot, 0, inSlot.copy()); + } - break; - case SHIFT_CLICK: - ItemHandlerUtil.setStackInSlot( theSlot, 0, ItemStack.EMPTY ); - break; + break; + case SHIFT_CLICK: + ItemHandlerUtil.setStackInSlot(theSlot, 0, ItemStack.EMPTY); + break; - case CREATIVE_DUPLICATE: + case CREATIVE_DUPLICATE: - if( player.capabilities.isCreativeMode && hasItemInHand ) - { - ItemHandlerUtil.setStackInSlot( theSlot, 0, player.inventory.getItemStack().copy() ); - } + if (player.capabilities.isCreativeMode && hasItemInHand) { + ItemHandlerUtil.setStackInSlot(theSlot, 0, player.inventory.getItemStack().copy()); + } - break; - default: - return; - } + break; + default: + return; + } - this.updateHeld( player ); - } - } + this.updateHeld(player); + } + } - private void regenList( final NBTTagCompound data ) - { - this.byId.clear(); - this.diList.clear(); + private void regenList(final NBTTagCompound data) { + this.byId.clear(); + this.diList.clear(); - final IActionHost host = this.getActionHost(); - if( host != null ) - { - final IGridNode agn = host.getActionableNode(); - if( agn != null && agn.isActive() ) - { - for( final IGridNode gn : this.grid.getMachines( TileInterface.class ) ) - { - final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - final DualityInterface dual = ih.getInterfaceDuality(); - if( gn.isActive() && dual.getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.YES ) - { - this.diList.put( ih, new ConfigTracker( dual, dual.getConfig(), dual.getTermName() ) ); - } - } + final IActionHost host = this.getActionHost(); + if (host != null) { + final IGridNode agn = host.getActionableNode(); + if (agn != null && agn.isActive()) { + for (final IGridNode gn : this.grid.getMachines(TileInterface.class)) { + final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + final DualityInterface dual = ih.getInterfaceDuality(); + if (gn.isActive() && dual.getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) == YesNo.YES) { + this.diList.put(ih, new ConfigTracker(dual, dual.getConfig(), dual.getTermName())); + } + } - for( final IGridNode gn : this.grid.getMachines( PartInterface.class ) ) - { - final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - final DualityInterface dual = ih.getInterfaceDuality(); - if( gn.isActive() && dual.getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.YES ) - { - this.diList.put( ih, new ConfigTracker( dual, dual.getConfig(), dual.getTermName() ) ); - } - } - } - } + for (final IGridNode gn : this.grid.getMachines(PartInterface.class)) { + final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + final DualityInterface dual = ih.getInterfaceDuality(); + if (gn.isActive() && dual.getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) == YesNo.YES) { + this.diList.put(ih, new ConfigTracker(dual, dual.getConfig(), dual.getTermName())); + } + } + } + } - data.setBoolean( "clear", true ); + data.setBoolean("clear", true); - for( final Entry en : this.diList.entrySet() ) - { - final ConfigTracker inv = en.getValue(); - this.byId.put( inv.which, inv ); - this.addItems( data, inv, 0, inv.server.getSlots() ); - } - } + for (final Entry en : this.diList.entrySet()) { + final ConfigTracker inv = en.getValue(); + this.byId.put(inv.which, inv); + this.addItems(data, inv, 0, inv.server.getSlots()); + } + } - private boolean isDifferent( final ItemStack a, final ItemStack b ) - { - if( a.isEmpty() && b.isEmpty() ) - { - return false; - } + private boolean isDifferent(final ItemStack a, final ItemStack b) { + if (a.isEmpty() && b.isEmpty()) { + return false; + } - if( a.isEmpty() || b.isEmpty() ) - { - return true; - } + if (a.isEmpty() || b.isEmpty()) { + return true; + } - return !ItemStack.areItemStacksEqual( a, b ); - } + return !ItemStack.areItemStacksEqual(a, b); + } - private void addItems( final NBTTagCompound data, final ConfigTracker inv, final int offset, final int length ) - { - final String name = '=' + Long.toString( inv.which, Character.MAX_RADIX ); - final NBTTagCompound tag = data.getCompoundTag( name ); + private void addItems(final NBTTagCompound data, final ConfigTracker inv, final int offset, final int length) { + final String name = '=' + Long.toString(inv.which, Character.MAX_RADIX); + final NBTTagCompound tag = data.getCompoundTag(name); - if( tag.hasNoTags() ) - { - tag.setLong( "sortBy", inv.sortBy ); - tag.setString( "un", inv.unlocalizedName ); - tag.setTag( "pos", NBTUtil.createPosTag( inv.pos ) ); - tag.setInteger( "dim", inv.dim ); - } + if (tag.hasNoTags()) { + tag.setLong("sortBy", inv.sortBy); + tag.setString("un", inv.unlocalizedName); + tag.setTag("pos", NBTUtil.createPosTag(inv.pos)); + tag.setInteger("dim", inv.dim); + } - for( int x = 0; x < length; x++ ) - { - final NBTTagCompound itemNBT = new NBTTagCompound(); + for (int x = 0; x < length; x++) { + final NBTTagCompound itemNBT = new NBTTagCompound(); - final ItemStack is = inv.server.getStackInSlot( x + offset ); + final ItemStack is = inv.server.getStackInSlot(x + offset); - // "update" client side. - ItemHandlerUtil.setStackInSlot( inv.client, x + offset, is.isEmpty() ? ItemStack.EMPTY : is.copy() ); + // "update" client side. + ItemHandlerUtil.setStackInSlot(inv.client, x + offset, is.isEmpty() ? ItemStack.EMPTY : is.copy()); - if( !is.isEmpty() ) - { - is.writeToNBT( itemNBT ); - } + if (!is.isEmpty()) { + is.writeToNBT(itemNBT); + } - tag.setTag( Integer.toString( x + offset ), itemNBT ); - } + tag.setTag(Integer.toString(x + offset), itemNBT); + } - data.setTag( name, tag ); - } + data.setTag(name, tag); + } - public static class ConfigTracker - { + public static class ConfigTracker { - private final long sortBy; - private final long which = autoBase++; - private final String unlocalizedName; - private final IItemHandler client; - private final IItemHandler server; - private final BlockPos pos; - private final int dim; + private final long sortBy; + private final long which = autoBase++; + private final String unlocalizedName; + private final IItemHandler client; + private final IItemHandler server; + private final BlockPos pos; + private final int dim; - public ConfigTracker( final DualityInterface dual, final IItemHandler configSlots, final String unlocalizedName ) - { - this.server = configSlots; - this.client = new AppEngInternalInventory( null, this.server.getSlots() ); - this.unlocalizedName = unlocalizedName; - this.sortBy = dual.getSortValue(); - this.pos = dual.getLocation().getPos(); - this.dim = dual.getLocation().getWorld().provider.getDimension(); - } + public ConfigTracker(final DualityInterface dual, final IItemHandler configSlots, final String unlocalizedName) { + this.server = configSlots; + this.client = new AppEngInternalInventory(null, this.server.getSlots()); + this.unlocalizedName = unlocalizedName; + this.sortBy = dual.getSortValue(); + this.pos = dual.getLocation().getPos(); + this.dim = dual.getLocation().getWorld().provider.getDimension(); + } - public IItemHandler getServer() - { - return server; - } - } + public IItemHandler getServer() { + return server; + } + } } diff --git a/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java b/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java index a9ce85fac..ddab57923 100644 --- a/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java +++ b/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java @@ -19,21 +19,8 @@ package appeng.container.implementations; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -import appeng.api.config.Upgrades; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTUtil; -import net.minecraft.util.math.BlockPos; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.Settings; +import appeng.api.config.Upgrades; import appeng.api.config.YesNo; import appeng.api.networking.IGrid; import appeng.api.networking.IGridNode; @@ -57,414 +44,347 @@ import appeng.util.inv.WrapperCursorItemHandler; import appeng.util.inv.WrapperFilteredItemHandler; import appeng.util.inv.WrapperRangeItemHandler; import appeng.util.inv.filter.IAEItemFilter; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTUtil; +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.items.IItemHandler; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; -public final class ContainerInterfaceTerminal extends AEBaseContainer -{ +public final class ContainerInterfaceTerminal extends AEBaseContainer { - /** - * this stuff is all server side.. - */ + /** + * this stuff is all server side.. + */ - private static long autoBase = Long.MIN_VALUE; - private final Map diList = new HashMap<>(); - private final Map byId = new HashMap<>(); - private IGrid grid; - private NBTTagCompound data = new NBTTagCompound(); + private static long autoBase = Long.MIN_VALUE; + private final Map diList = new HashMap<>(); + private final Map byId = new HashMap<>(); + private IGrid grid; + private NBTTagCompound data = new NBTTagCompound(); - public ContainerInterfaceTerminal( final InventoryPlayer ip, final PartInterfaceTerminal anchor ) - { - super( ip, anchor ); + public ContainerInterfaceTerminal(final InventoryPlayer ip, final PartInterfaceTerminal anchor) { + super(ip, anchor); - if( Platform.isServer() ) - { - this.grid = anchor.getActionableNode().getGrid(); - } + if (Platform.isServer()) { + this.grid = anchor.getActionableNode().getGrid(); + } - this.bindPlayerInventory( ip, 14, 256 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 14, 256 - /* height of player inventory */82); + } - @Override - public void detectAndSendChanges() - { - if( Platform.isClient() ) - { - return; - } + @Override + public void detectAndSendChanges() { + if (Platform.isClient()) { + return; + } - super.detectAndSendChanges(); + super.detectAndSendChanges(); - if( this.grid == null ) - { - return; - } + if (this.grid == null) { + return; + } - int total = 0; - boolean missing = false; + int total = 0; + boolean missing = false; - final IActionHost host = this.getActionHost(); - if( host != null ) - { - final IGridNode agn = host.getActionableNode(); - if( agn != null && agn.isActive() ) - { - for( final IGridNode gn : this.grid.getMachines( TileInterface.class ) ) - { - if( gn.isActive() ) - { - final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - if( ih.getInterfaceDuality().getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.NO ) - { - continue; - } + final IActionHost host = this.getActionHost(); + if (host != null) { + final IGridNode agn = host.getActionableNode(); + if (agn != null && agn.isActive()) { + for (final IGridNode gn : this.grid.getMachines(TileInterface.class)) { + if (gn.isActive()) { + final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + if (ih.getInterfaceDuality().getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) == YesNo.NO) { + continue; + } - final InvTracker t = this.diList.get( ih ); + final InvTracker t = this.diList.get(ih); - if( t == null ) - { - missing = true; - } - else - { - final DualityInterface dual = ih.getInterfaceDuality(); - if( !t.unlocalizedName.equals( dual.getTermName() ) ) - { - missing = true; - } - } + if (t == null) { + missing = true; + } else { + final DualityInterface dual = ih.getInterfaceDuality(); + if (!t.unlocalizedName.equals(dual.getTermName())) { + missing = true; + } + } - total++; - } - } + total++; + } + } - for( final IGridNode gn : this.grid.getMachines( PartInterface.class ) ) - { - if( gn.isActive() ) - { - final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - if( ih.getInterfaceDuality().getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.NO ) - { - continue; - } + for (final IGridNode gn : this.grid.getMachines(PartInterface.class)) { + if (gn.isActive()) { + final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + if (ih.getInterfaceDuality().getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) == YesNo.NO) { + continue; + } - final InvTracker t = this.diList.get( ih ); + final InvTracker t = this.diList.get(ih); - if( t == null ) - { - missing = true; - } - else - { - final DualityInterface dual = ih.getInterfaceDuality(); - if( !t.unlocalizedName.equals( dual.getTermName() ) ) - { - missing = true; - } - } + if (t == null) { + missing = true; + } else { + final DualityInterface dual = ih.getInterfaceDuality(); + if (!t.unlocalizedName.equals(dual.getTermName())) { + missing = true; + } + } - total++; - } - } - } - } + total++; + } + } + } + } - if( total != this.diList.size() || missing ) - { - this.regenList( this.data ); - } - else - { - for( final Entry en : this.diList.entrySet() ) - { - final InvTracker inv = en.getValue(); - for( int x = 0; x < inv.server.getSlots(); x++ ) - { - if( this.isDifferent( inv.server.getStackInSlot( x ), inv.client.getStackInSlot( x ) ) ) - { - this.addItems( this.data, inv, x, 1 ); - } - } - } - } + if (total != this.diList.size() || missing) { + this.regenList(this.data); + } else { + for (final Entry en : this.diList.entrySet()) { + final InvTracker inv = en.getValue(); + for (int x = 0; x < inv.server.getSlots(); x++) { + if (this.isDifferent(inv.server.getStackInSlot(x), inv.client.getStackInSlot(x))) { + this.addItems(this.data, inv, x, 1); + } + } + } + } - if( !this.data.hasNoTags() ) - { - try - { - NetworkHandler.instance().sendTo( new PacketCompressedNBT( this.data ), (EntityPlayerMP) this.getPlayerInv().player ); - } - catch( final IOException e ) - { - // :P - } + if (!this.data.hasNoTags()) { + try { + NetworkHandler.instance().sendTo(new PacketCompressedNBT(this.data), (EntityPlayerMP) this.getPlayerInv().player); + } catch (final IOException e) { + // :P + } - this.data = new NBTTagCompound(); - } - } + this.data = new NBTTagCompound(); + } + } - @Override - public void doAction( final EntityPlayerMP player, final InventoryAction action, final int slot, final long id ) - { - final InvTracker inv = this.byId.get( id ); - if( inv != null ) - { - final ItemStack is = inv.server.getStackInSlot( slot ); - final boolean hasItemInHand = !player.inventory.getItemStack().isEmpty(); + @Override + public void doAction(final EntityPlayerMP player, final InventoryAction action, final int slot, final long id) { + final InvTracker inv = this.byId.get(id); + if (inv != null) { + final ItemStack is = inv.server.getStackInSlot(slot); + final boolean hasItemInHand = !player.inventory.getItemStack().isEmpty(); - final InventoryAdaptor playerHand = new AdaptorItemHandler( new WrapperCursorItemHandler( player.inventory ) ); + final InventoryAdaptor playerHand = new AdaptorItemHandler(new WrapperCursorItemHandler(player.inventory)); - final IItemHandler theSlot = new WrapperFilteredItemHandler( new WrapperRangeItemHandler( inv.server, slot, slot + 1 ), new PatternSlotFilter() ); - final InventoryAdaptor interfaceSlot = new AdaptorItemHandler( theSlot ); + final IItemHandler theSlot = new WrapperFilteredItemHandler(new WrapperRangeItemHandler(inv.server, slot, slot + 1), new PatternSlotFilter()); + final InventoryAdaptor interfaceSlot = new AdaptorItemHandler(theSlot); - IItemHandler interfaceHandler = inv.server; - boolean canInsert = true; + IItemHandler interfaceHandler = inv.server; + boolean canInsert = true; - switch ( action ) - { - case PICKUP_OR_SET_DOWN: - if( hasItemInHand ) - { - for( int s = 0; s < interfaceHandler.getSlots(); s++ ) - { - if( Platform.itemComparisons().isSameItem( interfaceHandler.getStackInSlot( s ), player.inventory.getItemStack() ) ) - { - canInsert = false; - break; - } - } - if( canInsert ) - { - ItemStack inSlot = theSlot.getStackInSlot( 0 ); - if( inSlot.isEmpty() ) - { - player.inventory.setItemStack( interfaceSlot.addItems( player.inventory.getItemStack() ) ); - } - else - { - inSlot = inSlot.copy(); - final ItemStack inHand = player.inventory.getItemStack().copy(); + switch (action) { + case PICKUP_OR_SET_DOWN: + if (hasItemInHand) { + for (int s = 0; s < interfaceHandler.getSlots(); s++) { + if (Platform.itemComparisons().isSameItem(interfaceHandler.getStackInSlot(s), player.inventory.getItemStack())) { + canInsert = false; + break; + } + } + if (canInsert) { + ItemStack inSlot = theSlot.getStackInSlot(0); + if (inSlot.isEmpty()) { + player.inventory.setItemStack(interfaceSlot.addItems(player.inventory.getItemStack())); + } else { + inSlot = inSlot.copy(); + final ItemStack inHand = player.inventory.getItemStack().copy(); - ItemHandlerUtil.setStackInSlot( theSlot, 0, ItemStack.EMPTY ); - player.inventory.setItemStack( ItemStack.EMPTY ); + ItemHandlerUtil.setStackInSlot(theSlot, 0, ItemStack.EMPTY); + player.inventory.setItemStack(ItemStack.EMPTY); - player.inventory.setItemStack( interfaceSlot.addItems( inHand.copy() ) ); + player.inventory.setItemStack(interfaceSlot.addItems(inHand.copy())); - if( player.inventory.getItemStack().isEmpty() ) - { - player.inventory.setItemStack( inSlot ); - } - else - { - player.inventory.setItemStack( inHand ); - ItemHandlerUtil.setStackInSlot( theSlot, 0, inSlot ); - } - } - } - } - else - { - ItemHandlerUtil.setStackInSlot( theSlot, 0, playerHand.addItems( theSlot.getStackInSlot( 0 ) ) ); - } + if (player.inventory.getItemStack().isEmpty()) { + player.inventory.setItemStack(inSlot); + } else { + player.inventory.setItemStack(inHand); + ItemHandlerUtil.setStackInSlot(theSlot, 0, inSlot); + } + } + } + } else { + ItemHandlerUtil.setStackInSlot(theSlot, 0, playerHand.addItems(theSlot.getStackInSlot(0))); + } - break; - case SPLIT_OR_PLACE_SINGLE: - if( hasItemInHand ) - { - for( int s = 0; s < interfaceHandler.getSlots(); s++ ) - { - if( Platform.itemComparisons().isSameItem( interfaceHandler.getStackInSlot( s ), player.inventory.getItemStack() ) ) - { - canInsert = false; - break; - } - } - if( canInsert ) - { - ItemStack extra = playerHand.removeItems( 1, ItemStack.EMPTY, null ); - if( !extra.isEmpty() && !interfaceSlot.containsItems() ) - { - extra = interfaceSlot.addItems( extra ); - } - if( !extra.isEmpty() ) - { - playerHand.addItems( extra ); - } - } - } - else if( !is.isEmpty() ) - { - ItemStack extra = interfaceSlot.removeItems( ( is.getCount() + 1 ) / 2, ItemStack.EMPTY, null ); - if( !extra.isEmpty() ) - { - extra = playerHand.addItems( extra ); - } - if( !extra.isEmpty() ) - { - interfaceSlot.addItems( extra ); - } - } + break; + case SPLIT_OR_PLACE_SINGLE: + if (hasItemInHand) { + for (int s = 0; s < interfaceHandler.getSlots(); s++) { + if (Platform.itemComparisons().isSameItem(interfaceHandler.getStackInSlot(s), player.inventory.getItemStack())) { + canInsert = false; + break; + } + } + if (canInsert) { + ItemStack extra = playerHand.removeItems(1, ItemStack.EMPTY, null); + if (!extra.isEmpty() && !interfaceSlot.containsItems()) { + extra = interfaceSlot.addItems(extra); + } + if (!extra.isEmpty()) { + playerHand.addItems(extra); + } + } + } else if (!is.isEmpty()) { + ItemStack extra = interfaceSlot.removeItems((is.getCount() + 1) / 2, ItemStack.EMPTY, null); + if (!extra.isEmpty()) { + extra = playerHand.addItems(extra); + } + if (!extra.isEmpty()) { + interfaceSlot.addItems(extra); + } + } - break; - case SHIFT_CLICK: + break; + case SHIFT_CLICK: - final InventoryAdaptor playerInv = InventoryAdaptor.getAdaptor( player ); + final InventoryAdaptor playerInv = InventoryAdaptor.getAdaptor(player); - ItemHandlerUtil.setStackInSlot( theSlot, 0, playerInv.addItems( theSlot.getStackInSlot( 0 ) ) ); + ItemHandlerUtil.setStackInSlot(theSlot, 0, playerInv.addItems(theSlot.getStackInSlot(0))); - break; - case MOVE_REGION: + break; + case MOVE_REGION: - final InventoryAdaptor playerInvAd = InventoryAdaptor.getAdaptor( player ); - for( int x = 0; x < inv.server.getSlots(); x++ ) - { - ItemHandlerUtil.setStackInSlot( inv.server, x, playerInvAd.addItems( inv.server.getStackInSlot( x ) ) ); - } + final InventoryAdaptor playerInvAd = InventoryAdaptor.getAdaptor(player); + for (int x = 0; x < inv.server.getSlots(); x++) { + ItemHandlerUtil.setStackInSlot(inv.server, x, playerInvAd.addItems(inv.server.getStackInSlot(x))); + } - break; - case CREATIVE_DUPLICATE: + break; + case CREATIVE_DUPLICATE: - if( player.capabilities.isCreativeMode && !hasItemInHand ) - { - player.inventory.setItemStack( is.isEmpty() ? ItemStack.EMPTY : is.copy() ); - } + if (player.capabilities.isCreativeMode && !hasItemInHand) { + player.inventory.setItemStack(is.isEmpty() ? ItemStack.EMPTY : is.copy()); + } - break; - default: - return; - } + break; + default: + return; + } - this.updateHeld( player ); - } - } + this.updateHeld(player); + } + } - private void regenList( final NBTTagCompound data ) - { - this.byId.clear(); - this.diList.clear(); + private void regenList(final NBTTagCompound data) { + this.byId.clear(); + this.diList.clear(); - final IActionHost host = this.getActionHost(); - if( host != null ) - { - final IGridNode agn = host.getActionableNode(); - if( agn != null && agn.isActive() ) - { - for( final IGridNode gn : this.grid.getMachines( TileInterface.class ) ) - { - final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - final DualityInterface dual = ih.getInterfaceDuality(); - if( gn.isActive() && dual.getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.YES ) - { - this.diList.put( ih, new InvTracker( dual, dual.getPatterns(), dual.getTermName() ) ); - } - } + final IActionHost host = this.getActionHost(); + if (host != null) { + final IGridNode agn = host.getActionableNode(); + if (agn != null && agn.isActive()) { + for (final IGridNode gn : this.grid.getMachines(TileInterface.class)) { + final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + final DualityInterface dual = ih.getInterfaceDuality(); + if (gn.isActive() && dual.getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) == YesNo.YES) { + this.diList.put(ih, new InvTracker(dual, dual.getPatterns(), dual.getTermName())); + } + } - for( final IGridNode gn : this.grid.getMachines( PartInterface.class ) ) - { - final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - final DualityInterface dual = ih.getInterfaceDuality(); - if( gn.isActive() && dual.getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.YES ) - { - this.diList.put( ih, new InvTracker( dual, dual.getPatterns(), dual.getTermName() ) ); - } - } - } - } + for (final IGridNode gn : this.grid.getMachines(PartInterface.class)) { + final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + final DualityInterface dual = ih.getInterfaceDuality(); + if (gn.isActive() && dual.getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) == YesNo.YES) { + this.diList.put(ih, new InvTracker(dual, dual.getPatterns(), dual.getTermName())); + } + } + } + } - data.setBoolean( "clear", true ); + data.setBoolean("clear", true); - for( final Entry en : this.diList.entrySet() ) - { - final InvTracker inv = en.getValue(); - this.byId.put( inv.which, inv ); - this.addItems( data, inv, 0, inv.server.getSlots() ); - } - } + for (final Entry en : this.diList.entrySet()) { + final InvTracker inv = en.getValue(); + this.byId.put(inv.which, inv); + this.addItems(data, inv, 0, inv.server.getSlots()); + } + } - private boolean isDifferent( final ItemStack a, final ItemStack b ) - { - if( a.isEmpty() && b.isEmpty() ) - { - return false; - } + private boolean isDifferent(final ItemStack a, final ItemStack b) { + if (a.isEmpty() && b.isEmpty()) { + return false; + } - if( a.isEmpty() || b.isEmpty() ) - { - return true; - } + if (a.isEmpty() || b.isEmpty()) { + return true; + } - return !ItemStack.areItemStacksEqual( a, b ); - } + return !ItemStack.areItemStacksEqual(a, b); + } - private void addItems( final NBTTagCompound data, final InvTracker inv, final int offset, final int length ) - { - final String name = '=' + Long.toString( inv.which, Character.MAX_RADIX ); - final NBTTagCompound tag = data.getCompoundTag( name ); + private void addItems(final NBTTagCompound data, final InvTracker inv, final int offset, final int length) { + final String name = '=' + Long.toString(inv.which, Character.MAX_RADIX); + final NBTTagCompound tag = data.getCompoundTag(name); - if( tag.hasNoTags() ) - { - tag.setLong( "sortBy", inv.sortBy ); - tag.setString( "un", inv.unlocalizedName ); - tag.setTag( "pos", NBTUtil.createPosTag( inv.pos ) ); - tag.setInteger( "dim", inv.dim ); - tag.setInteger( "numUpgrades", inv.numUpgrades ); - } + if (tag.hasNoTags()) { + tag.setLong("sortBy", inv.sortBy); + tag.setString("un", inv.unlocalizedName); + tag.setTag("pos", NBTUtil.createPosTag(inv.pos)); + tag.setInteger("dim", inv.dim); + tag.setInteger("numUpgrades", inv.numUpgrades); + } - for( int x = 0; x < length; x++ ) - { - final NBTTagCompound itemNBT = new NBTTagCompound(); + for (int x = 0; x < length; x++) { + final NBTTagCompound itemNBT = new NBTTagCompound(); - final ItemStack is = inv.server.getStackInSlot( x + offset ); + final ItemStack is = inv.server.getStackInSlot(x + offset); - // "update" client side. - ItemHandlerUtil.setStackInSlot( inv.client, x + offset, is.isEmpty() ? ItemStack.EMPTY : is.copy() ); + // "update" client side. + ItemHandlerUtil.setStackInSlot(inv.client, x + offset, is.isEmpty() ? ItemStack.EMPTY : is.copy()); - if( !is.isEmpty() ) - { - is.writeToNBT( itemNBT ); - } + if (!is.isEmpty()) { + is.writeToNBT(itemNBT); + } - tag.setTag( Integer.toString( x + offset ), itemNBT ); - } + tag.setTag(Integer.toString(x + offset), itemNBT); + } - data.setTag( name, tag ); - } + data.setTag(name, tag); + } - private static class InvTracker - { + private static class InvTracker { - private final long sortBy; - private final long which = autoBase++; - private final String unlocalizedName; - private final IItemHandler client; - private final IItemHandler server; - private final BlockPos pos; - private final int dim; - private final int numUpgrades; + private final long sortBy; + private final long which = autoBase++; + private final String unlocalizedName; + private final IItemHandler client; + private final IItemHandler server; + private final BlockPos pos; + private final int dim; + private final int numUpgrades; - public InvTracker( final DualityInterface dual, final IItemHandler patterns, final String unlocalizedName ) - { - this.server = patterns; - this.client = new AppEngInternalInventory( null, this.server.getSlots() ); - this.unlocalizedName = unlocalizedName; - this.sortBy = dual.getSortValue(); - this.pos = dual.getLocation().getPos(); - this.dim = dual.getLocation().getWorld().provider.getDimension(); - this.numUpgrades = dual.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION); - } - } + public InvTracker(final DualityInterface dual, final IItemHandler patterns, final String unlocalizedName) { + this.server = patterns; + this.client = new AppEngInternalInventory(null, this.server.getSlots()); + this.unlocalizedName = unlocalizedName; + this.sortBy = dual.getSortValue(); + this.pos = dual.getLocation().getPos(); + this.dim = dual.getLocation().getWorld().provider.getDimension(); + this.numUpgrades = dual.getInstalledUpgrades(Upgrades.PATTERN_EXPANSION); + } + } - private static class PatternSlotFilter implements IAEItemFilter - { - @Override - public boolean allowExtract( IItemHandler inv, int slot, int amount ) - { - return true; - } + private static class PatternSlotFilter implements IAEItemFilter { + @Override + public boolean allowExtract(IItemHandler inv, int slot, int amount) { + return true; + } - @Override - public boolean allowInsert( IItemHandler inv, int slot, ItemStack stack ) - { - return !stack.isEmpty() && stack.getItem() instanceof ItemEncodedPattern; - } - } + @Override + public boolean allowInsert(IItemHandler inv, int slot, ItemStack stack) { + return !stack.isEmpty() && stack.getItem() instanceof ItemEncodedPattern; + } + } } diff --git a/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java b/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java index 93903bbcd..8034b57d0 100644 --- a/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java +++ b/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java @@ -19,6 +19,12 @@ package appeng.container.implementations; +import appeng.api.config.*; +import appeng.container.guisync.GuiSync; +import appeng.container.slot.SlotFakeTypeOnly; +import appeng.container.slot.SlotRestrictedInput; +import appeng.parts.automation.PartLevelEmitter; +import appeng.util.Platform; import net.minecraft.client.gui.GuiTextField; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; @@ -26,148 +32,116 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.IItemHandler; -import appeng.api.config.FuzzyMode; -import appeng.api.config.LevelType; -import appeng.api.config.RedstoneMode; -import appeng.api.config.SecurityPermissions; -import appeng.api.config.Settings; -import appeng.api.config.YesNo; -import appeng.container.guisync.GuiSync; -import appeng.container.slot.SlotFakeTypeOnly; -import appeng.container.slot.SlotRestrictedInput; -import appeng.parts.automation.PartLevelEmitter; -import appeng.util.Platform; +public class ContainerLevelEmitter extends ContainerUpgradeable { -public class ContainerLevelEmitter extends ContainerUpgradeable -{ + private final PartLevelEmitter lvlEmitter; - private final PartLevelEmitter lvlEmitter; + @SideOnly(Side.CLIENT) + private GuiTextField textField; + @GuiSync(2) + public LevelType lvType; + @GuiSync(3) + public long EmitterValue = -1; + @GuiSync(4) + public YesNo cmType; - @SideOnly( Side.CLIENT ) - private GuiTextField textField; - @GuiSync( 2 ) - public LevelType lvType; - @GuiSync( 3 ) - public long EmitterValue = -1; - @GuiSync( 4 ) - public YesNo cmType; + public ContainerLevelEmitter(final InventoryPlayer ip, final PartLevelEmitter te) { + super(ip, te); + this.lvlEmitter = te; + } - public ContainerLevelEmitter( final InventoryPlayer ip, final PartLevelEmitter te ) - { - super( ip, te ); - this.lvlEmitter = te; - } + @SideOnly(Side.CLIENT) + public void setTextField(final GuiTextField level) { + this.textField = level; + this.textField.setText(String.valueOf(this.EmitterValue)); + } - @SideOnly( Side.CLIENT ) - public void setTextField( final GuiTextField level ) - { - this.textField = level; - this.textField.setText( String.valueOf( this.EmitterValue ) ); - } + public void setLevel(final long l, final EntityPlayer player) { + this.lvlEmitter.setReportingValue(l); + this.EmitterValue = l; + } - public void setLevel( final long l, final EntityPlayer player ) - { - this.lvlEmitter.setReportingValue( l ); - this.EmitterValue = l; - } + @Override + protected void setupConfig() { + final IItemHandler upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + if (this.availableUpgrades() > 0) { + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer())) + .setNotDraggable()); + } + if (this.availableUpgrades() > 1) { + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer())) + .setNotDraggable()); + } + if (this.availableUpgrades() > 2) { + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer())) + .setNotDraggable()); + } + if (this.availableUpgrades() > 3) { + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer())) + .setNotDraggable()); + } - @Override - protected void setupConfig() - { - final IItemHandler upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - if( this.availableUpgrades() > 0 ) - { - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } - if( this.availableUpgrades() > 1 ) - { - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } - if( this.availableUpgrades() > 2 ) - { - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } - if( this.availableUpgrades() > 3 ) - { - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } + final IItemHandler inv = this.getUpgradeable().getInventoryByName("config"); + final int y = 40; + final int x = 80 + 44; + this.addSlotToContainer(new SlotFakeTypeOnly(inv, 0, x, y)); + } - final IItemHandler inv = this.getUpgradeable().getInventoryByName( "config" ); - final int y = 40; - final int x = 80 + 44; - this.addSlotToContainer( new SlotFakeTypeOnly( inv, 0, x, y ) ); - } + @Override + protected boolean supportCapacity() { + return false; + } - @Override - protected boolean supportCapacity() - { - return false; - } + @Override + public int availableUpgrades() { - @Override - public int availableUpgrades() - { + return 1; + } - return 1; - } + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + if (Platform.isServer()) { + this.EmitterValue = this.lvlEmitter.getReportingValue(); + this.setCraftingMode((YesNo) this.getUpgradeable().getConfigManager().getSetting(Settings.CRAFT_VIA_REDSTONE)); + this.setLevelMode((LevelType) this.getUpgradeable().getConfigManager().getSetting(Settings.LEVEL_TYPE)); + this.setFuzzyMode((FuzzyMode) this.getUpgradeable().getConfigManager().getSetting(Settings.FUZZY_MODE)); + this.setRedStoneMode((RedstoneMode) this.getUpgradeable().getConfigManager().getSetting(Settings.REDSTONE_EMITTER)); + } - if( Platform.isServer() ) - { - this.EmitterValue = this.lvlEmitter.getReportingValue(); - this.setCraftingMode( (YesNo) this.getUpgradeable().getConfigManager().getSetting( Settings.CRAFT_VIA_REDSTONE ) ); - this.setLevelMode( (LevelType) this.getUpgradeable().getConfigManager().getSetting( Settings.LEVEL_TYPE ) ); - this.setFuzzyMode( (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting( Settings.FUZZY_MODE ) ); - this.setRedStoneMode( (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting( Settings.REDSTONE_EMITTER ) ); - } + this.standardDetectAndSendChanges(); + } - this.standardDetectAndSendChanges(); - } + @Override + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("EmitterValue")) { + if (this.textField != null) { + this.textField.setText(String.valueOf(this.EmitterValue)); + } + } + } - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if( field.equals( "EmitterValue" ) ) - { - if( this.textField != null ) - { - this.textField.setText( String.valueOf( this.EmitterValue ) ); - } - } - } + @Override + public YesNo getCraftingMode() { + return this.cmType; + } - @Override - public YesNo getCraftingMode() - { - return this.cmType; - } + @Override + public void setCraftingMode(final YesNo cmType) { + this.cmType = cmType; + } - @Override - public void setCraftingMode( final YesNo cmType ) - { - this.cmType = cmType; - } + public LevelType getLevelMode() { + return this.lvType; + } - public LevelType getLevelMode() - { - return this.lvType; - } - - private void setLevelMode( final LevelType lvType ) - { - this.lvType = lvType; - } + private void setLevelMode(final LevelType lvType) { + this.lvType = lvType; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerMAC.java b/src/main/java/appeng/container/implementations/ContainerMAC.java index 25fe1d9f5..c146c7b66 100644 --- a/src/main/java/appeng/container/implementations/ContainerMAC.java +++ b/src/main/java/appeng/container/implementations/ContainerMAC.java @@ -19,11 +19,6 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.RedstoneMode; import appeng.api.config.SecurityPermissions; import appeng.api.config.Settings; @@ -36,132 +31,120 @@ import appeng.container.slot.SlotRestrictedInput; import appeng.items.misc.ItemEncodedPattern; import appeng.tile.crafting.TileMolecularAssembler; import appeng.util.Platform; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraftforge.items.IItemHandler; -public class ContainerMAC extends ContainerUpgradeable implements IProgressProvider -{ +public class ContainerMAC extends ContainerUpgradeable implements IProgressProvider { - private static final int MAX_CRAFT_PROGRESS = 100; - private final TileMolecularAssembler tma; - @GuiSync( 4 ) - public int craftProgress = 0; + private static final int MAX_CRAFT_PROGRESS = 100; + private final TileMolecularAssembler tma; + @GuiSync(4) + public int craftProgress = 0; - public ContainerMAC( final InventoryPlayer ip, final TileMolecularAssembler te ) - { - super( ip, te ); - this.tma = te; - } + public ContainerMAC(final InventoryPlayer ip, final TileMolecularAssembler te) { + super(ip, te); + this.tma = te; + } - public boolean isValidItemForSlot( final int slotIndex, final ItemStack i ) - { - final IItemHandler mac = this.getUpgradeable().getInventoryByName( "mac" ); + public boolean isValidItemForSlot(final int slotIndex, final ItemStack i) { + final IItemHandler mac = this.getUpgradeable().getInventoryByName("mac"); - final ItemStack is = mac.getStackInSlot( 10 ); - if( is.isEmpty() ) - { - return false; - } + final ItemStack is = mac.getStackInSlot(10); + if (is.isEmpty()) { + return false; + } - if( is.getItem() instanceof ItemEncodedPattern ) - { - final World w = this.getTileEntity().getWorld(); - final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - final ICraftingPatternDetails ph = iep.getPatternForItem( is, w ); - if( ph.isCraftable() ) - { - return ph.isValidItemForSlot( slotIndex, i, w ); - } - } + if (is.getItem() instanceof ItemEncodedPattern) { + final World w = this.getTileEntity().getWorld(); + final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + final ICraftingPatternDetails ph = iep.getPatternForItem(is, w); + if (ph.isCraftable()) { + return ph.isValidItemForSlot(slotIndex, i, w); + } + } - return false; - } + return false; + } - @Override - protected int getHeight() - { - return 197; - } + @Override + protected int getHeight() { + return 197; + } - @Override - protected void setupConfig() - { - int offX = 29; - int offY = 30; + @Override + protected void setupConfig() { + int offX = 29; + int offY = 30; - final IItemHandler mac = this.getUpgradeable().getInventoryByName( "mac" ); + final IItemHandler mac = this.getUpgradeable().getInventoryByName("mac"); - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 3; x++ ) - { - final SlotMACPattern s = new SlotMACPattern( this, mac, x + y * 3, offX + x * 18, offY + y * 18 ); - this.addSlotToContainer( s ); - } - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + final SlotMACPattern s = new SlotMACPattern(this, mac, x + y * 3, offX + x * 18, offY + y * 18); + this.addSlotToContainer(s); + } + } - offX = 126; - offY = 16; + offX = 126; + offY = 16; - this.addSlotToContainer( - new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_CRAFTING_PATTERN, mac, 10, offX, offY, this.getInventoryPlayer() ) ); - this.addSlotToContainer( new SlotOutput( mac, 9, offX, offY + 32, -1 ) ); + this.addSlotToContainer( + new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.ENCODED_CRAFTING_PATTERN, mac, 10, offX, offY, this.getInventoryPlayer())); + this.addSlotToContainer(new SlotOutput(mac, 9, offX, offY + 32, -1)); - offX = 122; - offY = 17; + offX = 122; + offY = 17; - final IItemHandler upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } + final IItemHandler upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer())) + .setNotDraggable()); + } - @Override - protected boolean supportCapacity() - { - return false; - } + @Override + protected boolean supportCapacity() { + return false; + } - @Override - public int availableUpgrades() - { - return 5; - } + @Override + public int availableUpgrades() { + return 5; + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - if( Platform.isServer() ) - { - this.setRedStoneMode( (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ) ); - } + if (Platform.isServer()) { + this.setRedStoneMode((RedstoneMode) this.getUpgradeable().getConfigManager().getSetting(Settings.REDSTONE_CONTROLLED)); + } - this.craftProgress = this.tma.getCraftingProgress(); + this.craftProgress = this.tma.getCraftingProgress(); - this.standardDetectAndSendChanges(); - } + this.standardDetectAndSendChanges(); + } - @Override - public int getCurrentProgress() - { - return this.craftProgress; - } + @Override + public int getCurrentProgress() { + return this.craftProgress; + } - @Override - public int getMaxProgress() - { - return MAX_CRAFT_PROGRESS; - } + @Override + public int getMaxProgress() { + return MAX_CRAFT_PROGRESS; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java b/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java index 068b3f326..928ee7f74 100644 --- a/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java +++ b/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java @@ -19,26 +19,8 @@ package appeng.container.implementations; -import java.io.IOException; -import java.nio.BufferOverflowException; - -import javax.annotation.Nonnull; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IContainerListener; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - import appeng.api.AEApi; -import appeng.api.config.Actionable; -import appeng.api.config.PowerMultiplier; -import appeng.api.config.SecurityPermissions; -import appeng.api.config.Settings; -import appeng.api.config.SortDir; -import appeng.api.config.SortOrder; -import appeng.api.config.ViewItems; +import appeng.api.config.*; import appeng.api.implementations.guiobjects.IPortableCell; import appeng.api.implementations.tiles.IMEChest; import appeng.api.implementations.tiles.IViewCellStorage; @@ -71,397 +53,315 @@ import appeng.me.helpers.ChannelPowerSrc; import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; import appeng.util.Platform; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IContainerListener; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; import net.minecraftforge.fml.common.Loader; - -public class ContainerMEMonitorable extends AEBaseContainer implements IConfigManagerHost, IConfigurableObject, IMEMonitorHandlerReceiver -{ - - private final SlotRestrictedInput[] cellView = new SlotRestrictedInput[5]; - private final IMEMonitor monitor; - private final IItemList items = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - private final IConfigManager clientCM; - private final ITerminalHost host; - @GuiSync( 99 ) - public boolean canAccessViewCells = false; - @GuiSync( 98 ) - public boolean hasPower = false; - private IConfigManagerHost gui; - private IConfigManager serverCM; - private IGridNode networkNode; - protected int jeiOffset = Loader.isModLoaded( "jei" ) ? 24 : 0; +import javax.annotation.Nonnull; +import java.io.IOException; +import java.nio.BufferOverflowException; - public ContainerMEMonitorable( final InventoryPlayer ip, final ITerminalHost monitorable ) - { - this( ip, monitorable, true ); - } +public class ContainerMEMonitorable extends AEBaseContainer implements IConfigManagerHost, IConfigurableObject, IMEMonitorHandlerReceiver { - protected ContainerMEMonitorable( final InventoryPlayer ip, final ITerminalHost monitorable, final boolean bindInventory ) - { - super( ip, monitorable instanceof TileEntity ? (TileEntity) monitorable : null, monitorable instanceof IPart ? (IPart) monitorable : null ); + private final SlotRestrictedInput[] cellView = new SlotRestrictedInput[5]; + private final IMEMonitor monitor; + private final IItemList items = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + private final IConfigManager clientCM; + private final ITerminalHost host; + @GuiSync(99) + public boolean canAccessViewCells = false; + @GuiSync(98) + public boolean hasPower = false; + private IConfigManagerHost gui; + private IConfigManager serverCM; + private IGridNode networkNode; + protected int jeiOffset = Loader.isModLoaded("jei") ? 24 : 0; - this.host = monitorable; - this.clientCM = new ConfigManager( this ); - this.clientCM.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - this.clientCM.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - this.clientCM.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); + public ContainerMEMonitorable(final InventoryPlayer ip, final ITerminalHost monitorable) { + this(ip, monitorable, true); + } - if( Platform.isServer() ) - { - this.serverCM = monitorable.getConfigManager(); + protected ContainerMEMonitorable(final InventoryPlayer ip, final ITerminalHost monitorable, final boolean bindInventory) { + super(ip, monitorable instanceof TileEntity ? (TileEntity) monitorable : null, monitorable instanceof IPart ? (IPart) monitorable : null); - this.monitor = monitorable.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - if( this.monitor != null ) - { - this.monitor.addListener( this, null ); + this.host = monitorable; + this.clientCM = new ConfigManager(this); - this.setCellInventory( this.monitor ); + this.clientCM.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.clientCM.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + this.clientCM.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); - if( monitorable instanceof IPortableCell ) - { - this.setPowerSource( (IEnergySource) monitorable ); - } - else if( monitorable instanceof IMEChest ) - { - this.setPowerSource( (IEnergySource) monitorable ); - } - else if( monitorable instanceof IGridHost || monitorable instanceof IActionHost ) - { - final IGridNode node; - if( monitorable instanceof IGridHost ) - { - node = ( (IGridHost) monitorable ).getGridNode( AEPartLocation.INTERNAL ); - } - else if( monitorable instanceof IActionHost ) - { - node = ( (IActionHost) monitorable ).getActionableNode(); - } - else - { - node = null; - } + if (Platform.isServer()) { + this.serverCM = monitorable.getConfigManager(); - if( node != null ) - { - this.networkNode = node; - final IGrid g = node.getGrid(); - if( g != null ) - { - this.setPowerSource( new ChannelPowerSrc( this.networkNode, (IEnergySource) g.getCache( IEnergyGrid.class ) ) ); - } - } - } - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.monitor = null; - } + this.monitor = monitorable.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + if (this.monitor != null) { + this.monitor.addListener(this, null); - this.canAccessViewCells = false; - if( monitorable instanceof IViewCellStorage ) - { - for( int y = 0; y < 5; y++ ) - { - this.cellView[y] = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.VIEW_CELL, ( (IViewCellStorage) monitorable ) - .getViewCellStorage(), y, 206, y * 18 + 8 + jeiOffset, this.getInventoryPlayer() ); - this.cellView[y].setAllowEdit( this.canAccessViewCells ); - this.addSlotToContainer( this.cellView[y] ); - } - } + this.setCellInventory(this.monitor); - if( bindInventory ) - { - this.bindPlayerInventory( ip, 0, 0 ); - } - } + if (monitorable instanceof IPortableCell) { + this.setPowerSource((IEnergySource) monitorable); + } else if (monitorable instanceof IMEChest) { + this.setPowerSource((IEnergySource) monitorable); + } else if (monitorable instanceof IGridHost || monitorable instanceof IActionHost) { + final IGridNode node; + if (monitorable instanceof IGridHost) { + node = ((IGridHost) monitorable).getGridNode(AEPartLocation.INTERNAL); + } else if (monitorable instanceof IActionHost) { + node = ((IActionHost) monitorable).getActionableNode(); + } else { + node = null; + } - public IGridNode getNetworkNode() - { - return this.networkNode; - } + if (node != null) { + this.networkNode = node; + final IGrid g = node.getGrid(); + if (g != null) { + this.setPowerSource(new ChannelPowerSrc(this.networkNode, g.getCache(IEnergyGrid.class))); + } + } + } + } else { + this.setValidContainer(false); + } + } else { + this.monitor = null; + } - @Override - public void detectAndSendChanges() - { - if( Platform.isServer() ) - { - if( this.monitor != this.host.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) ) - { - this.setValidContainer( false ); - } + this.canAccessViewCells = false; + if (monitorable instanceof IViewCellStorage) { + for (int y = 0; y < 5; y++) { + this.cellView[y] = new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.VIEW_CELL, ((IViewCellStorage) monitorable) + .getViewCellStorage(), y, 206, y * 18 + 8 + jeiOffset, this.getInventoryPlayer()); + this.cellView[y].setAllowEdit(this.canAccessViewCells); + this.addSlotToContainer(this.cellView[y]); + } + } - for( final Settings set : this.serverCM.getSettings() ) - { - final Enum sideLocal = this.serverCM.getSetting( set ); - final Enum sideRemote = this.clientCM.getSetting( set ); + if (bindInventory) { + this.bindPlayerInventory(ip, 0, 0); + } + } - if( sideLocal != sideRemote ) - { - this.clientCM.putSetting( set, sideLocal ); - for( final IContainerListener crafter : this.listeners ) - { - if( crafter instanceof EntityPlayerMP ) - { - try - { - NetworkHandler.instance().sendTo( new PacketValueConfig( set.name(), sideLocal.name() ), (EntityPlayerMP) crafter ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } - } + public IGridNode getNetworkNode() { + return this.networkNode; + } - if( !this.items.isEmpty() ) - { - try - { - final IItemList monitorCache = this.monitor.getStorageList(); + @Override + public void detectAndSendChanges() { + if (Platform.isServer()) { + if (this.monitor != this.host.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class))) { + this.setValidContainer(false); + } - final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); + for (final Settings set : this.serverCM.getSettings()) { + final Enum sideLocal = this.serverCM.getSetting(set); + final Enum sideRemote = this.clientCM.getSetting(set); - for( final IAEItemStack is : this.items ) - { - final IAEItemStack send = monitorCache.findPrecise( is ); - if( send == null ) - { - is.setStackSize( 0 ); - piu.appendItem( is ); - } - else - { - piu.appendItem( send ); - } - } + if (sideLocal != sideRemote) { + this.clientCM.putSetting(set, sideLocal); + for (final IContainerListener crafter : this.listeners) { + if (crafter instanceof EntityPlayerMP) { + try { + NetworkHandler.instance().sendTo(new PacketValueConfig(set.name(), sideLocal.name()), (EntityPlayerMP) crafter); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } + } - if( !piu.isEmpty() ) - { - this.items.resetStatus(); + if (!this.items.isEmpty()) { + try { + final IItemList monitorCache = this.monitor.getStorageList(); - for( final Object c : this.listeners ) - { - if( c instanceof EntityPlayer ) - { - NetworkHandler.instance().sendTo( piu, (EntityPlayerMP) c ); - } - } - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); - this.updatePowerStatus(); + for (final IAEItemStack is : this.items) { + final IAEItemStack send = monitorCache.findPrecise(is); + if (send == null) { + is.setStackSize(0); + piu.appendItem(is); + } else { + piu.appendItem(send); + } + } - final boolean oldAccessible = this.canAccessViewCells; - this.canAccessViewCells = this.hasAccess( SecurityPermissions.BUILD, false ); - if( this.canAccessViewCells != oldAccessible ) - { - for( int y = 0; y < 5; y++ ) - { - if( this.cellView[y] != null ) - { - this.cellView[y].setAllowEdit( this.canAccessViewCells ); - } - } - } + if (!piu.isEmpty()) { + this.items.resetStatus(); - super.detectAndSendChanges(); - } + for (final Object c : this.listeners) { + if (c instanceof EntityPlayer) { + NetworkHandler.instance().sendTo(piu, (EntityPlayerMP) c); + } + } + } + } catch (final IOException e) { + AELog.debug(e); + } + } - } + this.updatePowerStatus(); - protected void updatePowerStatus() - { - try - { - if( this.networkNode != null ) - { - this.setPowered( this.networkNode.isActive() ); - } - else if( this.getPowerSource() instanceof IEnergyGrid ) - { - this.setPowered( ( (IEnergyGrid) this.getPowerSource() ).isNetworkPowered() ); - } - else - { - this.setPowered( this.getPowerSource().extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.8 ); - } - } - catch( final Throwable t ) - { - // :P - } - } + final boolean oldAccessible = this.canAccessViewCells; + this.canAccessViewCells = this.hasAccess(SecurityPermissions.BUILD, false); + if (this.canAccessViewCells != oldAccessible) { + for (int y = 0; y < 5; y++) { + if (this.cellView[y] != null) { + this.cellView[y].setAllowEdit(this.canAccessViewCells); + } + } + } - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if( field.equals( "canAccessViewCells" ) ) - { - for( int y = 0; y < 5; y++ ) - { - if( this.cellView[y] != null ) - { - this.cellView[y].setAllowEdit( this.canAccessViewCells ); - } - } - } + super.detectAndSendChanges(); + } - super.onUpdate( field, oldValue, newValue ); - } + } - @Override - public void addListener( final IContainerListener c ) - { - super.addListener( c ); + protected void updatePowerStatus() { + try { + if (this.networkNode != null) { + this.setPowered(this.networkNode.isActive()); + } else if (this.getPowerSource() instanceof IEnergyGrid) { + this.setPowered(((IEnergyGrid) this.getPowerSource()).isNetworkPowered()); + } else { + this.setPowered(this.getPowerSource().extractAEPower(1, Actionable.SIMULATE, PowerMultiplier.CONFIG) > 0.8); + } + } catch (final Throwable t) { + // :P + } + } - this.queueInventory( c ); - } + @Override + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("canAccessViewCells")) { + for (int y = 0; y < 5; y++) { + if (this.cellView[y] != null) { + this.cellView[y].setAllowEdit(this.canAccessViewCells); + } + } + } - private void queueInventory( final IContainerListener c ) - { - if( Platform.isServer() && c instanceof EntityPlayer && this.monitor != null ) - { - try - { - PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); - final IItemList monitorCache = this.monitor.getStorageList(); + super.onUpdate(field, oldValue, newValue); + } - for( final IAEItemStack send : monitorCache ) - { - try - { - piu.appendItem( send ); - } - catch( final BufferOverflowException boe ) - { - NetworkHandler.instance().sendTo( piu, (EntityPlayerMP) c ); + @Override + public void addListener(final IContainerListener c) { + super.addListener(c); - piu = new PacketMEInventoryUpdate(); - piu.appendItem( send ); - } - } + this.queueInventory(c); + } - NetworkHandler.instance().sendTo( piu, (EntityPlayerMP) c ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } + private void queueInventory(final IContainerListener c) { + if (Platform.isServer() && c instanceof EntityPlayer && this.monitor != null) { + try { + PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); + final IItemList monitorCache = this.monitor.getStorageList(); - @Override - public void removeListener( final IContainerListener c ) - { - super.removeListener( c ); + for (final IAEItemStack send : monitorCache) { + try { + piu.appendItem(send); + } catch (final BufferOverflowException boe) { + NetworkHandler.instance().sendTo(piu, (EntityPlayerMP) c); - if( this.listeners.isEmpty() && this.monitor != null ) - { - this.monitor.removeListener( this ); - } - } + piu = new PacketMEInventoryUpdate(); + piu.appendItem(send); + } + } - @Override - public void onContainerClosed( final EntityPlayer player ) - { - super.onContainerClosed( player ); - if( this.monitor != null ) - { - this.monitor.removeListener( this ); - } - } + NetworkHandler.instance().sendTo(piu, (EntityPlayerMP) c); + } catch (final IOException e) { + AELog.debug(e); + } + } + } - @Override - public boolean isValid( final Object verificationToken ) - { - return true; - } + @Override + public void removeListener(final IContainerListener c) { + super.removeListener(c); - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final IActionSource source ) - { - for( final IAEItemStack is : change ) - { - this.items.add( is ); - } - } + if (this.listeners.isEmpty() && this.monitor != null) { + this.monitor.removeListener(this); + } + } - @Override - public void onListUpdate() - { - for( final IContainerListener c : this.listeners ) - { - this.queueInventory( c ); - } - } + @Override + public void onContainerClosed(final EntityPlayer player) { + super.onContainerClosed(player); + if (this.monitor != null) { + this.monitor.removeListener(this); + } + } - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - if( this.getGui() != null ) - { - this.getGui().updateSetting( manager, settingName, newValue ); - } - } + @Override + public boolean isValid(final Object verificationToken) { + return true; + } - @Override - public IConfigManager getConfigManager() - { - if( Platform.isServer() ) - { - return this.serverCM; - } - return this.clientCM; - } + @Override + public void postChange(final IBaseMonitor monitor, final Iterable change, final IActionSource source) { + for (final IAEItemStack is : change) { + this.items.add(is); + } + } - public ItemStack[] getViewCells() - { - final ItemStack[] list = new ItemStack[this.cellView.length]; + @Override + public void onListUpdate() { + for (final IContainerListener c : this.listeners) { + this.queueInventory(c); + } + } - for( int x = 0; x < this.cellView.length; x++ ) - { - list[x] = this.cellView[x].getStack(); - } + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + if (this.getGui() != null) { + this.getGui().updateSetting(manager, settingName, newValue); + } + } - return list; - } + @Override + public IConfigManager getConfigManager() { + if (Platform.isServer()) { + return this.serverCM; + } + return this.clientCM; + } - public SlotRestrictedInput getCellViewSlot( final int index ) - { - return this.cellView[index]; - } + public ItemStack[] getViewCells() { + final ItemStack[] list = new ItemStack[this.cellView.length]; - public boolean isPowered() - { - return this.hasPower; - } + for (int x = 0; x < this.cellView.length; x++) { + list[x] = this.cellView[x].getStack(); + } - private void setPowered( final boolean isPowered ) - { - this.hasPower = isPowered; - } + return list; + } - private IConfigManagerHost getGui() - { - return this.gui; - } + public SlotRestrictedInput getCellViewSlot(final int index) { + return this.cellView[index]; + } - public void setGui( @Nonnull final IConfigManagerHost gui ) - { - this.gui = gui; - } + public boolean isPowered() { + return this.hasPower; + } + + private void setPowered(final boolean isPowered) { + this.hasPower = isPowered; + } + + private IConfigManagerHost getGui() { + return this.gui; + } + + public void setGui(@Nonnull final IConfigManagerHost gui) { + this.gui = gui; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java b/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java index c5948f0f5..c1a2d43fe 100644 --- a/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java +++ b/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java @@ -19,80 +19,64 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; - import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.implementations.guiobjects.IPortableCell; import appeng.container.interfaces.IInventorySlotAware; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; -public class ContainerMEPortableCell extends ContainerMEMonitorable -{ +public class ContainerMEPortableCell extends ContainerMEMonitorable { - private double powerMultiplier = 0.5; + private double powerMultiplier = 0.5; - private final IPortableCell civ; - private int ticks = 0; - private final int slot; + private final IPortableCell civ; + private int ticks = 0; + private final int slot; - public ContainerMEPortableCell( final InventoryPlayer ip, final IPortableCell monitorable ) - { - super( ip, monitorable, false ); - if( monitorable instanceof IInventorySlotAware ) - { - final int slotIndex = ( (IInventorySlotAware) monitorable ).getInventorySlot(); - this.lockPlayerInventorySlot( slotIndex ); - this.slot = slotIndex; - } - else - { - this.slot = -1; - this.lockPlayerInventorySlot( ip.currentItem ); - } - this.civ = monitorable; - this.bindPlayerInventory( ip, 0, 0 ); - } + public ContainerMEPortableCell(final InventoryPlayer ip, final IPortableCell monitorable) { + super(ip, monitorable, false); + if (monitorable instanceof IInventorySlotAware) { + final int slotIndex = ((IInventorySlotAware) monitorable).getInventorySlot(); + this.lockPlayerInventorySlot(slotIndex); + this.slot = slotIndex; + } else { + this.slot = -1; + this.lockPlayerInventorySlot(ip.currentItem); + } + this.civ = monitorable; + this.bindPlayerInventory(ip, 0, 0); + } - @Override - public void detectAndSendChanges() - { - final ItemStack currentItem = this.slot < 0 ? this.getPlayerInv().getCurrentItem() : this.getPlayerInv().getStackInSlot( this.slot ); + @Override + public void detectAndSendChanges() { + final ItemStack currentItem = this.slot < 0 ? this.getPlayerInv().getCurrentItem() : this.getPlayerInv().getStackInSlot(this.slot); - if( this.civ == null || currentItem.isEmpty() ) - { - this.setValidContainer( false ); - } - else if( this.civ != null && !this.civ.getItemStack().isEmpty() && currentItem != this.civ.getItemStack() ) - { - if( ItemStack.areItemsEqual( this.civ.getItemStack(), currentItem ) ) - { - this.getPlayerInv().setInventorySlotContents( this.getPlayerInv().currentItem, this.civ.getItemStack() ); - } - else - { - this.setValidContainer( false ); - } - } + if (this.civ == null || currentItem.isEmpty()) { + this.setValidContainer(false); + } else if (this.civ != null && !this.civ.getItemStack().isEmpty() && currentItem != this.civ.getItemStack()) { + if (ItemStack.areItemsEqual(this.civ.getItemStack(), currentItem)) { + this.getPlayerInv().setInventorySlotContents(this.getPlayerInv().currentItem, this.civ.getItemStack()); + } else { + this.setValidContainer(false); + } + } - // drain 1 ae t - this.ticks++; - if( this.ticks > 10 ) - { - this.civ.extractAEPower( this.getPowerMultiplier() * this.ticks, Actionable.MODULATE, PowerMultiplier.CONFIG ); - this.ticks = 0; - } - super.detectAndSendChanges(); - } + // drain 1 ae t + this.ticks++; + if (this.ticks > 10) { + this.civ.extractAEPower(this.getPowerMultiplier() * this.ticks, Actionable.MODULATE, PowerMultiplier.CONFIG); + this.ticks = 0; + } + super.detectAndSendChanges(); + } - private double getPowerMultiplier() - { - return this.powerMultiplier; - } + private double getPowerMultiplier() { + return this.powerMultiplier; + } - void setPowerMultiplier( final double powerMultiplier ) - { - this.powerMultiplier = powerMultiplier; - } + void setPowerMultiplier(final double powerMultiplier) { + this.powerMultiplier = powerMultiplier; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java b/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java index f188debd0..a30165032 100644 --- a/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java +++ b/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java @@ -19,13 +19,6 @@ package appeng.container.implementations; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.api.implementations.guiobjects.INetworkTool; import appeng.api.networking.IGrid; @@ -43,150 +36,128 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketMEInventoryUpdate; import appeng.util.Platform; import appeng.util.item.AEItemStack; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; + +import java.io.IOException; -public class ContainerNetworkStatus extends AEBaseContainer -{ +public class ContainerNetworkStatus extends AEBaseContainer { - @GuiSync( 0 ) - public long avgAddition; - @GuiSync( 1 ) - public long powerUsage; - @GuiSync( 2 ) - public long currentPower; - @GuiSync( 3 ) - public long maxPower; - private IGrid network; - private int delay = 40; + @GuiSync(0) + public long avgAddition; + @GuiSync(1) + public long powerUsage; + @GuiSync(2) + public long currentPower; + @GuiSync(3) + public long maxPower; + private IGrid network; + private int delay = 40; - public ContainerNetworkStatus( final InventoryPlayer ip, final INetworkTool te ) - { - super( ip, null, null ); - final IGridHost host = te.getGridHost(); + public ContainerNetworkStatus(final InventoryPlayer ip, final INetworkTool te) { + super(ip, null, null); + final IGridHost host = te.getGridHost(); - if( host != null ) - { - this.findNode( host, AEPartLocation.INTERNAL ); - for( final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS ) - { - this.findNode( host, d ); - } - } + if (host != null) { + this.findNode(host, AEPartLocation.INTERNAL); + for (final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS) { + this.findNode(host, d); + } + } - if( this.network == null && Platform.isServer() ) - { - this.setValidContainer( false ); - } - } + if (this.network == null && Platform.isServer()) { + this.setValidContainer(false); + } + } - private void findNode( final IGridHost host, final AEPartLocation d ) - { - if( this.network == null ) - { - final IGridNode node = host.getGridNode( d ); - if( node != null ) - { - this.network = node.getGrid(); - } - } - } + private void findNode(final IGridHost host, final AEPartLocation d) { + if (this.network == null) { + final IGridNode node = host.getGridNode(d); + if (node != null) { + this.network = node.getGrid(); + } + } + } - @Override - public void detectAndSendChanges() - { - this.delay++; - if( Platform.isServer() && this.delay > 15 && this.network != null ) - { - this.delay = 0; + @Override + public void detectAndSendChanges() { + this.delay++; + if (Platform.isServer() && this.delay > 15 && this.network != null) { + this.delay = 0; - final IEnergyGrid eg = this.network.getCache( IEnergyGrid.class ); - if( eg != null ) - { - this.setAverageAddition( (long) ( 100.0 * eg.getAvgPowerInjection() ) ); - this.setPowerUsage( (long) ( 100.0 * eg.getAvgPowerUsage() ) ); - this.setCurrentPower( (long) ( 100.0 * eg.getStoredPower() ) ); - this.setMaxPower( (long) ( 100.0 * eg.getMaxStoredPower() ) ); - } + final IEnergyGrid eg = this.network.getCache(IEnergyGrid.class); + if (eg != null) { + this.setAverageAddition((long) (100.0 * eg.getAvgPowerInjection())); + this.setPowerUsage((long) (100.0 * eg.getAvgPowerUsage())); + this.setCurrentPower((long) (100.0 * eg.getStoredPower())); + this.setMaxPower((long) (100.0 * eg.getMaxStoredPower())); + } - try - { - final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); + try { + final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); - for( final Class machineClass : this.network.getMachinesClasses() ) - { - final IItemList list = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - for( final IGridNode machine : this.network.getMachines( machineClass ) ) - { - final IGridBlock blk = machine.getGridBlock(); - final ItemStack is = blk.getMachineRepresentation(); - if( !is.isEmpty() ) - { - final IAEItemStack ais = AEItemStack.fromItemStack( is ); - ais.setStackSize( 1 ); - ais.setCountRequestable( (long) ( blk.getIdlePowerUsage() * 100.0 ) ); - list.add( ais ); - } - } + for (final Class machineClass : this.network.getMachinesClasses()) { + final IItemList list = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + for (final IGridNode machine : this.network.getMachines(machineClass)) { + final IGridBlock blk = machine.getGridBlock(); + final ItemStack is = blk.getMachineRepresentation(); + if (!is.isEmpty()) { + final IAEItemStack ais = AEItemStack.fromItemStack(is); + ais.setStackSize(1); + ais.setCountRequestable((long) (blk.getIdlePowerUsage() * 100.0)); + list.add(ais); + } + } - for( final IAEItemStack ais : list ) - { - piu.appendItem( ais ); - } - } + for (final IAEItemStack ais : list) { + piu.appendItem(ais); + } + } - for( final Object c : this.listeners ) - { - if( c instanceof EntityPlayer ) - { - NetworkHandler.instance().sendTo( piu, (EntityPlayerMP) c ); - } - } - } - catch( final IOException e ) - { - // :P - } - } - super.detectAndSendChanges(); - } + for (final Object c : this.listeners) { + if (c instanceof EntityPlayer) { + NetworkHandler.instance().sendTo(piu, (EntityPlayerMP) c); + } + } + } catch (final IOException e) { + // :P + } + } + super.detectAndSendChanges(); + } - public long getCurrentPower() - { - return this.currentPower; - } + public long getCurrentPower() { + return this.currentPower; + } - private void setCurrentPower( final long currentPower ) - { - this.currentPower = currentPower; - } + private void setCurrentPower(final long currentPower) { + this.currentPower = currentPower; + } - public long getMaxPower() - { - return this.maxPower; - } + public long getMaxPower() { + return this.maxPower; + } - private void setMaxPower( final long maxPower ) - { - this.maxPower = maxPower; - } + private void setMaxPower(final long maxPower) { + this.maxPower = maxPower; + } - public long getAverageAddition() - { - return this.avgAddition; - } + public long getAverageAddition() { + return this.avgAddition; + } - private void setAverageAddition( final long avgAddition ) - { - this.avgAddition = avgAddition; - } + private void setAverageAddition(final long avgAddition) { + this.avgAddition = avgAddition; + } - public long getPowerUsage() - { - return this.powerUsage; - } + public long getPowerUsage() { + return this.powerUsage; + } - private void setPowerUsage( final long powerUsage ) - { - this.powerUsage = powerUsage; - } + private void setPowerUsage(final long powerUsage) { + this.powerUsage = powerUsage; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerNetworkTool.java b/src/main/java/appeng/container/implementations/ContainerNetworkTool.java index 86d9e931f..977a991f0 100644 --- a/src/main/java/appeng/container/implementations/ContainerNetworkTool.java +++ b/src/main/java/appeng/container/implementations/ContainerNetworkTool.java @@ -19,99 +19,81 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import appeng.api.implementations.guiobjects.INetworkTool; import appeng.container.AEBaseContainer; import appeng.container.guisync.GuiSync; import appeng.container.slot.SlotRestrictedInput; import appeng.util.Platform; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; -public class ContainerNetworkTool extends AEBaseContainer -{ +public class ContainerNetworkTool extends AEBaseContainer { - private final INetworkTool toolInv; + private final INetworkTool toolInv; - @GuiSync( 1 ) - public boolean facadeMode; + @GuiSync(1) + public boolean facadeMode; - public ContainerNetworkTool( final InventoryPlayer ip, final INetworkTool te ) - { - super( ip, null, null ); - this.toolInv = te; + public ContainerNetworkTool(final InventoryPlayer ip, final INetworkTool te) { + super(ip, null, null); + this.toolInv = te; - this.lockPlayerInventorySlot( ip.currentItem ); + this.lockPlayerInventorySlot(ip.currentItem); - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 3; x++ ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, te - .getInventory(), y * 3 + x, 80 - 18 + x * 18, 37 - 18 + y * 18, this.getInventoryPlayer() ) ) ); - } - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + this.addSlotToContainer((new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, te + .getInventory(), y * 3 + x, 80 - 18 + x * 18, 37 - 18 + y * 18, this.getInventoryPlayer()))); + } + } - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 166 - /* height of player inventory */82); + } - public void toggleFacadeMode() - { - final NBTTagCompound data = Platform.openNbtData( this.toolInv.getItemStack() ); - data.setBoolean( "hideFacades", !data.getBoolean( "hideFacades" ) ); - this.detectAndSendChanges(); - } + public void toggleFacadeMode() { + final NBTTagCompound data = Platform.openNbtData(this.toolInv.getItemStack()); + data.setBoolean("hideFacades", !data.getBoolean("hideFacades")); + this.detectAndSendChanges(); + } - @Override - public void detectAndSendChanges() - { - final ItemStack currentItem = this.getPlayerInv().getCurrentItem(); + @Override + public void detectAndSendChanges() { + final ItemStack currentItem = this.getPlayerInv().getCurrentItem(); - if( currentItem != this.toolInv.getItemStack() ) - { - if( !currentItem.isEmpty() ) - { - if( ItemStack.areItemsEqual( this.toolInv.getItemStack(), currentItem ) ) - { - this.getPlayerInv().setInventorySlotContents( this.getPlayerInv().currentItem, this.toolInv.getItemStack() ); - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.setValidContainer( false ); - } - } + if (currentItem != this.toolInv.getItemStack()) { + if (!currentItem.isEmpty()) { + if (ItemStack.areItemsEqual(this.toolInv.getItemStack(), currentItem)) { + this.getPlayerInv().setInventorySlotContents(this.getPlayerInv().currentItem, this.toolInv.getItemStack()); + } else { + this.setValidContainer(false); + } + } else { + this.setValidContainer(false); + } + } - if( this.isValidContainer() ) - { - final NBTTagCompound data = Platform.openNbtData( currentItem ); - this.setFacadeMode( data.getBoolean( "hideFacades" ) ); - } + if (this.isValidContainer()) { + final NBTTagCompound data = Platform.openNbtData(currentItem); + this.setFacadeMode(data.getBoolean("hideFacades")); + } - super.detectAndSendChanges(); - } + super.detectAndSendChanges(); + } - @Override - public void onSlotChange( Slot s ) - { - super.detectAndSendChanges(); - } + @Override + public void onSlotChange(Slot s) { + super.detectAndSendChanges(); + } - public boolean isFacadeMode() - { - return this.facadeMode; - } + public boolean isFacadeMode() { + return this.facadeMode; + } - private void setFacadeMode( final boolean facadeMode ) - { - this.facadeMode = facadeMode; - } + private void setFacadeMode(final boolean facadeMode) { + this.facadeMode = facadeMode; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerOreDictStorageBus.java b/src/main/java/appeng/container/implementations/ContainerOreDictStorageBus.java index f0655c673..05cb6eec0 100644 --- a/src/main/java/appeng/container/implementations/ContainerOreDictStorageBus.java +++ b/src/main/java/appeng/container/implementations/ContainerOreDictStorageBus.java @@ -1,7 +1,10 @@ package appeng.container.implementations; import appeng.api.AEApi; -import appeng.api.config.*; +import appeng.api.config.AccessRestriction; +import appeng.api.config.SecurityPermissions; +import appeng.api.config.Settings; +import appeng.api.config.StorageFilter; import appeng.api.storage.IMEInventory; import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEItemStack; @@ -23,118 +26,96 @@ import java.util.Iterator; import java.util.Set; -public class ContainerOreDictStorageBus extends AEBaseContainer -{ +public class ContainerOreDictStorageBus extends AEBaseContainer { private final PartOreDicStorageBus part; - @GuiSync( 3 ) + @GuiSync(3) public AccessRestriction rwMode = AccessRestriction.READ_WRITE; - @GuiSync( 4 ) + @GuiSync(4) public StorageFilter storageFilter = StorageFilter.EXTRACTABLE_ONLY; - public ContainerOreDictStorageBus( final InventoryPlayer ip, final PartOreDicStorageBus anchor ) - { - super( ip, anchor ); + public ContainerOreDictStorageBus(final InventoryPlayer ip, final PartOreDicStorageBus anchor) { + super(ip, anchor); this.part = anchor; - this.bindPlayerInventory( ip, 14, 256 - /* height of player inventory */82 ); + this.bindPlayerInventory(ip, 14, 256 - /* height of player inventory */82); } @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - if( Platform.isServer() ) - { - this.setReadWriteMode( (AccessRestriction) part.getConfigManager().getSetting( Settings.ACCESS ) ); - this.setStorageFilter( (StorageFilter) part.getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); + if (Platform.isServer()) { + this.setReadWriteMode((AccessRestriction) part.getConfigManager().getSetting(Settings.ACCESS)); + this.setStorageFilter((StorageFilter) part.getConfigManager().getSetting(Settings.STORAGE_FILTER)); } super.detectAndSendChanges(); } - public void partition() - { + public void partition() { final IMEInventory cellInv = this.part.getInternalHandler(); - if( cellInv == null ) - { + if (cellInv == null) { return; } Set oreIDs = new HashSet<>(); - for( IAEItemStack itemStack : cellInv.getAvailableItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList() ) ) - { - OreReference ref = ( (AEItemStack) itemStack ).getOre().orElse( null ); - if( ref != null ) - { - oreIDs.addAll( ref.getOres() ); + for (IAEItemStack itemStack : cellInv.getAvailableItems(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList())) { + OreReference ref = ((AEItemStack) itemStack).getOre().orElse(null); + if (ref != null) { + oreIDs.addAll(ref.getOres()); } } String oreMatch = "("; String append = ""; - for( Iterator it = oreIDs.iterator(); it.hasNext(); ) - { + for (Iterator it = oreIDs.iterator(); it.hasNext(); ) { int oreID = it.next(); - if( it.hasNext() ) - { + if (it.hasNext()) { append = ")|("; - } - else - { + } else { append = ")"; } - oreMatch = oreMatch.concat( OreDictionary.getOreName( oreID ) + append ); + oreMatch = oreMatch.concat(OreDictionary.getOreName(oreID) + append); } - if( oreMatch.equals( "(" ) ) - { + if (oreMatch.equals("(")) { oreMatch = ""; } - part.saveOreMatch( oreMatch ); + part.saveOreMatch(oreMatch); this.detectAndSendChanges(); } - public void saveOreMatch( String value ) - { - part.saveOreMatch( value ); + public void saveOreMatch(String value) { + part.saveOreMatch(value); } - public void sendRegex() - { - try - { - NetworkHandler.instance().sendTo( new PacketValueConfig( "OreDictStorageBus.sendRegex", part.getOreExp() ), (EntityPlayerMP) getInventoryPlayer().player ); - } - catch( IOException e ) - { + public void sendRegex() { + try { + NetworkHandler.instance().sendTo(new PacketValueConfig("OreDictStorageBus.sendRegex", part.getOreExp()), (EntityPlayerMP) getInventoryPlayer().player); + } catch (IOException e) { e.printStackTrace(); } } - public AccessRestriction getReadWriteMode() - { + public AccessRestriction getReadWriteMode() { return this.rwMode; } - private void setReadWriteMode( final AccessRestriction rwMode ) - { + private void setReadWriteMode(final AccessRestriction rwMode) { this.rwMode = rwMode; } - public StorageFilter getStorageFilter() - { + public StorageFilter getStorageFilter() { return this.storageFilter; } - private void setStorageFilter( final StorageFilter storageFilter ) - { + private void setStorageFilter(final StorageFilter storageFilter) { this.storageFilter = storageFilter; } } diff --git a/src/main/java/appeng/container/implementations/ContainerPatternTerm.java b/src/main/java/appeng/container/implementations/ContainerPatternTerm.java index ff7e00a43..9e264fb35 100644 --- a/src/main/java/appeng/container/implementations/ContainerPatternTerm.java +++ b/src/main/java/appeng/container/implementations/ContainerPatternTerm.java @@ -19,29 +19,6 @@ package appeng.container.implementations; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import appeng.container.slot.*; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IContainerListener; -import net.minecraft.inventory.InventoryCraftResult; -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.inventory.Slot; -import net.minecraft.inventory.SlotCrafting; -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.CraftingManager; -import net.minecraft.item.crafting.IRecipe; -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.world.World; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.wrapper.PlayerInvWrapper; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.definitions.IDefinitions; @@ -52,6 +29,7 @@ import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import appeng.container.ContainerNull; import appeng.container.guisync.GuiSync; +import appeng.container.slot.*; import appeng.core.sync.packets.PacketPatternSlot; import appeng.helpers.IContainerCraftingPacket; import appeng.items.storage.ItemViewCell; @@ -65,772 +43,649 @@ import appeng.util.inv.IAEAppEngInventory; import appeng.util.inv.InvOperation; import appeng.util.inv.WrapperCursorItemHandler; import appeng.util.item.AEItemStack; - - -public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEAppEngInventory, IOptionalSlotHost, IContainerCraftingPacket -{ - - private final PartPatternTerminal patternTerminal; - private final AppEngInternalInventory cOut = new AppEngInternalInventory( null, 1 ); - private final IItemHandler crafting; - private final SlotFakeCraftingMatrix[] craftingSlots = new SlotFakeCraftingMatrix[9]; - private final OptionalSlotFake[] outputSlots = new OptionalSlotFake[3]; - private final SlotPatternTerm craftSlot; - private final SlotRestrictedInput patternSlotIN; - private final SlotRestrictedInput patternSlotOUT; - - private IRecipe currentRecipe; - @GuiSync( 97 ) - public boolean craftingMode = true; - @GuiSync( 96 ) - public boolean substitute = false; - - public ContainerPatternTerm( final InventoryPlayer ip, final ITerminalHost monitorable ) - { - super( ip, monitorable, false ); - this.patternTerminal = (PartPatternTerminal) monitorable; - - final IItemHandler patternInv = this.getPatternTerminal().getInventoryByName( "pattern" ); - final IItemHandler output = this.getPatternTerminal().getInventoryByName( "output" ); - - this.crafting = this.getPatternTerminal().getInventoryByName( "crafting" ); - - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 3; x++ ) - { - this.addSlotToContainer( this.craftingSlots[x + y * 3] = new SlotFakeCraftingMatrix( this.crafting, x + y * 3, 18 + x * 18, -76 + y * 18 ) ); - } - } - - this.addSlotToContainer( this.craftSlot = new SlotPatternTerm( ip.player, this.getActionSource(), this - .getPowerSource(), monitorable, this.crafting, patternInv, this.cOut, 110, -76 + 18, this, 2, this ) ); - this.craftSlot.setIIcon( -1 ); - - for( int y = 0; y < 3; y++ ) - { - this.addSlotToContainer( this.outputSlots[y] = new SlotPatternOutputs( output, this, y, 110, -76 + y * 18, 0, 0, 1 ) ); - this.outputSlots[y].setRenderDisabled( false ); - this.outputSlots[y].setIIcon( -1 ); - } - - this.addSlotToContainer( - this.patternSlotIN = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.BLANK_PATTERN, patternInv, 0, 147, -72 - 9, this - .getInventoryPlayer() ) ); - this.addSlotToContainer( - this.patternSlotOUT = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, patternInv, 1, 147, -72 + 34, this - .getInventoryPlayer() ) ); - - this.patternSlotOUT.setStackLimit( 1 ); - - this.bindPlayerInventory( ip, 0, 0 ); - this.updateOrderOfOutputSlots(); - } - - @Override - public ItemStack transferStackInSlot( final EntityPlayer p, final int idx ) - { - if( Platform.isClient() ) - { - return ItemStack.EMPTY; - } - if( this.inventorySlots.get( idx ) instanceof SlotPlayerInv || this.inventorySlots.get( idx ) instanceof SlotPlayerHotBar ) - { - final AppEngSlot clickSlot = ( AppEngSlot ) this.inventorySlots.get( idx ); // require AE SLots! - ItemStack itemStack = clickSlot.getStack(); - if( AEApi.instance().definitions().materials().blankPattern().isSameAs( itemStack ) ) - { - IItemHandler patternInv = this.getPatternTerminal().getInventoryByName( "pattern" ); - ItemStack remainder = patternInv.insertItem( 0, itemStack, false ); - clickSlot.putStack( remainder ); - } - } - return super.transferStackInSlot( p, idx ); - } - - - private void updateOrderOfOutputSlots() - { - if( !this.isCraftingMode() ) - { - this.craftSlot.xPos = -9000; - - for( int y = 0; y < 3; y++ ) - { - this.outputSlots[y].xPos = this.outputSlots[y].getX(); - } - } - else - { - this.craftSlot.xPos = this.craftSlot.getX(); - - for( int y = 0; y < 3; y++ ) - { - this.outputSlots[y].xPos = -9000; - } - } - } - - @Override - public void putStackInSlot( int slotID, ItemStack stack ) - { - super.putStackInSlot( slotID, stack ); - this.getAndUpdateOutput(); - } - - protected ItemStack getAndUpdateOutput() - { - final World world = this.getPlayerInv().player.world; - final InventoryCrafting ic = new InventoryCrafting( this, 3, 3 ); - - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - ic.setInventorySlotContents( x, this.crafting.getStackInSlot( x ) ); - } - - if( this.currentRecipe == null || !this.currentRecipe.matches( ic, world ) ) - { - this.currentRecipe = CraftingManager.findMatchingRecipe( ic, world ); - } - - final ItemStack is; - - if( this.currentRecipe == null ) - { - is = ItemStack.EMPTY; - } - else - { - is = this.currentRecipe.getCraftingResult( ic ); - } - - this.cOut.setStackInSlot( 0, is ); - return is; - } - - @Override - public void saveChanges() - { - - } - - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - - } - - public void encodeAndMoveToInventory() - { - encode(); - ItemStack output = this.patternSlotOUT.getStack(); - if ( !output.isEmpty() ) - { - if (!getPlayerInv().addItemStackToInventory( output )){ - getPlayerInv().player.dropItem( output , false ); - } - this.patternSlotOUT.putStack( ItemStack.EMPTY ); - } - } - - public void encode() - { - ItemStack output = this.patternSlotOUT.getStack(); - - final ItemStack[] in = this.getInputs(); - final ItemStack[] out = this.getOutputs(); - - // if there is no input, this would be silly. - if( in == null || out == null ) - { - return; - } - - // first check the output slots, should either be null, or a pattern - if( !output.isEmpty() && !this.isPattern( output ) ) - { - return; - } // if nothing is there we should snag a new pattern. - else if( output.isEmpty() ) - { - output = this.patternSlotIN.getStack(); - if( output.isEmpty() || !this.isPattern( output ) ) - { - return; // no blanks. - } - - // remove one, and clear the input slot. - output.setCount( output.getCount() - 1 ); - if( output.getCount() == 0 ) - { - this.patternSlotIN.putStack( ItemStack.EMPTY ); - } - - // add a new encoded pattern. - Optional maybePattern = AEApi.instance().definitions().items().encodedPattern().maybeStack( 1 ); - if( maybePattern.isPresent() ) - { - output = maybePattern.get(); - this.patternSlotOUT.putStack( output ); - } - } - - // encode the slot. - final NBTTagCompound encodedValue = new NBTTagCompound(); - - final NBTTagList tagIn = new NBTTagList(); - final NBTTagList tagOut = new NBTTagList(); - - for( final ItemStack i : in ) - { - tagIn.appendTag( this.createItemTag( i ) ); - } - - for( final ItemStack i : out ) - { - tagOut.appendTag( this.createItemTag( i ) ); - } - - encodedValue.setTag( "in", tagIn ); - encodedValue.setTag( "out", tagOut ); - encodedValue.setBoolean( "crafting", this.isCraftingMode() ); - encodedValue.setBoolean( "substitute", this.isSubstitute() ); - - output.setTagCompound( encodedValue ); - } - - public void multiply(int multiple) - { - ItemStack[] input = new ItemStack[9]; - boolean canMultiplyInputs = true; - boolean canMultiplyOutputs = true; - - for( int x = 0; x < this.craftingSlots.length; x++ ) - { - input[x] = this.craftingSlots[x].getStack(); - if( !input[x].isEmpty() && input[x].getCount() * multiple > input[x].getMaxStackSize() ) - { - canMultiplyInputs = false; - } - } - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); - if( !out.isEmpty() && out.getCount() * multiple > out.getMaxStackSize() ) - { - canMultiplyOutputs = false; - } - } - if( canMultiplyInputs && canMultiplyOutputs ) - { - for( SlotFakeCraftingMatrix craftingSlot : this.craftingSlots ) - { - ItemStack stack = craftingSlot.getStack(); - if( !stack.isEmpty() ) - craftingSlot.getStack().setCount( stack.getCount() * multiple ); - } - for( OptionalSlotFake outputSlot : this.outputSlots ) - { - ItemStack stack = outputSlot.getStack(); - if( !stack.isEmpty() ) - outputSlot.getStack().setCount( stack.getCount() * multiple ); - } - } - } - - public void divide(int divide) - { - ItemStack[] input = new ItemStack[9]; - boolean canDivideInputs = true; - boolean canDivideOutputs = true; - - for( int x = 0; x < this.craftingSlots.length; x++ ) - { - input[x] = this.craftingSlots[x].getStack(); - if( !input[x].isEmpty() && input[x].getCount() % divide != 0 ) - { - canDivideInputs = false; - } - } - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); - if( !out.isEmpty() && out.getCount() % divide != 0 ) - { - canDivideOutputs = false; - } - } - if( canDivideInputs && canDivideOutputs ) - { - for( SlotFakeCraftingMatrix craftingSlot : this.craftingSlots ) - { - ItemStack stack = craftingSlot.getStack(); - if( !stack.isEmpty() ) - craftingSlot.getStack().setCount( stack.getCount() / divide ); - } - for( OptionalSlotFake outputSlot : this.outputSlots ) - { - ItemStack stack = outputSlot.getStack(); - if( !stack.isEmpty() ) - outputSlot.getStack().setCount( stack.getCount() / divide ); - } - } - } - - public void increase(int increase) - { - ItemStack[] input = new ItemStack[9]; - boolean canIncreaseInputs = true; - boolean canIncreaseOutputs = true; - - for( int x = 0; x < this.craftingSlots.length; x++ ) - { - input[x] = this.craftingSlots[x].getStack(); - if( !input[x].isEmpty() && input[x].getCount() + increase > input[x].getMaxStackSize() ) - { - canIncreaseInputs = false; - } - } - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); - if( !out.isEmpty() && out.getCount() + increase > out.getMaxStackSize() ) - { - canIncreaseOutputs = false; - } - } - if( canIncreaseInputs && canIncreaseOutputs ) - { - for( SlotFakeCraftingMatrix craftingSlot : this.craftingSlots ) - { - ItemStack stack = craftingSlot.getStack(); - if( !stack.isEmpty() ) - craftingSlot.getStack().setCount( stack.getCount() + increase ); - } - for( OptionalSlotFake outputSlot : this.outputSlots ) - { - ItemStack stack = outputSlot.getStack(); - if( !stack.isEmpty() ) - outputSlot.getStack().setCount( stack.getCount() + increase ); - } - } - } - - public void decrease(int decrease) - { - ItemStack[] input = new ItemStack[9]; - boolean canDecreaseInputs = true; - boolean canDecreaseOutputs = true; - - for( int x = 0; x < this.craftingSlots.length; x++ ) - { - input[x] = this.craftingSlots[x].getStack(); - if( !input[x].isEmpty() && input[x].getCount() - decrease < 1 ) - { - canDecreaseInputs = false; - } - } - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); - if( !out.isEmpty() && out.getCount() - decrease < 1 ) - { - canDecreaseOutputs = false; - } - } - if( canDecreaseInputs && canDecreaseOutputs ) - { - for( SlotFakeCraftingMatrix craftingSlot : this.craftingSlots ) - { - ItemStack stack = craftingSlot.getStack(); - if( !stack.isEmpty() ) - craftingSlot.getStack().setCount( stack.getCount() - decrease ); - } - for( OptionalSlotFake outputSlot : this.outputSlots ) - { - ItemStack stack = outputSlot.getStack(); - if( !stack.isEmpty() ) - outputSlot.getStack().setCount( stack.getCount() - decrease ); - } - } - } - - public void maximizeCount() - { - ItemStack[] input = new ItemStack[9]; - boolean canGrowInputs = true; - boolean canGrowOutputs = true; - int maxInputStackGrowth = 0; - int maxOutputStackGrowth = 0; - - - for( int x = 0; x < this.craftingSlots.length; x++ ) - { - input[x] = this.craftingSlots[x].getStack(); - if( !input[x].isEmpty() && input[x].getMaxStackSize() - input[x].getCount() > maxInputStackGrowth ) - { - maxInputStackGrowth = input[x].getMaxStackSize() - input[x].getCount(); - } - if( !input[x].isEmpty() && input[x].getCount() + maxInputStackGrowth > input[x].getMaxStackSize() ) - { - canGrowInputs = false; - } - } - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); - { - maxOutputStackGrowth = out.getMaxStackSize() - out.getCount(); - } - if( !out.isEmpty() && out.getCount() + maxOutputStackGrowth > out.getMaxStackSize() ) - { - canGrowOutputs = false; - } - } - if( canGrowInputs && canGrowOutputs ) - { - int maxStackGrowth = Math.min(maxInputStackGrowth,maxOutputStackGrowth); - for( SlotFakeCraftingMatrix craftingSlot : this.craftingSlots ) - { - ItemStack stack = craftingSlot.getStack(); - if( !stack.isEmpty() ) - craftingSlot.getStack().setCount( stack.getCount() + maxStackGrowth ); - } - for( OptionalSlotFake outputSlot : this.outputSlots ) - { - ItemStack stack = outputSlot.getStack(); - if( !stack.isEmpty() ) - outputSlot.getStack().setCount( stack.getCount() + maxStackGrowth ); - } - } - } - - protected ItemStack[] getInputs() - { - final ItemStack[] input = new ItemStack[9]; - boolean hasValue = false; - - for( int x = 0; x < this.craftingSlots.length; x++ ) - { - input[x] = this.craftingSlots[x].getStack(); - if( !input[x].isEmpty() ) - { - hasValue = true; - } - } - - if( hasValue ) - { - return input; - } - - return null; - } - - protected ItemStack[] getOutputs() - { - if( this.isCraftingMode() ) - { - final ItemStack out = this.getAndUpdateOutput(); - - if( !out.isEmpty() && out.getCount() > 0 ) - { - return new ItemStack[]{out}; - } - } - else - { - final List list = new ArrayList<>( 3 ); - boolean hasValue = false; - - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); - - if( !out.isEmpty() && out.getCount() > 0 ) - { - list.add( out ); - hasValue = true; - } - } - - if( hasValue ) - { - return list.toArray( new ItemStack[list.size()] ); - } - } - - return null; - } - - boolean isPattern( final ItemStack output ) - { - if( output.isEmpty() ) - { - return false; - } - - final IDefinitions definitions = AEApi.instance().definitions(); - - boolean isPattern = definitions.items().encodedPattern().isSameAs( output ); - isPattern |= definitions.materials().blankPattern().isSameAs( output ); - - return isPattern; - } - - NBTBase createItemTag( final ItemStack i ) - { - final NBTTagCompound c = new NBTTagCompound(); - - if( !i.isEmpty() ) - { - i.writeToNBT( c ); - } - - return c; - } - - @Override - public boolean isSlotEnabled( final int idx ) - { - if( idx == 1 ) - { - return Platform.isServer() ? !this.getPatternTerminal().isCraftingRecipe() : !this.isCraftingMode(); - } - else if( idx == 2 ) - { - return Platform.isServer() ? this.getPatternTerminal().isCraftingRecipe() : this.isCraftingMode(); - } - else - { - return false; - } - } - - public void craftOrGetItem( final PacketPatternSlot packetPatternSlot ) - { - if( packetPatternSlot.slotItem != null && this.getCellInventory() != null ) - { - final IAEItemStack out = packetPatternSlot.slotItem.copy(); - InventoryAdaptor inv = new AdaptorItemHandler( new WrapperCursorItemHandler( this.getPlayerInv().player.inventory ) ); - final InventoryAdaptor playerInv = InventoryAdaptor.getAdaptor( this.getPlayerInv().player ); - - if( packetPatternSlot.shift ) - { - inv = playerInv; - } - - if( !inv.simulateAdd( out.createItemStack() ).isEmpty() ) - { - return; - } - - final IAEItemStack extracted = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), out, this.getActionSource() ); - final EntityPlayer p = this.getPlayerInv().player; - - if( extracted != null ) - { - inv.addItems( extracted.createItemStack() ); - if( p instanceof EntityPlayerMP ) - { - this.updateHeld( (EntityPlayerMP) p ); - } - this.detectAndSendChanges(); - return; - } - - final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); - final InventoryCrafting real = new InventoryCrafting( new ContainerNull(), 3, 3 ); - - for( int x = 0; x < 9; x++ ) - { - ic.setInventorySlotContents( x, packetPatternSlot.pattern[x] == null ? ItemStack.EMPTY : packetPatternSlot.pattern[x].createItemStack() ); - } - - final IRecipe r = CraftingManager.findMatchingRecipe( ic, p.world ); - - if( r == null ) - { - return; - } - - final IMEMonitor storage = this.getPatternTerminal() - .getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - final IItemList all = storage.getStorageList(); - - final ItemStack is = r.getCraftingResult( ic ); - - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - if( !ic.getStackInSlot( x ).isEmpty() ) - { - final ItemStack pulled = Platform.extractItemsByRecipe( this.getPowerSource(), this.getActionSource(), storage, p.world, r, is, ic, - ic.getStackInSlot( x ), x, all, Actionable.MODULATE, ItemViewCell.createFilter( this.getViewCells() ) ); - real.setInventorySlotContents( x, pulled ); - } - } - - final IRecipe rr = CraftingManager.findMatchingRecipe( real, p.world ); - - if( rr == r && Platform.itemComparisons().isSameItem( rr.getCraftingResult( real ), is ) ) - { - final InventoryCraftResult craftingResult = new InventoryCraftResult(); - craftingResult.setRecipeUsed( rr ); - - final SlotCrafting sc = new SlotCrafting( p, real, craftingResult, 0, 0, 0 ); - sc.onTake( p, is ); - - for( int x = 0; x < real.getSizeInventory(); x++ ) - { - final ItemStack failed = playerInv.addItems( real.getStackInSlot( x ) ); - - if( !failed.isEmpty() ) - { - p.dropItem( failed, false ); - } - } - - inv.addItems( is ); - if( p instanceof EntityPlayerMP ) - { - this.updateHeld( (EntityPlayerMP) p ); - } - this.detectAndSendChanges(); - } - else - { - for( int x = 0; x < real.getSizeInventory(); x++ ) - { - final ItemStack failed = real.getStackInSlot( x ); - if( !failed.isEmpty() ) - { - this.getCellInventory() - .injectItems( AEItemStack.fromItemStack( failed ), Actionable.MODULATE, - new MachineSource( this.getPatternTerminal() ) ); - } - } - } - } - } - - @Override - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - if( Platform.isServer() ) - { - if( this.isCraftingMode() != this.getPatternTerminal().isCraftingRecipe() ) - { - this.setCraftingMode( this.getPatternTerminal().isCraftingRecipe() ); - this.updateOrderOfOutputSlots(); - } - - this.substitute = this.patternTerminal.isSubstitution(); - } - } - - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - super.onUpdate( field, oldValue, newValue ); - - if( field.equals( "craftingMode" ) ) - { - this.getAndUpdateOutput(); - this.updateOrderOfOutputSlots(); - } - } - - @Override - public void onSlotChange( final Slot s ) - { - if( s == this.patternSlotOUT && Platform.isServer() ) - { - for( final IContainerListener listener : this.listeners ) - { - for( final Slot slot : this.inventorySlots ) - { - if( slot instanceof OptionalSlotFake || slot instanceof SlotFakeCraftingMatrix ) - { - listener.sendSlotContents( this, slot.slotNumber, slot.getStack() ); - } - } - if( listener instanceof EntityPlayerMP ) - { - ( (EntityPlayerMP) listener ).isChangingQuantityOnly = false; - } - } - this.detectAndSendChanges(); - } - - if( s == this.craftSlot && Platform.isClient() ) - { - this.getAndUpdateOutput(); - } - } - - public void clear() - { - for( final Slot s : this.craftingSlots ) - { - s.putStack( ItemStack.EMPTY ); - } - - for( final Slot s : this.outputSlots ) - { - s.putStack( ItemStack.EMPTY ); - } - - this.detectAndSendChanges(); - this.getAndUpdateOutput(); - } - - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "player" ) ) - { - return new PlayerInvWrapper( this.getInventoryPlayer() ); - } - return this.getPatternTerminal().getInventoryByName( name ); - } - - @Override - public boolean useRealItems() - { - return false; - } - - public void toggleSubstitute() - { - this.substitute = !this.substitute; - - this.detectAndSendChanges(); - this.getAndUpdateOutput(); - } - - public boolean isCraftingMode() - { - return this.craftingMode; - } - - private void setCraftingMode( final boolean craftingMode ) - { - this.craftingMode = craftingMode; - } - - public PartPatternTerminal getPatternTerminal() - { - return this.patternTerminal; - } - - boolean isSubstitute() - { - return this.substitute; - } - - public void setSubstitute( final boolean substitute ) - { - this.substitute = substitute; - } +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.*; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.world.World; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.wrapper.PlayerInvWrapper; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + + +public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEAppEngInventory, IOptionalSlotHost, IContainerCraftingPacket { + + private final PartPatternTerminal patternTerminal; + private final AppEngInternalInventory cOut = new AppEngInternalInventory(null, 1); + private final IItemHandler crafting; + private final SlotFakeCraftingMatrix[] craftingSlots = new SlotFakeCraftingMatrix[9]; + private final OptionalSlotFake[] outputSlots = new OptionalSlotFake[3]; + private final SlotPatternTerm craftSlot; + private final SlotRestrictedInput patternSlotIN; + private final SlotRestrictedInput patternSlotOUT; + + private IRecipe currentRecipe; + @GuiSync(97) + public boolean craftingMode = true; + @GuiSync(96) + public boolean substitute = false; + + public ContainerPatternTerm(final InventoryPlayer ip, final ITerminalHost monitorable) { + super(ip, monitorable, false); + this.patternTerminal = (PartPatternTerminal) monitorable; + + final IItemHandler patternInv = this.getPatternTerminal().getInventoryByName("pattern"); + final IItemHandler output = this.getPatternTerminal().getInventoryByName("output"); + + this.crafting = this.getPatternTerminal().getInventoryByName("crafting"); + + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + this.addSlotToContainer(this.craftingSlots[x + y * 3] = new SlotFakeCraftingMatrix(this.crafting, x + y * 3, 18 + x * 18, -76 + y * 18)); + } + } + + this.addSlotToContainer(this.craftSlot = new SlotPatternTerm(ip.player, this.getActionSource(), this + .getPowerSource(), monitorable, this.crafting, patternInv, this.cOut, 110, -76 + 18, this, 2, this)); + this.craftSlot.setIIcon(-1); + + for (int y = 0; y < 3; y++) { + this.addSlotToContainer(this.outputSlots[y] = new SlotPatternOutputs(output, this, y, 110, -76 + y * 18, 0, 0, 1)); + this.outputSlots[y].setRenderDisabled(false); + this.outputSlots[y].setIIcon(-1); + } + + this.addSlotToContainer( + this.patternSlotIN = new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.BLANK_PATTERN, patternInv, 0, 147, -72 - 9, this + .getInventoryPlayer())); + this.addSlotToContainer( + this.patternSlotOUT = new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, patternInv, 1, 147, -72 + 34, this + .getInventoryPlayer())); + + this.patternSlotOUT.setStackLimit(1); + + this.bindPlayerInventory(ip, 0, 0); + this.updateOrderOfOutputSlots(); + } + + @Override + public ItemStack transferStackInSlot(final EntityPlayer p, final int idx) { + if (Platform.isClient()) { + return ItemStack.EMPTY; + } + if (this.inventorySlots.get(idx) instanceof SlotPlayerInv || this.inventorySlots.get(idx) instanceof SlotPlayerHotBar) { + final AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get(idx); // require AE SLots! + ItemStack itemStack = clickSlot.getStack(); + if (AEApi.instance().definitions().materials().blankPattern().isSameAs(itemStack)) { + IItemHandler patternInv = this.getPatternTerminal().getInventoryByName("pattern"); + ItemStack remainder = patternInv.insertItem(0, itemStack, false); + clickSlot.putStack(remainder); + } + } + return super.transferStackInSlot(p, idx); + } + + + private void updateOrderOfOutputSlots() { + if (!this.isCraftingMode()) { + this.craftSlot.xPos = -9000; + + for (int y = 0; y < 3; y++) { + this.outputSlots[y].xPos = this.outputSlots[y].getX(); + } + } else { + this.craftSlot.xPos = this.craftSlot.getX(); + + for (int y = 0; y < 3; y++) { + this.outputSlots[y].xPos = -9000; + } + } + } + + @Override + public void putStackInSlot(int slotID, ItemStack stack) { + super.putStackInSlot(slotID, stack); + this.getAndUpdateOutput(); + } + + protected ItemStack getAndUpdateOutput() { + final World world = this.getPlayerInv().player.world; + final InventoryCrafting ic = new InventoryCrafting(this, 3, 3); + + for (int x = 0; x < ic.getSizeInventory(); x++) { + ic.setInventorySlotContents(x, this.crafting.getStackInSlot(x)); + } + + if (this.currentRecipe == null || !this.currentRecipe.matches(ic, world)) { + this.currentRecipe = CraftingManager.findMatchingRecipe(ic, world); + } + + final ItemStack is; + + if (this.currentRecipe == null) { + is = ItemStack.EMPTY; + } else { + is = this.currentRecipe.getCraftingResult(ic); + } + + this.cOut.setStackInSlot(0, is); + return is; + } + + @Override + public void saveChanges() { + + } + + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { + + } + + public void encodeAndMoveToInventory() { + encode(); + ItemStack output = this.patternSlotOUT.getStack(); + if (!output.isEmpty()) { + if (!getPlayerInv().addItemStackToInventory(output)) { + getPlayerInv().player.dropItem(output, false); + } + this.patternSlotOUT.putStack(ItemStack.EMPTY); + } + } + + public void encode() { + ItemStack output = this.patternSlotOUT.getStack(); + + final ItemStack[] in = this.getInputs(); + final ItemStack[] out = this.getOutputs(); + + // if there is no input, this would be silly. + if (in == null || out == null) { + return; + } + + // first check the output slots, should either be null, or a pattern + if (!output.isEmpty() && !this.isPattern(output)) { + return; + } // if nothing is there we should snag a new pattern. + else if (output.isEmpty()) { + output = this.patternSlotIN.getStack(); + if (output.isEmpty() || !this.isPattern(output)) { + return; // no blanks. + } + + // remove one, and clear the input slot. + output.setCount(output.getCount() - 1); + if (output.getCount() == 0) { + this.patternSlotIN.putStack(ItemStack.EMPTY); + } + + // add a new encoded pattern. + Optional maybePattern = AEApi.instance().definitions().items().encodedPattern().maybeStack(1); + if (maybePattern.isPresent()) { + output = maybePattern.get(); + this.patternSlotOUT.putStack(output); + } + } + + // encode the slot. + final NBTTagCompound encodedValue = new NBTTagCompound(); + + final NBTTagList tagIn = new NBTTagList(); + final NBTTagList tagOut = new NBTTagList(); + + for (final ItemStack i : in) { + tagIn.appendTag(this.createItemTag(i)); + } + + for (final ItemStack i : out) { + tagOut.appendTag(this.createItemTag(i)); + } + + encodedValue.setTag("in", tagIn); + encodedValue.setTag("out", tagOut); + encodedValue.setBoolean("crafting", this.isCraftingMode()); + encodedValue.setBoolean("substitute", this.isSubstitute()); + + output.setTagCompound(encodedValue); + } + + public void multiply(int multiple) { + ItemStack[] input = new ItemStack[9]; + boolean canMultiplyInputs = true; + boolean canMultiplyOutputs = true; + + for (int x = 0; x < this.craftingSlots.length; x++) { + input[x] = this.craftingSlots[x].getStack(); + if (!input[x].isEmpty() && input[x].getCount() * multiple > input[x].getMaxStackSize()) { + canMultiplyInputs = false; + } + } + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); + if (!out.isEmpty() && out.getCount() * multiple > out.getMaxStackSize()) { + canMultiplyOutputs = false; + } + } + if (canMultiplyInputs && canMultiplyOutputs) { + for (SlotFakeCraftingMatrix craftingSlot : this.craftingSlots) { + ItemStack stack = craftingSlot.getStack(); + if (!stack.isEmpty()) + craftingSlot.getStack().setCount(stack.getCount() * multiple); + } + for (OptionalSlotFake outputSlot : this.outputSlots) { + ItemStack stack = outputSlot.getStack(); + if (!stack.isEmpty()) + outputSlot.getStack().setCount(stack.getCount() * multiple); + } + } + } + + public void divide(int divide) { + ItemStack[] input = new ItemStack[9]; + boolean canDivideInputs = true; + boolean canDivideOutputs = true; + + for (int x = 0; x < this.craftingSlots.length; x++) { + input[x] = this.craftingSlots[x].getStack(); + if (!input[x].isEmpty() && input[x].getCount() % divide != 0) { + canDivideInputs = false; + } + } + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); + if (!out.isEmpty() && out.getCount() % divide != 0) { + canDivideOutputs = false; + } + } + if (canDivideInputs && canDivideOutputs) { + for (SlotFakeCraftingMatrix craftingSlot : this.craftingSlots) { + ItemStack stack = craftingSlot.getStack(); + if (!stack.isEmpty()) + craftingSlot.getStack().setCount(stack.getCount() / divide); + } + for (OptionalSlotFake outputSlot : this.outputSlots) { + ItemStack stack = outputSlot.getStack(); + if (!stack.isEmpty()) + outputSlot.getStack().setCount(stack.getCount() / divide); + } + } + } + + public void increase(int increase) { + ItemStack[] input = new ItemStack[9]; + boolean canIncreaseInputs = true; + boolean canIncreaseOutputs = true; + + for (int x = 0; x < this.craftingSlots.length; x++) { + input[x] = this.craftingSlots[x].getStack(); + if (!input[x].isEmpty() && input[x].getCount() + increase > input[x].getMaxStackSize()) { + canIncreaseInputs = false; + } + } + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); + if (!out.isEmpty() && out.getCount() + increase > out.getMaxStackSize()) { + canIncreaseOutputs = false; + } + } + if (canIncreaseInputs && canIncreaseOutputs) { + for (SlotFakeCraftingMatrix craftingSlot : this.craftingSlots) { + ItemStack stack = craftingSlot.getStack(); + if (!stack.isEmpty()) + craftingSlot.getStack().setCount(stack.getCount() + increase); + } + for (OptionalSlotFake outputSlot : this.outputSlots) { + ItemStack stack = outputSlot.getStack(); + if (!stack.isEmpty()) + outputSlot.getStack().setCount(stack.getCount() + increase); + } + } + } + + public void decrease(int decrease) { + ItemStack[] input = new ItemStack[9]; + boolean canDecreaseInputs = true; + boolean canDecreaseOutputs = true; + + for (int x = 0; x < this.craftingSlots.length; x++) { + input[x] = this.craftingSlots[x].getStack(); + if (!input[x].isEmpty() && input[x].getCount() - decrease < 1) { + canDecreaseInputs = false; + } + } + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); + if (!out.isEmpty() && out.getCount() - decrease < 1) { + canDecreaseOutputs = false; + } + } + if (canDecreaseInputs && canDecreaseOutputs) { + for (SlotFakeCraftingMatrix craftingSlot : this.craftingSlots) { + ItemStack stack = craftingSlot.getStack(); + if (!stack.isEmpty()) + craftingSlot.getStack().setCount(stack.getCount() - decrease); + } + for (OptionalSlotFake outputSlot : this.outputSlots) { + ItemStack stack = outputSlot.getStack(); + if (!stack.isEmpty()) + outputSlot.getStack().setCount(stack.getCount() - decrease); + } + } + } + + public void maximizeCount() { + ItemStack[] input = new ItemStack[9]; + boolean canGrowInputs = true; + boolean canGrowOutputs = true; + int maxInputStackGrowth = 0; + int maxOutputStackGrowth = 0; + + + for (int x = 0; x < this.craftingSlots.length; x++) { + input[x] = this.craftingSlots[x].getStack(); + if (!input[x].isEmpty() && input[x].getMaxStackSize() - input[x].getCount() > maxInputStackGrowth) { + maxInputStackGrowth = input[x].getMaxStackSize() - input[x].getCount(); + } + if (!input[x].isEmpty() && input[x].getCount() + maxInputStackGrowth > input[x].getMaxStackSize()) { + canGrowInputs = false; + } + } + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); + { + maxOutputStackGrowth = out.getMaxStackSize() - out.getCount(); + } + if (!out.isEmpty() && out.getCount() + maxOutputStackGrowth > out.getMaxStackSize()) { + canGrowOutputs = false; + } + } + if (canGrowInputs && canGrowOutputs) { + int maxStackGrowth = Math.min(maxInputStackGrowth, maxOutputStackGrowth); + for (SlotFakeCraftingMatrix craftingSlot : this.craftingSlots) { + ItemStack stack = craftingSlot.getStack(); + if (!stack.isEmpty()) + craftingSlot.getStack().setCount(stack.getCount() + maxStackGrowth); + } + for (OptionalSlotFake outputSlot : this.outputSlots) { + ItemStack stack = outputSlot.getStack(); + if (!stack.isEmpty()) + outputSlot.getStack().setCount(stack.getCount() + maxStackGrowth); + } + } + } + + protected ItemStack[] getInputs() { + final ItemStack[] input = new ItemStack[9]; + boolean hasValue = false; + + for (int x = 0; x < this.craftingSlots.length; x++) { + input[x] = this.craftingSlots[x].getStack(); + if (!input[x].isEmpty()) { + hasValue = true; + } + } + + if (hasValue) { + return input; + } + + return null; + } + + protected ItemStack[] getOutputs() { + if (this.isCraftingMode()) { + final ItemStack out = this.getAndUpdateOutput(); + + if (!out.isEmpty() && out.getCount() > 0) { + return new ItemStack[]{out}; + } + } else { + final List list = new ArrayList<>(3); + boolean hasValue = false; + + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); + + if (!out.isEmpty() && out.getCount() > 0) { + list.add(out); + hasValue = true; + } + } + + if (hasValue) { + return list.toArray(new ItemStack[list.size()]); + } + } + + return null; + } + + boolean isPattern(final ItemStack output) { + if (output.isEmpty()) { + return false; + } + + final IDefinitions definitions = AEApi.instance().definitions(); + + boolean isPattern = definitions.items().encodedPattern().isSameAs(output); + isPattern |= definitions.materials().blankPattern().isSameAs(output); + + return isPattern; + } + + NBTBase createItemTag(final ItemStack i) { + final NBTTagCompound c = new NBTTagCompound(); + + if (!i.isEmpty()) { + i.writeToNBT(c); + } + + return c; + } + + @Override + public boolean isSlotEnabled(final int idx) { + if (idx == 1) { + return Platform.isServer() ? !this.getPatternTerminal().isCraftingRecipe() : !this.isCraftingMode(); + } else if (idx == 2) { + return Platform.isServer() ? this.getPatternTerminal().isCraftingRecipe() : this.isCraftingMode(); + } else { + return false; + } + } + + public void craftOrGetItem(final PacketPatternSlot packetPatternSlot) { + if (packetPatternSlot.slotItem != null && this.getCellInventory() != null) { + final IAEItemStack out = packetPatternSlot.slotItem.copy(); + InventoryAdaptor inv = new AdaptorItemHandler(new WrapperCursorItemHandler(this.getPlayerInv().player.inventory)); + final InventoryAdaptor playerInv = InventoryAdaptor.getAdaptor(this.getPlayerInv().player); + + if (packetPatternSlot.shift) { + inv = playerInv; + } + + if (!inv.simulateAdd(out.createItemStack()).isEmpty()) { + return; + } + + final IAEItemStack extracted = Platform.poweredExtraction(this.getPowerSource(), this.getCellInventory(), out, this.getActionSource()); + final EntityPlayer p = this.getPlayerInv().player; + + if (extracted != null) { + inv.addItems(extracted.createItemStack()); + if (p instanceof EntityPlayerMP) { + this.updateHeld((EntityPlayerMP) p); + } + this.detectAndSendChanges(); + return; + } + + final InventoryCrafting ic = new InventoryCrafting(new ContainerNull(), 3, 3); + final InventoryCrafting real = new InventoryCrafting(new ContainerNull(), 3, 3); + + for (int x = 0; x < 9; x++) { + ic.setInventorySlotContents(x, packetPatternSlot.pattern[x] == null ? ItemStack.EMPTY : packetPatternSlot.pattern[x].createItemStack()); + } + + final IRecipe r = CraftingManager.findMatchingRecipe(ic, p.world); + + if (r == null) { + return; + } + + final IMEMonitor storage = this.getPatternTerminal() + .getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + final IItemList all = storage.getStorageList(); + + final ItemStack is = r.getCraftingResult(ic); + + for (int x = 0; x < ic.getSizeInventory(); x++) { + if (!ic.getStackInSlot(x).isEmpty()) { + final ItemStack pulled = Platform.extractItemsByRecipe(this.getPowerSource(), this.getActionSource(), storage, p.world, r, is, ic, + ic.getStackInSlot(x), x, all, Actionable.MODULATE, ItemViewCell.createFilter(this.getViewCells())); + real.setInventorySlotContents(x, pulled); + } + } + + final IRecipe rr = CraftingManager.findMatchingRecipe(real, p.world); + + if (rr == r && Platform.itemComparisons().isSameItem(rr.getCraftingResult(real), is)) { + final InventoryCraftResult craftingResult = new InventoryCraftResult(); + craftingResult.setRecipeUsed(rr); + + final SlotCrafting sc = new SlotCrafting(p, real, craftingResult, 0, 0, 0); + sc.onTake(p, is); + + for (int x = 0; x < real.getSizeInventory(); x++) { + final ItemStack failed = playerInv.addItems(real.getStackInSlot(x)); + + if (!failed.isEmpty()) { + p.dropItem(failed, false); + } + } + + inv.addItems(is); + if (p instanceof EntityPlayerMP) { + this.updateHeld((EntityPlayerMP) p); + } + this.detectAndSendChanges(); + } else { + for (int x = 0; x < real.getSizeInventory(); x++) { + final ItemStack failed = real.getStackInSlot(x); + if (!failed.isEmpty()) { + this.getCellInventory() + .injectItems(AEItemStack.fromItemStack(failed), Actionable.MODULATE, + new MachineSource(this.getPatternTerminal())); + } + } + } + } + } + + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + if (Platform.isServer()) { + if (this.isCraftingMode() != this.getPatternTerminal().isCraftingRecipe()) { + this.setCraftingMode(this.getPatternTerminal().isCraftingRecipe()); + this.updateOrderOfOutputSlots(); + } + + this.substitute = this.patternTerminal.isSubstitution(); + } + } + + @Override + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + super.onUpdate(field, oldValue, newValue); + + if (field.equals("craftingMode")) { + this.getAndUpdateOutput(); + this.updateOrderOfOutputSlots(); + } + } + + @Override + public void onSlotChange(final Slot s) { + if (s == this.patternSlotOUT && Platform.isServer()) { + for (final IContainerListener listener : this.listeners) { + for (final Slot slot : this.inventorySlots) { + if (slot instanceof OptionalSlotFake || slot instanceof SlotFakeCraftingMatrix) { + listener.sendSlotContents(this, slot.slotNumber, slot.getStack()); + } + } + if (listener instanceof EntityPlayerMP) { + ((EntityPlayerMP) listener).isChangingQuantityOnly = false; + } + } + this.detectAndSendChanges(); + } + + if (s == this.craftSlot && Platform.isClient()) { + this.getAndUpdateOutput(); + } + } + + public void clear() { + for (final Slot s : this.craftingSlots) { + s.putStack(ItemStack.EMPTY); + } + + for (final Slot s : this.outputSlots) { + s.putStack(ItemStack.EMPTY); + } + + this.detectAndSendChanges(); + this.getAndUpdateOutput(); + } + + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("player")) { + return new PlayerInvWrapper(this.getInventoryPlayer()); + } + return this.getPatternTerminal().getInventoryByName(name); + } + + @Override + public boolean useRealItems() { + return false; + } + + public void toggleSubstitute() { + this.substitute = !this.substitute; + + this.detectAndSendChanges(); + this.getAndUpdateOutput(); + } + + public boolean isCraftingMode() { + return this.craftingMode; + } + + private void setCraftingMode(final boolean craftingMode) { + this.craftingMode = craftingMode; + } + + public PartPatternTerminal getPatternTerminal() { + return this.patternTerminal; + } + + boolean isSubstitute() { + return this.substitute; + } + + public void setSubstitute(final boolean substitute) { + this.substitute = substitute; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerPriority.java b/src/main/java/appeng/container/implementations/ContainerPriority.java index e9d9112cc..9f98ee89f 100644 --- a/src/main/java/appeng/container/implementations/ContainerPriority.java +++ b/src/main/java/appeng/container/implementations/ContainerPriority.java @@ -19,6 +19,12 @@ package appeng.container.implementations; +import appeng.api.config.SecurityPermissions; +import appeng.api.parts.IPart; +import appeng.container.AEBaseContainer; +import appeng.container.guisync.GuiSync; +import appeng.helpers.IPriorityHost; +import appeng.util.Platform; import net.minecraft.client.gui.GuiTextField; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; @@ -26,71 +32,54 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.config.SecurityPermissions; -import appeng.api.parts.IPart; -import appeng.container.AEBaseContainer; -import appeng.container.guisync.GuiSync; -import appeng.helpers.IPriorityHost; -import appeng.util.Platform; +public class ContainerPriority extends AEBaseContainer { -public class ContainerPriority extends AEBaseContainer -{ + private final IPriorityHost priHost; - private final IPriorityHost priHost; + @SideOnly(Side.CLIENT) + private GuiTextField textField; + @GuiSync(2) + public long PriorityValue = -1; - @SideOnly( Side.CLIENT ) - private GuiTextField textField; - @GuiSync( 2 ) - public long PriorityValue = -1; + public ContainerPriority(final InventoryPlayer ip, final IPriorityHost te) { + super(ip, (TileEntity) (te instanceof TileEntity ? te : null), (IPart) (te instanceof IPart ? te : null)); + this.priHost = te; + } - public ContainerPriority( final InventoryPlayer ip, final IPriorityHost te ) - { - super( ip, (TileEntity) ( te instanceof TileEntity ? te : null ), (IPart) ( te instanceof IPart ? te : null ) ); - this.priHost = te; - } + @SideOnly(Side.CLIENT) + public void setTextField(final GuiTextField level) { + this.textField = level; + this.textField.setText(String.valueOf(this.PriorityValue)); + } - @SideOnly( Side.CLIENT ) - public void setTextField( final GuiTextField level ) - { - this.textField = level; - this.textField.setText( String.valueOf( this.PriorityValue ) ); - } + public void setPriority(final int newValue, final EntityPlayer player) { + this.priHost.setPriority(newValue); + this.PriorityValue = newValue; + } - public void setPriority( final int newValue, final EntityPlayer player ) - { - this.priHost.setPriority( newValue ); - this.PriorityValue = newValue; - } + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + this.verifyPermissions(SecurityPermissions.BUILD, false); - @Override - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - this.verifyPermissions( SecurityPermissions.BUILD, false ); + if (Platform.isServer()) { + this.PriorityValue = this.priHost.getPriority(); + } + } - if( Platform.isServer() ) - { - this.PriorityValue = this.priHost.getPriority(); - } - } + @Override + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("PriorityValue")) { + if (this.textField != null) { + this.textField.setText(String.valueOf(this.PriorityValue)); + } + } - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if( field.equals( "PriorityValue" ) ) - { - if( this.textField != null ) - { - this.textField.setText( String.valueOf( this.PriorityValue ) ); - } - } + super.onUpdate(field, oldValue, newValue); + } - super.onUpdate( field, oldValue, newValue ); - } - - public IPriorityHost getPriorityHost() - { - return this.priHost; - } + public IPriorityHost getPriorityHost() { + return this.priHost; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerQNB.java b/src/main/java/appeng/container/implementations/ContainerQNB.java index 876740ad1..c34ab38a7 100644 --- a/src/main/java/appeng/container/implementations/ContainerQNB.java +++ b/src/main/java/appeng/container/implementations/ContainerQNB.java @@ -19,23 +19,20 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.qnb.TileQuantumBridge; +import net.minecraft.entity.player.InventoryPlayer; -public class ContainerQNB extends AEBaseContainer -{ +public class ContainerQNB extends AEBaseContainer { - public ContainerQNB( final InventoryPlayer ip, final TileQuantumBridge quantumBridge ) - { - super( ip, quantumBridge, null ); + public ContainerQNB(final InventoryPlayer ip, final TileQuantumBridge quantumBridge) { + super(ip, quantumBridge, null); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.QE_SINGULARITY, quantumBridge - .getInternalInventory(), 0, 80, 37, this.getInventoryPlayer() ) ).setStackLimit( 1 ) ); + this.addSlotToContainer((new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.QE_SINGULARITY, quantumBridge + .getInternalInventory(), 0, 80, 37, this.getInventoryPlayer())).setStackLimit(1)); - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 166 - /* height of player inventory */82); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java b/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java index 42c35b59d..f6d111a1b 100644 --- a/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java +++ b/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java @@ -19,9 +19,13 @@ package appeng.container.implementations; -import javax.annotation.Nonnull; - +import appeng.api.AEApi; +import appeng.container.AEBaseContainer; +import appeng.container.slot.SlotOutput; +import appeng.container.slot.SlotRestrictedInput; import appeng.items.contents.QuartzKnifeObj; +import appeng.tile.inventory.AppEngInternalInventory; +import appeng.util.Platform; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; @@ -30,150 +34,118 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; import net.minecraftforge.items.IItemHandler; -import appeng.api.AEApi; -import appeng.container.AEBaseContainer; -import appeng.container.slot.SlotOutput; -import appeng.container.slot.SlotRestrictedInput; -import appeng.tile.inventory.AppEngInternalInventory; -import appeng.util.Platform; +import javax.annotation.Nonnull; -public class ContainerQuartzKnife extends AEBaseContainer -{ +public class ContainerQuartzKnife extends AEBaseContainer { - private final QuartzKnifeObj toolInv; + private final QuartzKnifeObj toolInv; - private final IItemHandler inSlot = new AppEngInternalInventory( null, 1, 1 ); - private String myName = ""; + private final IItemHandler inSlot = new AppEngInternalInventory(null, 1, 1); + private String myName = ""; - public ContainerQuartzKnife( final InventoryPlayer ip, final QuartzKnifeObj te ) - { - super( ip, null, null ); - this.toolInv = te; + public ContainerQuartzKnife(final InventoryPlayer ip, final QuartzKnifeObj te) { + super(ip, null, null); + this.toolInv = te; - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.METAL_INGOTS, this.inSlot, 0, 94, 44, ip ) ); - this.addSlotToContainer( new QuartzKniveSlot( this.inSlot, 0, 134, 44, -1 ) ); + this.addSlotToContainer(new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.METAL_INGOTS, this.inSlot, 0, 94, 44, ip)); + this.addSlotToContainer(new QuartzKniveSlot(this.inSlot, 0, 134, 44, -1)); - this.lockPlayerInventorySlot( ip.currentItem ); + this.lockPlayerInventorySlot(ip.currentItem); - this.bindPlayerInventory( ip, 0, 184 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 184 - /* height of player inventory */82); + } - public void setName( final String value ) - { - this.myName = value; - } + public void setName(final String value) { + this.myName = value; + } - @Override - public void detectAndSendChanges() - { - final ItemStack currentItem = this.getPlayerInv().getCurrentItem(); + @Override + public void detectAndSendChanges() { + final ItemStack currentItem = this.getPlayerInv().getCurrentItem(); - if( currentItem != this.toolInv.getItemStack() ) - { - if( !currentItem.isEmpty() ) - { - if( ItemStack.areItemsEqual( this.toolInv.getItemStack(), currentItem ) ) - { - this.getPlayerInv().setInventorySlotContents( this.getPlayerInv().currentItem, this.toolInv.getItemStack() ); - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.setValidContainer( false ); - } - } + if (currentItem != this.toolInv.getItemStack()) { + if (!currentItem.isEmpty()) { + if (ItemStack.areItemsEqual(this.toolInv.getItemStack(), currentItem)) { + this.getPlayerInv().setInventorySlotContents(this.getPlayerInv().currentItem, this.toolInv.getItemStack()); + } else { + this.setValidContainer(false); + } + } else { + this.setValidContainer(false); + } + } - super.detectAndSendChanges(); - } + super.detectAndSendChanges(); + } - @Override - public void onContainerClosed( final EntityPlayer par1EntityPlayer ) - { - if( this.inSlot.getStackInSlot( 0 ) != null ) - { - par1EntityPlayer.dropItem( this.inSlot.getStackInSlot( 0 ), false ); - } - } + @Override + public void onContainerClosed(final EntityPlayer par1EntityPlayer) { + if (this.inSlot.getStackInSlot(0) != null) { + par1EntityPlayer.dropItem(this.inSlot.getStackInSlot(0), false); + } + } - private class QuartzKniveSlot extends SlotOutput - { - QuartzKniveSlot( IItemHandler a, int b, int c, int d, int i ) - { - super( a, b, c, d, i ); - } + private class QuartzKniveSlot extends SlotOutput { + QuartzKniveSlot(IItemHandler a, int b, int c, int d, int i) { + super(a, b, c, d, i); + } - @Override - public ItemStack getStack() - { - final IItemHandler baseInv = this.getItemHandler(); - final ItemStack input = baseInv.getStackInSlot( 0 ); - if( input == ItemStack.EMPTY ) - { - return ItemStack.EMPTY; - } + @Override + public ItemStack getStack() { + final IItemHandler baseInv = this.getItemHandler(); + final ItemStack input = baseInv.getStackInSlot(0); + if (input == ItemStack.EMPTY) { + return ItemStack.EMPTY; + } - if( SlotRestrictedInput.isMetalIngot( input ) ) - { - if( ContainerQuartzKnife.this.myName.length() > 0 ) - { - return AEApi.instance().definitions().materials().namePress().maybeStack( 1 ).map( namePressStack -> - { - final NBTTagCompound compound = Platform.openNbtData( namePressStack ); - compound.setString( "InscribeName", ContainerQuartzKnife.this.myName ); + if (SlotRestrictedInput.isMetalIngot(input)) { + if (ContainerQuartzKnife.this.myName.length() > 0) { + return AEApi.instance().definitions().materials().namePress().maybeStack(1).map(namePressStack -> + { + final NBTTagCompound compound = Platform.openNbtData(namePressStack); + compound.setString("InscribeName", ContainerQuartzKnife.this.myName); - return namePressStack; - } ).orElse( ItemStack.EMPTY ); - } - } - return ItemStack.EMPTY; - } + return namePressStack; + }).orElse(ItemStack.EMPTY); + } + } + return ItemStack.EMPTY; + } - @Override - @Nonnull - public ItemStack decrStackSize( int amount ) - { - ItemStack ret = this.getStack(); - if( !ret.isEmpty() ) - { - this.makePlate(); - } - return ret; - } + @Override + @Nonnull + public ItemStack decrStackSize(int amount) { + ItemStack ret = this.getStack(); + if (!ret.isEmpty()) { + this.makePlate(); + } + return ret; + } - @Override - public void putStack( final ItemStack stack ) - { - if( stack.isEmpty() ) - { - this.makePlate(); - } - } + @Override + public void putStack(final ItemStack stack) { + if (stack.isEmpty()) { + this.makePlate(); + } + } - private void makePlate() - { - if( Platform.isServer() ) - { - if( !this.getItemHandler().extractItem( 0, 1, false ).isEmpty() ) - { - final ItemStack item = ContainerQuartzKnife.this.toolInv.getItemStack(); - final ItemStack before = item.copy(); - item.damageItem( 1, ContainerQuartzKnife.this.getPlayerInv().player ); + private void makePlate() { + if (Platform.isServer()) { + if (!this.getItemHandler().extractItem(0, 1, false).isEmpty()) { + final ItemStack item = ContainerQuartzKnife.this.toolInv.getItemStack(); + final ItemStack before = item.copy(); + item.damageItem(1, ContainerQuartzKnife.this.getPlayerInv().player); - if( item.getCount() == 0 ) - { - ContainerQuartzKnife.this.getPlayerInv() - .setInventorySlotContents( ContainerQuartzKnife.this.getPlayerInv().currentItem, ItemStack.EMPTY ); - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( ContainerQuartzKnife.this.getPlayerInv().player, before, null ) ); - } + if (item.getCount() == 0) { + ContainerQuartzKnife.this.getPlayerInv() + .setInventorySlotContents(ContainerQuartzKnife.this.getPlayerInv().currentItem, ItemStack.EMPTY); + MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(ContainerQuartzKnife.this.getPlayerInv().player, before, null)); + } - ContainerQuartzKnife.this.detectAndSendChanges(); - } - } - } - } + ContainerQuartzKnife.this.detectAndSendChanges(); + } + } + } + } } diff --git a/src/main/java/appeng/container/implementations/ContainerRenamer.java b/src/main/java/appeng/container/implementations/ContainerRenamer.java index c92c53123..72e5b33dd 100644 --- a/src/main/java/appeng/container/implementations/ContainerRenamer.java +++ b/src/main/java/appeng/container/implementations/ContainerRenamer.java @@ -25,7 +25,7 @@ public class ContainerRenamer extends AEBaseContainer { @SideOnly(Side.CLIENT) public void setTextField(final MEGuiTextField name) { this.textField = name; - if(getCustomName() != null) textField.setText(getCustomName()); + if (getCustomName() != null) textField.setText(getCustomName()); } public void setNewName(String newValue) { @@ -36,13 +36,13 @@ public class ContainerRenamer extends AEBaseContainer { @Override public void setCustomName(final String customName) { super.setCustomName(customName); - if(!Platform.isServer() && customName != null) textField.setText(customName); + if (!Platform.isServer() && customName != null) textField.setText(customName); } @Override public void detectAndSendChanges() { verifyPermissions(SecurityPermissions.BUILD, false); super.detectAndSendChanges(); - if(!Platform.isServer() && getCustomName() != null) textField.setText(getCustomName()); + if (!Platform.isServer() && getCustomName() != null) textField.setText(getCustomName()); } } diff --git a/src/main/java/appeng/container/implementations/ContainerSecurityStation.java b/src/main/java/appeng/container/implementations/ContainerSecurityStation.java index 158d6d4df..29039b613 100644 --- a/src/main/java/appeng/container/implementations/ContainerSecurityStation.java +++ b/src/main/java/appeng/container/implementations/ContainerSecurityStation.java @@ -19,12 +19,6 @@ package appeng.container.implementations; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IContainerListener; -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.SecurityPermissions; import appeng.api.features.INetworkEncodable; @@ -38,155 +32,134 @@ import appeng.tile.inventory.AppEngInternalInventory; import appeng.tile.misc.TileSecurityStation; import appeng.util.inv.IAEAppEngInventory; import appeng.util.inv.InvOperation; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IContainerListener; +import net.minecraft.item.ItemStack; +import net.minecraftforge.items.IItemHandler; -public class ContainerSecurityStation extends ContainerMEMonitorable implements IAEAppEngInventory -{ +public class ContainerSecurityStation extends ContainerMEMonitorable implements IAEAppEngInventory { - private final SlotRestrictedInput configSlot; + private final SlotRestrictedInput configSlot; - private final AppEngInternalInventory wirelessEncoder = new AppEngInternalInventory( this, 2 ); + private final AppEngInternalInventory wirelessEncoder = new AppEngInternalInventory(this, 2); - private final SlotRestrictedInput wirelessIn; - private final SlotOutput wirelessOut; + private final SlotRestrictedInput wirelessIn; + private final SlotOutput wirelessOut; - private final TileSecurityStation securityBox; - @GuiSync( 0 ) - public int permissionMode = 0; + private final TileSecurityStation securityBox; + @GuiSync(0) + public int permissionMode = 0; - public ContainerSecurityStation( final InventoryPlayer ip, final ITerminalHost monitorable ) - { - super( ip, monitorable, false ); + public ContainerSecurityStation(final InventoryPlayer ip, final ITerminalHost monitorable) { + super(ip, monitorable, false); - this.securityBox = (TileSecurityStation) monitorable; + this.securityBox = (TileSecurityStation) monitorable; - this.addSlotToContainer( this.configSlot = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.BIOMETRIC_CARD, this.securityBox - .getConfigSlot(), 0, 37, -33, ip ) ); + this.addSlotToContainer(this.configSlot = new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.BIOMETRIC_CARD, this.securityBox + .getConfigSlot(), 0, 37, -33, ip)); - this.addSlotToContainer( - this.wirelessIn = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODABLE_ITEM, this.wirelessEncoder, 0, 212, 10, ip ) ); - this.addSlotToContainer( this.wirelessOut = new SlotOutput( this.wirelessEncoder, 1, 212, 68, -1 ) ); + this.addSlotToContainer( + this.wirelessIn = new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.ENCODABLE_ITEM, this.wirelessEncoder, 0, 212, 10, ip)); + this.addSlotToContainer(this.wirelessOut = new SlotOutput(this.wirelessEncoder, 1, 212, 68, -1)); - this.bindPlayerInventory( ip, 0, 0 ); - } + this.bindPlayerInventory(ip, 0, 0); + } - public void toggleSetting( final String value, final EntityPlayer player ) - { - try - { - final SecurityPermissions permission = SecurityPermissions.valueOf( value ); + public void toggleSetting(final String value, final EntityPlayer player) { + try { + final SecurityPermissions permission = SecurityPermissions.valueOf(value); - final ItemStack a = this.configSlot.getStack(); - if( !a.isEmpty() && a.getItem() instanceof IBiometricCard ) - { - final IBiometricCard bc = (IBiometricCard) a.getItem(); - if( bc.hasPermission( a, permission ) ) - { - bc.removePermission( a, permission ); - } - else - { - bc.addPermission( a, permission ); - } - } - } - catch( final EnumConstantNotPresentException ex ) - { - // :( - } - } + final ItemStack a = this.configSlot.getStack(); + if (!a.isEmpty() && a.getItem() instanceof IBiometricCard) { + final IBiometricCard bc = (IBiometricCard) a.getItem(); + if (bc.hasPermission(a, permission)) { + bc.removePermission(a, permission); + } else { + bc.addPermission(a, permission); + } + } + } catch (final EnumConstantNotPresentException ex) { + // :( + } + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.SECURITY, false ); + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.SECURITY, false); - this.setPermissionMode( 0 ); + this.setPermissionMode(0); - final ItemStack a = this.configSlot.getStack(); - if( !a.isEmpty() && a.getItem() instanceof IBiometricCard ) - { - final IBiometricCard bc = (IBiometricCard) a.getItem(); + final ItemStack a = this.configSlot.getStack(); + if (!a.isEmpty() && a.getItem() instanceof IBiometricCard) { + final IBiometricCard bc = (IBiometricCard) a.getItem(); - for( final SecurityPermissions sp : bc.getPermissions( a ) ) - { - this.setPermissionMode( this.getPermissionMode() | ( 1 << sp.ordinal() ) ); - } - } + for (final SecurityPermissions sp : bc.getPermissions(a)) { + this.setPermissionMode(this.getPermissionMode() | (1 << sp.ordinal())); + } + } - this.updatePowerStatus(); + this.updatePowerStatus(); - super.detectAndSendChanges(); - } + super.detectAndSendChanges(); + } - @Override - public void onContainerClosed( final EntityPlayer player ) - { - super.onContainerClosed( player ); + @Override + public void onContainerClosed(final EntityPlayer player) { + super.onContainerClosed(player); - if( this.wirelessIn.getHasStack() ) - { - player.dropItem( this.wirelessIn.getStack(), false ); - } + if (this.wirelessIn.getHasStack()) { + player.dropItem(this.wirelessIn.getStack(), false); + } - if( this.wirelessOut.getHasStack() ) - { - player.dropItem( this.wirelessOut.getStack(), false ); - } - } + if (this.wirelessOut.getHasStack()) { + player.dropItem(this.wirelessOut.getStack(), false); + } + } - @Override - public void saveChanges() - { - // :P - } + @Override + public void saveChanges() { + // :P + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( !this.wirelessOut.getHasStack() ) - { - if( this.wirelessIn.getHasStack() ) - { - final ItemStack term = this.wirelessIn.getStack().copy(); - INetworkEncodable networkEncodable = null; + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { + if (!this.wirelessOut.getHasStack()) { + if (this.wirelessIn.getHasStack()) { + final ItemStack term = this.wirelessIn.getStack().copy(); + INetworkEncodable networkEncodable = null; - if( term.getItem() instanceof INetworkEncodable ) - { - networkEncodable = (INetworkEncodable) term.getItem(); - } + if (term.getItem() instanceof INetworkEncodable) { + networkEncodable = (INetworkEncodable) term.getItem(); + } - final IWirelessTermHandler wTermHandler = AEApi.instance().registries().wireless().getWirelessTerminalHandler( term ); - if( wTermHandler != null ) - { - networkEncodable = wTermHandler; - } + final IWirelessTermHandler wTermHandler = AEApi.instance().registries().wireless().getWirelessTerminalHandler(term); + if (wTermHandler != null) { + networkEncodable = wTermHandler; + } - if( networkEncodable != null ) - { - networkEncodable.setEncryptionKey( term, String.valueOf( this.securityBox.getSecurityKey() ), "" ); + if (networkEncodable != null) { + networkEncodable.setEncryptionKey(term, String.valueOf(this.securityBox.getSecurityKey()), ""); - this.wirelessIn.putStack( ItemStack.EMPTY ); - this.wirelessOut.putStack( term ); + this.wirelessIn.putStack(ItemStack.EMPTY); + this.wirelessOut.putStack(term); - // update the two slots in question... - for( final IContainerListener listener : this.listeners ) - { - listener.sendSlotContents( this, this.wirelessIn.slotNumber, this.wirelessIn.getStack() ); - listener.sendSlotContents( this, this.wirelessOut.slotNumber, this.wirelessOut.getStack() ); - } - } - } - } - } + // update the two slots in question... + for (final IContainerListener listener : this.listeners) { + listener.sendSlotContents(this, this.wirelessIn.slotNumber, this.wirelessIn.getStack()); + listener.sendSlotContents(this, this.wirelessOut.slotNumber, this.wirelessOut.getStack()); + } + } + } + } + } - public int getPermissionMode() - { - return this.permissionMode; - } + public int getPermissionMode() { + return this.permissionMode; + } - private void setPermissionMode( final int permissionMode ) - { - this.permissionMode = permissionMode; - } + private void setPermissionMode(final int permissionMode) { + this.permissionMode = permissionMode; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerSkyChest.java b/src/main/java/appeng/container/implementations/ContainerSkyChest.java index 9c838f346..8078d2075 100644 --- a/src/main/java/appeng/container/implementations/ContainerSkyChest.java +++ b/src/main/java/appeng/container/implementations/ContainerSkyChest.java @@ -19,41 +19,35 @@ package appeng.container.implementations; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotNormal; import appeng.tile.storage.TileSkyChest; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; -public class ContainerSkyChest extends AEBaseContainer -{ +public class ContainerSkyChest extends AEBaseContainer { - private final TileSkyChest chest; + private final TileSkyChest chest; - public ContainerSkyChest( final InventoryPlayer ip, final TileSkyChest chest ) - { - super( ip, chest, null ); - this.chest = chest; + public ContainerSkyChest(final InventoryPlayer ip, final TileSkyChest chest) { + super(ip, chest, null); + this.chest = chest; - for( int y = 0; y < 4; y++ ) - { - for( int x = 0; x < 9; x++ ) - { - this.addSlotToContainer( new SlotNormal( this.chest.getInternalInventory(), y * 9 + x, 8 + 18 * x, 24 + 18 * y ) ); - } - } + for (int y = 0; y < 4; y++) { + for (int x = 0; x < 9; x++) { + this.addSlotToContainer(new SlotNormal(this.chest.getInternalInventory(), y * 9 + x, 8 + 18 * x, 24 + 18 * y)); + } + } - this.chest.openInventory( ip.player ); + this.chest.openInventory(ip.player); - this.bindPlayerInventory( ip, 0, 195 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 195 - /* height of player inventory */82); + } - @Override - public void onContainerClosed( final EntityPlayer par1EntityPlayer ) - { - super.onContainerClosed( par1EntityPlayer ); - this.chest.closeInventory( par1EntityPlayer ); - } + @Override + public void onContainerClosed(final EntityPlayer par1EntityPlayer) { + super.onContainerClosed(par1EntityPlayer); + this.chest.closeInventory(par1EntityPlayer); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java b/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java index 0926e1c4b..0f4de6cac 100644 --- a/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java +++ b/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java @@ -19,8 +19,6 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; import appeng.api.networking.energy.IEnergyGrid; @@ -33,126 +31,109 @@ import appeng.container.slot.SlotOutput; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.spatial.TileSpatialIOPort; import appeng.util.Platform; +import net.minecraft.entity.player.InventoryPlayer; -public class ContainerSpatialIOPort extends AEBaseContainer -{ +public class ContainerSpatialIOPort extends AEBaseContainer { - @GuiSync( 0 ) - public long currentPower; - @GuiSync( 1 ) - public long maxPower; - @GuiSync( 2 ) - public long reqPower; - @GuiSync( 3 ) - public long eff; - private IGrid network; - private int delay = 40; + @GuiSync(0) + public long currentPower; + @GuiSync(1) + public long maxPower; + @GuiSync(2) + public long reqPower; + @GuiSync(3) + public long eff; + private IGrid network; + private int delay = 40; - @GuiSync( 31 ) - public int xSize; - @GuiSync( 32 ) - public int ySize; - @GuiSync( 33 ) - public int zSize; + @GuiSync(31) + public int xSize; + @GuiSync(32) + public int ySize; + @GuiSync(33) + public int zSize; - public ContainerSpatialIOPort( final InventoryPlayer ip, final TileSpatialIOPort spatialIOPort ) - { - super( ip, spatialIOPort, null ); + public ContainerSpatialIOPort(final InventoryPlayer ip, final TileSpatialIOPort spatialIOPort) { + super(ip, spatialIOPort, null); - if( Platform.isServer() ) - { - this.network = spatialIOPort.getGridNode( AEPartLocation.INTERNAL ).getGrid(); - } + if (Platform.isServer()) { + this.network = spatialIOPort.getGridNode(AEPartLocation.INTERNAL).getGrid(); + } - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.SPATIAL_STORAGE_CELLS, spatialIOPort - .getInternalInventory(), 0, 52, 48, this.getInventoryPlayer() ) ); - this.addSlotToContainer( - new SlotOutput( spatialIOPort.getInternalInventory(), 1, 113, 48, SlotRestrictedInput.PlacableItemType.SPATIAL_STORAGE_CELLS.IIcon ) ); + this.addSlotToContainer(new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.SPATIAL_STORAGE_CELLS, spatialIOPort + .getInternalInventory(), 0, 52, 48, this.getInventoryPlayer())); + this.addSlotToContainer( + new SlotOutput(spatialIOPort.getInternalInventory(), 1, 113, 48, SlotRestrictedInput.PlacableItemType.SPATIAL_STORAGE_CELLS.IIcon)); - this.bindPlayerInventory( ip, 0, 197 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 197 - /* height of player inventory */82); + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - if( Platform.isServer() ) - { - this.delay++; - if( this.delay > 15 && this.network != null ) - { - this.delay = 0; + if (Platform.isServer()) { + this.delay++; + if (this.delay > 15 && this.network != null) { + this.delay = 0; - final IEnergyGrid eg = this.network.getCache( IEnergyGrid.class ); - final ISpatialCache sc = this.network.getCache( ISpatialCache.class ); - if( eg != null ) - { - this.setCurrentPower( (long) ( 100.0 * eg.getStoredPower() ) ); - this.setMaxPower( (long) ( 100.0 * eg.getMaxStoredPower() ) ); - this.setRequiredPower( (long) ( 100.0 * sc.requiredPower() ) ); - this.setEfficency( (long) ( 100.0f * sc.currentEfficiency() ) ); + final IEnergyGrid eg = this.network.getCache(IEnergyGrid.class); + final ISpatialCache sc = this.network.getCache(ISpatialCache.class); + if (eg != null) { + this.setCurrentPower((long) (100.0 * eg.getStoredPower())); + this.setMaxPower((long) (100.0 * eg.getMaxStoredPower())); + this.setRequiredPower((long) (100.0 * sc.requiredPower())); + this.setEfficency((long) (100.0f * sc.currentEfficiency())); - final DimensionalCoord min = sc.getMin(); - final DimensionalCoord max = sc.getMax(); + final DimensionalCoord min = sc.getMin(); + final DimensionalCoord max = sc.getMax(); - if( min != null && max != null && sc.isValidRegion() ) - { - this.xSize = sc.getMax().x - sc.getMin().x - 1; - this.ySize = sc.getMax().y - sc.getMin().y - 1; - this.zSize = sc.getMax().z - sc.getMin().z - 1; - } - else - { - this.xSize = 0; - this.ySize = 0; - this.zSize = 0; - } - } - } - } + if (min != null && max != null && sc.isValidRegion()) { + this.xSize = sc.getMax().x - sc.getMin().x - 1; + this.ySize = sc.getMax().y - sc.getMin().y - 1; + this.zSize = sc.getMax().z - sc.getMin().z - 1; + } else { + this.xSize = 0; + this.ySize = 0; + this.zSize = 0; + } + } + } + } - super.detectAndSendChanges(); - } + super.detectAndSendChanges(); + } - public long getCurrentPower() - { - return this.currentPower; - } + public long getCurrentPower() { + return this.currentPower; + } - private void setCurrentPower( final long currentPower ) - { - this.currentPower = currentPower; - } + private void setCurrentPower(final long currentPower) { + this.currentPower = currentPower; + } - public long getMaxPower() - { - return this.maxPower; - } + public long getMaxPower() { + return this.maxPower; + } - private void setMaxPower( final long maxPower ) - { - this.maxPower = maxPower; - } + private void setMaxPower(final long maxPower) { + this.maxPower = maxPower; + } - public long getRequiredPower() - { - return this.reqPower; - } + public long getRequiredPower() { + return this.reqPower; + } - private void setRequiredPower( final long reqPower ) - { - this.reqPower = reqPower; - } + private void setRequiredPower(final long reqPower) { + this.reqPower = reqPower; + } - public long getEfficency() - { - return this.eff; - } + public long getEfficency() { + return this.eff; + } - private void setEfficency( final long eff ) - { - this.eff = eff; - } + private void setEfficency(final long eff) { + this.eff = eff; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerStorageBus.java b/src/main/java/appeng/container/implementations/ContainerStorageBus.java index 5c6965a6a..e74ff1a29 100644 --- a/src/main/java/appeng/container/implementations/ContainerStorageBus.java +++ b/src/main/java/appeng/container/implementations/ContainerStorageBus.java @@ -19,19 +19,8 @@ package appeng.container.implementations; -import java.util.Iterator; - -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; -import appeng.api.config.AccessRestriction; -import appeng.api.config.FuzzyMode; -import appeng.api.config.SecurityPermissions; -import appeng.api.config.Settings; -import appeng.api.config.StorageFilter; -import appeng.api.config.Upgrades; +import appeng.api.config.*; import appeng.api.storage.IMEInventory; import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEItemStack; @@ -44,159 +33,139 @@ import appeng.parts.misc.PartStorageBus; import appeng.util.Platform; import appeng.util.helpers.ItemHandlerUtil; import appeng.util.iterators.NullIterator; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraftforge.items.IItemHandler; + +import java.util.Iterator; -public class ContainerStorageBus extends ContainerUpgradeable -{ +public class ContainerStorageBus extends ContainerUpgradeable { - private final PartStorageBus storageBus; + private final PartStorageBus storageBus; - @GuiSync( 3 ) - public AccessRestriction rwMode = AccessRestriction.READ_WRITE; + @GuiSync(3) + public AccessRestriction rwMode = AccessRestriction.READ_WRITE; - @GuiSync( 4 ) - public StorageFilter storageFilter = StorageFilter.EXTRACTABLE_ONLY; + @GuiSync(4) + public StorageFilter storageFilter = StorageFilter.EXTRACTABLE_ONLY; - public ContainerStorageBus( final InventoryPlayer ip, final PartStorageBus te ) - { - super( ip, te ); - this.storageBus = te; - } + public ContainerStorageBus(final InventoryPlayer ip, final PartStorageBus te) { + super(ip, te); + this.storageBus = te; + } - @Override - protected int getHeight() - { - return 251; - } + @Override + protected int getHeight() { + return 251; + } - @Override - protected void setupConfig() - { - final int xo = 8; - final int yo = 23 + 6; + @Override + protected void setupConfig() { + final int xo = 8; + final int yo = 23 + 6; - final IItemHandler config = this.getUpgradeable().getInventoryByName( "config" ); - for( int y = 0; y < 7; y++ ) - { - for( int x = 0; x < 9; x++ ) - { - if( y < 2 ) - { - this.addSlotToContainer( new SlotFakeTypeOnly( config, y * 9 + x, xo + x * 18, yo + y * 18 ) ); - } - else - { - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( config, this, y * 9 + x, xo, yo, x, y, y - 2 ) ); - } - } - } + final IItemHandler config = this.getUpgradeable().getInventoryByName("config"); + for (int y = 0; y < 7; y++) { + for (int x = 0; x < 9; x++) { + if (y < 2) { + this.addSlotToContainer(new SlotFakeTypeOnly(config, y * 9 + x, xo + x * 18, yo + y * 18)); + } else { + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(config, this, y * 9 + x, xo, yo, x, y, y - 2)); + } + } + } - final IItemHandler upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } + final IItemHandler upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer())) + .setNotDraggable()); + } - @Override - protected boolean supportCapacity() - { - return true; - } + @Override + protected boolean supportCapacity() { + return true; + } - @Override - public int availableUpgrades() - { - return 5; - } + @Override + public int availableUpgrades() { + return 5; + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - if( Platform.isServer() ) - { - this.setFuzzyMode( (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting( Settings.FUZZY_MODE ) ); - this.setReadWriteMode( (AccessRestriction) this.getUpgradeable().getConfigManager().getSetting( Settings.ACCESS ) ); - this.setStorageFilter( (StorageFilter) this.getUpgradeable().getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); - } + if (Platform.isServer()) { + this.setFuzzyMode((FuzzyMode) this.getUpgradeable().getConfigManager().getSetting(Settings.FUZZY_MODE)); + this.setReadWriteMode((AccessRestriction) this.getUpgradeable().getConfigManager().getSetting(Settings.ACCESS)); + this.setStorageFilter((StorageFilter) this.getUpgradeable().getConfigManager().getSetting(Settings.STORAGE_FILTER)); + } - this.standardDetectAndSendChanges(); - } + this.standardDetectAndSendChanges(); + } - @Override - public boolean isSlotEnabled( final int idx ) - { - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); + @Override + public boolean isSlotEnabled(final int idx) { + final int upgrades = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); - return upgrades > idx; - } + return upgrades > idx; + } - public void clear() - { - ItemHandlerUtil.clear( this.getUpgradeable().getInventoryByName( "config" ) ); - this.detectAndSendChanges(); - } + public void clear() { + ItemHandlerUtil.clear(this.getUpgradeable().getInventoryByName("config")); + this.detectAndSendChanges(); + } - public void partition() - { - final IItemHandler inv = this.getUpgradeable().getInventoryByName( "config" ); + public void partition() { + final IItemHandler inv = this.getUpgradeable().getInventoryByName("config"); - final IMEInventory cellInv = this.storageBus.getInternalHandler(); + final IMEInventory cellInv = this.storageBus.getInternalHandler(); - Iterator i = new NullIterator<>(); - if( cellInv != null ) - { - final IItemList list = cellInv - .getAvailableItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList() ); - i = list.iterator(); - } + Iterator i = new NullIterator<>(); + if (cellInv != null) { + final IItemList list = cellInv + .getAvailableItems(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList()); + i = list.iterator(); + } - for( int x = 0; x < inv.getSlots(); x++ ) - { - if( i.hasNext() && this.isSlotEnabled( ( x / 9 ) - 2 ) ) - { - // TODO: check if ok - final ItemStack g = i.next().asItemStackRepresentation(); - ItemHandlerUtil.setStackInSlot( inv, x, g ); - } - else - { - ItemHandlerUtil.setStackInSlot( inv, x, ItemStack.EMPTY ); - } - } + for (int x = 0; x < inv.getSlots(); x++) { + if (i.hasNext() && this.isSlotEnabled((x / 9) - 2)) { + // TODO: check if ok + final ItemStack g = i.next().asItemStackRepresentation(); + ItemHandlerUtil.setStackInSlot(inv, x, g); + } else { + ItemHandlerUtil.setStackInSlot(inv, x, ItemStack.EMPTY); + } + } - this.detectAndSendChanges(); - } + this.detectAndSendChanges(); + } - public AccessRestriction getReadWriteMode() - { - return this.rwMode; - } + public AccessRestriction getReadWriteMode() { + return this.rwMode; + } - private void setReadWriteMode( final AccessRestriction rwMode ) - { - this.rwMode = rwMode; - } + private void setReadWriteMode(final AccessRestriction rwMode) { + this.rwMode = rwMode; + } - public StorageFilter getStorageFilter() - { - return this.storageFilter; - } + public StorageFilter getStorageFilter() { + return this.storageFilter; + } - private void setStorageFilter( final StorageFilter storageFilter ) - { - this.storageFilter = storageFilter; - } + private void setStorageFilter(final StorageFilter storageFilter) { + this.storageFilter = storageFilter; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerUpgradeable.java b/src/main/java/appeng/container/implementations/ContainerUpgradeable.java index b601d2cee..c9831edd4 100644 --- a/src/main/java/appeng/container/implementations/ContainerUpgradeable.java +++ b/src/main/java/appeng/container/implementations/ContainerUpgradeable.java @@ -19,7 +19,18 @@ package appeng.container.implementations; +import appeng.api.config.*; +import appeng.api.implementations.IUpgradeableHost; +import appeng.api.implementations.guiobjects.IGuiItem; +import appeng.api.parts.IPart; +import appeng.api.util.IConfigManager; +import appeng.container.AEBaseContainer; +import appeng.container.guisync.GuiSync; +import appeng.container.slot.*; import appeng.items.contents.NetworkToolViewer; +import appeng.items.tools.ToolNetworkTool; +import appeng.parts.automation.PartExportBus; +import appeng.util.Platform; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -28,304 +39,229 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.items.IItemHandler; -import appeng.api.config.FuzzyMode; -import appeng.api.config.RedstoneMode; -import appeng.api.config.SchedulingMode; -import appeng.api.config.SecurityPermissions; -import appeng.api.config.Settings; -import appeng.api.config.Upgrades; -import appeng.api.config.YesNo; -import appeng.api.implementations.IUpgradeableHost; -import appeng.api.implementations.guiobjects.IGuiItem; -import appeng.api.parts.IPart; -import appeng.api.util.IConfigManager; -import appeng.container.AEBaseContainer; -import appeng.container.guisync.GuiSync; -import appeng.container.slot.IOptionalSlotHost; -import appeng.container.slot.OptionalSlotFake; -import appeng.container.slot.OptionalSlotFakeTypeOnly; -import appeng.container.slot.SlotFakeTypeOnly; -import appeng.container.slot.SlotRestrictedInput; -import appeng.items.tools.ToolNetworkTool; -import appeng.parts.automation.PartExportBus; -import appeng.util.Platform; +public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSlotHost { -public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSlotHost -{ + private final IUpgradeableHost upgradeable; + @GuiSync(0) + public RedstoneMode rsMode = RedstoneMode.IGNORE; + @GuiSync(1) + public FuzzyMode fzMode = FuzzyMode.IGNORE_ALL; + @GuiSync(5) + public YesNo cMode = YesNo.NO; + @GuiSync(6) + public SchedulingMode schedulingMode = SchedulingMode.DEFAULT; + private int tbSlot; + private NetworkToolViewer tbInventory; - private final IUpgradeableHost upgradeable; - @GuiSync( 0 ) - public RedstoneMode rsMode = RedstoneMode.IGNORE; - @GuiSync( 1 ) - public FuzzyMode fzMode = FuzzyMode.IGNORE_ALL; - @GuiSync( 5 ) - public YesNo cMode = YesNo.NO; - @GuiSync( 6 ) - public SchedulingMode schedulingMode = SchedulingMode.DEFAULT; - private int tbSlot; - private NetworkToolViewer tbInventory; + public ContainerUpgradeable(final InventoryPlayer ip, final IUpgradeableHost te) { + super(ip, (TileEntity) (te instanceof TileEntity ? te : null), (IPart) (te instanceof IPart ? te : null)); + this.upgradeable = te; - public ContainerUpgradeable( final InventoryPlayer ip, final IUpgradeableHost te ) - { - super( ip, (TileEntity) ( te instanceof TileEntity ? te : null ), (IPart) ( te instanceof IPart ? te : null ) ); - this.upgradeable = te; + World w = null; + int xCoord = 0; + int yCoord = 0; + int zCoord = 0; - World w = null; - int xCoord = 0; - int yCoord = 0; - int zCoord = 0; + if (te instanceof TileEntity) { + final TileEntity myTile = (TileEntity) te; + w = myTile.getWorld(); + xCoord = myTile.getPos().getX(); + yCoord = myTile.getPos().getY(); + zCoord = myTile.getPos().getZ(); + } - if( te instanceof TileEntity ) - { - final TileEntity myTile = (TileEntity) te; - w = myTile.getWorld(); - xCoord = myTile.getPos().getX(); - yCoord = myTile.getPos().getY(); - zCoord = myTile.getPos().getZ(); - } + if (te instanceof IPart) { + final TileEntity mk = te.getTile(); + w = mk.getWorld(); + xCoord = mk.getPos().getX(); + yCoord = mk.getPos().getY(); + zCoord = mk.getPos().getZ(); + } - if( te instanceof IPart ) - { - final TileEntity mk = te.getTile(); - w = mk.getWorld(); - xCoord = mk.getPos().getX(); - yCoord = mk.getPos().getY(); - zCoord = mk.getPos().getZ(); - } + final IInventory pi = this.getPlayerInv(); + for (int x = 0; x < pi.getSizeInventory(); x++) { + final ItemStack pii = pi.getStackInSlot(x); + if (!pii.isEmpty() && pii.getItem() instanceof ToolNetworkTool) { + this.lockPlayerInventorySlot(x); + this.tbSlot = x; + this.tbInventory = (NetworkToolViewer) ((IGuiItem) pii.getItem()).getGuiObject(pii, w, new BlockPos(xCoord, yCoord, zCoord)); + break; + } + } - final IInventory pi = this.getPlayerInv(); - for( int x = 0; x < pi.getSizeInventory(); x++ ) - { - final ItemStack pii = pi.getStackInSlot( x ); - if( !pii.isEmpty() && pii.getItem() instanceof ToolNetworkTool ) - { - this.lockPlayerInventorySlot( x ); - this.tbSlot = x; - this.tbInventory = (NetworkToolViewer) ( (IGuiItem) pii.getItem() ).getGuiObject( pii, w, new BlockPos( xCoord, yCoord, zCoord ) ); - break; - } - } + if (this.hasToolbox()) { + for (int v = 0; v < 3; v++) { + for (int u = 0; u < 3; u++) { + this.addSlotToContainer((new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, this.tbInventory + .getInternalInventory(), u + v * 3, 186 + u * 18, this.getHeight() - 82 + v * 18, this.getInventoryPlayer())).setPlayerSide()); + } + } + } - if( this.hasToolbox() ) - { - for( int v = 0; v < 3; v++ ) - { - for( int u = 0; u < 3; u++ ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, this.tbInventory - .getInternalInventory(), u + v * 3, 186 + u * 18, this.getHeight() - 82 + v * 18, this.getInventoryPlayer() ) ).setPlayerSide() ); - } - } - } + this.setupConfig(); - this.setupConfig(); + this.bindPlayerInventory(ip, 0, this.getHeight() - /* height of player inventory */82); + } - this.bindPlayerInventory( ip, 0, this.getHeight() - /* height of player inventory */82 ); - } + public boolean hasToolbox() { + return this.tbInventory != null; + } - public boolean hasToolbox() - { - return this.tbInventory != null; - } + protected int getHeight() { + return 184; + } - protected int getHeight() - { - return 184; - } + protected void setupConfig() { + this.setupUpgrades(); - protected void setupConfig() - { - this.setupUpgrades(); + final IItemHandler inv = this.getUpgradeable().getInventoryByName("config"); + final int y = 40; + final int x = 80; + this.addSlotToContainer(new SlotFakeTypeOnly(inv, 0, x, y)); - final IItemHandler inv = this.getUpgradeable().getInventoryByName( "config" ); - final int y = 40; - final int x = 80; - this.addSlotToContainer( new SlotFakeTypeOnly( inv, 0, x, y ) ); + if (this.supportCapacity()) { + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 1, x, y, -1, 0, 1)); + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 2, x, y, 1, 0, 1)); + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 3, x, y, 0, -1, 1)); + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 4, x, y, 0, 1, 1)); - if( this.supportCapacity() ) - { - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 1, x, y, -1, 0, 1 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 2, x, y, 1, 0, 1 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 3, x, y, 0, -1, 1 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 4, x, y, 0, 1, 1 ) ); + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 5, x, y, -1, -1, 2)); + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 6, x, y, 1, -1, 2)); + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 7, x, y, -1, 1, 2)); + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 8, x, y, 1, 1, 2)); + } + } - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 5, x, y, -1, -1, 2 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 6, x, y, 1, -1, 2 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 7, x, y, -1, 1, 2 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 8, x, y, 1, 1, 2 ) ); - } - } + protected void setupUpgrades() { + final IItemHandler upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + if (this.availableUpgrades() > 0) { + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer())) + .setNotDraggable()); + } + if (this.availableUpgrades() > 1) { + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer())) + .setNotDraggable()); + } + if (this.availableUpgrades() > 2) { + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer())) + .setNotDraggable()); + } + if (this.availableUpgrades() > 3) { + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer())) + .setNotDraggable()); + } + } - protected void setupUpgrades() - { - final IItemHandler upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - if( this.availableUpgrades() > 0 ) - { - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } - if( this.availableUpgrades() > 1 ) - { - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } - if( this.availableUpgrades() > 2 ) - { - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } - if( this.availableUpgrades() > 3 ) - { - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } - } + protected boolean supportCapacity() { + return true; + } - protected boolean supportCapacity() - { - return true; - } + public int availableUpgrades() { + return 4; + } - public int availableUpgrades() - { - return 4; - } + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + if (Platform.isServer()) { + final IConfigManager cm = this.getUpgradeable().getConfigManager(); + this.loadSettingsFromHost(cm); + } - if( Platform.isServer() ) - { - final IConfigManager cm = this.getUpgradeable().getConfigManager(); - this.loadSettingsFromHost( cm ); - } + this.checkToolbox(); - this.checkToolbox(); + for (final Object o : this.inventorySlots) { + if (o instanceof OptionalSlotFake) { + final OptionalSlotFake fs = (OptionalSlotFake) o; + if (!fs.isSlotEnabled() && !fs.getDisplayStack().isEmpty()) { + fs.clearStack(); + } + } + } - for( final Object o : this.inventorySlots ) - { - if( o instanceof OptionalSlotFake ) - { - final OptionalSlotFake fs = (OptionalSlotFake) o; - if( !fs.isSlotEnabled() && !fs.getDisplayStack().isEmpty() ) - { - fs.clearStack(); - } - } - } + this.standardDetectAndSendChanges(); + } - this.standardDetectAndSendChanges(); - } + protected void loadSettingsFromHost(final IConfigManager cm) { + this.setFuzzyMode((FuzzyMode) cm.getSetting(Settings.FUZZY_MODE)); + this.setRedStoneMode((RedstoneMode) cm.getSetting(Settings.REDSTONE_CONTROLLED)); + if (this.getUpgradeable() instanceof PartExportBus) { + this.setCraftingMode((YesNo) cm.getSetting(Settings.CRAFT_ONLY)); + this.setSchedulingMode((SchedulingMode) cm.getSetting(Settings.SCHEDULING_MODE)); + } + } - protected void loadSettingsFromHost( final IConfigManager cm ) - { - this.setFuzzyMode( (FuzzyMode) cm.getSetting( Settings.FUZZY_MODE ) ); - this.setRedStoneMode( (RedstoneMode) cm.getSetting( Settings.REDSTONE_CONTROLLED ) ); - if( this.getUpgradeable() instanceof PartExportBus ) - { - this.setCraftingMode( (YesNo) cm.getSetting( Settings.CRAFT_ONLY ) ); - this.setSchedulingMode( (SchedulingMode) cm.getSetting( Settings.SCHEDULING_MODE ) ); - } - } + protected void checkToolbox() { + if (this.hasToolbox()) { + final ItemStack currentItem = this.getPlayerInv().getStackInSlot(this.tbSlot); - protected void checkToolbox() - { - if( this.hasToolbox() ) - { - final ItemStack currentItem = this.getPlayerInv().getStackInSlot( this.tbSlot ); + if (currentItem != this.tbInventory.getItemStack()) { + if (!currentItem.isEmpty()) { + if (ItemStack.areItemsEqual(this.tbInventory.getItemStack(), currentItem)) { + this.getPlayerInv().setInventorySlotContents(this.tbSlot, this.tbInventory.getItemStack()); + } else { + this.setValidContainer(false); + } + } else { + this.setValidContainer(false); + } + } + } + } - if( currentItem != this.tbInventory.getItemStack() ) - { - if( !currentItem.isEmpty() ) - { - if( ItemStack.areItemsEqual( this.tbInventory.getItemStack(), currentItem ) ) - { - this.getPlayerInv().setInventorySlotContents( this.tbSlot, this.tbInventory.getItemStack() ); - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.setValidContainer( false ); - } - } - } - } + protected void standardDetectAndSendChanges() { + super.detectAndSendChanges(); + } - protected void standardDetectAndSendChanges() - { - super.detectAndSendChanges(); - } + @Override + public boolean isSlotEnabled(final int idx) { + final int upgrades = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); - @Override - public boolean isSlotEnabled( final int idx ) - { - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); + if (idx == 1 && upgrades > 0) { + return true; + } + return idx == 2 && upgrades > 1; + } - if( idx == 1 && upgrades > 0 ) - { - return true; - } - if( idx == 2 && upgrades > 1 ) - { - return true; - } + public FuzzyMode getFuzzyMode() { + return this.fzMode; + } - return false; - } + public void setFuzzyMode(final FuzzyMode fzMode) { + this.fzMode = fzMode; + } - public FuzzyMode getFuzzyMode() - { - return this.fzMode; - } + public YesNo getCraftingMode() { + return this.cMode; + } - public void setFuzzyMode( final FuzzyMode fzMode ) - { - this.fzMode = fzMode; - } + public void setCraftingMode(final YesNo cMode) { + this.cMode = cMode; + } - public YesNo getCraftingMode() - { - return this.cMode; - } + public RedstoneMode getRedStoneMode() { + return this.rsMode; + } - public void setCraftingMode( final YesNo cMode ) - { - this.cMode = cMode; - } + public void setRedStoneMode(final RedstoneMode rsMode) { + this.rsMode = rsMode; + } - public RedstoneMode getRedStoneMode() - { - return this.rsMode; - } + public SchedulingMode getSchedulingMode() { + return this.schedulingMode; + } - public void setRedStoneMode( final RedstoneMode rsMode ) - { - this.rsMode = rsMode; - } + private void setSchedulingMode(final SchedulingMode schedulingMode) { + this.schedulingMode = schedulingMode; + } - public SchedulingMode getSchedulingMode() - { - return this.schedulingMode; - } - - private void setSchedulingMode( final SchedulingMode schedulingMode ) - { - this.schedulingMode = schedulingMode; - } - - protected IUpgradeableHost getUpgradeable() - { - return this.upgradeable; - } + protected IUpgradeableHost getUpgradeable() { + return this.upgradeable; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java b/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java index 30c51ac98..bfca1c362 100644 --- a/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java +++ b/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java @@ -19,62 +19,54 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.container.AEBaseContainer; import appeng.container.guisync.GuiSync; import appeng.container.interfaces.IProgressProvider; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.misc.TileVibrationChamber; import appeng.util.Platform; +import net.minecraft.entity.player.InventoryPlayer; -public class ContainerVibrationChamber extends AEBaseContainer implements IProgressProvider -{ - private final TileVibrationChamber vibrationChamber; - @GuiSync( 0 ) - public int burnSpeed = 0; - @GuiSync( 1 ) - public int remainingBurnTime = 0; +public class ContainerVibrationChamber extends AEBaseContainer implements IProgressProvider { + private final TileVibrationChamber vibrationChamber; + @GuiSync(0) + public int burnSpeed = 0; + @GuiSync(1) + public int remainingBurnTime = 0; - public ContainerVibrationChamber( final InventoryPlayer ip, final TileVibrationChamber vibrationChamber ) - { - super( ip, vibrationChamber, null ); - this.vibrationChamber = vibrationChamber; + public ContainerVibrationChamber(final InventoryPlayer ip, final TileVibrationChamber vibrationChamber) { + super(ip, vibrationChamber, null); + this.vibrationChamber = vibrationChamber; - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.FUEL, vibrationChamber.getInternalInventory(), 0, 80, 37, this - .getInventoryPlayer() ) ); + this.addSlotToContainer(new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.FUEL, vibrationChamber.getInternalInventory(), 0, 80, 37, this + .getInventoryPlayer())); - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 166 - /* height of player inventory */82); + } - @Override - public void detectAndSendChanges() - { - if( Platform.isServer() ) - { - this.remainingBurnTime = this.vibrationChamber - .getMaxBurnTime() <= 0 ? 0 : (int) ( 100.0 * this.vibrationChamber.getBurnTime() / this.vibrationChamber.getMaxBurnTime() ); - this.burnSpeed = this.remainingBurnTime <= 0 ? 0 : this.vibrationChamber.getBurnSpeed(); + @Override + public void detectAndSendChanges() { + if (Platform.isServer()) { + this.remainingBurnTime = this.vibrationChamber + .getMaxBurnTime() <= 0 ? 0 : (int) (100.0 * this.vibrationChamber.getBurnTime() / this.vibrationChamber.getMaxBurnTime()); + this.burnSpeed = this.remainingBurnTime <= 0 ? 0 : this.vibrationChamber.getBurnSpeed(); - } - super.detectAndSendChanges(); - } + } + super.detectAndSendChanges(); + } - @Override - public int getCurrentProgress() - { - return this.burnSpeed; - } + @Override + public int getCurrentProgress() { + return this.burnSpeed; + } - public int getRemainingBurnTime() - { - return this.remainingBurnTime; - } + public int getRemainingBurnTime() { + return this.remainingBurnTime; + } - @Override - public int getMaxProgress() - { - return TileVibrationChamber.MAX_BURN_SPEED; - } + @Override + public int getMaxProgress() { + return TileVibrationChamber.MAX_BURN_SPEED; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerWireless.java b/src/main/java/appeng/container/implementations/ContainerWireless.java index babe4d180..6f69a62bf 100644 --- a/src/main/java/appeng/container/implementations/ContainerWireless.java +++ b/src/main/java/appeng/container/implementations/ContainerWireless.java @@ -19,64 +19,56 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.container.AEBaseContainer; import appeng.container.guisync.GuiSync; import appeng.container.slot.SlotRestrictedInput; import appeng.core.AEConfig; import appeng.tile.networking.TileWireless; +import net.minecraft.entity.player.InventoryPlayer; -public class ContainerWireless extends AEBaseContainer -{ +public class ContainerWireless extends AEBaseContainer { - private final TileWireless wirelessTerminal; - private final SlotRestrictedInput boosterSlot; - @GuiSync( 1 ) - public long range = 0; - @GuiSync( 2 ) - public long drain = 0; + private final TileWireless wirelessTerminal; + private final SlotRestrictedInput boosterSlot; + @GuiSync(1) + public long range = 0; + @GuiSync(2) + public long drain = 0; - public ContainerWireless( final InventoryPlayer ip, final TileWireless te ) - { - super( ip, te, null ); - this.wirelessTerminal = te; + public ContainerWireless(final InventoryPlayer ip, final TileWireless te) { + super(ip, te, null); + this.wirelessTerminal = te; - this.addSlotToContainer( this.boosterSlot = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.RANGE_BOOSTER, this.wirelessTerminal - .getInternalInventory(), 0, 80, 47, this.getInventoryPlayer() ) ); + this.addSlotToContainer(this.boosterSlot = new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.RANGE_BOOSTER, this.wirelessTerminal + .getInternalInventory(), 0, 80, 47, this.getInventoryPlayer())); - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 166 - /* height of player inventory */82); + } - @Override - public void detectAndSendChanges() - { - final int boosters = this.boosterSlot.getStack().isEmpty() ? 0 : this.boosterSlot.getStack().getCount(); + @Override + public void detectAndSendChanges() { + final int boosters = this.boosterSlot.getStack().isEmpty() ? 0 : this.boosterSlot.getStack().getCount(); - this.setRange( (long) ( 10 * AEConfig.instance().wireless_getMaxRange( boosters ) ) ); - this.setDrain( (long) ( 100 * AEConfig.instance().wireless_getPowerDrain( boosters ) ) ); + this.setRange((long) (10 * AEConfig.instance().wireless_getMaxRange(boosters))); + this.setDrain((long) (100 * AEConfig.instance().wireless_getPowerDrain(boosters))); - super.detectAndSendChanges(); - } + super.detectAndSendChanges(); + } - public long getRange() - { - return this.range; - } + public long getRange() { + return this.range; + } - private void setRange( final long range ) - { - this.range = range; - } + private void setRange(final long range) { + this.range = range; + } - public long getDrain() - { - return this.drain; - } + public long getDrain() { + return this.drain; + } - private void setDrain( final long drain ) - { - this.drain = drain; - } + private void setDrain(final long drain) { + this.drain = drain; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java b/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java index ee97cdc99..0eac8fdbc 100644 --- a/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java +++ b/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java @@ -19,42 +19,34 @@ package appeng.container.implementations; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.core.AEConfig; import appeng.core.localization.PlayerMessages; import appeng.helpers.WirelessTerminalGuiObject; import appeng.util.Platform; +import net.minecraft.entity.player.InventoryPlayer; -public class ContainerWirelessTerm extends ContainerMEPortableCell -{ +public class ContainerWirelessTerm extends ContainerMEPortableCell { - private final WirelessTerminalGuiObject wirelessTerminalGUIObject; + private final WirelessTerminalGuiObject wirelessTerminalGUIObject; - public ContainerWirelessTerm( final InventoryPlayer ip, final WirelessTerminalGuiObject gui ) - { - super( ip, gui ); - this.wirelessTerminalGUIObject = gui; - } + public ContainerWirelessTerm(final InventoryPlayer ip, final WirelessTerminalGuiObject gui) { + super(ip, gui); + this.wirelessTerminalGUIObject = gui; + } - @Override - public void detectAndSendChanges() - { - super.detectAndSendChanges(); + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); - if( !this.wirelessTerminalGUIObject.rangeCheck() ) - { - if( Platform.isServer() && this.isValidContainer() ) - { - this.getPlayerInv().player.sendMessage( PlayerMessages.OutOfRange.get() ); - } + if (!this.wirelessTerminalGUIObject.rangeCheck()) { + if (Platform.isServer() && this.isValidContainer()) { + this.getPlayerInv().player.sendMessage(PlayerMessages.OutOfRange.get()); + } - this.setValidContainer( false ); - } - else - { - this.setPowerMultiplier( AEConfig.instance().wireless_getDrainRate( this.wirelessTerminalGUIObject.getRange() ) ); - } - } + this.setValidContainer(false); + } else { + this.setPowerMultiplier(AEConfig.instance().wireless_getDrainRate(this.wirelessTerminalGUIObject.getRange())); + } + } } diff --git a/src/main/java/appeng/container/implementations/CraftingCPURecord.java b/src/main/java/appeng/container/implementations/CraftingCPURecord.java index 538210287..ee0bfa13f 100644 --- a/src/main/java/appeng/container/implementations/CraftingCPURecord.java +++ b/src/main/java/appeng/container/implementations/CraftingCPURecord.java @@ -19,55 +19,47 @@ package appeng.container.implementations; -import javax.annotation.Nonnull; - import appeng.api.networking.crafting.ICraftingCPU; +import javax.annotation.Nonnull; -public class CraftingCPURecord implements Comparable -{ - private final String myName; - private final ICraftingCPU cpu; - private final long size; - private final int processors; +public class CraftingCPURecord implements Comparable { - public CraftingCPURecord( final long size, final int coProcessors, final ICraftingCPU server ) - { - this.size = size; - this.processors = coProcessors; - this.cpu = server; - this.myName = server.getName(); - } + private final String myName; + private final ICraftingCPU cpu; + private final long size; + private final int processors; - @Override - public int compareTo( @Nonnull final CraftingCPURecord o ) - { - final int a = Long.compare( o.getProcessors(), this.getProcessors() ); - if( a != 0 ) - { - return a; - } - return Long.compare( o.getSize(), this.getSize() ); - } + public CraftingCPURecord(final long size, final int coProcessors, final ICraftingCPU server) { + this.size = size; + this.processors = coProcessors; + this.cpu = server; + this.myName = server.getName(); + } - ICraftingCPU getCpu() - { - return this.cpu; - } + @Override + public int compareTo(@Nonnull final CraftingCPURecord o) { + final int a = Long.compare(o.getProcessors(), this.getProcessors()); + if (a != 0) { + return a; + } + return Long.compare(o.getSize(), this.getSize()); + } - String getName() - { - return this.myName; - } + ICraftingCPU getCpu() { + return this.cpu; + } - int getProcessors() - { - return this.processors; - } + String getName() { + return this.myName; + } - long getSize() - { - return this.size; - } + int getProcessors() { + return this.processors; + } + + long getSize() { + return this.size; + } } diff --git a/src/main/java/appeng/container/implementations/CraftingCPUStatus.java b/src/main/java/appeng/container/implementations/CraftingCPUStatus.java index def36e6b3..3dfdbacb8 100644 --- a/src/main/java/appeng/container/implementations/CraftingCPUStatus.java +++ b/src/main/java/appeng/container/implementations/CraftingCPUStatus.java @@ -23,8 +23,7 @@ public class CraftingCPUStatus implements Comparable { private final long remainingItems; private final IAEItemStack crafting; - public CraftingCPUStatus( ) - { + public CraftingCPUStatus() { this.serverCluster = null; this.name = "ERROR"; this.serial = 0; @@ -35,19 +34,15 @@ public class CraftingCPUStatus implements Comparable { this.crafting = null; } - public CraftingCPUStatus( ICraftingCPU cluster, int serial ) - { + public CraftingCPUStatus(ICraftingCPU cluster, int serial) { this.serverCluster = cluster; this.name = cluster.getName(); this.serial = serial; - if (cluster.isBusy()) - { + if (cluster.isBusy()) { crafting = cluster.getFinalOutput(); totalItems = cluster.getStartItemCount(); remainingItems = cluster.getRemainingItemCount(); - } - else - { + } else { crafting = null; totalItems = 0; remainingItems = 0; @@ -56,141 +51,114 @@ public class CraftingCPUStatus implements Comparable { this.coprocessors = cluster.getCoProcessors(); } - public CraftingCPUStatus( NBTTagCompound i ) - { + public CraftingCPUStatus(NBTTagCompound i) { this.serverCluster = null; - this.name = i.getString( "name" ); - this.serial = i.getInteger( "serial" ); + this.name = i.getString("name"); + this.serial = i.getInteger("serial"); this.storage = i.getLong("storage"); this.coprocessors = i.getLong("coprocessors"); this.totalItems = i.getLong("totalItems"); this.remainingItems = i.getLong("remainingItems"); - this.crafting = i.hasKey( "crafting" ) ? AEItemStack.fromNBT( i.getCompoundTag( "crafting" ) ) : null; + this.crafting = i.hasKey("crafting") ? AEItemStack.fromNBT(i.getCompoundTag("crafting")) : null; } - public CraftingCPUStatus(ByteBuf packet) throws IOException - { - this(readNBTFromPacket( packet )); + public CraftingCPUStatus(ByteBuf packet) throws IOException { + this(readNBTFromPacket(packet)); } - private static NBTTagCompound readNBTFromPacket(ByteBuf packet) throws IOException - { + private static NBTTagCompound readNBTFromPacket(ByteBuf packet) throws IOException { final int size = packet.readInt(); final byte[] tagBytes = new byte[size]; - packet.readBytes( tagBytes ); - final ByteArrayInputStream di = new ByteArrayInputStream( tagBytes ); - return CompressedStreamTools.read( new DataInputStream( di )); + packet.readBytes(tagBytes); + final ByteArrayInputStream di = new ByteArrayInputStream(tagBytes); + return CompressedStreamTools.read(new DataInputStream(di)); } - public void writeToNBT( NBTTagCompound i ) - { - if (name != null && !name.isEmpty()) - { - i.setString( "name", name ); + public void writeToNBT(NBTTagCompound i) { + if (name != null && !name.isEmpty()) { + i.setString("name", name); } - i.setInteger( "serial", serial ); - i.setLong( "storage", storage ); - i.setLong( "coprocessors", coprocessors ); - i.setLong( "totalItems", totalItems ); - i.setLong( "remainingItems", remainingItems ); - if (crafting != null) - { + i.setInteger("serial", serial); + i.setLong("storage", storage); + i.setLong("coprocessors", coprocessors); + i.setLong("totalItems", totalItems); + i.setLong("remainingItems", remainingItems); + if (crafting != null) { NBTTagCompound stack = new NBTTagCompound(); - crafting.writeToNBT( stack ); - i.setTag( "crafting", stack ); + crafting.writeToNBT(stack); + i.setTag("crafting", stack); } } - public void writeToPacket( ByteBuf i ) throws IOException - { + public void writeToPacket(ByteBuf i) throws IOException { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final DataOutputStream data = new DataOutputStream( bytes ); + final DataOutputStream data = new DataOutputStream(bytes); NBTTagCompound tag = new NBTTagCompound(); - this.writeToNBT( tag ); - CompressedStreamTools.write( tag, data ); + this.writeToNBT(tag); + CompressedStreamTools.write(tag, data); final byte[] tagBytes = bytes.toByteArray(); final int size = tagBytes.length; - i.writeInt( size ); - i.writeBytes( tagBytes ); + i.writeInt(size); + i.writeBytes(tagBytes); } @Nullable - public ICraftingCPU getServerCluster() - { + public ICraftingCPU getServerCluster() { return serverCluster; } - public String getName() - { + public String getName() { return name; } - public int getSerial() - { + public int getSerial() { return serial; } - public long getStorage() - { + public long getStorage() { return storage; } - public long getCoprocessors() - { + public long getCoprocessors() { return coprocessors; } - public long getTotalItems() - { + public long getTotalItems() { return totalItems; } - public long getRemainingItems() - { + public long getRemainingItems() { return remainingItems; } - public IAEItemStack getCrafting() - { + public IAEItemStack getCrafting() { return crafting; } @Override - public int compareTo( CraftingCPUStatus o ) - { - final int a = ItemSorters.compareLong( o.getCoprocessors(), this.getCoprocessors() ); - if( a != 0 ) - { + public int compareTo(CraftingCPUStatus o) { + final int a = ItemSorters.compareLong(o.getCoprocessors(), this.getCoprocessors()); + if (a != 0) { return a; } - return ItemSorters.compareLong( o.getStorage(), this.getStorage() ); + return ItemSorters.compareLong(o.getStorage(), this.getStorage()); } - public String formatStorage() - { + public String formatStorage() { long val = getStorage(); - if (val > 4_000_000_000_000L) - { + if (val > 4_000_000_000_000L) { return String.format("%dT", val / 1024 / 1024 / 1024 / 1024); - } - else if (val > 4_000_000_000L) - { + } else if (val > 4_000_000_000L) { return String.format("%dG", val / 1024 / 1024 / 1024); - } - else if (val > 4_000_000L) - { + } else if (val > 4_000_000L) { return String.format("%dM", val / 1024 / 1024); - } - else if (val > 4_000L) - { + } else if (val > 4_000L) { return String.format("%dk", val / 1024); - } - else - { - return Long.toString( val ); + } else { + return Long.toString(val); } } } diff --git a/src/main/java/appeng/container/interfaces/IInventorySlotAware.java b/src/main/java/appeng/container/interfaces/IInventorySlotAware.java index 492ed793f..1af2a7be7 100644 --- a/src/main/java/appeng/container/interfaces/IInventorySlotAware.java +++ b/src/main/java/appeng/container/interfaces/IInventorySlotAware.java @@ -21,17 +21,15 @@ package appeng.container.interfaces; /** * Any item providing a GUI and depending on an exact inventory slot. - * + *

* This interface is likely a volatile one until a general GUI refactoring occurred. * Use it with care and expect changes. - * */ -public interface IInventorySlotAware -{ - /** - * This is needed to select the correct slot index. - * - * @return the inventory index of this portable cell. - */ - int getInventorySlot(); +public interface IInventorySlotAware { + /** + * This is needed to select the correct slot index. + * + * @return the inventory index of this portable cell. + */ + int getInventorySlot(); } diff --git a/src/main/java/appeng/container/interfaces/IJEIGhostIngredients.java b/src/main/java/appeng/container/interfaces/IJEIGhostIngredients.java index f70eb0630..c4056aa8b 100644 --- a/src/main/java/appeng/container/interfaces/IJEIGhostIngredients.java +++ b/src/main/java/appeng/container/interfaces/IJEIGhostIngredients.java @@ -7,11 +7,10 @@ import java.util.List; import java.util.Map; -public interface IJEIGhostIngredients -{ - List> getPhantomTargets( Object ingredient ); +public interface IJEIGhostIngredients { + List> getPhantomTargets(Object ingredient); - default Map, Object> getFakeSlotTargetMap(){ + default Map, Object> getFakeSlotTargetMap() { return new HashMap<>(); } diff --git a/src/main/java/appeng/container/interfaces/IProgressProvider.java b/src/main/java/appeng/container/interfaces/IProgressProvider.java index 4dbb294a7..443013064 100644 --- a/src/main/java/appeng/container/interfaces/IProgressProvider.java +++ b/src/main/java/appeng/container/interfaces/IProgressProvider.java @@ -24,27 +24,26 @@ import appeng.client.gui.widgets.GuiProgressBar; /** * This interface provides the data for anything simulating a progress. - * + *

* Its main use is in combination with the {@link GuiProgressBar}, which ensures to scale it to a percentage of 0 to * 100. */ -public interface IProgressProvider -{ +public interface IProgressProvider { - /** - * The current value of the progress. It should cover a range from 0 to the max progress - * - * @return An int representing the current progress - */ - int getCurrentProgress(); + /** + * The current value of the progress. It should cover a range from 0 to the max progress + * + * @return An int representing the current progress + */ + int getCurrentProgress(); - /** - * The max value the progress. - * - * It is not limited to a value of 100 and can be scaled to fit the current needs. For example scaled down to - * decrease or scaled up to increase the precision. - * - * @return An int representing the max progress - */ - int getMaxProgress(); + /** + * The max value the progress. + *

+ * It is not limited to a value of 100 and can be scaled to fit the current needs. For example scaled down to + * decrease or scaled up to increase the precision. + * + * @return An int representing the max progress + */ + int getMaxProgress(); } diff --git a/src/main/java/appeng/container/slot/AppEngCraftingSlot.java b/src/main/java/appeng/container/slot/AppEngCraftingSlot.java index b0e93cdff..376e67737 100644 --- a/src/main/java/appeng/container/slot/AppEngCraftingSlot.java +++ b/src/main/java/appeng/container/slot/AppEngCraftingSlot.java @@ -19,6 +19,8 @@ package appeng.container.slot; +import appeng.util.helpers.ItemHandlerUtil; +import appeng.util.inv.WrapperInvItemHandler; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; @@ -27,179 +29,160 @@ import net.minecraft.util.NonNullList; import net.minecraft.world.World; import net.minecraftforge.items.IItemHandler; -import appeng.util.helpers.ItemHandlerUtil; -import appeng.util.inv.WrapperInvItemHandler; +public class AppEngCraftingSlot extends AppEngSlot { -public class AppEngCraftingSlot extends AppEngSlot -{ + /** + * The craft matrix inventory linked to this result slot. + */ + private final IItemHandler craftMatrix; - /** - * The craft matrix inventory linked to this result slot. - */ - private final IItemHandler craftMatrix; + /** + * The player that is using the GUI where this slot resides. + */ + private final EntityPlayer thePlayer; - /** - * The player that is using the GUI where this slot resides. - */ - private final EntityPlayer thePlayer; + /** + * The number of items that have been crafted so far. Gets passed to ItemStack.onCrafting before being reset. + */ + private int amountCrafted; - /** - * The number of items that have been crafted so far. Gets passed to ItemStack.onCrafting before being reset. - */ - private int amountCrafted; + public AppEngCraftingSlot(final EntityPlayer par1EntityPlayer, final IItemHandler par2IInventory, final IItemHandler par3IInventory, final int par4, final int par5, final int par6) { + super(par3IInventory, par4, par5, par6); + this.thePlayer = par1EntityPlayer; + this.craftMatrix = par2IInventory; + } - public AppEngCraftingSlot( final EntityPlayer par1EntityPlayer, final IItemHandler par2IInventory, final IItemHandler par3IInventory, final int par4, final int par5, final int par6 ) - { - super( par3IInventory, par4, par5, par6 ); - this.thePlayer = par1EntityPlayer; - this.craftMatrix = par2IInventory; - } + /** + * Check if the stack is a valid item for this slot. Always true beside for the armor slots. + */ + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - /** - * Check if the stack is a valid item for this slot. Always true beside for the armor slots. - */ - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + /** + * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. Typically increases an + * internal count then calls onCrafting(item). + */ + @Override + protected void onCrafting(final ItemStack par1ItemStack, final int par2) { + this.amountCrafted += par2; + this.onCrafting(par1ItemStack); + } - /** - * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. Typically increases an - * internal count then calls onCrafting(item). - */ - @Override - protected void onCrafting( final ItemStack par1ItemStack, final int par2 ) - { - this.amountCrafted += par2; - this.onCrafting( par1ItemStack ); - } + /** + * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. + */ + @Override + protected void onCrafting(final ItemStack par1ItemStack) { + par1ItemStack.onCrafting(this.thePlayer.world, this.thePlayer, this.amountCrafted); + this.amountCrafted = 0; - /** - * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. - */ - @Override - protected void onCrafting( final ItemStack par1ItemStack ) - { - par1ItemStack.onCrafting( this.thePlayer.world, this.thePlayer, this.amountCrafted ); - this.amountCrafted = 0; + // if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.CRAFTING_TABLE ) ) + // { + // this.thePlayer.addStat( AchievementList.BUILD_WORK_BENCH, 1 ); + // } + // + // if( par1ItemStack.getItem() instanceof ItemPickaxe ) + // { + // this.thePlayer.addStat( AchievementList.BUILD_PICKAXE, 1 ); + // } + // + // if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.FURNACE ) ) + // { + // this.thePlayer.addStat( AchievementList.BUILD_FURNACE, 1 ); + // } + // + // if( par1ItemStack.getItem() instanceof ItemHoe ) + // { + // this.thePlayer.addStat( AchievementList.BUILD_HOE, 1 ); + // } + // + // if( par1ItemStack.getItem() == Items.BREAD ) + // { + // this.thePlayer.addStat( AchievementList.MAKE_BREAD, 1 ); + // } + // + // if( par1ItemStack.getItem() == Items.CAKE ) + // { + // this.thePlayer.addStat( AchievementList.BAKE_CAKE, 1 ); + // } + // + // if( par1ItemStack.getItem() instanceof ItemPickaxe && ( (ItemTool) par1ItemStack.getItem() + // ).getToolMaterial() != Item.ToolMaterial.WOOD ) + // { + // this.thePlayer.addStat( AchievementList.BUILD_BETTER_PICKAXE, 1 ); + // } + // + // if( par1ItemStack.getItem() instanceof ItemSword ) + // { + // this.thePlayer.addStat( AchievementList.BUILD_SWORD, 1 ); + // } + // + // if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.ENCHANTING_TABLE ) ) + // { + // this.thePlayer.addStat( AchievementList.ENCHANTMENTS, 1 ); + // } + // + // if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.BOOKSHELF ) ) + // { + // this.thePlayer.addStat( AchievementList.BOOKCASE, 1 ); + // } + } - // if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.CRAFTING_TABLE ) ) - // { - // this.thePlayer.addStat( AchievementList.BUILD_WORK_BENCH, 1 ); - // } - // - // if( par1ItemStack.getItem() instanceof ItemPickaxe ) - // { - // this.thePlayer.addStat( AchievementList.BUILD_PICKAXE, 1 ); - // } - // - // if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.FURNACE ) ) - // { - // this.thePlayer.addStat( AchievementList.BUILD_FURNACE, 1 ); - // } - // - // if( par1ItemStack.getItem() instanceof ItemHoe ) - // { - // this.thePlayer.addStat( AchievementList.BUILD_HOE, 1 ); - // } - // - // if( par1ItemStack.getItem() == Items.BREAD ) - // { - // this.thePlayer.addStat( AchievementList.MAKE_BREAD, 1 ); - // } - // - // if( par1ItemStack.getItem() == Items.CAKE ) - // { - // this.thePlayer.addStat( AchievementList.BAKE_CAKE, 1 ); - // } - // - // if( par1ItemStack.getItem() instanceof ItemPickaxe && ( (ItemTool) par1ItemStack.getItem() - // ).getToolMaterial() != Item.ToolMaterial.WOOD ) - // { - // this.thePlayer.addStat( AchievementList.BUILD_BETTER_PICKAXE, 1 ); - // } - // - // if( par1ItemStack.getItem() instanceof ItemSword ) - // { - // this.thePlayer.addStat( AchievementList.BUILD_SWORD, 1 ); - // } - // - // if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.ENCHANTING_TABLE ) ) - // { - // this.thePlayer.addStat( AchievementList.ENCHANTMENTS, 1 ); - // } - // - // if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.BOOKSHELF ) ) - // { - // this.thePlayer.addStat( AchievementList.BOOKCASE, 1 ); - // } - } + @Override + public ItemStack onTake(final EntityPlayer playerIn, final ItemStack stack) { + net.minecraftforge.fml.common.FMLCommonHandler.instance().firePlayerCraftingEvent(playerIn, stack, new WrapperInvItemHandler(this.craftMatrix)); + this.onCrafting(stack); + net.minecraftforge.common.ForgeHooks.setCraftingPlayer(playerIn); + final InventoryCrafting ic = new InventoryCrafting(this.getContainer(), 3, 3); - @Override - public ItemStack onTake( final EntityPlayer playerIn, final ItemStack stack ) - { - net.minecraftforge.fml.common.FMLCommonHandler.instance().firePlayerCraftingEvent( playerIn, stack, new WrapperInvItemHandler( this.craftMatrix ) ); - this.onCrafting( stack ); - net.minecraftforge.common.ForgeHooks.setCraftingPlayer( playerIn ); - final InventoryCrafting ic = new InventoryCrafting( this.getContainer(), 3, 3 ); + for (int x = 0; x < this.craftMatrix.getSlots(); x++) { + ic.setInventorySlotContents(x, this.craftMatrix.getStackInSlot(x)); + } - for( int x = 0; x < this.craftMatrix.getSlots(); x++ ) - { - ic.setInventorySlotContents( x, this.craftMatrix.getStackInSlot( x ) ); - } + final NonNullList aitemstack = this.getRemainingItems(ic, playerIn.world); - final NonNullList aitemstack = this.getRemainingItems( ic, playerIn.world ); + ItemHandlerUtil.copy(ic, this.craftMatrix, false); - ItemHandlerUtil.copy( ic, this.craftMatrix, false ); + net.minecraftforge.common.ForgeHooks.setCraftingPlayer(null); - net.minecraftforge.common.ForgeHooks.setCraftingPlayer( null ); + for (int i = 0; i < aitemstack.size(); ++i) { + final ItemStack itemstack1 = this.craftMatrix.getStackInSlot(i); + final ItemStack itemstack2 = aitemstack.get(i); - for( int i = 0; i < aitemstack.size(); ++i ) - { - final ItemStack itemstack1 = this.craftMatrix.getStackInSlot( i ); - final ItemStack itemstack2 = aitemstack.get( i ); + if (!itemstack1.isEmpty()) { + this.craftMatrix.extractItem(i, 1, false); + } - if( !itemstack1.isEmpty() ) - { - this.craftMatrix.extractItem( i, 1, false ); - } + if (!itemstack2.isEmpty()) { + if (this.craftMatrix.getStackInSlot(i).isEmpty()) { + ItemHandlerUtil.setStackInSlot(this.craftMatrix, i, itemstack2); + } else if (!this.thePlayer.inventory.addItemStackToInventory(itemstack2)) { + this.thePlayer.dropItem(itemstack2, false); + } + } + } - if( !itemstack2.isEmpty() ) - { - if( this.craftMatrix.getStackInSlot( i ).isEmpty() ) - { - ItemHandlerUtil.setStackInSlot( this.craftMatrix, i, itemstack2 ); - } - else if( !this.thePlayer.inventory.addItemStackToInventory( itemstack2 ) ) - { - this.thePlayer.dropItem( itemstack2, false ); - } - } - } + return stack; + } - return stack; - } + /** + * Decrease the size of the stack in slot (first int arg) by the amount of the second int arg. Returns the new + * stack. + */ + @Override + public ItemStack decrStackSize(final int par1) { + if (this.getHasStack()) { + this.amountCrafted += Math.min(par1, this.getStack().getCount()); + } - /** - * Decrease the size of the stack in slot (first int arg) by the amount of the second int arg. Returns the new - * stack. - */ - @Override - public ItemStack decrStackSize( final int par1 ) - { - if( this.getHasStack() ) - { - this.amountCrafted += Math.min( par1, this.getStack().getCount() ); - } + return super.decrStackSize(par1); + } - return super.decrStackSize( par1 ); - } - - // TODO: This is really hacky and NEEDS to be solved with a full container/gui refactoring. - protected NonNullList getRemainingItems( InventoryCrafting ic, World world ) - { - return CraftingManager.getRemainingItems( ic, world ); - } + // TODO: This is really hacky and NEEDS to be solved with a full container/gui refactoring. + protected NonNullList getRemainingItems(InventoryCrafting ic, World world) { + return CraftingManager.getRemainingItems(ic, world); + } } diff --git a/src/main/java/appeng/container/slot/AppEngSlot.java b/src/main/java/appeng/container/slot/AppEngSlot.java index 9b09b41f5..93b19492a 100644 --- a/src/main/java/appeng/container/slot/AppEngSlot.java +++ b/src/main/java/appeng/container/slot/AppEngSlot.java @@ -19,8 +19,8 @@ package appeng.container.slot; -import javax.annotation.Nonnull; - +import appeng.container.AEBaseContainer; +import appeng.util.helpers.ItemHandlerUtil; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryBasic; @@ -30,270 +30,222 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.IItemHandler; -import appeng.container.AEBaseContainer; -import appeng.util.helpers.ItemHandlerUtil; +import javax.annotation.Nonnull; -public class AppEngSlot extends Slot -{ - private static IInventory emptyInventory = new InventoryBasic( "[Null]", true, 0 ); - private final IItemHandler itemHandler; - private final int index; +public class AppEngSlot extends Slot { + private static final IInventory emptyInventory = new InventoryBasic("[Null]", true, 0); + private final IItemHandler itemHandler; + private final int index; - private final int defX; - private final int defY; - private boolean isDraggable = true; - private boolean isPlayerSide = false; - private AEBaseContainer myContainer = null; - private int IIcon = -1; - private hasCalculatedValidness isValid; - private boolean isDisplay = false; + private final int defX; + private final int defY; + private boolean isDraggable = true; + private boolean isPlayerSide = false; + private AEBaseContainer myContainer = null; + private int IIcon = -1; + private hasCalculatedValidness isValid; + private boolean isDisplay = false; - public AppEngSlot( final IItemHandler inv, final int idx, final int x, final int y ) - { - super( emptyInventory, idx, x, y ); - this.itemHandler = inv; - this.index = idx; + public AppEngSlot(final IItemHandler inv, final int idx, final int x, final int y) { + super(emptyInventory, idx, x, y); + this.itemHandler = inv; + this.index = idx; - this.defX = x; - this.defY = y; - this.setIsValid( hasCalculatedValidness.NotAvailable ); - } + this.defX = x; + this.defY = y; + this.setIsValid(hasCalculatedValidness.NotAvailable); + } - public Slot setNotDraggable() - { - this.setDraggable( false ); - return this; - } + public Slot setNotDraggable() { + this.setDraggable(false); + return this; + } - public Slot setPlayerSide() - { - this.isPlayerSide = true; - return this; - } + public Slot setPlayerSide() { + this.isPlayerSide = true; + return this; + } - public String getTooltip() - { - return null; - } + public String getTooltip() { + return null; + } - public void clearStack() - { - ItemHandlerUtil.setStackInSlot( this.itemHandler, this.index, ItemStack.EMPTY ); - } + public void clearStack() { + ItemHandlerUtil.setStackInSlot(this.itemHandler, this.index, ItemStack.EMPTY); + } - @Override - public boolean isItemValid( @Nonnull final ItemStack par1ItemStack ) - { - if( this.isSlotEnabled() ) - { - return this.itemHandler.isItemValid( this.index, par1ItemStack ); - } - return false; - } + @Override + public boolean isItemValid(@Nonnull final ItemStack par1ItemStack) { + if (this.isSlotEnabled()) { + return this.itemHandler.isItemValid(this.index, par1ItemStack); + } + return false; + } - @Override - @Nonnull - public ItemStack getStack() - { - if( !this.isSlotEnabled() ) - { - return ItemStack.EMPTY; - } + @Override + @Nonnull + public ItemStack getStack() { + if (!this.isSlotEnabled()) { + return ItemStack.EMPTY; + } - if( this.itemHandler.getSlots() <= this.getSlotIndex() ) - { - return ItemStack.EMPTY; - } + if (this.itemHandler.getSlots() <= this.getSlotIndex()) { + return ItemStack.EMPTY; + } - if( this.isDisplay() ) - { - this.setDisplay( false ); - return this.getDisplayStack(); - } + if (this.isDisplay()) { + this.setDisplay(false); + return this.getDisplayStack(); + } - return this.itemHandler.getStackInSlot( this.index ); - } + return this.itemHandler.getStackInSlot(this.index); + } - @Override - public void putStack( final ItemStack stack ) - { - if( this.isSlotEnabled() ) - { - ItemHandlerUtil.setStackInSlot( this.itemHandler, this.index, stack ); + @Override + public void putStack(final ItemStack stack) { + if (this.isSlotEnabled()) { + ItemHandlerUtil.setStackInSlot(this.itemHandler, this.index, stack); - if( this.getContainer() != null ) - { - this.getContainer().onSlotChange( this ); - } - } - } + if (this.getContainer() != null) { + this.getContainer().onSlotChange(this); + } + } + } - public IItemHandler getItemHandler() - { - return this.itemHandler; - } + public IItemHandler getItemHandler() { + return this.itemHandler; + } - @Override - public void onSlotChanged() - { - this.setIsValid( hasCalculatedValidness.NotAvailable ); - if( this.isSlotEnabled() ) - { - ItemHandlerUtil.setStackInSlot( this.itemHandler, this.index, this.getStack().copy() ); + @Override + public void onSlotChanged() { + this.setIsValid(hasCalculatedValidness.NotAvailable); + if (this.isSlotEnabled()) { + ItemHandlerUtil.setStackInSlot(this.itemHandler, this.index, this.getStack().copy()); - if( this.getContainer() != null ) - { - this.getContainer().onSlotChange( this ); - } - } - super.onSlotChanged(); - } + if (this.getContainer() != null) { + this.getContainer().onSlotChange(this); + } + } + super.onSlotChanged(); + } - @Override - public int getSlotStackLimit() - { - return this.itemHandler.getSlotLimit( this.index ); - } + @Override + public int getSlotStackLimit() { + return this.itemHandler.getSlotLimit(this.index); + } - @Override - public int getItemStackLimit( @Nonnull ItemStack stack ) - { - return Math.min( this.getSlotStackLimit(), stack.getMaxStackSize() ); - } + @Override + public int getItemStackLimit(@Nonnull ItemStack stack) { + return Math.min(this.getSlotStackLimit(), stack.getMaxStackSize()); + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - if( this.isSlotEnabled() ) - { - return !this.itemHandler.extractItem( this.index, Integer.MAX_VALUE, true ).isEmpty(); - } - return false; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + if (this.isSlotEnabled()) { + return !this.itemHandler.extractItem(this.index, Integer.MAX_VALUE, true).isEmpty(); + } + return false; + } - @Override - @Nonnull - public ItemStack decrStackSize( int amount ) - { - return this.itemHandler.extractItem( this.index, amount, false ); - } + @Override + @Nonnull + public ItemStack decrStackSize(int amount) { + return this.itemHandler.extractItem(this.index, amount, false); + } - @Override - public boolean isSameInventory( Slot other ) - { - return other instanceof AppEngSlot && ( (AppEngSlot) other ).itemHandler == this.itemHandler; - } + @Override + public boolean isSameInventory(Slot other) { + return other instanceof AppEngSlot && ((AppEngSlot) other).itemHandler == this.itemHandler; + } - @Override - @SideOnly( Side.CLIENT ) - public boolean isEnabled() - { - return this.isSlotEnabled(); - } + @Override + @SideOnly(Side.CLIENT) + public boolean isEnabled() { + return this.isSlotEnabled(); + } - public boolean isSlotEnabled() - { - return true; - } + public boolean isSlotEnabled() { + return true; + } - public ItemStack getDisplayStack() - { - return this.itemHandler.getStackInSlot( this.index ); - } + public ItemStack getDisplayStack() { + return this.itemHandler.getStackInSlot(this.index); + } - public float getOpacityOfIcon() - { - return 0.4f; - } + public float getOpacityOfIcon() { + return 0.4f; + } - public boolean renderIconWithItem() - { - return false; - } + public boolean renderIconWithItem() { + return false; + } - public int getIcon() - { - return this.getIIcon(); - } + public int getIcon() { + return this.getIIcon(); + } - public boolean isPlayerSide() - { - return this.isPlayerSide; - } + public boolean isPlayerSide() { + return this.isPlayerSide; + } - public boolean shouldDisplay() - { - return this.isSlotEnabled(); - } + public boolean shouldDisplay() { + return this.isSlotEnabled(); + } - public int getX() - { - return this.defX; - } + public int getX() { + return this.defX; + } - public int getY() - { - return this.defY; - } + public int getY() { + return this.defY; + } - private int getIIcon() - { - return this.IIcon; - } + private int getIIcon() { + return this.IIcon; + } - public void setIIcon( final int iIcon ) - { - this.IIcon = iIcon; - } + public void setIIcon(final int iIcon) { + this.IIcon = iIcon; + } - private boolean isDisplay() - { - return this.isDisplay; - } + private boolean isDisplay() { + return this.isDisplay; + } - public void setDisplay( final boolean isDisplay ) - { - this.isDisplay = isDisplay; - } + public void setDisplay(final boolean isDisplay) { + this.isDisplay = isDisplay; + } - public boolean isDraggable() - { - return this.isDraggable; - } + public boolean isDraggable() { + return this.isDraggable; + } - private void setDraggable( final boolean isDraggable ) - { - this.isDraggable = isDraggable; - } + private void setDraggable(final boolean isDraggable) { + this.isDraggable = isDraggable; + } - void setPlayerSide( final boolean isPlayerSide ) - { - this.isPlayerSide = isPlayerSide; - } + void setPlayerSide(final boolean isPlayerSide) { + this.isPlayerSide = isPlayerSide; + } - public hasCalculatedValidness getIsValid() - { - return this.isValid; - } + public hasCalculatedValidness getIsValid() { + return this.isValid; + } - public void setIsValid( final hasCalculatedValidness isValid ) - { - this.isValid = isValid; - } + public void setIsValid(final hasCalculatedValidness isValid) { + this.isValid = isValid; + } - protected AEBaseContainer getContainer() - { - return this.myContainer; - } + protected AEBaseContainer getContainer() { + return this.myContainer; + } - public void setContainer( final AEBaseContainer myContainer ) - { - this.myContainer = myContainer; - } + public void setContainer(final AEBaseContainer myContainer) { + this.myContainer = myContainer; + } - public enum hasCalculatedValidness - { - NotAvailable, Valid, Invalid - } + public enum hasCalculatedValidness { + NotAvailable, Valid, Invalid + } } diff --git a/src/main/java/appeng/container/slot/IOptionalSlot.java b/src/main/java/appeng/container/slot/IOptionalSlot.java index 727b6a2f2..d6ca9bb1c 100644 --- a/src/main/java/appeng/container/slot/IOptionalSlot.java +++ b/src/main/java/appeng/container/slot/IOptionalSlot.java @@ -24,14 +24,12 @@ package appeng.container.slot; * @version rv6 - 2/05/2018 * @since rv6 2/05/2018 */ -public interface IOptionalSlot -{ - default boolean isRenderDisabled() - { - return false; - } +public interface IOptionalSlot { + default boolean isRenderDisabled() { + return false; + } - int getSourceX(); + int getSourceX(); - int getSourceY(); + int getSourceY(); } diff --git a/src/main/java/appeng/container/slot/IOptionalSlotHost.java b/src/main/java/appeng/container/slot/IOptionalSlotHost.java index 995959ce0..2699d24b5 100644 --- a/src/main/java/appeng/container/slot/IOptionalSlotHost.java +++ b/src/main/java/appeng/container/slot/IOptionalSlotHost.java @@ -19,8 +19,7 @@ package appeng.container.slot; -public interface IOptionalSlotHost -{ +public interface IOptionalSlotHost { - boolean isSlotEnabled( int idx ); + boolean isSlotEnabled(int idx); } diff --git a/src/main/java/appeng/container/slot/NullSlot.java b/src/main/java/appeng/container/slot/NullSlot.java index e489b8385..6635a798c 100644 --- a/src/main/java/appeng/container/slot/NullSlot.java +++ b/src/main/java/appeng/container/slot/NullSlot.java @@ -19,86 +19,73 @@ package appeng.container.slot; -import javax.annotation.Nonnull; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; +import javax.annotation.Nonnull; -public class NullSlot extends Slot -{ - public NullSlot() - { - super( null, 0, 0, 0 ); - } +public class NullSlot extends Slot { - @Override - public void onSlotChange( final ItemStack par1ItemStack, final ItemStack par2ItemStack ) - { + public NullSlot() { + super(null, 0, 0, 0); + } - } + @Override + public void onSlotChange(final ItemStack par1ItemStack, final ItemStack par2ItemStack) { - @Override - public ItemStack onTake( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) - { - return par2ItemStack; - } + } - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + @Override + public ItemStack onTake(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) { + return par2ItemStack; + } - @Override - @Nonnull - public ItemStack getStack() - { - return ItemStack.EMPTY; - } + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - @Override - public void putStack( final ItemStack par1ItemStack ) - { + @Override + @Nonnull + public ItemStack getStack() { + return ItemStack.EMPTY; + } - } + @Override + public void putStack(final ItemStack par1ItemStack) { - @Override - public void onSlotChanged() - { + } - } + @Override + public void onSlotChanged() { - @Override - public int getSlotStackLimit() - { - return 0; - } + } - @Override - public ItemStack decrStackSize( final int par1 ) - { - return ItemStack.EMPTY; - } + @Override + public int getSlotStackLimit() { + return 0; + } - @Override - public boolean isHere( final IInventory inv, final int slotIn ) - { - return false; - } + @Override + public ItemStack decrStackSize(final int par1) { + return ItemStack.EMPTY; + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean isHere(final IInventory inv, final int slotIn) { + return false; + } - @Override - public int getSlotIndex() - { - return 0; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } + + @Override + public int getSlotIndex() { + return 0; + } } diff --git a/src/main/java/appeng/container/slot/OptionalSlotFake.java b/src/main/java/appeng/container/slot/OptionalSlotFake.java index b187c4503..f2e48398c 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotFake.java +++ b/src/main/java/appeng/container/slot/OptionalSlotFake.java @@ -19,76 +19,65 @@ package appeng.container.slot; -import javax.annotation.Nonnull; - import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; +import javax.annotation.Nonnull; -public class OptionalSlotFake extends SlotFake implements IOptionalSlot -{ - private final int srcX; - private final int srcY; - private final int groupNum; - private final IOptionalSlotHost host; - private boolean renderDisabled = true; +public class OptionalSlotFake extends SlotFake implements IOptionalSlot { - public OptionalSlotFake( final IItemHandler inv, final IOptionalSlotHost containerBus, final int idx, final int x, final int y, final int offX, final int offY, final int groupNum ) - { - super( inv, idx, x + offX * 18, y + offY * 18 ); - this.srcX = x; - this.srcY = y; - this.groupNum = groupNum; - this.host = containerBus; - } + private final int srcX; + private final int srcY; + private final int groupNum; + private final IOptionalSlotHost host; + private boolean renderDisabled = true; - @Override - @Nonnull - public ItemStack getStack() - { - if( !this.isSlotEnabled() ) - { - if( !this.getDisplayStack().isEmpty() ) - { - this.clearStack(); - } - } + public OptionalSlotFake(final IItemHandler inv, final IOptionalSlotHost containerBus, final int idx, final int x, final int y, final int offX, final int offY, final int groupNum) { + super(inv, idx, x + offX * 18, y + offY * 18); + this.srcX = x; + this.srcY = y; + this.groupNum = groupNum; + this.host = containerBus; + } - return super.getStack(); - } + @Override + @Nonnull + public ItemStack getStack() { + if (!this.isSlotEnabled()) { + if (!this.getDisplayStack().isEmpty()) { + this.clearStack(); + } + } - @Override - public boolean isSlotEnabled() - { - if( this.host == null ) - { - return false; - } + return super.getStack(); + } - return this.host.isSlotEnabled( this.groupNum ); - } + @Override + public boolean isSlotEnabled() { + if (this.host == null) { + return false; + } - @Override - public boolean isRenderDisabled() - { - return this.renderDisabled; - } + return this.host.isSlotEnabled(this.groupNum); + } - public void setRenderDisabled( final boolean renderDisabled ) - { - this.renderDisabled = renderDisabled; - } + @Override + public boolean isRenderDisabled() { + return this.renderDisabled; + } - @Override - public int getSourceX() - { - return this.srcX; - } + public void setRenderDisabled(final boolean renderDisabled) { + this.renderDisabled = renderDisabled; + } - @Override - public int getSourceY() - { - return this.srcY; - } + @Override + public int getSourceX() { + return this.srcX; + } + + @Override + public int getSourceY() { + return this.srcY; + } } diff --git a/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java b/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java index 7c86c8b53..7a612606b 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java +++ b/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java @@ -23,30 +23,23 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; -public class OptionalSlotFakeTypeOnly extends OptionalSlotFake -{ +public class OptionalSlotFakeTypeOnly extends OptionalSlotFake { - public OptionalSlotFakeTypeOnly( final IItemHandler inv, final IOptionalSlotHost containerBus, final int idx, final int x, final int y, final int offX, final int offY, final int groupNum ) - { - super( inv, containerBus, idx, x, y, offX, offY, groupNum ); - } + public OptionalSlotFakeTypeOnly(final IItemHandler inv, final IOptionalSlotHost containerBus, final int idx, final int x, final int y, final int offX, final int offY, final int groupNum) { + super(inv, containerBus, idx, x, y, offX, offY, groupNum); + } - @Override - public void putStack( ItemStack is ) - { - if( !is.isEmpty() ) - { - is = is.copy(); - if( is.getCount() > 1 ) - { - is.setCount( 1 ); - } - else if( is.getCount() < -1 ) - { - is.setCount( -1 ); - } - } + @Override + public void putStack(ItemStack is) { + if (!is.isEmpty()) { + is = is.copy(); + if (is.getCount() > 1) { + is.setCount(1); + } else if (is.getCount() < -1) { + is.setCount(-1); + } + } - super.putStack( is ); - } + super.putStack(is); + } } diff --git a/src/main/java/appeng/container/slot/OptionalSlotNormal.java b/src/main/java/appeng/container/slot/OptionalSlotNormal.java index 44d4edd37..fe76412aa 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotNormal.java +++ b/src/main/java/appeng/container/slot/OptionalSlotNormal.java @@ -22,39 +22,33 @@ package appeng.container.slot; import net.minecraftforge.items.IItemHandler; -public class OptionalSlotNormal extends AppEngSlot implements IOptionalSlot -{ +public class OptionalSlotNormal extends AppEngSlot implements IOptionalSlot { - private final int groupNum; - private final IOptionalSlotHost host; + private final int groupNum; + private final IOptionalSlotHost host; - public OptionalSlotNormal( final IItemHandler inv, final IOptionalSlotHost containerBus, final int slot, final int xPos, final int yPos, final int groupNum ) - { - super( inv, slot, xPos, yPos ); - this.groupNum = groupNum; - this.host = containerBus; - } + public OptionalSlotNormal(final IItemHandler inv, final IOptionalSlotHost containerBus, final int slot, final int xPos, final int yPos, final int groupNum) { + super(inv, slot, xPos, yPos); + this.groupNum = groupNum; + this.host = containerBus; + } - @Override - public boolean isSlotEnabled() - { - if( this.host == null ) - { - return false; - } + @Override + public boolean isSlotEnabled() { + if (this.host == null) { + return false; + } - return this.host.isSlotEnabled( this.groupNum ); - } + return this.host.isSlotEnabled(this.groupNum); + } - @Override - public int getSourceX() - { - return this.xPos; - } + @Override + public int getSourceX() { + return this.xPos; + } - @Override - public int getSourceY() - { - return this.yPos; - } + @Override + public int getSourceY() { + return this.yPos; + } } diff --git a/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java b/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java index c82406bd6..87094f415 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java +++ b/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java @@ -23,27 +23,23 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraftforge.items.IItemHandler; -public class OptionalSlotRestrictedInput extends SlotRestrictedInput -{ +public class OptionalSlotRestrictedInput extends SlotRestrictedInput { - private final int groupNum; - private final IOptionalSlotHost host; + private final int groupNum; + private final IOptionalSlotHost host; - public OptionalSlotRestrictedInput( final PlacableItemType valid, final IItemHandler i, final IOptionalSlotHost host, final int slotIndex, final int x, final int y, final int grpNum, final InventoryPlayer invPlayer ) - { - super( valid, i, slotIndex, x, y, invPlayer ); - this.groupNum = grpNum; - this.host = host; - } + public OptionalSlotRestrictedInput(final PlacableItemType valid, final IItemHandler i, final IOptionalSlotHost host, final int slotIndex, final int x, final int y, final int grpNum, final InventoryPlayer invPlayer) { + super(valid, i, slotIndex, x, y, invPlayer); + this.groupNum = grpNum; + this.host = host; + } - @Override - public boolean isSlotEnabled() - { - if( this.host == null ) - { - return false; - } + @Override + public boolean isSlotEnabled() { + if (this.host == null) { + return false; + } - return this.host.isSlotEnabled( this.groupNum ); - } + return this.host.isSlotEnabled(this.groupNum); + } } diff --git a/src/main/java/appeng/container/slot/SlotCraftingMatrix.java b/src/main/java/appeng/container/slot/SlotCraftingMatrix.java index e33dff30f..52f915f87 100644 --- a/src/main/java/appeng/container/slot/SlotCraftingMatrix.java +++ b/src/main/java/appeng/container/slot/SlotCraftingMatrix.java @@ -19,51 +19,44 @@ package appeng.container.slot; +import appeng.container.AEBaseContainer; +import appeng.util.inv.WrapperInvItemHandler; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; -import appeng.container.AEBaseContainer; -import appeng.util.inv.WrapperInvItemHandler; +public class SlotCraftingMatrix extends AppEngSlot { + private final AEBaseContainer c; + private final IInventory wrappedInventory; -public class SlotCraftingMatrix extends AppEngSlot -{ - private final AEBaseContainer c; - private final IInventory wrappedInventory; + public SlotCraftingMatrix(final AEBaseContainer c, final IItemHandler par1iInventory, final int par2, final int par3, final int par4) { + super(par1iInventory, par2, par3, par4); + this.c = c; + this.wrappedInventory = new WrapperInvItemHandler(par1iInventory); + } - public SlotCraftingMatrix( final AEBaseContainer c, final IItemHandler par1iInventory, final int par2, final int par3, final int par4 ) - { - super( par1iInventory, par2, par3, par4 ); - this.c = c; - this.wrappedInventory = new WrapperInvItemHandler( par1iInventory ); - } + @Override + public void clearStack() { + super.clearStack(); + this.c.onCraftMatrixChanged(this.wrappedInventory); + } - @Override - public void clearStack() - { - super.clearStack(); - this.c.onCraftMatrixChanged( this.wrappedInventory ); - } + @Override + public void putStack(final ItemStack par1ItemStack) { + super.putStack(par1ItemStack); + this.c.onCraftMatrixChanged(this.wrappedInventory); + } - @Override - public void putStack( final ItemStack par1ItemStack ) - { - super.putStack( par1ItemStack ); - this.c.onCraftMatrixChanged( this.wrappedInventory ); - } + @Override + public boolean isPlayerSide() { + return true; + } - @Override - public boolean isPlayerSide() - { - return true; - } - - @Override - public ItemStack decrStackSize( final int par1 ) - { - final ItemStack is = super.decrStackSize( par1 ); - this.c.onCraftMatrixChanged( this.wrappedInventory ); - return is; - } + @Override + public ItemStack decrStackSize(final int par1) { + final ItemStack is = super.decrStackSize(par1); + this.c.onCraftMatrixChanged(this.wrappedInventory); + return is; + } } diff --git a/src/main/java/appeng/container/slot/SlotCraftingTerm.java b/src/main/java/appeng/container/slot/SlotCraftingTerm.java index e072e13d5..93e0b8f5b 100644 --- a/src/main/java/appeng/container/slot/SlotCraftingTerm.java +++ b/src/main/java/appeng/container/slot/SlotCraftingTerm.java @@ -19,21 +19,6 @@ package appeng.container.slot; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.CraftingManager; -import net.minecraft.item.crafting.IRecipe; -import net.minecraft.util.NonNullList; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.networking.energy.IEnergySource; @@ -55,276 +40,243 @@ import appeng.util.inv.AdaptorItemHandler; import appeng.util.inv.WrapperCursorItemHandler; import appeng.util.inv.WrapperInvItemHandler; import appeng.util.item.AEItemStack; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.items.IItemHandler; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; -public class SlotCraftingTerm extends AppEngCraftingSlot -{ +public class SlotCraftingTerm extends AppEngCraftingSlot { - private final IItemHandler craftInv; - private final IItemHandler pattern; + private final IItemHandler craftInv; + private final IItemHandler pattern; - private final IActionSource mySrc; - private final IEnergySource energySrc; - private final IStorageMonitorable storage; - private final IContainerCraftingPacket container; + private final IActionSource mySrc; + private final IEnergySource energySrc; + private final IStorageMonitorable storage; + private final IContainerCraftingPacket container; - public SlotCraftingTerm( final EntityPlayer player, final IActionSource mySrc, final IEnergySource energySrc, final IStorageMonitorable storage, final IItemHandler cMatrix, final IItemHandler secondMatrix, final IItemHandler output, final int x, final int y, final IContainerCraftingPacket ccp ) - { - super( player, cMatrix, output, 0, x, y ); - this.energySrc = energySrc; - this.storage = storage; - this.mySrc = mySrc; - this.pattern = cMatrix; - this.craftInv = secondMatrix; - this.container = ccp; - } + public SlotCraftingTerm(final EntityPlayer player, final IActionSource mySrc, final IEnergySource energySrc, final IStorageMonitorable storage, final IItemHandler cMatrix, final IItemHandler secondMatrix, final IItemHandler output, final int x, final int y, final IContainerCraftingPacket ccp) { + super(player, cMatrix, output, 0, x, y); + this.energySrc = energySrc; + this.storage = storage; + this.mySrc = mySrc; + this.pattern = cMatrix; + this.craftInv = secondMatrix; + this.container = ccp; + } - public IItemHandler getCraftingMatrix() - { - return this.craftInv; - } + public IItemHandler getCraftingMatrix() { + return this.craftInv; + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } - @Override - public ItemStack onTake( final EntityPlayer p, final ItemStack is ) - { - return is; - } + @Override + public ItemStack onTake(final EntityPlayer p, final ItemStack is) { + return is; + } - public void doClick( final InventoryAction action, final EntityPlayer who ) - { - if( this.getStack().isEmpty() ) - { - return; - } - if( Platform.isClient() ) - { - return; - } + public void doClick(final InventoryAction action, final EntityPlayer who) { + if (this.getStack().isEmpty()) { + return; + } + if (Platform.isClient()) { + return; + } - final IMEMonitor inv = this.storage.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - final int howManyPerCraft = this.getStack().getCount(); - int maxTimesToCraft = 0; + final IMEMonitor inv = this.storage.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + final int howManyPerCraft = this.getStack().getCount(); + int maxTimesToCraft = 0; - InventoryAdaptor ia = null; - if( action == InventoryAction.CRAFT_SHIFT ) // craft into player inventory... - { - ia = InventoryAdaptor.getAdaptor( who ); - maxTimesToCraft = (int) Math.floor( (double) this.getStack().getMaxStackSize() / (double) howManyPerCraft ); - } - else if( action == InventoryAction.CRAFT_STACK ) // craft into hand, full stack - { - ia = new AdaptorItemHandler( new WrapperCursorItemHandler( who.inventory ) ); - maxTimesToCraft = (int) Math.floor( (double) this.getStack().getMaxStackSize() / (double) howManyPerCraft ); - } - else - // pick up what was crafted... - { - ia = new AdaptorItemHandler( new WrapperCursorItemHandler( who.inventory ) ); - maxTimesToCraft = 1; - } + InventoryAdaptor ia = null; + if (action == InventoryAction.CRAFT_SHIFT) // craft into player inventory... + { + ia = InventoryAdaptor.getAdaptor(who); + maxTimesToCraft = (int) Math.floor((double) this.getStack().getMaxStackSize() / (double) howManyPerCraft); + } else if (action == InventoryAction.CRAFT_STACK) // craft into hand, full stack + { + ia = new AdaptorItemHandler(new WrapperCursorItemHandler(who.inventory)); + maxTimesToCraft = (int) Math.floor((double) this.getStack().getMaxStackSize() / (double) howManyPerCraft); + } else + // pick up what was crafted... + { + ia = new AdaptorItemHandler(new WrapperCursorItemHandler(who.inventory)); + maxTimesToCraft = 1; + } - maxTimesToCraft = this.capCraftingAttempts( maxTimesToCraft ); + maxTimesToCraft = this.capCraftingAttempts(maxTimesToCraft); - if( ia == null ) - { - return; - } + if (ia == null) { + return; + } - final ItemStack rs = this.getStack().copy(); - if( rs.isEmpty() ) - { - return; - } + final ItemStack rs = this.getStack().copy(); + if (rs.isEmpty()) { + return; + } - for( int x = 0; x < maxTimesToCraft; x++ ) - { - if( ia.simulateAdd( rs ).isEmpty() ) - { - final IItemList all = inv.getStorageList(); - final ItemStack extra = ia.addItems( this.craftItem( who, rs, inv, all ) ); - if( !extra.isEmpty() ) - { - final List drops = new ArrayList<>(); - drops.add( extra ); - Platform.spawnDrops( who.world, new BlockPos( (int) who.posX, (int) who.posY, (int) who.posZ ), drops ); - return; - } - } - } - } + for (int x = 0; x < maxTimesToCraft; x++) { + if (ia.simulateAdd(rs).isEmpty()) { + final IItemList all = inv.getStorageList(); + final ItemStack extra = ia.addItems(this.craftItem(who, rs, inv, all)); + if (!extra.isEmpty()) { + final List drops = new ArrayList<>(); + drops.add(extra); + Platform.spawnDrops(who.world, new BlockPos((int) who.posX, (int) who.posY, (int) who.posZ), drops); + return; + } + } + } + } - // TODO: This is really hacky and NEEDS to be solved with a full container/gui refactoring. - protected IRecipe findRecipe( InventoryCrafting ic, World world ) - { - if( this.container instanceof ContainerCraftingTerm ) - { - final ContainerCraftingTerm containerTerminal = (ContainerCraftingTerm) this.container; - final IRecipe recipe = containerTerminal.getCurrentRecipe(); + // TODO: This is really hacky and NEEDS to be solved with a full container/gui refactoring. + protected IRecipe findRecipe(InventoryCrafting ic, World world) { + if (this.container instanceof ContainerCraftingTerm) { + final ContainerCraftingTerm containerTerminal = (ContainerCraftingTerm) this.container; + final IRecipe recipe = containerTerminal.getCurrentRecipe(); - if( recipe != null && recipe.matches( ic, world ) ) - { - return containerTerminal.getCurrentRecipe(); - } - } + if (recipe != null && recipe.matches(ic, world)) { + return containerTerminal.getCurrentRecipe(); + } + } - return CraftingManager.findMatchingRecipe( ic, world ); - } + return CraftingManager.findMatchingRecipe(ic, world); + } - // TODO: This is really hacky and NEEDS to be solved with a full container/gui refactoring. - @Override - protected NonNullList getRemainingItems( InventoryCrafting ic, World world ) - { - if( this.container instanceof ContainerCraftingTerm ) - { - final ContainerCraftingTerm containerTerminal = (ContainerCraftingTerm) this.container; - final IRecipe recipe = containerTerminal.getCurrentRecipe(); + // TODO: This is really hacky and NEEDS to be solved with a full container/gui refactoring. + @Override + protected NonNullList getRemainingItems(InventoryCrafting ic, World world) { + if (this.container instanceof ContainerCraftingTerm) { + final ContainerCraftingTerm containerTerminal = (ContainerCraftingTerm) this.container; + final IRecipe recipe = containerTerminal.getCurrentRecipe(); - if( recipe != null && recipe.matches( ic, world ) ) - { - return containerTerminal.getCurrentRecipe().getRemainingItems( ic ); - } - } + if (recipe != null && recipe.matches(ic, world)) { + return containerTerminal.getCurrentRecipe().getRemainingItems(ic); + } + } - return CraftingManager.getRemainingItems( ic, world ); - } + return CraftingManager.getRemainingItems(ic, world); + } - private int capCraftingAttempts( final int maxTimesToCraft ) - { - return maxTimesToCraft; - } + private int capCraftingAttempts(final int maxTimesToCraft) { + return maxTimesToCraft; + } - private ItemStack craftItem( final EntityPlayer p, final ItemStack request, final IMEMonitor inv, final IItemList all ) - { - // update crafting matrix... - ItemStack is = this.getStack(); + private ItemStack craftItem(final EntityPlayer p, final ItemStack request, final IMEMonitor inv, final IItemList all) { + // update crafting matrix... + ItemStack is = this.getStack(); - if( !is.isEmpty() && ItemStack.areItemsEqual( request, is ) ) - { - final ItemStack[] set = new ItemStack[this.getPattern().getSlots()]; - // Safeguard for empty slots in the inventory for now - Arrays.fill( set, ItemStack.EMPTY ); + if (!is.isEmpty() && ItemStack.areItemsEqual(request, is)) { + final ItemStack[] set = new ItemStack[this.getPattern().getSlots()]; + // Safeguard for empty slots in the inventory for now + Arrays.fill(set, ItemStack.EMPTY); - // add one of each item to the items on the board... - if( Platform.isServer() ) - { - final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); - for( int x = 0; x < 9; x++ ) - { - ic.setInventorySlotContents( x, this.getPattern().getStackInSlot( x ) ); - } + // add one of each item to the items on the board... + if (Platform.isServer()) { + final InventoryCrafting ic = new InventoryCrafting(new ContainerNull(), 3, 3); + for (int x = 0; x < 9; x++) { + ic.setInventorySlotContents(x, this.getPattern().getStackInSlot(x)); + } - final IRecipe r = this.findRecipe( ic, p.world ); + final IRecipe r = this.findRecipe(ic, p.world); - if( r == null ) - { - final Item target = request.getItem(); - if( target.isDamageable() && target.isRepairable() ) - { - boolean isBad = false; - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack pis = ic.getStackInSlot( x ); - if( pis.isEmpty() ) - { - continue; - } - if( pis.getItem() != target ) - { - isBad = true; - } - } - if( !isBad ) - { - super.onTake( p, is ); - // actually necessary to cleanup this case... - p.openContainer.onCraftMatrixChanged( new WrapperInvItemHandler( this.craftInv ) ); - return request; - } - } - return ItemStack.EMPTY; - } + if (r == null) { + final Item target = request.getItem(); + if (target.isDamageable() && target.isRepairable()) { + boolean isBad = false; + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack pis = ic.getStackInSlot(x); + if (pis.isEmpty()) { + continue; + } + if (pis.getItem() != target) { + isBad = true; + } + } + if (!isBad) { + super.onTake(p, is); + // actually necessary to cleanup this case... + p.openContainer.onCraftMatrixChanged(new WrapperInvItemHandler(this.craftInv)); + return request; + } + } + return ItemStack.EMPTY; + } - is = r.getCraftingResult( ic ); + is = r.getCraftingResult(ic); - if( inv != null ) - { - for( int x = 0; x < this.getPattern().getSlots(); x++ ) - { - if( !this.getPattern().getStackInSlot( x ).isEmpty() ) - { - set[x] = Platform.extractItemsByRecipe( this.energySrc, this.mySrc, inv, p.world, r, is, ic, this.getPattern().getStackInSlot( x ), - x, all, Actionable.MODULATE, ItemViewCell.createFilter( this.container.getViewCells() ) ); - ic.setInventorySlotContents( x, set[x] ); - } - } - } - } + if (inv != null) { + for (int x = 0; x < this.getPattern().getSlots(); x++) { + if (!this.getPattern().getStackInSlot(x).isEmpty()) { + set[x] = Platform.extractItemsByRecipe(this.energySrc, this.mySrc, inv, p.world, r, is, ic, this.getPattern().getStackInSlot(x), + x, all, Actionable.MODULATE, ItemViewCell.createFilter(this.container.getViewCells())); + ic.setInventorySlotContents(x, set[x]); + } + } + } + } - if( this.preCraft( p, inv, set, is ) ) - { - this.makeItem( p, is ); + if (this.preCraft(p, inv, set, is)) { + this.makeItem(p, is); - this.postCraft( p, inv, set, is ); - } + this.postCraft(p, inv, set, is); + } - p.openContainer.onCraftMatrixChanged( new WrapperInvItemHandler( this.craftInv ) ); + p.openContainer.onCraftMatrixChanged(new WrapperInvItemHandler(this.craftInv)); - return is; - } + return is; + } - return ItemStack.EMPTY; - } + return ItemStack.EMPTY; + } - private boolean preCraft( final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set, final ItemStack result ) - { - return true; - } + private boolean preCraft(final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set, final ItemStack result) { + return true; + } - private void makeItem( final EntityPlayer p, final ItemStack is ) - { - super.onTake( p, is ); - } + private void makeItem(final EntityPlayer p, final ItemStack is) { + super.onTake(p, is); + } - private void postCraft( final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set, final ItemStack result ) - { - final List drops = new ArrayList<>(); + private void postCraft(final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set, final ItemStack result) { + final List drops = new ArrayList<>(); - // add one of each item to the items on the board... - if( Platform.isServer() ) - { - // set new items onto the crafting table... - for( int x = 0; x < this.craftInv.getSlots(); x++ ) - { - if( this.craftInv.getStackInSlot( x ).isEmpty() ) - { - ItemHandlerUtil.setStackInSlot( this.craftInv, x, set[x] ); - } - else if( !set[x].isEmpty() ) - { - // eek! put it back! - final IAEItemStack fail = inv.injectItems( AEItemStack.fromItemStack( set[x] ), Actionable.MODULATE, this.mySrc ); - if( fail != null ) - { - drops.add( fail.createItemStack() ); - } - } - } - } + // add one of each item to the items on the board... + if (Platform.isServer()) { + // set new items onto the crafting table... + for (int x = 0; x < this.craftInv.getSlots(); x++) { + if (this.craftInv.getStackInSlot(x).isEmpty()) { + ItemHandlerUtil.setStackInSlot(this.craftInv, x, set[x]); + } else if (!set[x].isEmpty()) { + // eek! put it back! + final IAEItemStack fail = inv.injectItems(AEItemStack.fromItemStack(set[x]), Actionable.MODULATE, this.mySrc); + if (fail != null) { + drops.add(fail.createItemStack()); + } + } + } + } - if( drops.size() > 0 ) - { - Platform.spawnDrops( p.world, new BlockPos( (int) p.posX, (int) p.posY, (int) p.posZ ), drops ); - } - } + if (drops.size() > 0) { + Platform.spawnDrops(p.world, new BlockPos((int) p.posX, (int) p.posY, (int) p.posZ), drops); + } + } - IItemHandler getPattern() - { - return this.pattern; - } + IItemHandler getPattern() { + return this.pattern; + } } diff --git a/src/main/java/appeng/container/slot/SlotDisabled.java b/src/main/java/appeng/container/slot/SlotDisabled.java index c57c086f6..7cac2ed5e 100644 --- a/src/main/java/appeng/container/slot/SlotDisabled.java +++ b/src/main/java/appeng/container/slot/SlotDisabled.java @@ -24,23 +24,19 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; -public class SlotDisabled extends AppEngSlot -{ +public class SlotDisabled extends AppEngSlot { - public SlotDisabled( final IItemHandler par1iInventory, final int slotIndex, final int x, final int y ) - { - super( par1iInventory, slotIndex, x, y ); - } + public SlotDisabled(final IItemHandler par1iInventory, final int slotIndex, final int x, final int y) { + super(par1iInventory, slotIndex, x, y); + } - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } } diff --git a/src/main/java/appeng/container/slot/SlotFake.java b/src/main/java/appeng/container/slot/SlotFake.java index 96b0a2212..5f15bb472 100644 --- a/src/main/java/appeng/container/slot/SlotFake.java +++ b/src/main/java/appeng/container/slot/SlotFake.java @@ -24,46 +24,38 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; -public class SlotFake extends AppEngSlot implements IJEITargetSlot -{ +public class SlotFake extends AppEngSlot implements IJEITargetSlot { - public SlotFake( final IItemHandler inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - } + public SlotFake(final IItemHandler inv, final int idx, final int x, final int y) { + super(inv, idx, x, y); + } - @Override - public ItemStack onTake( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) - { - return par2ItemStack; - } + @Override + public ItemStack onTake(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) { + return par2ItemStack; + } - @Override - public ItemStack decrStackSize( final int par1 ) - { - return ItemStack.EMPTY; - } + @Override + public ItemStack decrStackSize(final int par1) { + return ItemStack.EMPTY; + } - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - @Override - public void putStack( ItemStack is ) - { - if( !is.isEmpty() ) - { - is = is.copy(); - } + @Override + public void putStack(ItemStack is) { + if (!is.isEmpty()) { + is = is.copy(); + } - super.putStack( is ); - } + super.putStack(is); + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } } diff --git a/src/main/java/appeng/container/slot/SlotFakeBlacklist.java b/src/main/java/appeng/container/slot/SlotFakeBlacklist.java index e13318a47..347cc2c44 100644 --- a/src/main/java/appeng/container/slot/SlotFakeBlacklist.java +++ b/src/main/java/appeng/container/slot/SlotFakeBlacklist.java @@ -22,33 +22,27 @@ package appeng.container.slot; import net.minecraftforge.items.IItemHandler; -public class SlotFakeBlacklist extends SlotFakeTypeOnly -{ +public class SlotFakeBlacklist extends SlotFakeTypeOnly { - public SlotFakeBlacklist( final IItemHandler inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - } + public SlotFakeBlacklist(final IItemHandler inv, final int idx, final int x, final int y) { + super(inv, idx, x, y); + } - @Override - public float getOpacityOfIcon() - { - return 0.8f; - } + @Override + public float getOpacityOfIcon() { + return 0.8f; + } - @Override - public boolean renderIconWithItem() - { - return true; - } + @Override + public boolean renderIconWithItem() { + return true; + } - @Override - public int getIcon() - { - if( this.getHasStack() ) - { - return this.getStack().getCount() > 0 ? 16 + 14 : 14; - } - return -1; - } + @Override + public int getIcon() { + if (this.getHasStack()) { + return this.getStack().getCount() > 0 ? 16 + 14 : 14; + } + return -1; + } } diff --git a/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java b/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java index f92cd4a99..2418e1f42 100644 --- a/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java +++ b/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java @@ -22,11 +22,9 @@ package appeng.container.slot; import net.minecraftforge.items.IItemHandler; -public class SlotFakeCraftingMatrix extends SlotFake -{ +public class SlotFakeCraftingMatrix extends SlotFake { - public SlotFakeCraftingMatrix( final IItemHandler inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - } + public SlotFakeCraftingMatrix(final IItemHandler inv, final int idx, final int x, final int y) { + super(inv, idx, x, y); + } } diff --git a/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java b/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java index d93c0a183..974fef89e 100644 --- a/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java +++ b/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java @@ -23,30 +23,23 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; -public class SlotFakeTypeOnly extends SlotFake -{ +public class SlotFakeTypeOnly extends SlotFake { - public SlotFakeTypeOnly( final IItemHandler inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - } + public SlotFakeTypeOnly(final IItemHandler inv, final int idx, final int x, final int y) { + super(inv, idx, x, y); + } - @Override - public void putStack( ItemStack is ) - { - if( !is.isEmpty() ) - { - is = is.copy(); - if( is.getCount() > 1 ) - { - is.setCount( 1 ); - } - else if( is.getCount() < -1 ) - { - is.setCount( -1 ); - } - } + @Override + public void putStack(ItemStack is) { + if (!is.isEmpty()) { + is = is.copy(); + if (is.getCount() > 1) { + is.setCount(1); + } else if (is.getCount() < -1) { + is.setCount(-1); + } + } - super.putStack( is ); - } + super.putStack(is); + } } diff --git a/src/main/java/appeng/container/slot/SlotInaccessible.java b/src/main/java/appeng/container/slot/SlotInaccessible.java index e509f8ee2..88c8ab7b6 100644 --- a/src/main/java/appeng/container/slot/SlotInaccessible.java +++ b/src/main/java/appeng/container/slot/SlotInaccessible.java @@ -24,46 +24,38 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; -public class SlotInaccessible extends AppEngSlot -{ +public class SlotInaccessible extends AppEngSlot { - private ItemStack dspStack = ItemStack.EMPTY; + private ItemStack dspStack = ItemStack.EMPTY; - public SlotInaccessible( final IItemHandler i, final int slotIdx, final int x, final int y ) - { - super( i, slotIdx, x, y ); - } + public SlotInaccessible(final IItemHandler i, final int slotIdx, final int x, final int y) { + super(i, slotIdx, x, y); + } - @Override - public boolean isItemValid( final ItemStack i ) - { - return false; - } + @Override + public boolean isItemValid(final ItemStack i) { + return false; + } - @Override - public void onSlotChanged() - { - super.onSlotChanged(); - this.dspStack = ItemStack.EMPTY; - } + @Override + public void onSlotChanged() { + super.onSlotChanged(); + this.dspStack = ItemStack.EMPTY; + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } - @Override - public ItemStack getDisplayStack() - { - if( this.dspStack.isEmpty() ) - { - final ItemStack dsp = super.getDisplayStack(); - if( !dsp.isEmpty() ) - { - this.dspStack = dsp.copy(); - } - } - return this.dspStack; - } + @Override + public ItemStack getDisplayStack() { + if (this.dspStack.isEmpty()) { + final ItemStack dsp = super.getDisplayStack(); + if (!dsp.isEmpty()) { + this.dspStack = dsp.copy(); + } + } + return this.dspStack; + } } diff --git a/src/main/java/appeng/container/slot/SlotInaccessibleHD.java b/src/main/java/appeng/container/slot/SlotInaccessibleHD.java index b95a62e7c..b35645e0e 100644 --- a/src/main/java/appeng/container/slot/SlotInaccessibleHD.java +++ b/src/main/java/appeng/container/slot/SlotInaccessibleHD.java @@ -22,11 +22,9 @@ package appeng.container.slot; import net.minecraftforge.items.IItemHandler; -public class SlotInaccessibleHD extends SlotInaccessible -{ +public class SlotInaccessibleHD extends SlotInaccessible { - public SlotInaccessibleHD( final IItemHandler i, final int slotIdx, final int x, final int y ) - { - super( i, slotIdx, x, y ); - } + public SlotInaccessibleHD(final IItemHandler i, final int slotIdx, final int x, final int y) { + super(i, slotIdx, x, y); + } } diff --git a/src/main/java/appeng/container/slot/SlotMACPattern.java b/src/main/java/appeng/container/slot/SlotMACPattern.java index c7e05542d..2630edab2 100644 --- a/src/main/java/appeng/container/slot/SlotMACPattern.java +++ b/src/main/java/appeng/container/slot/SlotMACPattern.java @@ -19,26 +19,22 @@ package appeng.container.slot; +import appeng.container.implementations.ContainerMAC; import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; -import appeng.container.implementations.ContainerMAC; +public class SlotMACPattern extends AppEngSlot { -public class SlotMACPattern extends AppEngSlot -{ + private final ContainerMAC mac; - private final ContainerMAC mac; + public SlotMACPattern(final ContainerMAC mac, final IItemHandler i, final int slotIdx, final int x, final int y) { + super(i, slotIdx, x, y); + this.mac = mac; + } - public SlotMACPattern( final ContainerMAC mac, final IItemHandler i, final int slotIdx, final int x, final int y ) - { - super( i, slotIdx, x, y ); - this.mac = mac; - } - - @Override - public boolean isItemValid( final ItemStack i ) - { - return this.mac.isValidItemForSlot( this.getSlotIndex(), i ); - } + @Override + public boolean isItemValid(final ItemStack i) { + return this.mac.isValidItemForSlot(this.getSlotIndex(), i); + } } diff --git a/src/main/java/appeng/container/slot/SlotNormal.java b/src/main/java/appeng/container/slot/SlotNormal.java index 3e2a509ea..8ba9d3733 100644 --- a/src/main/java/appeng/container/slot/SlotNormal.java +++ b/src/main/java/appeng/container/slot/SlotNormal.java @@ -22,11 +22,9 @@ package appeng.container.slot; import net.minecraftforge.items.IItemHandler; -public class SlotNormal extends AppEngSlot -{ +public class SlotNormal extends AppEngSlot { - public SlotNormal( final IItemHandler inv, final int slot, final int xPos, final int yPos ) - { - super( inv, slot, xPos, yPos ); - } + public SlotNormal(final IItemHandler inv, final int slot, final int xPos, final int yPos) { + super(inv, slot, xPos, yPos); + } } diff --git a/src/main/java/appeng/container/slot/SlotOutput.java b/src/main/java/appeng/container/slot/SlotOutput.java index 687483e5b..395c2c4fa 100644 --- a/src/main/java/appeng/container/slot/SlotOutput.java +++ b/src/main/java/appeng/container/slot/SlotOutput.java @@ -23,18 +23,15 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; -public class SlotOutput extends AppEngSlot -{ +public class SlotOutput extends AppEngSlot { - public SlotOutput( final IItemHandler a, final int b, final int c, final int d, final int i ) - { - super( a, b, c, d ); - this.setIIcon( i ); - } + public SlotOutput(final IItemHandler a, final int b, final int c, final int d, final int i) { + super(a, b, c, d); + this.setIIcon(i); + } - @Override - public boolean isItemValid( final ItemStack i ) - { - return false; - } + @Override + public boolean isItemValid(final ItemStack i) { + return false; + } } diff --git a/src/main/java/appeng/container/slot/SlotPatternOutputs.java b/src/main/java/appeng/container/slot/SlotPatternOutputs.java index 70b873d03..82f840702 100644 --- a/src/main/java/appeng/container/slot/SlotPatternOutputs.java +++ b/src/main/java/appeng/container/slot/SlotPatternOutputs.java @@ -22,23 +22,19 @@ package appeng.container.slot; import net.minecraftforge.items.IItemHandler; -public class SlotPatternOutputs extends OptionalSlotFake -{ +public class SlotPatternOutputs extends OptionalSlotFake { - public SlotPatternOutputs( final IItemHandler inv, final IOptionalSlotHost containerBus, final int idx, final int x, final int y, final int offX, final int offY, final int groupNum ) - { - super( inv, containerBus, idx, x, y, offX, offY, groupNum ); - } + public SlotPatternOutputs(final IItemHandler inv, final IOptionalSlotHost containerBus, final int idx, final int x, final int y, final int offX, final int offY, final int groupNum) { + super(inv, containerBus, idx, x, y, offX, offY, groupNum); + } - @Override - public boolean isSlotEnabled() - { - return true; - } + @Override + public boolean isSlotEnabled() { + return true; + } - @Override - public boolean shouldDisplay() - { - return super.isSlotEnabled(); - } + @Override + public boolean shouldDisplay() { + return super.isSlotEnabled(); + } } diff --git a/src/main/java/appeng/container/slot/SlotPatternTerm.java b/src/main/java/appeng/container/slot/SlotPatternTerm.java index bdd6b60da..5fdc42a33 100644 --- a/src/main/java/appeng/container/slot/SlotPatternTerm.java +++ b/src/main/java/appeng/container/slot/SlotPatternTerm.java @@ -19,12 +19,6 @@ package appeng.container.slot; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.networking.energy.IEnergySource; import appeng.api.networking.security.IActionSource; @@ -33,50 +27,47 @@ import appeng.api.storage.channels.IItemStorageChannel; import appeng.core.sync.AppEngPacket; import appeng.core.sync.packets.PacketPatternSlot; import appeng.helpers.IContainerCraftingPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraftforge.items.IItemHandler; + +import java.io.IOException; -public class SlotPatternTerm extends SlotCraftingTerm -{ +public class SlotPatternTerm extends SlotCraftingTerm { - private final int groupNum; - private final IOptionalSlotHost host; + private final int groupNum; + private final IOptionalSlotHost host; - public SlotPatternTerm( final EntityPlayer player, final IActionSource mySrc, final IEnergySource energySrc, final IStorageMonitorable storage, final IItemHandler cMatrix, final IItemHandler secondMatrix, final IItemHandler output, final int x, final int y, final IOptionalSlotHost h, final int groupNumber, final IContainerCraftingPacket c ) - { - super( player, mySrc, energySrc, storage, cMatrix, secondMatrix, output, x, y, c ); + public SlotPatternTerm(final EntityPlayer player, final IActionSource mySrc, final IEnergySource energySrc, final IStorageMonitorable storage, final IItemHandler cMatrix, final IItemHandler secondMatrix, final IItemHandler output, final int x, final int y, final IOptionalSlotHost h, final int groupNumber, final IContainerCraftingPacket c) { + super(player, mySrc, energySrc, storage, cMatrix, secondMatrix, output, x, y, c); - this.host = h; - this.groupNum = groupNumber; - } + this.host = h; + this.groupNum = groupNumber; + } - public AppEngPacket getRequest( final boolean shift ) throws IOException - { - return new PacketPatternSlot( this - .getPattern(), AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( this.getStack() ), shift ); - } + public AppEngPacket getRequest(final boolean shift) throws IOException { + return new PacketPatternSlot(this + .getPattern(), AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(this.getStack()), shift); + } - @Override - public ItemStack getStack() - { - if( !this.isSlotEnabled() ) - { - if( !this.getDisplayStack().isEmpty() ) - { - this.clearStack(); - } - } + @Override + public ItemStack getStack() { + if (!this.isSlotEnabled()) { + if (!this.getDisplayStack().isEmpty()) { + this.clearStack(); + } + } - return super.getStack(); - } + return super.getStack(); + } - @Override - public boolean isSlotEnabled() - { - if( this.host == null ) - { - return false; - } + @Override + public boolean isSlotEnabled() { + if (this.host == null) { + return false; + } - return this.host.isSlotEnabled( this.groupNum ); - } + return this.host.isSlotEnabled(this.groupNum); + } } diff --git a/src/main/java/appeng/container/slot/SlotPlayerHotBar.java b/src/main/java/appeng/container/slot/SlotPlayerHotBar.java index 2d81df4ff..7f3f0b8db 100644 --- a/src/main/java/appeng/container/slot/SlotPlayerHotBar.java +++ b/src/main/java/appeng/container/slot/SlotPlayerHotBar.java @@ -22,12 +22,10 @@ package appeng.container.slot; import net.minecraftforge.items.IItemHandler; -public class SlotPlayerHotBar extends AppEngSlot -{ +public class SlotPlayerHotBar extends AppEngSlot { - public SlotPlayerHotBar( final IItemHandler par1iInventory, final int par2, final int par3, final int par4 ) - { - super( par1iInventory, par2, par3, par4 ); - this.setPlayerSide( true ); - } + public SlotPlayerHotBar(final IItemHandler par1iInventory, final int par2, final int par3, final int par4) { + super(par1iInventory, par2, par3, par4); + this.setPlayerSide(true); + } } diff --git a/src/main/java/appeng/container/slot/SlotPlayerInv.java b/src/main/java/appeng/container/slot/SlotPlayerInv.java index 721c78976..b27c39334 100644 --- a/src/main/java/appeng/container/slot/SlotPlayerInv.java +++ b/src/main/java/appeng/container/slot/SlotPlayerInv.java @@ -24,13 +24,11 @@ import net.minecraftforge.items.IItemHandler; // there is nothing special about this slot, its simply used to represent the players inventory, vs a container slot. -public class SlotPlayerInv extends AppEngSlot -{ +public class SlotPlayerInv extends AppEngSlot { - public SlotPlayerInv( final IItemHandler par1iInventory, final int par2, final int par3, final int par4 ) - { - super( par1iInventory, par2, par3, par4 ); + public SlotPlayerInv(final IItemHandler par1iInventory, final int par2, final int par3, final int par4) { + super(par1iInventory, par2, par3, par4); - this.setPlayerSide( true ); - } + this.setPlayerSide(true); + } } diff --git a/src/main/java/appeng/container/slot/SlotRestrictedInput.java b/src/main/java/appeng/container/slot/SlotRestrictedInput.java index 420552dd2..8b0350d85 100644 --- a/src/main/java/appeng/container/slot/SlotRestrictedInput.java +++ b/src/main/java/appeng/container/slot/SlotRestrictedInput.java @@ -19,16 +19,6 @@ package appeng.container.slot; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.init.Items; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntityFurnace; -import net.minecraft.world.World; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.oredict.OreDictionary; - import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.definitions.IItems; @@ -43,6 +33,15 @@ import appeng.api.networking.crafting.ICraftingPatternDetails; import appeng.api.storage.ICellWorkbenchItem; import appeng.items.misc.ItemEncodedPattern; import appeng.util.Platform; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.init.Items; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntityFurnace; +import net.minecraft.world.World; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.oredict.OreDictionary; /** @@ -51,280 +50,241 @@ import appeng.util.Platform; * @version rv2 * @since rv0 */ -public class SlotRestrictedInput extends AppEngSlot -{ +public class SlotRestrictedInput extends AppEngSlot { - private final PlacableItemType which; - private final InventoryPlayer p; - private boolean allowEdit = true; - private int stackLimit = -1; + private final PlacableItemType which; + private final InventoryPlayer p; + private boolean allowEdit = true; + private int stackLimit = -1; - public SlotRestrictedInput( final PlacableItemType valid, final IItemHandler i, final int slotIndex, final int x, final int y, final InventoryPlayer p ) - { - super( i, slotIndex, x, y ); - this.which = valid; - this.setIIcon( valid.IIcon ); - this.p = p; - } + public SlotRestrictedInput(final PlacableItemType valid, final IItemHandler i, final int slotIndex, final int x, final int y, final InventoryPlayer p) { + super(i, slotIndex, x, y); + this.which = valid; + this.setIIcon(valid.IIcon); + this.p = p; + } - @Override - public int getSlotStackLimit() - { - if( this.stackLimit != -1 ) - { - return this.stackLimit; - } - return super.getSlotStackLimit(); - } + @Override + public int getSlotStackLimit() { + if (this.stackLimit != -1) { + return this.stackLimit; + } + return super.getSlotStackLimit(); + } - public boolean isValid( final ItemStack is, final World theWorld ) - { - if( this.which == PlacableItemType.VALID_ENCODED_PATTERN_W_OUTPUT ) - { - final ICraftingPatternDetails ap = is.getItem() instanceof ICraftingPatternItem ? ( (ICraftingPatternItem) is.getItem() ).getPatternForItem( is, - theWorld ) : null; - return ap != null; - } - return true; - } + public boolean isValid(final ItemStack is, final World theWorld) { + if (this.which == PlacableItemType.VALID_ENCODED_PATTERN_W_OUTPUT) { + final ICraftingPatternDetails ap = is.getItem() instanceof ICraftingPatternItem ? ((ICraftingPatternItem) is.getItem()).getPatternForItem(is, + theWorld) : null; + return ap != null; + } + return true; + } - public Slot setStackLimit( final int i ) - { - this.stackLimit = i; - return this; - } + public Slot setStackLimit(final int i) { + this.stackLimit = i; + return this; + } - @Override - public boolean isItemValid( final ItemStack i ) - { - if( !this.getContainer().isValidForSlot( this, i ) ) - { - return false; - } + @Override + public boolean isItemValid(final ItemStack i) { + if (!this.getContainer().isValidForSlot(this, i)) { + return false; + } - if( i.isEmpty() ) - { - return false; - } + if (i.isEmpty()) { + return false; + } - if( i.getItem() == Items.AIR ) - { - return false; - } + if (i.getItem() == Items.AIR) { + return false; + } - if( !super.isItemValid( i ) ) - { - return false; - } + if (!super.isItemValid(i)) { + return false; + } - if( !this.isAllowEdit() ) - { - return false; - } + if (!this.isAllowEdit()) { + return false; + } - final IDefinitions definitions = AEApi.instance().definitions(); - final IMaterials materials = definitions.materials(); - final IItems items = definitions.items(); + final IDefinitions definitions = AEApi.instance().definitions(); + final IMaterials materials = definitions.materials(); + final IItems items = definitions.items(); - switch( this.which ) - { - case ENCODED_CRAFTING_PATTERN: - if( i.getItem() instanceof ICraftingPatternItem ) - { - final ICraftingPatternItem b = (ICraftingPatternItem) i.getItem(); - final ICraftingPatternDetails de = b.getPatternForItem( i, this.p.player.world ); - if( de != null ) - { - return de.isCraftable(); - } - } - return false; - case VALID_ENCODED_PATTERN_W_OUTPUT: - case ENCODED_PATTERN_W_OUTPUT: - case ENCODED_PATTERN: - { - if( i.getItem() instanceof ICraftingPatternItem ) - { - return true; - } - // ICraftingPatternDetails pattern = i.getItem() instanceof ICraftingPatternItem ? - // ((ICraftingPatternItem) - // i.getItem()).getPatternForItem( i ) : null; - return false;// pattern != null; - } - case BLANK_PATTERN: - return materials.blankPattern().isSameAs( i ); + switch (this.which) { + case ENCODED_CRAFTING_PATTERN: + if (i.getItem() instanceof ICraftingPatternItem) { + final ICraftingPatternItem b = (ICraftingPatternItem) i.getItem(); + final ICraftingPatternDetails de = b.getPatternForItem(i, this.p.player.world); + if (de != null) { + return de.isCraftable(); + } + } + return false; + case VALID_ENCODED_PATTERN_W_OUTPUT: + case ENCODED_PATTERN_W_OUTPUT: + case ENCODED_PATTERN: { + return i.getItem() instanceof ICraftingPatternItem; + // ICraftingPatternDetails pattern = i.getItem() instanceof ICraftingPatternItem ? + // ((ICraftingPatternItem) + // i.getItem()).getPatternForItem( i ) : null; +// pattern != null; + } + case BLANK_PATTERN: + return materials.blankPattern().isSameAs(i); - case PATTERN: + case PATTERN: - if( i.getItem() instanceof ICraftingPatternItem ) - { - return true; - } + if (i.getItem() instanceof ICraftingPatternItem) { + return true; + } - return materials.blankPattern().isSameAs( i ); + return materials.blankPattern().isSameAs(i); - case INSCRIBER_PLATE: - if( materials.namePress().isSameAs( i ) ) - { - return true; - } + case INSCRIBER_PLATE: + if (materials.namePress().isSameAs(i)) { + return true; + } - for( final ItemStack optional : AEApi.instance().registries().inscriber().getOptionals() ) - { - if( Platform.itemComparisons().isSameItem( i, optional ) ) - { - return true; - } - } + for (final ItemStack optional : AEApi.instance().registries().inscriber().getOptionals()) { + if (Platform.itemComparisons().isSameItem(i, optional)) { + return true; + } + } - return false; + return false; - case INSCRIBER_INPUT: - return true;/* - * for (ItemStack is : Inscribe.inputs) if ( Platform.isSameItemPrecise( is, i ) ) return - * true; - * return false; - */ + case INSCRIBER_INPUT: + return true;/* + * for (ItemStack is : Inscribe.inputs) if ( Platform.isSameItemPrecise( is, i ) ) return + * true; + * return false; + */ - case METAL_INGOTS: + case METAL_INGOTS: - return isMetalIngot( i ); + return isMetalIngot(i); - case VIEW_CELL: - return items.viewCell().isSameAs( i ); - case ORE: - return appeng.api.AEApi.instance().registries().grinder().getRecipeForInput( i ) != null; - case FUEL: - return TileEntityFurnace.getItemBurnTime( i ) > 0; - case POWERED_TOOL: - return Platform.isChargeable( i ); - case QE_SINGULARITY: - return materials.qESingularity().isSameAs( i ); + case VIEW_CELL: + return items.viewCell().isSameAs(i); + case ORE: + return appeng.api.AEApi.instance().registries().grinder().getRecipeForInput(i) != null; + case FUEL: + return TileEntityFurnace.getItemBurnTime(i) > 0; + case POWERED_TOOL: + return Platform.isChargeable(i); + case QE_SINGULARITY: + return materials.qESingularity().isSameAs(i); - case RANGE_BOOSTER: - return materials.wirelessBooster().isSameAs( i ); + case RANGE_BOOSTER: + return materials.wirelessBooster().isSameAs(i); - case SPATIAL_STORAGE_CELLS: - return i.getItem() instanceof ISpatialStorageCell && ( (ISpatialStorageCell) i.getItem() ).isSpatialStorage( i ); - case STORAGE_CELLS: - return AEApi.instance().registries().cell().isCellHandled( i ); - case WORKBENCH_CELL: - return i.getItem() instanceof ICellWorkbenchItem && ( (ICellWorkbenchItem) i.getItem() ).isEditable( i ); - case STORAGE_COMPONENT: - return i.getItem() instanceof IStorageComponent && ( (IStorageComponent) i.getItem() ).isStorageComponent( i ); - case TRASH: - if( AEApi.instance().registries().cell().isCellHandled( i ) ) - { - return false; - } + case SPATIAL_STORAGE_CELLS: + return i.getItem() instanceof ISpatialStorageCell && ((ISpatialStorageCell) i.getItem()).isSpatialStorage(i); + case STORAGE_CELLS: + return AEApi.instance().registries().cell().isCellHandled(i); + case WORKBENCH_CELL: + return i.getItem() instanceof ICellWorkbenchItem && ((ICellWorkbenchItem) i.getItem()).isEditable(i); + case STORAGE_COMPONENT: + return i.getItem() instanceof IStorageComponent && ((IStorageComponent) i.getItem()).isStorageComponent(i); + case TRASH: + if (AEApi.instance().registries().cell().isCellHandled(i)) { + return false; + } - return !( i.getItem() instanceof IStorageComponent && ( (IStorageComponent) i.getItem() ).isStorageComponent( i ) ); - case ENCODABLE_ITEM: - return i.getItem() instanceof INetworkEncodable || AEApi.instance().registries().wireless().isWirelessTerminal( i ); - case BIOMETRIC_CARD: - return i.getItem() instanceof IBiometricCard; - case UPGRADES: - return i.getItem() instanceof IUpgradeModule && ( (IUpgradeModule) i.getItem() ).getType( i ) != null; - default: - break; - } + return !(i.getItem() instanceof IStorageComponent && ((IStorageComponent) i.getItem()).isStorageComponent(i)); + case ENCODABLE_ITEM: + return i.getItem() instanceof INetworkEncodable || AEApi.instance().registries().wireless().isWirelessTerminal(i); + case BIOMETRIC_CARD: + return i.getItem() instanceof IBiometricCard; + case UPGRADES: + return i.getItem() instanceof IUpgradeModule && ((IUpgradeModule) i.getItem()).getType(i) != null; + default: + break; + } - return false; - } + return false; + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return this.isAllowEdit(); - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return this.isAllowEdit(); + } - @Override - public ItemStack getDisplayStack() - { - if( Platform.isClient() && ( this.which == PlacableItemType.ENCODED_PATTERN ) ) - { - final ItemStack is = super.getStack(); - if( !is.isEmpty() && is.getItem() instanceof ItemEncodedPattern ) - { - final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - final ItemStack out = iep.getOutput( is ); - if( !out.isEmpty() ) - { - return out; - } - } - } - return super.getStack(); - } + @Override + public ItemStack getDisplayStack() { + if (Platform.isClient() && (this.which == PlacableItemType.ENCODED_PATTERN)) { + final ItemStack is = super.getStack(); + if (!is.isEmpty() && is.getItem() instanceof ItemEncodedPattern) { + final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + final ItemStack out = iep.getOutput(is); + if (!out.isEmpty()) { + return out; + } + } + } + return super.getStack(); + } - public static boolean isMetalIngot( final ItemStack i ) - { - if( Platform.itemComparisons().isSameItem( i, new ItemStack( Items.IRON_INGOT ) ) ) - { - return true; - } + public static boolean isMetalIngot(final ItemStack i) { + if (Platform.itemComparisons().isSameItem(i, new ItemStack(Items.IRON_INGOT))) { + return true; + } - for( final String name : new String[] { "Copper", "Tin", "Obsidian", "Iron", "Lead", "Bronze", "Brass", "Nickel", "Aluminium" } ) - { - for( final ItemStack ingot : OreDictionary.getOres( "ingot" + name ) ) - { - if( Platform.itemComparisons().isSameItem( i, ingot ) ) - { - return true; - } - } - } + for (final String name : new String[]{"Copper", "Tin", "Obsidian", "Iron", "Lead", "Bronze", "Brass", "Nickel", "Aluminium"}) { + for (final ItemStack ingot : OreDictionary.getOres("ingot" + name)) { + if (Platform.itemComparisons().isSameItem(i, ingot)) { + return true; + } + } + } - return false; - } + return false; + } - private boolean isAllowEdit() - { - return this.allowEdit; - } + private boolean isAllowEdit() { + return this.allowEdit; + } - public void setAllowEdit( final boolean allowEdit ) - { - this.allowEdit = allowEdit; - } + public void setAllowEdit(final boolean allowEdit) { + this.allowEdit = allowEdit; + } - public enum PlacableItemType - { - STORAGE_CELLS( 15 ), - ORE( 16 + 15 ), - STORAGE_COMPONENT( 3 * 16 + 15 ), + public enum PlacableItemType { + STORAGE_CELLS(15), + ORE(16 + 15), + STORAGE_COMPONENT(3 * 16 + 15), - ENCODABLE_ITEM( 4 * 16 + 15 ), - TRASH( 5 * 16 + 15 ), - VALID_ENCODED_PATTERN_W_OUTPUT( 7 * 16 + 15 ), - ENCODED_PATTERN_W_OUTPUT( 7 * 16 + 15 ), + ENCODABLE_ITEM(4 * 16 + 15), + TRASH(5 * 16 + 15), + VALID_ENCODED_PATTERN_W_OUTPUT(7 * 16 + 15), + ENCODED_PATTERN_W_OUTPUT(7 * 16 + 15), - ENCODED_CRAFTING_PATTERN( 7 * 16 + 15 ), - ENCODED_PATTERN( 7 * 16 + 15 ), - PATTERN( 8 * 16 + 15 ), - BLANK_PATTERN( 8 * 16 + 15 ), - POWERED_TOOL( 9 * 16 + 15 ), + ENCODED_CRAFTING_PATTERN(7 * 16 + 15), + ENCODED_PATTERN(7 * 16 + 15), + PATTERN(8 * 16 + 15), + BLANK_PATTERN(8 * 16 + 15), + POWERED_TOOL(9 * 16 + 15), - RANGE_BOOSTER( 6 * 16 + 15 ), - QE_SINGULARITY( 10 * 16 + 15 ), - SPATIAL_STORAGE_CELLS( 11 * 16 + 15 ), + RANGE_BOOSTER(6 * 16 + 15), + QE_SINGULARITY(10 * 16 + 15), + SPATIAL_STORAGE_CELLS(11 * 16 + 15), - FUEL( 12 * 16 + 15 ), - UPGRADES( 13 * 16 + 15 ), - WORKBENCH_CELL( 15 ), - BIOMETRIC_CARD( 14 * 16 + 15 ), - VIEW_CELL( 4 * 16 + 14 ), + FUEL(12 * 16 + 15), + UPGRADES(13 * 16 + 15), + WORKBENCH_CELL(15), + BIOMETRIC_CARD(14 * 16 + 15), + VIEW_CELL(4 * 16 + 14), - INSCRIBER_PLATE( 2 * 16 + 14 ), - INSCRIBER_INPUT( 3 * 16 + 14 ), - METAL_INGOTS( 3 * 16 + 14 ); + INSCRIBER_PLATE(2 * 16 + 14), + INSCRIBER_INPUT(3 * 16 + 14), + METAL_INGOTS(3 * 16 + 14); - public final int IIcon; + public final int IIcon; - PlacableItemType( final int o ) - { - this.IIcon = o; - } - } + PlacableItemType(final int o) { + this.IIcon = o; + } + } } diff --git a/src/main/java/appeng/core/AEConfig.java b/src/main/java/appeng/core/AEConfig.java index 44cd93a3b..b7d0ae309 100644 --- a/src/main/java/appeng/core/AEConfig.java +++ b/src/main/java/appeng/core/AEConfig.java @@ -41,741 +41,633 @@ import java.util.*; import java.util.stream.Stream; -public final class AEConfig extends Configuration implements IConfigurableObject, IConfigManagerHost -{ - - public static final String VERSION = "@version@"; - public static final String CHANNEL = "@aechannel@"; - public static final String PACKET_CHANNEL = "AE"; - // Tunnels - public static final double TUNNEL_POWER_LOSS = 0.05; - // Default Grindstone ores - private static final String[] ORES_VANILLA = {"Obsidian", "Ender", "EnderPearl", "Coal", "Iron", "Gold", "Charcoal", "NetherQuartz"}; - private static final String[] ORES_AE = {"CertusQuartz", "Wheat", "Fluix"}; - private static final String[] ORES_COMMON = {"Copper", "Tin", "Silver", "Lead", "Bronze"}; - private static final String[] ORES_MISC = {"Brass", "Platinum", "Nickel", "Invar", "Aluminium", "Electrum", "Osmium", "Zinc"}; - // Default Energy Conversion Rates - private static final double DEFAULT_IC2_EXCHANGE = 2.0; - private static final double DEFAULT_GTEU_EXCHANGE = 2.0; - private static final double DEFAULT_RF_EXCHANGE = 0.5; - // Config instance - private static AEConfig instance; - private final IConfigManager settings = new ConfigManager( this ); - - private final EnumSet featureFlags = EnumSet.noneOf( AEFeature.class ); - private final File configFile; - // GUI Buttons - private final int[] craftByStacks = {1, 10, 100, 1000}; - private final int[] priorityByStacks = {1, 10, 100, 1000}; - private final int[] levelByStacks = {1, 10, 100, 1000}; - private final int[] levelByMillibuckets = {10, 100, 1000, 10000}; - private final Set grinderBlackList; - private final int chargedChange = 4; - private final double wirelessHighWirelessCount = 64; - private String[] nonBlockingItems = {"[gregtech|actuallyadditions]", "gregtech:circuit.integrated", "gregtech:shape.mold.plate", "gregtech:shape.mold.gear", "gregtech:shape.mold.credit", "gregtech:shape.mold.bottle", "gregtech:shape.mold.ingot", "gregtech:shape.mold.ball", "gregtech:shape.mold.block", "gregtech:shape.mold.nugget", "gregtech:shape.mold.cylinder", "gregtech:shape.mold.anvil", "gregtech:shape.mold.name", "gregtech:shape.mold.gear.small", "gregtech:shape.mold.rotor", "gregtech:shape.extruder.plate", "gregtech:shape.extruder.rod", "gregtech:shape.extruder.bolt", "gregtech:shape.extruder.ring", "gregtech:shape.extruder.cell", "gregtech:shape.extruder.ingot", "gregtech:shape.extruder.wire", "gregtech:shape.extruder.pipe.tiny", "gregtech:shape.extruder.pipe.small", "gregtech:shape.extruder.pipe.medium", "gregtech:shape.extruder.pipe.normal", "gregtech:shape.extruder.pipe.large", "gregtech:shape.extruder.pipe.huge", "gregtech:shape.extruder.block", "gregtech:shape.extruder.sword", "gregtech:shape.extruder.pickaxe", "gregtech:shape.extruder.shovel", "gregtech:shape.extruder.axe", "gregtech:shape.extruder.hoe", "gregtech:shape.extruder.hammer", "gregtech:shape.extruder.file", "gregtech:shape.extruder.saw", "gregtech:shape.extruder.gear", "gregtech:shape.extruder.bottle", "gregtech:shape.extruder.foil", "gregtech:shape.extruder.gear_small", "gregtech:shape.extruder.rod_long", "gregtech:shape.extruder.rotor", "gregtech:glass_lens.white", "gregtech:glass_lens.orange", "gregtech:glass_lens.magenta", "gregtech:glass_lens.light_blue", "gregtech:glass_lens.yellow", "gregtech:glass_lens.lime", "gregtech:glass_lens.pink", "gregtech:glass_lens.gray", "gregtech:glass_lens.light_gray", "gregtech:glass_lens.cyan", "gregtech:glass_lens.purple", "gregtech:glass_lens.blue", "gregtech:glass_lens.brown", "gregtech:glass_lens.green", "gregtech:glass_lens.red", "gregtech:glass_lens.black", "contenttweaker:smallgearextrudershape", "contenttweaker:creativeportabletankmold", "ore:lensAlmandine", "ore:lensBlueTopaz", "ore:lensDiamond", "ore:lensEmerald", "ore:lensGreenSapphire", "ore:lensRutile", "ore:lensRuby", "ore:lensSapphire", "ore:lensTopaz", "ore:lensJasper", "ore:lensGlass", "ore:lensOlivine", "ore:lensOpal", "ore:lensAmethyst", "ore:lensLapis", "ore:lensEnderPearl", "ore:lensEnderEye", "ore:lensGarnetRed", "ore:lensGarnetYellow", "ore:lensVinteum", "ore:lensNetherStar",}; - private boolean updatable = false; - // Misc - private boolean removeCrashingItemsOnLoad = false; - private int formationPlaneEntityLimit = 128; - private boolean enableEffects = true; - private boolean useLargeFonts = false; - private boolean useColoredCraftingStatus; - private boolean disableColoredCableRecipesInJEI = true; - private int craftingCalculationTimePerTick = 5; - private PowerUnits selectedPowerUnit = PowerUnits.AE; - // Spatial IO/Dimension - private int storageProviderID = -1; - private int storageDimensionID = -1; - private double spatialPowerExponent = 1.35; - private double spatialPowerMultiplier = 1250.0; - // Grindstone - private String[] grinderOres = Stream.of( ORES_VANILLA, ORES_AE, ORES_COMMON, ORES_MISC ).flatMap( Stream::of ).toArray( String[]::new ); - private double oreDoublePercentage = 90.0; - // Batteries - private int wirelessTerminalBattery = 1600000; - private int entropyManipulatorBattery = 200000; - private int matterCannonBattery = 200000; - private int portableCellBattery = 20000; - private int colorApplicatorBattery = 20000; - private int chargedStaffBattery = 8000; - // Certus quartz - private float spawnChargedChance = 0.92f; - private int quartzOresPerCluster = 4; - private int quartzOresClusterAmount = 15; - // Meteors - private int minMeteoriteDistance = 707; - private int minMeteoriteDistanceSq = this.minMeteoriteDistance * this.minMeteoriteDistance; - private double meteoriteClusterChance = 0.1; - private int meteoriteMaximumSpawnHeight = 180; - private int[] meteoriteDimensionWhitelist = {0}; - // Wireless - private double wirelessBaseCost = 8; - private double wirelessCostMultiplier = 1; - private double wirelessTerminalDrainMultiplier = 1; - private double wirelessBaseRange = 16; - private double wirelessBoosterRangeMultiplier = 1; - private double wirelessBoosterExp = 1.5; - // Autocrafting - private boolean enableCraftingSubstitutes = false; - // Controller sizes - private int maxControllerSizeX = 7; - private int maxControllerSizeY = 7; - private int maxControllerSizeZ = 7; - - private AEConfig( final File configFile ) - { - super( configFile ); - this.configFile = configFile; - - MinecraftForge.EVENT_BUS.register( this ); - - PowerUnits.EU.conversionRatio = this.get( "PowerRatios", "IC2", DEFAULT_IC2_EXCHANGE ).getDouble( DEFAULT_IC2_EXCHANGE ); - PowerUnits.RF.conversionRatio = this.get( "PowerRatios", "ForgeEnergy", DEFAULT_RF_EXCHANGE ).getDouble( DEFAULT_RF_EXCHANGE ); - PowerUnits.GTEU.conversionRatio = this.get( "PowerRatios", "GTEU", DEFAULT_GTEU_EXCHANGE ).getDouble( DEFAULT_GTEU_EXCHANGE ); - - final double usageEffective = this.get( "PowerRatios", "UsageMultiplier", 1.0 ).getDouble( 1.0 ); - PowerMultiplier.CONFIG.multiplier = Math.max( 0.01, usageEffective ); - - CondenserOutput.MATTER_BALLS.requiredPower = this.get( "Condenser", "MatterBalls", 256 ).getInt( 256 ); - CondenserOutput.SINGULARITY.requiredPower = this.get( "Condenser", "Singularity", 256000 ).getInt( 256000 ); - - this.removeCrashingItemsOnLoad = this.get( "general", "removeCrashingItemsOnLoad", false, "Will auto-remove items that crash when being loaded from storage. This will destroy those items instead of crashing the game!" ).getBoolean(); - - this.setCategoryComment( "BlockingMode", "Map of items to not block when blockingmode is enabled.\n[modid]\nmodid:item:metadata(optional,default:0)\nSupports more than one modid, so you can block different things between, for example, gregtech or enderio" ); - this.nonBlockingItems = this.get( "BlockingMode", "nonBlockingItems", nonBlockingItems, "NonBlockingItems" ).getStringList(); - - this.setCategoryComment( "GrindStone", "Creates recipe of the following pattern automatically: '1 oreTYPE => 2 dustTYPE' and '(1 ingotTYPE or 1 crystalTYPE or 1 gemTYPE) => 1 dustTYPE'" ); - this.grinderOres = this.get( "GrindStone", "grinderOres", this.grinderOres, "The list of types to handle. Specify without a prefix like ore or dust." ).getStringList(); - this.grinderBlackList = Sets.newHashSet( this.get( "GrindStone", "blacklist", new String[]{}, "Blacklists the exact oredict name from being handled by any recipe." ).getStringList() ); - this.oreDoublePercentage = this.get( "GrindStone", "oreDoublePercentage", this.oreDoublePercentage, "Chance to actually get an output with stacksize > 1." ).getDouble( this.oreDoublePercentage ); - - this.settings.registerSetting( Settings.SEARCH_TOOLTIPS, YesNo.YES ); - this.settings.registerSetting( Settings.TERMINAL_STYLE, TerminalStyle.TALL ); - this.settings.registerSetting( Settings.SEARCH_MODE, SearchBoxMode.AUTOSEARCH ); - - this.spawnChargedChance = (float) ( 1.0 - this.get( "worldGen", "spawnChargedChance", 1.0 - this.spawnChargedChance ).getDouble( 1.0 - this.spawnChargedChance ) ); - this.minMeteoriteDistance = this.get( "worldGen", "minMeteoriteDistance", this.minMeteoriteDistance ).getInt( this.minMeteoriteDistance ); - this.meteoriteClusterChance = this.get( "worldGen", "meteoriteClusterChance", this.meteoriteClusterChance ).getDouble( this.meteoriteClusterChance ); - this.meteoriteMaximumSpawnHeight = this.get( "worldGen", "meteoriteMaximumSpawnHeight", this.meteoriteMaximumSpawnHeight ).getInt( this.meteoriteMaximumSpawnHeight ); - this.meteoriteDimensionWhitelist = this.get( "worldGen", "meteoriteDimensionWhitelist", this.meteoriteDimensionWhitelist ).getIntList(); - - this.quartzOresPerCluster = this.get( "worldGen", "quartzOresPerCluster", this.quartzOresPerCluster ).getInt( this.quartzOresPerCluster ); - this.quartzOresClusterAmount = this.get( "worldGen", "quartzOresClusterAmount", this.quartzOresClusterAmount ).getInt( this.quartzOresClusterAmount ); - - this.minMeteoriteDistanceSq = this.minMeteoriteDistance * this.minMeteoriteDistance; - - this.addCustomCategoryComment( "wireless", "Range= wirelessBaseRange + wirelessBoosterRangeMultiplier * Math.pow( boosters, wirelessBoosterExp )\nPowerDrain= wirelessBaseCost + wirelessCostMultiplier * Math.pow( boosters, 1 + boosters / wirelessHighWirelessCount )" ); - - this.wirelessBaseCost = this.get( "wireless", "wirelessBaseCost", this.wirelessBaseCost ).getDouble( this.wirelessBaseCost ); - this.wirelessCostMultiplier = this.get( "wireless", "wirelessCostMultiplier", this.wirelessCostMultiplier ).getDouble( this.wirelessCostMultiplier ); - this.wirelessBaseRange = this.get( "wireless", "wirelessBaseRange", this.wirelessBaseRange ).getDouble( this.wirelessBaseRange ); - this.wirelessBoosterRangeMultiplier = this.get( "wireless", "wirelessBoosterRangeMultiplier", this.wirelessBoosterRangeMultiplier ).getDouble( this.wirelessBoosterRangeMultiplier ); - this.wirelessBoosterExp = this.get( "wireless", "wirelessBoosterExp", this.wirelessBoosterExp ).getDouble( this.wirelessBoosterExp ); - this.wirelessTerminalDrainMultiplier = this.get( "wireless", "wirelessTerminalDrainMultiplier", this.wirelessTerminalDrainMultiplier ).getDouble( this.wirelessTerminalDrainMultiplier ); - - this.formationPlaneEntityLimit = this.get( "automation", "formationPlaneEntityLimit", this.formationPlaneEntityLimit ).getInt( this.formationPlaneEntityLimit ); - - this.wirelessTerminalBattery = this.get( "battery", "wirelessTerminal", this.wirelessTerminalBattery ).getInt( this.wirelessTerminalBattery ); - this.chargedStaffBattery = this.get( "battery", "chargedStaff", this.chargedStaffBattery ).getInt( this.chargedStaffBattery ); - this.entropyManipulatorBattery = this.get( "battery", "entropyManipulator", this.entropyManipulatorBattery ).getInt( this.entropyManipulatorBattery ); - this.portableCellBattery = this.get( "battery", "portableCell", this.portableCellBattery ).getInt( this.portableCellBattery ); - this.colorApplicatorBattery = this.get( "battery", "colorApplicator", this.colorApplicatorBattery ).getInt( this.colorApplicatorBattery ); - this.matterCannonBattery = this.get( "battery", "matterCannon", this.matterCannonBattery ).getInt( this.matterCannonBattery ); - - this.addCustomCategoryComment( "autocrafting", "Enable patterns with substitutions on to have their substitutes to be auto craftable.\nThis changes the crafting tree, and can show missing ingredients for the substitute, instead of the patterned item" ); - this.enableCraftingSubstitutes = this.get( "autocrafting", "EnableAutocraftinSubstitutes", this.enableCraftingSubstitutes ).getBoolean( this.enableCraftingSubstitutes ); - - this.addCustomCategoryComment( "ControllerSize", "Set the max size of a controller in any of the 3 axis.\nEach is between [1, 64)" ); - this.maxControllerSizeX = Math.min(Math.max(this.get( "ControllerSize", "maxControllerSizeX", this.maxControllerSizeX ).getInt(this.maxControllerSizeX), 1), 63); - this.maxControllerSizeY = Math.min(Math.max(this.get( "ControllerSize", "maxControllerSizeY", this.maxControllerSizeY ).getInt(this.maxControllerSizeY), 1), 63); - this.maxControllerSizeZ = Math.min(Math.max(this.get( "ControllerSize", "maxControllerSizeZ", this.maxControllerSizeZ ).getInt(this.maxControllerSizeZ), 1), 63); - - this.clientSync(); - - this.addCustomCategoryComment( "features", "Warning: Disabling a feature may disable other features depending on it." ); - for( final AEFeature feature : AEFeature.values() ) - { - if( feature.isVisible() ) - { - final Property option = this.get( "Features." + feature.category(), feature.key(), feature.isEnabled(), feature.comment() ); - - if( option.getBoolean( feature.isEnabled() ) ) - { - this.featureFlags.add( feature ); - } - } - else - { - this.featureFlags.add( feature ); - } - } - - final ModContainer imb = net.minecraftforge.fml.common.Loader.instance().getIndexedModList().get( "ImmibisCore" ); - if( imb != null ) - { - final List version = Arrays.asList( "59.0.0", "59.0.1", "59.0.2" ); - if( version.contains( imb.getVersion() ) ) - { - this.featureFlags.remove( AEFeature.ALPHA_PASS ); - } - } - - try - { - this.selectedPowerUnit = PowerUnits.valueOf( this.get( "Client", "PowerUnit", this.selectedPowerUnit.name(), this.getListComment( this.selectedPowerUnit ) ).getString() ); - } - catch( final Throwable t ) - { - this.selectedPowerUnit = PowerUnits.AE; - } - - for( final TickRates tr : TickRates.values() ) - { - tr.Load( this ); - } - - if( this.isFeatureEnabled( AEFeature.SPATIAL_IO ) ) - { - this.storageProviderID = this.get( "spatialio", "storageProviderID", this.storageProviderID ).getInt( this.storageProviderID ); - this.storageDimensionID = this.get( "spatialio", "storageDimensionID", this.storageDimensionID ).getInt( this.storageDimensionID ); - this.spatialPowerMultiplier = this.get( "spatialio", "spatialPowerMultiplier", this.spatialPowerMultiplier ).getDouble( this.spatialPowerMultiplier ); - this.spatialPowerExponent = this.get( "spatialio", "spatialPowerExponent", this.spatialPowerExponent ).getDouble( this.spatialPowerExponent ); - } - - if( this.isFeatureEnabled( AEFeature.CRAFTING_CPU ) ) - { - this.craftingCalculationTimePerTick = this.get( "craftingCPU", "craftingCalculationTimePerTick", this.craftingCalculationTimePerTick ).getInt( this.craftingCalculationTimePerTick ); - } - - this.updatable = true; - } - - public static void init( final File configFile ) - { - instance = new AEConfig( configFile ); - } - - public static AEConfig instance() - { - return instance; - } - - private void clientSync() - { - this.disableColoredCableRecipesInJEI = this.get( "Client", "disableColoredCableRecipesInJEI", true ).getBoolean( true ); - this.enableEffects = this.get( "Client", "enableEffects", true ).getBoolean( true ); - this.useLargeFonts = this.get( "Client", "useTerminalUseLargeFont", false ).getBoolean( false ); - this.useColoredCraftingStatus = this.get( "Client", "useColoredCraftingStatus", true ).getBoolean( true ); - - // load buttons.. - for( int btnNum = 0; btnNum < 4; btnNum++ ) - { - final Property cmb = this.get( "Client", "craftAmtButton" + ( btnNum + 1 ), this.craftByStacks[btnNum] ); - final Property pmb = this.get( "Client", "priorityAmtButton" + ( btnNum + 1 ), this.priorityByStacks[btnNum] ); - final Property lmb = this.get( "Client", "levelAmtButton" + ( btnNum + 1 ), this.levelByStacks[btnNum] ); - - final int buttonCap = (int) ( Math.pow( 10, btnNum + 1 ) - 1 ); - - this.craftByStacks[btnNum] = Math.abs( cmb.getInt( this.craftByStacks[btnNum] ) ); - this.priorityByStacks[btnNum] = Math.abs( pmb.getInt( this.priorityByStacks[btnNum] ) ); - this.levelByStacks[btnNum] = Math.abs( pmb.getInt( this.levelByStacks[btnNum] ) ); - - cmb.setComment( "Controls buttons on Crafting Screen : Capped at " + buttonCap ); - pmb.setComment( "Controls buttons on Priority Screen : Capped at " + buttonCap ); - lmb.setComment( "Controls buttons on Level Emitter Screen : Capped at " + buttonCap ); - - this.craftByStacks[btnNum] = Math.min( this.craftByStacks[btnNum], buttonCap ); - this.priorityByStacks[btnNum] = Math.min( this.priorityByStacks[btnNum], buttonCap ); - this.levelByStacks[btnNum] = Math.min( this.levelByStacks[btnNum], buttonCap ); - } - - for( final Settings e : this.settings.getSettings() ) - { - final String Category = "Client"; // e.getClass().getSimpleName(); - Enum value = this.settings.getSetting( e ); - - final Property p = this.get( Category, e.name(), value.name(), this.getListComment( value ) ); - - try - { - value = Enum.valueOf( value.getClass(), p.getString() ); - } - catch( final IllegalArgumentException er ) - { - AELog.info( "Invalid value '" + p.getString() + "' for " + e.name() + " using '" + value.name() + "' instead" ); - } - - this.settings.putSetting( e, value ); - } - } - - private String getListComment( final Enum value ) - { - String comment = null; - - if( value != null ) - { - final EnumSet set = EnumSet.allOf( value.getClass() ); - - for( final Object Oeg : set ) - { - final Enum eg = (Enum) Oeg; - if( comment == null ) - { - comment = "Possible Values: " + eg.name(); - } - else - { - comment += ", " + eg.name(); - } - } - } - - return comment; - } - - public boolean isFeatureEnabled( final AEFeature f ) - { - return this.featureFlags.contains( f ); - } - - public boolean areFeaturesEnabled( Collection features ) - { - return this.featureFlags.containsAll( features ); - } - - public double wireless_getDrainRate( final double range ) - { - return this.wirelessTerminalDrainMultiplier * range; - } - - public double wireless_getMaxRange( final int boosters ) - { - return this.wirelessBaseRange + this.wirelessBoosterRangeMultiplier * Math.pow( boosters, this.wirelessBoosterExp ); - } - - public double wireless_getPowerDrain( final int boosters ) - { - return this.wirelessBaseCost + this.wirelessCostMultiplier * Math.pow( boosters, 1 + boosters / this.wirelessHighWirelessCount ); - } - - @Override - public Property get( final String category, final String key, final String defaultValue, final String comment, final Property.Type type ) - { - final Property prop = super.get( category, key, defaultValue, comment, type ); - - if( prop != null ) - { - if( !category.equals( "Client" ) ) - { - prop.setRequiresMcRestart( true ); - } - } - - return prop; - } - - @Override - public void save() - { - if( this.isFeatureEnabled( AEFeature.SPATIAL_IO ) ) - { - this.get( "spatialio", "storageProviderID", this.storageProviderID ).set( this.storageProviderID ); - this.get( "spatialio", "storageDimensionID", this.storageDimensionID ).set( this.storageDimensionID ); - } - - this.get( "Client", "PowerUnit", this.selectedPowerUnit.name(), this.getListComment( this.selectedPowerUnit ) ).set( this.selectedPowerUnit.name() ); - - if( this.hasChanged() ) - { - super.save(); - } - } - - @SubscribeEvent - public void onConfigChanged( final ConfigChangedEvent.OnConfigChangedEvent eventArgs ) - { - if( eventArgs.getModID().equals( AppEng.MOD_ID ) ) - { - this.clientSync(); - } - } - - public boolean disableColoredCableRecipesInJEI() - { - return this.disableColoredCableRecipesInJEI; - } - - public String getFilePath() - { - return this.configFile.toString(); - } - - public boolean useAEVersion( final MaterialType mt ) - { - if( this.isFeatureEnabled( AEFeature.WEBSITE_RECIPES ) ) - { - return true; - } - - this.setCategoryComment( "OreCamouflage", "AE2 Automatically uses alternative ores present in your instance of MC to blend better with its surroundings, if you prefer you can disable this selectively using these flags; Its important to note, that some if these items even if enabled may not be craftable in game because other items are overriding their recipes." ); - final Property p = this.get( "OreCamouflage", mt.name(), true ); - p.setComment( "OreDictionary Names: " + mt.getOreName() ); - - return !p.getBoolean( true ); - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum setting, final Enum newValue ) - { - for( final Settings e : this.settings.getSettings() ) - { - if( e == setting ) - { - final String Category = "Client"; - final Property p = this.get( Category, e.name(), this.settings.getSetting( e ).name(), this.getListComment( newValue ) ); - p.set( newValue.name() ); - } - } - - if( this.updatable ) - { - this.save(); - } - } - - public int getFreeMaterial( final int varID ) - { - return this.getFreeIDSLot( varID, "materials" ); - } - - public int getFreeIDSLot( final int varID, final String category ) - { - boolean alreadyUsed = false; - int min = 0; - - for( final Property p : this.getCategory( category ).getValues().values() ) - { - final int thisInt = p.getInt(); - - if( varID == thisInt ) - { - alreadyUsed = true; - } - - min = Math.max( min, thisInt + 1 ); - } - - if( alreadyUsed ) - { - if( min < 16383 ) - { - min = 16383; - } - - return min; - } - - return varID; - } - - public int getFreePart( final int varID ) - { - return this.getFreeIDSLot( varID, "parts" ); - } - - @Override - public IConfigManager getConfigManager() - { - return this.settings; - } - - public boolean useTerminalUseLargeFont() - { - return this.useLargeFonts; - } - - public int craftItemsByStackAmounts( final int i ) - { - return this.craftByStacks[i]; - } - - public int priorityByStacksAmounts( final int i ) - { - return this.priorityByStacks[i]; - } - - public int levelByStackAmounts( final int i ) - { - return this.levelByStacks[i]; - } - - public int levelByMillyBuckets( final int i ) - { - return this.levelByMillibuckets[i]; - } - - public Enum getSetting( final String category, final Class class1, final Enum myDefault ) - { - final String name = class1.getSimpleName(); - final Property p = this.get( category, name, myDefault.name() ); - - try - { - return (Enum) class1.getField( p.toString() ).get( class1 ); - } - catch( final Throwable t ) - { - // :{ - } - - return myDefault; - } - - public void setSetting( final String category, final Enum s ) - { - final String name = s.getClass().getSimpleName(); - this.get( category, name, s.name() ).set( s.name() ); - this.save(); - } - - public PowerUnits selectedPowerUnit() - { - return this.selectedPowerUnit; - } - - public void nextPowerUnit( final boolean backwards ) - { - this.selectedPowerUnit = Platform.rotateEnum( this.selectedPowerUnit, backwards, Settings.POWER_UNITS.getPossibleValues() ); - this.save(); - } - - // Getters - public boolean isRemoveCrashingItemsOnLoad() - { - return this.removeCrashingItemsOnLoad; - } - - public int getFormationPlaneEntityLimit() - { - return this.formationPlaneEntityLimit; - } - - public boolean isEnableEffects() - { - return this.enableEffects; - } - - public boolean isUseLargeFonts() - { - return this.useLargeFonts; - } - - public boolean isUseColoredCraftingStatus() - { - return this.useColoredCraftingStatus; - } - - public boolean isDisableColoredCableRecipesInJEI() - { - return this.disableColoredCableRecipesInJEI; - } - - public int getCraftingCalculationTimePerTick() - { - return this.craftingCalculationTimePerTick; - } - - public PowerUnits getSelectedPowerUnit() - { - return this.selectedPowerUnit; - } - - public int[] getCraftByStacks() - { - return this.craftByStacks; - } - - public int[] getPriorityByStacks() - { - return this.priorityByStacks; - } - - public int[] getLevelByStacks() - { - return this.levelByStacks; - } - - public int getStorageProviderID() - { - return this.storageProviderID; - } - - void setStorageProviderID( int id ) - { - this.storageProviderID = id; - } - - public int getStorageDimensionID() - { - return this.storageDimensionID; - } - - void setStorageDimensionID( int id ) - { - this.storageDimensionID = id; - } - - public double getSpatialPowerExponent() - { - return this.spatialPowerExponent; - } - - public double getSpatialPowerMultiplier() - { - return this.spatialPowerMultiplier; - } - - public String[] getGrinderOres() - { - return this.grinderOres; - } - - public Set getGrinderBlackList() - { - return this.grinderBlackList; - } - - public double getOreDoublePercentage() - { - return this.oreDoublePercentage; - } - - public int getWirelessTerminalBattery() - { - return this.wirelessTerminalBattery; - } - - public int getEntropyManipulatorBattery() - { - return this.entropyManipulatorBattery; - } - - public int getMatterCannonBattery() - { - return this.matterCannonBattery; - } - - public int getPortableCellBattery() - { - return this.portableCellBattery; - } - - public int getColorApplicatorBattery() - { - return this.colorApplicatorBattery; - } - - public int getChargedStaffBattery() - { - return this.chargedStaffBattery; - } - - public float getSpawnChargedChance() - { - return this.spawnChargedChance; - } - - public int getQuartzOresPerCluster() - { - return this.quartzOresPerCluster; - } - - public int getQuartzOresClusterAmount() - { - return this.quartzOresClusterAmount; - } - - public String[] getNonBlockingItems() - { - return nonBlockingItems; - } - - public int getChargedChange() - { - return this.chargedChange; - } - - public int getMinMeteoriteDistance() - { - return this.minMeteoriteDistance; - } - - public int getMinMeteoriteDistanceSq() - { - return this.minMeteoriteDistanceSq; - } - - public double getMeteoriteClusterChance() - { - return this.meteoriteClusterChance; - } - - public int getMeteoriteMaximumSpawnHeight() - { - return this.meteoriteMaximumSpawnHeight; - } - - public int[] getMeteoriteDimensionWhitelist() - { - return this.meteoriteDimensionWhitelist; - } - - public double getWirelessBaseCost() - { - return this.wirelessBaseCost; - } - - public double getWirelessCostMultiplier() - { - return this.wirelessCostMultiplier; - } - - public double getWirelessTerminalDrainMultiplier() - { - return this.wirelessTerminalDrainMultiplier; - } - - public double getWirelessBaseRange() - { - return this.wirelessBaseRange; - } - - public double getWirelessBoosterRangeMultiplier() - { - return this.wirelessBoosterRangeMultiplier; - } - - public double getWirelessBoosterExp() - { - return this.wirelessBoosterExp; - } - - // Setters keep visibility as low as possible. - - public double getWirelessHighWirelessCount() - { - return this.wirelessHighWirelessCount; - } - - public boolean getEnableCraftingSubstitutes() - { - return this.enableCraftingSubstitutes; - } - - public int getMaxControllerSizeX() { return this.maxControllerSizeX; } - - public int getMaxControllerSizeY() { return this.maxControllerSizeY; } - - public int getMaxControllerSizeZ() { return this.maxControllerSizeZ; } +public final class AEConfig extends Configuration implements IConfigurableObject, IConfigManagerHost { + + public static final String VERSION = "@version@"; + public static final String CHANNEL = "@aechannel@"; + public static final String PACKET_CHANNEL = "AE"; + // Tunnels + public static final double TUNNEL_POWER_LOSS = 0.05; + // Default Grindstone ores + private static final String[] ORES_VANILLA = {"Obsidian", "Ender", "EnderPearl", "Coal", "Iron", "Gold", "Charcoal", "NetherQuartz"}; + private static final String[] ORES_AE = {"CertusQuartz", "Wheat", "Fluix"}; + private static final String[] ORES_COMMON = {"Copper", "Tin", "Silver", "Lead", "Bronze"}; + private static final String[] ORES_MISC = {"Brass", "Platinum", "Nickel", "Invar", "Aluminium", "Electrum", "Osmium", "Zinc"}; + // Default Energy Conversion Rates + private static final double DEFAULT_IC2_EXCHANGE = 2.0; + private static final double DEFAULT_GTEU_EXCHANGE = 2.0; + private static final double DEFAULT_RF_EXCHANGE = 0.5; + // Config instance + private static AEConfig instance; + private final IConfigManager settings = new ConfigManager(this); + + private final EnumSet featureFlags = EnumSet.noneOf(AEFeature.class); + private final File configFile; + // GUI Buttons + private final int[] craftByStacks = {1, 10, 100, 1000}; + private final int[] priorityByStacks = {1, 10, 100, 1000}; + private final int[] levelByStacks = {1, 10, 100, 1000}; + private final int[] levelByMillibuckets = {10, 100, 1000, 10000}; + private final Set grinderBlackList; + private final int chargedChange = 4; + private final double wirelessHighWirelessCount = 64; + private String[] nonBlockingItems = {"[gregtech|actuallyadditions]", "gregtech:circuit.integrated", "gregtech:shape.mold.plate", "gregtech:shape.mold.gear", "gregtech:shape.mold.credit", "gregtech:shape.mold.bottle", "gregtech:shape.mold.ingot", "gregtech:shape.mold.ball", "gregtech:shape.mold.block", "gregtech:shape.mold.nugget", "gregtech:shape.mold.cylinder", "gregtech:shape.mold.anvil", "gregtech:shape.mold.name", "gregtech:shape.mold.gear.small", "gregtech:shape.mold.rotor", "gregtech:shape.extruder.plate", "gregtech:shape.extruder.rod", "gregtech:shape.extruder.bolt", "gregtech:shape.extruder.ring", "gregtech:shape.extruder.cell", "gregtech:shape.extruder.ingot", "gregtech:shape.extruder.wire", "gregtech:shape.extruder.pipe.tiny", "gregtech:shape.extruder.pipe.small", "gregtech:shape.extruder.pipe.medium", "gregtech:shape.extruder.pipe.normal", "gregtech:shape.extruder.pipe.large", "gregtech:shape.extruder.pipe.huge", "gregtech:shape.extruder.block", "gregtech:shape.extruder.sword", "gregtech:shape.extruder.pickaxe", "gregtech:shape.extruder.shovel", "gregtech:shape.extruder.axe", "gregtech:shape.extruder.hoe", "gregtech:shape.extruder.hammer", "gregtech:shape.extruder.file", "gregtech:shape.extruder.saw", "gregtech:shape.extruder.gear", "gregtech:shape.extruder.bottle", "gregtech:shape.extruder.foil", "gregtech:shape.extruder.gear_small", "gregtech:shape.extruder.rod_long", "gregtech:shape.extruder.rotor", "gregtech:glass_lens.white", "gregtech:glass_lens.orange", "gregtech:glass_lens.magenta", "gregtech:glass_lens.light_blue", "gregtech:glass_lens.yellow", "gregtech:glass_lens.lime", "gregtech:glass_lens.pink", "gregtech:glass_lens.gray", "gregtech:glass_lens.light_gray", "gregtech:glass_lens.cyan", "gregtech:glass_lens.purple", "gregtech:glass_lens.blue", "gregtech:glass_lens.brown", "gregtech:glass_lens.green", "gregtech:glass_lens.red", "gregtech:glass_lens.black", "contenttweaker:smallgearextrudershape", "contenttweaker:creativeportabletankmold", "ore:lensAlmandine", "ore:lensBlueTopaz", "ore:lensDiamond", "ore:lensEmerald", "ore:lensGreenSapphire", "ore:lensRutile", "ore:lensRuby", "ore:lensSapphire", "ore:lensTopaz", "ore:lensJasper", "ore:lensGlass", "ore:lensOlivine", "ore:lensOpal", "ore:lensAmethyst", "ore:lensLapis", "ore:lensEnderPearl", "ore:lensEnderEye", "ore:lensGarnetRed", "ore:lensGarnetYellow", "ore:lensVinteum", "ore:lensNetherStar",}; + private boolean updatable = false; + // Misc + private boolean removeCrashingItemsOnLoad = false; + private int formationPlaneEntityLimit = 128; + private boolean enableEffects = true; + private boolean useLargeFonts = false; + private boolean useColoredCraftingStatus; + private boolean disableColoredCableRecipesInJEI = true; + private int craftingCalculationTimePerTick = 5; + private PowerUnits selectedPowerUnit = PowerUnits.AE; + // Spatial IO/Dimension + private int storageProviderID = -1; + private int storageDimensionID = -1; + private double spatialPowerExponent = 1.35; + private double spatialPowerMultiplier = 1250.0; + // Grindstone + private String[] grinderOres = Stream.of(ORES_VANILLA, ORES_AE, ORES_COMMON, ORES_MISC).flatMap(Stream::of).toArray(String[]::new); + private double oreDoublePercentage = 90.0; + // Batteries + private int wirelessTerminalBattery = 1600000; + private int entropyManipulatorBattery = 200000; + private int matterCannonBattery = 200000; + private int portableCellBattery = 20000; + private int colorApplicatorBattery = 20000; + private int chargedStaffBattery = 8000; + // Certus quartz + private float spawnChargedChance = 0.92f; + private int quartzOresPerCluster = 4; + private int quartzOresClusterAmount = 15; + // Meteors + private int minMeteoriteDistance = 707; + private int minMeteoriteDistanceSq = this.minMeteoriteDistance * this.minMeteoriteDistance; + private double meteoriteClusterChance = 0.1; + private int meteoriteMaximumSpawnHeight = 180; + private int[] meteoriteDimensionWhitelist = {0}; + // Wireless + private double wirelessBaseCost = 8; + private double wirelessCostMultiplier = 1; + private double wirelessTerminalDrainMultiplier = 1; + private double wirelessBaseRange = 16; + private double wirelessBoosterRangeMultiplier = 1; + private double wirelessBoosterExp = 1.5; + // Autocrafting + private boolean enableCraftingSubstitutes = false; + // Controller sizes + private int maxControllerSizeX = 7; + private int maxControllerSizeY = 7; + private int maxControllerSizeZ = 7; + + private AEConfig(final File configFile) { + super(configFile); + this.configFile = configFile; + + MinecraftForge.EVENT_BUS.register(this); + + PowerUnits.EU.conversionRatio = this.get("PowerRatios", "IC2", DEFAULT_IC2_EXCHANGE).getDouble(DEFAULT_IC2_EXCHANGE); + PowerUnits.RF.conversionRatio = this.get("PowerRatios", "ForgeEnergy", DEFAULT_RF_EXCHANGE).getDouble(DEFAULT_RF_EXCHANGE); + PowerUnits.GTEU.conversionRatio = this.get("PowerRatios", "GTEU", DEFAULT_GTEU_EXCHANGE).getDouble(DEFAULT_GTEU_EXCHANGE); + + final double usageEffective = this.get("PowerRatios", "UsageMultiplier", 1.0).getDouble(1.0); + PowerMultiplier.CONFIG.multiplier = Math.max(0.01, usageEffective); + + CondenserOutput.MATTER_BALLS.requiredPower = this.get("Condenser", "MatterBalls", 256).getInt(256); + CondenserOutput.SINGULARITY.requiredPower = this.get("Condenser", "Singularity", 256000).getInt(256000); + + this.removeCrashingItemsOnLoad = this.get("general", "removeCrashingItemsOnLoad", false, "Will auto-remove items that crash when being loaded from storage. This will destroy those items instead of crashing the game!").getBoolean(); + + this.setCategoryComment("BlockingMode", "Map of items to not block when blockingmode is enabled.\n[modid]\nmodid:item:metadata(optional,default:0)\nSupports more than one modid, so you can block different things between, for example, gregtech or enderio"); + this.nonBlockingItems = this.get("BlockingMode", "nonBlockingItems", nonBlockingItems, "NonBlockingItems").getStringList(); + + this.setCategoryComment("GrindStone", "Creates recipe of the following pattern automatically: '1 oreTYPE => 2 dustTYPE' and '(1 ingotTYPE or 1 crystalTYPE or 1 gemTYPE) => 1 dustTYPE'"); + this.grinderOres = this.get("GrindStone", "grinderOres", this.grinderOres, "The list of types to handle. Specify without a prefix like ore or dust.").getStringList(); + this.grinderBlackList = Sets.newHashSet(this.get("GrindStone", "blacklist", new String[]{}, "Blacklists the exact oredict name from being handled by any recipe.").getStringList()); + this.oreDoublePercentage = this.get("GrindStone", "oreDoublePercentage", this.oreDoublePercentage, "Chance to actually get an output with stacksize > 1.").getDouble(this.oreDoublePercentage); + + this.settings.registerSetting(Settings.SEARCH_TOOLTIPS, YesNo.YES); + this.settings.registerSetting(Settings.TERMINAL_STYLE, TerminalStyle.TALL); + this.settings.registerSetting(Settings.SEARCH_MODE, SearchBoxMode.AUTOSEARCH); + + this.spawnChargedChance = (float) (1.0 - this.get("worldGen", "spawnChargedChance", 1.0 - this.spawnChargedChance).getDouble(1.0 - this.spawnChargedChance)); + this.minMeteoriteDistance = this.get("worldGen", "minMeteoriteDistance", this.minMeteoriteDistance).getInt(this.minMeteoriteDistance); + this.meteoriteClusterChance = this.get("worldGen", "meteoriteClusterChance", this.meteoriteClusterChance).getDouble(this.meteoriteClusterChance); + this.meteoriteMaximumSpawnHeight = this.get("worldGen", "meteoriteMaximumSpawnHeight", this.meteoriteMaximumSpawnHeight).getInt(this.meteoriteMaximumSpawnHeight); + this.meteoriteDimensionWhitelist = this.get("worldGen", "meteoriteDimensionWhitelist", this.meteoriteDimensionWhitelist).getIntList(); + + this.quartzOresPerCluster = this.get("worldGen", "quartzOresPerCluster", this.quartzOresPerCluster).getInt(this.quartzOresPerCluster); + this.quartzOresClusterAmount = this.get("worldGen", "quartzOresClusterAmount", this.quartzOresClusterAmount).getInt(this.quartzOresClusterAmount); + + this.minMeteoriteDistanceSq = this.minMeteoriteDistance * this.minMeteoriteDistance; + + this.addCustomCategoryComment("wireless", "Range= wirelessBaseRange + wirelessBoosterRangeMultiplier * Math.pow( boosters, wirelessBoosterExp )\nPowerDrain= wirelessBaseCost + wirelessCostMultiplier * Math.pow( boosters, 1 + boosters / wirelessHighWirelessCount )"); + + this.wirelessBaseCost = this.get("wireless", "wirelessBaseCost", this.wirelessBaseCost).getDouble(this.wirelessBaseCost); + this.wirelessCostMultiplier = this.get("wireless", "wirelessCostMultiplier", this.wirelessCostMultiplier).getDouble(this.wirelessCostMultiplier); + this.wirelessBaseRange = this.get("wireless", "wirelessBaseRange", this.wirelessBaseRange).getDouble(this.wirelessBaseRange); + this.wirelessBoosterRangeMultiplier = this.get("wireless", "wirelessBoosterRangeMultiplier", this.wirelessBoosterRangeMultiplier).getDouble(this.wirelessBoosterRangeMultiplier); + this.wirelessBoosterExp = this.get("wireless", "wirelessBoosterExp", this.wirelessBoosterExp).getDouble(this.wirelessBoosterExp); + this.wirelessTerminalDrainMultiplier = this.get("wireless", "wirelessTerminalDrainMultiplier", this.wirelessTerminalDrainMultiplier).getDouble(this.wirelessTerminalDrainMultiplier); + + this.formationPlaneEntityLimit = this.get("automation", "formationPlaneEntityLimit", this.formationPlaneEntityLimit).getInt(this.formationPlaneEntityLimit); + + this.wirelessTerminalBattery = this.get("battery", "wirelessTerminal", this.wirelessTerminalBattery).getInt(this.wirelessTerminalBattery); + this.chargedStaffBattery = this.get("battery", "chargedStaff", this.chargedStaffBattery).getInt(this.chargedStaffBattery); + this.entropyManipulatorBattery = this.get("battery", "entropyManipulator", this.entropyManipulatorBattery).getInt(this.entropyManipulatorBattery); + this.portableCellBattery = this.get("battery", "portableCell", this.portableCellBattery).getInt(this.portableCellBattery); + this.colorApplicatorBattery = this.get("battery", "colorApplicator", this.colorApplicatorBattery).getInt(this.colorApplicatorBattery); + this.matterCannonBattery = this.get("battery", "matterCannon", this.matterCannonBattery).getInt(this.matterCannonBattery); + + this.addCustomCategoryComment("autocrafting", "Enable patterns with substitutions on to have their substitutes to be auto craftable.\nThis changes the crafting tree, and can show missing ingredients for the substitute, instead of the patterned item"); + this.enableCraftingSubstitutes = this.get("autocrafting", "EnableAutocraftinSubstitutes", this.enableCraftingSubstitutes).getBoolean(this.enableCraftingSubstitutes); + + this.addCustomCategoryComment("ControllerSize", "Set the max size of a controller in any of the 3 axis.\nEach is between [1, 64)"); + this.maxControllerSizeX = Math.min(Math.max(this.get("ControllerSize", "maxControllerSizeX", this.maxControllerSizeX).getInt(this.maxControllerSizeX), 1), 63); + this.maxControllerSizeY = Math.min(Math.max(this.get("ControllerSize", "maxControllerSizeY", this.maxControllerSizeY).getInt(this.maxControllerSizeY), 1), 63); + this.maxControllerSizeZ = Math.min(Math.max(this.get("ControllerSize", "maxControllerSizeZ", this.maxControllerSizeZ).getInt(this.maxControllerSizeZ), 1), 63); + + this.clientSync(); + + this.addCustomCategoryComment("features", "Warning: Disabling a feature may disable other features depending on it."); + for (final AEFeature feature : AEFeature.values()) { + if (feature.isVisible()) { + final Property option = this.get("Features." + feature.category(), feature.key(), feature.isEnabled(), feature.comment()); + + if (option.getBoolean(feature.isEnabled())) { + this.featureFlags.add(feature); + } + } else { + this.featureFlags.add(feature); + } + } + + final ModContainer imb = net.minecraftforge.fml.common.Loader.instance().getIndexedModList().get("ImmibisCore"); + if (imb != null) { + final List version = Arrays.asList("59.0.0", "59.0.1", "59.0.2"); + if (version.contains(imb.getVersion())) { + this.featureFlags.remove(AEFeature.ALPHA_PASS); + } + } + + try { + this.selectedPowerUnit = PowerUnits.valueOf(this.get("Client", "PowerUnit", this.selectedPowerUnit.name(), this.getListComment(this.selectedPowerUnit)).getString()); + } catch (final Throwable t) { + this.selectedPowerUnit = PowerUnits.AE; + } + + for (final TickRates tr : TickRates.values()) { + tr.Load(this); + } + + if (this.isFeatureEnabled(AEFeature.SPATIAL_IO)) { + this.storageProviderID = this.get("spatialio", "storageProviderID", this.storageProviderID).getInt(this.storageProviderID); + this.storageDimensionID = this.get("spatialio", "storageDimensionID", this.storageDimensionID).getInt(this.storageDimensionID); + this.spatialPowerMultiplier = this.get("spatialio", "spatialPowerMultiplier", this.spatialPowerMultiplier).getDouble(this.spatialPowerMultiplier); + this.spatialPowerExponent = this.get("spatialio", "spatialPowerExponent", this.spatialPowerExponent).getDouble(this.spatialPowerExponent); + } + + if (this.isFeatureEnabled(AEFeature.CRAFTING_CPU)) { + this.craftingCalculationTimePerTick = this.get("craftingCPU", "craftingCalculationTimePerTick", this.craftingCalculationTimePerTick).getInt(this.craftingCalculationTimePerTick); + } + + this.updatable = true; + } + + public static void init(final File configFile) { + instance = new AEConfig(configFile); + } + + public static AEConfig instance() { + return instance; + } + + private void clientSync() { + this.disableColoredCableRecipesInJEI = this.get("Client", "disableColoredCableRecipesInJEI", true).getBoolean(true); + this.enableEffects = this.get("Client", "enableEffects", true).getBoolean(true); + this.useLargeFonts = this.get("Client", "useTerminalUseLargeFont", false).getBoolean(false); + this.useColoredCraftingStatus = this.get("Client", "useColoredCraftingStatus", true).getBoolean(true); + + // load buttons.. + for (int btnNum = 0; btnNum < 4; btnNum++) { + final Property cmb = this.get("Client", "craftAmtButton" + (btnNum + 1), this.craftByStacks[btnNum]); + final Property pmb = this.get("Client", "priorityAmtButton" + (btnNum + 1), this.priorityByStacks[btnNum]); + final Property lmb = this.get("Client", "levelAmtButton" + (btnNum + 1), this.levelByStacks[btnNum]); + + final int buttonCap = (int) (Math.pow(10, btnNum + 1) - 1); + + this.craftByStacks[btnNum] = Math.abs(cmb.getInt(this.craftByStacks[btnNum])); + this.priorityByStacks[btnNum] = Math.abs(pmb.getInt(this.priorityByStacks[btnNum])); + this.levelByStacks[btnNum] = Math.abs(pmb.getInt(this.levelByStacks[btnNum])); + + cmb.setComment("Controls buttons on Crafting Screen : Capped at " + buttonCap); + pmb.setComment("Controls buttons on Priority Screen : Capped at " + buttonCap); + lmb.setComment("Controls buttons on Level Emitter Screen : Capped at " + buttonCap); + + this.craftByStacks[btnNum] = Math.min(this.craftByStacks[btnNum], buttonCap); + this.priorityByStacks[btnNum] = Math.min(this.priorityByStacks[btnNum], buttonCap); + this.levelByStacks[btnNum] = Math.min(this.levelByStacks[btnNum], buttonCap); + } + + for (final Settings e : this.settings.getSettings()) { + final String Category = "Client"; // e.getClass().getSimpleName(); + Enum value = this.settings.getSetting(e); + + final Property p = this.get(Category, e.name(), value.name(), this.getListComment(value)); + + try { + value = Enum.valueOf(value.getClass(), p.getString()); + } catch (final IllegalArgumentException er) { + AELog.info("Invalid value '" + p.getString() + "' for " + e.name() + " using '" + value.name() + "' instead"); + } + + this.settings.putSetting(e, value); + } + } + + private String getListComment(final Enum value) { + String comment = null; + + if (value != null) { + final EnumSet set = EnumSet.allOf(value.getClass()); + + for (final Object Oeg : set) { + final Enum eg = (Enum) Oeg; + if (comment == null) { + comment = "Possible Values: " + eg.name(); + } else { + comment += ", " + eg.name(); + } + } + } + + return comment; + } + + public boolean isFeatureEnabled(final AEFeature f) { + return this.featureFlags.contains(f); + } + + public boolean areFeaturesEnabled(Collection features) { + return this.featureFlags.containsAll(features); + } + + public double wireless_getDrainRate(final double range) { + return this.wirelessTerminalDrainMultiplier * range; + } + + public double wireless_getMaxRange(final int boosters) { + return this.wirelessBaseRange + this.wirelessBoosterRangeMultiplier * Math.pow(boosters, this.wirelessBoosterExp); + } + + public double wireless_getPowerDrain(final int boosters) { + return this.wirelessBaseCost + this.wirelessCostMultiplier * Math.pow(boosters, 1 + boosters / this.wirelessHighWirelessCount); + } + + @Override + public Property get(final String category, final String key, final String defaultValue, final String comment, final Property.Type type) { + final Property prop = super.get(category, key, defaultValue, comment, type); + + if (prop != null) { + if (!category.equals("Client")) { + prop.setRequiresMcRestart(true); + } + } + + return prop; + } + + @Override + public void save() { + if (this.isFeatureEnabled(AEFeature.SPATIAL_IO)) { + this.get("spatialio", "storageProviderID", this.storageProviderID).set(this.storageProviderID); + this.get("spatialio", "storageDimensionID", this.storageDimensionID).set(this.storageDimensionID); + } + + this.get("Client", "PowerUnit", this.selectedPowerUnit.name(), this.getListComment(this.selectedPowerUnit)).set(this.selectedPowerUnit.name()); + + if (this.hasChanged()) { + super.save(); + } + } + + @SubscribeEvent + public void onConfigChanged(final ConfigChangedEvent.OnConfigChangedEvent eventArgs) { + if (eventArgs.getModID().equals(AppEng.MOD_ID)) { + this.clientSync(); + } + } + + public boolean disableColoredCableRecipesInJEI() { + return this.disableColoredCableRecipesInJEI; + } + + public String getFilePath() { + return this.configFile.toString(); + } + + public boolean useAEVersion(final MaterialType mt) { + if (this.isFeatureEnabled(AEFeature.WEBSITE_RECIPES)) { + return true; + } + + this.setCategoryComment("OreCamouflage", "AE2 Automatically uses alternative ores present in your instance of MC to blend better with its surroundings, if you prefer you can disable this selectively using these flags; Its important to note, that some if these items even if enabled may not be craftable in game because other items are overriding their recipes."); + final Property p = this.get("OreCamouflage", mt.name(), true); + p.setComment("OreDictionary Names: " + mt.getOreName()); + + return !p.getBoolean(true); + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum setting, final Enum newValue) { + for (final Settings e : this.settings.getSettings()) { + if (e == setting) { + final String Category = "Client"; + final Property p = this.get(Category, e.name(), this.settings.getSetting(e).name(), this.getListComment(newValue)); + p.set(newValue.name()); + } + } + + if (this.updatable) { + this.save(); + } + } + + public int getFreeMaterial(final int varID) { + return this.getFreeIDSLot(varID, "materials"); + } + + public int getFreeIDSLot(final int varID, final String category) { + boolean alreadyUsed = false; + int min = 0; + + for (final Property p : this.getCategory(category).getValues().values()) { + final int thisInt = p.getInt(); + + if (varID == thisInt) { + alreadyUsed = true; + } + + min = Math.max(min, thisInt + 1); + } + + if (alreadyUsed) { + if (min < 16383) { + min = 16383; + } + + return min; + } + + return varID; + } + + public int getFreePart(final int varID) { + return this.getFreeIDSLot(varID, "parts"); + } + + @Override + public IConfigManager getConfigManager() { + return this.settings; + } + + public boolean useTerminalUseLargeFont() { + return this.useLargeFonts; + } + + public int craftItemsByStackAmounts(final int i) { + return this.craftByStacks[i]; + } + + public int priorityByStacksAmounts(final int i) { + return this.priorityByStacks[i]; + } + + public int levelByStackAmounts(final int i) { + return this.levelByStacks[i]; + } + + public int levelByMillyBuckets(final int i) { + return this.levelByMillibuckets[i]; + } + + public Enum getSetting(final String category, final Class class1, final Enum myDefault) { + final String name = class1.getSimpleName(); + final Property p = this.get(category, name, myDefault.name()); + + try { + return (Enum) class1.getField(p.toString()).get(class1); + } catch (final Throwable t) { + // :{ + } + + return myDefault; + } + + public void setSetting(final String category, final Enum s) { + final String name = s.getClass().getSimpleName(); + this.get(category, name, s.name()).set(s.name()); + this.save(); + } + + public PowerUnits selectedPowerUnit() { + return this.selectedPowerUnit; + } + + public void nextPowerUnit(final boolean backwards) { + this.selectedPowerUnit = Platform.rotateEnum(this.selectedPowerUnit, backwards, Settings.POWER_UNITS.getPossibleValues()); + this.save(); + } + + // Getters + public boolean isRemoveCrashingItemsOnLoad() { + return this.removeCrashingItemsOnLoad; + } + + public int getFormationPlaneEntityLimit() { + return this.formationPlaneEntityLimit; + } + + public boolean isEnableEffects() { + return this.enableEffects; + } + + public boolean isUseLargeFonts() { + return this.useLargeFonts; + } + + public boolean isUseColoredCraftingStatus() { + return this.useColoredCraftingStatus; + } + + public boolean isDisableColoredCableRecipesInJEI() { + return this.disableColoredCableRecipesInJEI; + } + + public int getCraftingCalculationTimePerTick() { + return this.craftingCalculationTimePerTick; + } + + public PowerUnits getSelectedPowerUnit() { + return this.selectedPowerUnit; + } + + public int[] getCraftByStacks() { + return this.craftByStacks; + } + + public int[] getPriorityByStacks() { + return this.priorityByStacks; + } + + public int[] getLevelByStacks() { + return this.levelByStacks; + } + + public int getStorageProviderID() { + return this.storageProviderID; + } + + void setStorageProviderID(int id) { + this.storageProviderID = id; + } + + public int getStorageDimensionID() { + return this.storageDimensionID; + } + + void setStorageDimensionID(int id) { + this.storageDimensionID = id; + } + + public double getSpatialPowerExponent() { + return this.spatialPowerExponent; + } + + public double getSpatialPowerMultiplier() { + return this.spatialPowerMultiplier; + } + + public String[] getGrinderOres() { + return this.grinderOres; + } + + public Set getGrinderBlackList() { + return this.grinderBlackList; + } + + public double getOreDoublePercentage() { + return this.oreDoublePercentage; + } + + public int getWirelessTerminalBattery() { + return this.wirelessTerminalBattery; + } + + public int getEntropyManipulatorBattery() { + return this.entropyManipulatorBattery; + } + + public int getMatterCannonBattery() { + return this.matterCannonBattery; + } + + public int getPortableCellBattery() { + return this.portableCellBattery; + } + + public int getColorApplicatorBattery() { + return this.colorApplicatorBattery; + } + + public int getChargedStaffBattery() { + return this.chargedStaffBattery; + } + + public float getSpawnChargedChance() { + return this.spawnChargedChance; + } + + public int getQuartzOresPerCluster() { + return this.quartzOresPerCluster; + } + + public int getQuartzOresClusterAmount() { + return this.quartzOresClusterAmount; + } + + public String[] getNonBlockingItems() { + return nonBlockingItems; + } + + public int getChargedChange() { + return this.chargedChange; + } + + public int getMinMeteoriteDistance() { + return this.minMeteoriteDistance; + } + + public int getMinMeteoriteDistanceSq() { + return this.minMeteoriteDistanceSq; + } + + public double getMeteoriteClusterChance() { + return this.meteoriteClusterChance; + } + + public int getMeteoriteMaximumSpawnHeight() { + return this.meteoriteMaximumSpawnHeight; + } + + public int[] getMeteoriteDimensionWhitelist() { + return this.meteoriteDimensionWhitelist; + } + + public double getWirelessBaseCost() { + return this.wirelessBaseCost; + } + + public double getWirelessCostMultiplier() { + return this.wirelessCostMultiplier; + } + + public double getWirelessTerminalDrainMultiplier() { + return this.wirelessTerminalDrainMultiplier; + } + + public double getWirelessBaseRange() { + return this.wirelessBaseRange; + } + + public double getWirelessBoosterRangeMultiplier() { + return this.wirelessBoosterRangeMultiplier; + } + + public double getWirelessBoosterExp() { + return this.wirelessBoosterExp; + } + + // Setters keep visibility as low as possible. + + public double getWirelessHighWirelessCount() { + return this.wirelessHighWirelessCount; + } + + public boolean getEnableCraftingSubstitutes() { + return this.enableCraftingSubstitutes; + } + + public int getMaxControllerSizeX() { + return this.maxControllerSizeX; + } + + public int getMaxControllerSizeY() { + return this.maxControllerSizeY; + } + + public int getMaxControllerSizeZ() { + return this.maxControllerSizeZ; + } } diff --git a/src/main/java/appeng/core/AELog.java b/src/main/java/appeng/core/AELog.java index 217e4ba4f..052408e2a 100644 --- a/src/main/java/appeng/core/AELog.java +++ b/src/main/java/appeng/core/AELog.java @@ -19,370 +19,323 @@ package appeng.core; -import javax.annotation.Nonnull; - +import appeng.core.features.AEFeature; +import appeng.tile.AEBaseTile; +import appeng.util.Platform; +import net.minecraft.util.math.BlockPos; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; -import net.minecraft.util.math.BlockPos; - -import appeng.core.features.AEFeature; -import appeng.tile.AEBaseTile; -import appeng.util.Platform; +import javax.annotation.Nonnull; -public final class AELog -{ - private static final String LOGGER_PREFIX = "AE2:"; - private static final String SERVER_SUFFIX = "S"; - private static final String CLIENT_SUFFIX = "C"; +public final class AELog { + private static final String LOGGER_PREFIX = "AE2:"; + private static final String SERVER_SUFFIX = "S"; + private static final String CLIENT_SUFFIX = "C"; - private static final Logger SERVER = LogManager.getFormatterLogger( LOGGER_PREFIX + SERVER_SUFFIX ); - private static final Logger CLIENT = LogManager.getFormatterLogger( LOGGER_PREFIX + CLIENT_SUFFIX ); + private static final Logger SERVER = LogManager.getFormatterLogger(LOGGER_PREFIX + SERVER_SUFFIX); + private static final Logger CLIENT = LogManager.getFormatterLogger(LOGGER_PREFIX + CLIENT_SUFFIX); - private static final String BLOCK_UPDATE = "Block Update of %s @ ( %s )"; + private static final String BLOCK_UPDATE = "Block Update of %s @ ( %s )"; - private static final String DEFAULT_EXCEPTION_MESSAGE = "Exception: "; + private static final String DEFAULT_EXCEPTION_MESSAGE = "Exception: "; - private AELog() - { - } + private AELog() { + } - /** - * Returns a {@link Logger} logger suitable for the effective side (client/server). - * - * @return a suitable logger instance - */ - private static Logger getLogger() - { - return Platform.isServer() ? SERVER : CLIENT; - } + /** + * Returns a {@link Logger} logger suitable for the effective side (client/server). + * + * @return a suitable logger instance + */ + private static Logger getLogger() { + return Platform.isServer() ? SERVER : CLIENT; + } - /** - * Indicates of the global log is enabled or disabled. - * - * By default it is enabled. - * - * @return true when the log is enabled. - */ - public static boolean isLogEnabled() - { - return AEConfig.instance() == null || AEConfig.instance().isFeatureEnabled( AEFeature.LOGGING ); - } + /** + * Indicates of the global log is enabled or disabled. + *

+ * By default it is enabled. + * + * @return true when the log is enabled. + */ + public static boolean isLogEnabled() { + return AEConfig.instance() == null || AEConfig.instance().isFeatureEnabled(AEFeature.LOGGING); + } - /** - * Logs a formatted message with a specific log level. - * - * This uses {@link String#format(String, Object...)} as opposed to the {@link ParameterizedMessage} to allow a more - * flexible formatting. - * - * The output can be globally disabled via the configuration file. - * - * @param level the intended level. - * @param message the message to be formatted. - * @param params the parameters used for {@link String#format(String, Object...)}. - */ - public static void log( @Nonnull final Level level, @Nonnull final String message, final Object... params ) - { - if( AELog.isLogEnabled() ) - { - final String formattedMessage = String.format( message, params ); - final Logger logger = getLogger(); + /** + * Logs a formatted message with a specific log level. + *

+ * This uses {@link String#format(String, Object...)} as opposed to the {@link ParameterizedMessage} to allow a more + * flexible formatting. + *

+ * The output can be globally disabled via the configuration file. + * + * @param level the intended level. + * @param message the message to be formatted. + * @param params the parameters used for {@link String#format(String, Object...)}. + */ + public static void log(@Nonnull final Level level, @Nonnull final String message, final Object... params) { + if (AELog.isLogEnabled()) { + final String formattedMessage = String.format(message, params); + final Logger logger = getLogger(); - logger.log( level, formattedMessage ); - } - } + logger.log(level, formattedMessage); + } + } - /** - * Log an exception with a custom message formated via {@link String#format(String, Object...)} - * - * Similar to {@link AELog#log(Level, String, Object...)}. - * - * @see AELog#log(Level, String, Object...) - * - * @param level the intended level. - * @param exception - * @param message the message to be formatted. - * @param params the parameters used for {@link String#format(String, Object...)}. - */ - public static void log( @Nonnull final Level level, @Nonnull final Throwable exception, @Nonnull String message, final Object... params ) - { - if( AELog.isLogEnabled() ) - { - final String formattedMessage = String.format( message, params ); - final Logger logger = getLogger(); + /** + * Log an exception with a custom message formated via {@link String#format(String, Object...)} + *

+ * Similar to {@link AELog#log(Level, String, Object...)}. + * + * @param level the intended level. + * @param exception + * @param message the message to be formatted. + * @param params the parameters used for {@link String#format(String, Object...)}. + * @see AELog#log(Level, String, Object...) + */ + public static void log(@Nonnull final Level level, @Nonnull final Throwable exception, @Nonnull String message, final Object... params) { + if (AELog.isLogEnabled()) { + final String formattedMessage = String.format(message, params); + final Logger logger = getLogger(); - logger.log( level, formattedMessage, exception ); - } - } + logger.log(level, formattedMessage, exception); + } + } - /** - * @see AELog#log(Level, String, Object...) - * @param format - * @param params - */ - public static void info( @Nonnull final String format, final Object... params ) - { - log( Level.INFO, format, params ); - } + /** + * @param format + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void info(@Nonnull final String format, final Object... params) { + log(Level.INFO, format, params); + } - /** - * Log exception as {@link Level#INFO} - * - * @see AELog#log(Level, Throwable, String, Object...) - * - * @param exception - */ - public static void info( @Nonnull final Throwable exception ) - { - log( Level.INFO, exception, DEFAULT_EXCEPTION_MESSAGE ); - } + /** + * Log exception as {@link Level#INFO} + * + * @param exception + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void info(@Nonnull final Throwable exception) { + log(Level.INFO, exception, DEFAULT_EXCEPTION_MESSAGE); + } - /** - * Log exception as {@link Level#INFO} - * - * @see AELog#log(Level, Throwable, String, Object...) - * - * @param exception - * @param message - */ - public static void info( @Nonnull final Throwable exception, @Nonnull final String message ) - { - log( Level.INFO, exception, message ); - } + /** + * Log exception as {@link Level#INFO} + * + * @param exception + * @param message + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void info(@Nonnull final Throwable exception, @Nonnull final String message) { + log(Level.INFO, exception, message); + } - /** - * @see AELog#log(Level, String, Object...) - * @param format - * @param params - */ - public static void warn( @Nonnull final String format, final Object... params ) - { - log( Level.WARN, format, params ); - } + /** + * @param format + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void warn(@Nonnull final String format, final Object... params) { + log(Level.WARN, format, params); + } - /** - * Log exception as {@link Level#WARN} - * - * @see AELog#log(Level, Throwable, String, Object...) - * - * @param exception - */ - public static void warn( @Nonnull final Throwable exception ) - { - log( Level.WARN, exception, DEFAULT_EXCEPTION_MESSAGE ); - } + /** + * Log exception as {@link Level#WARN} + * + * @param exception + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void warn(@Nonnull final Throwable exception) { + log(Level.WARN, exception, DEFAULT_EXCEPTION_MESSAGE); + } - /** - * Log exception as {@link Level#WARN} - * - * @see AELog#log(Level, Throwable, String, Object...) - * - * @param exception - * @param message - */ - public static void warn( @Nonnull final Throwable exception, @Nonnull final String message ) - { - log( Level.WARN, exception, message ); - } + /** + * Log exception as {@link Level#WARN} + * + * @param exception + * @param message + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void warn(@Nonnull final Throwable exception, @Nonnull final String message) { + log(Level.WARN, exception, message); + } - /** - * @see AELog#log(Level, String, Object...) - * @param format - * @param params - */ - public static void error( @Nonnull final String format, final Object... params ) - { - log( Level.ERROR, format, params ); - } + /** + * @param format + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void error(@Nonnull final String format, final Object... params) { + log(Level.ERROR, format, params); + } - /** - * Log exception as {@link Level#ERROR} - * - * @see AELog#log(Level, Throwable, String, Object...) - * - * @param exception - */ - public static void error( @Nonnull final Throwable exception ) - { - log( Level.ERROR, exception, DEFAULT_EXCEPTION_MESSAGE ); - } + /** + * Log exception as {@link Level#ERROR} + * + * @param exception + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void error(@Nonnull final Throwable exception) { + log(Level.ERROR, exception, DEFAULT_EXCEPTION_MESSAGE); + } - /** - * Log exception as {@link Level#ERROR} - * - * @see AELog#log(Level, Throwable, String, Object...) - * - * @param exception - * @param message - */ - public static void error( @Nonnull final Throwable exception, @Nonnull final String message ) - { - log( Level.ERROR, exception, message ); - } + /** + * Log exception as {@link Level#ERROR} + * + * @param exception + * @param message + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void error(@Nonnull final Throwable exception, @Nonnull final String message) { + log(Level.ERROR, exception, message); + } - /** - * Log message as {@link Level#DEBUG} - * - * @see AELog#log(Level, String, Object...) - * @param format - * @param data - */ - public static void debug( @Nonnull final String format, final Object... data ) - { - if( AELog.isDebugLogEnabled() ) - { - log( Level.DEBUG, format, data ); - } - } + /** + * Log message as {@link Level#DEBUG} + * + * @param format + * @param data + * @see AELog#log(Level, String, Object...) + */ + public static void debug(@Nonnull final String format, final Object... data) { + if (AELog.isDebugLogEnabled()) { + log(Level.DEBUG, format, data); + } + } - /** - * Log exception as {@link Level#DEBUG} - * - * @see AELog#log(Level, Throwable, String, Object...) - * - * @param exception - */ - public static void debug( @Nonnull final Throwable exception ) - { - if( AELog.isDebugLogEnabled() ) - { - log( Level.DEBUG, exception, DEFAULT_EXCEPTION_MESSAGE ); - } - } + /** + * Log exception as {@link Level#DEBUG} + * + * @param exception + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void debug(@Nonnull final Throwable exception) { + if (AELog.isDebugLogEnabled()) { + log(Level.DEBUG, exception, DEFAULT_EXCEPTION_MESSAGE); + } + } - /** - * Log exception as {@link Level#DEBUG} - * - * @see AELog#log(Level, Throwable, String, Object...) - * - * @param exception - * @param message - */ - public static void debug( @Nonnull final Throwable exception, @Nonnull final String message ) - { - if( AELog.isDebugLogEnabled() ) - { - log( Level.DEBUG, exception, message ); - } - } + /** + * Log exception as {@link Level#DEBUG} + * + * @param exception + * @param message + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void debug(@Nonnull final Throwable exception, @Nonnull final String message) { + if (AELog.isDebugLogEnabled()) { + log(Level.DEBUG, exception, message); + } + } - /** - * Use to check for an enabled debug log. - * - * Can be used to prevent the execution of debug logic. - * - * @return true when the debug log is enabled. - */ - public static boolean isDebugLogEnabled() - { - return AEConfig.instance().isFeatureEnabled( AEFeature.DEBUG_LOGGING ); - } + /** + * Use to check for an enabled debug log. + *

+ * Can be used to prevent the execution of debug logic. + * + * @return true when the debug log is enabled. + */ + public static boolean isDebugLogEnabled() { + return AEConfig.instance().isFeatureEnabled(AEFeature.DEBUG_LOGGING); + } - // - // Specialized handlers - // + // + // Specialized handlers + // - /** - * A specialized logging for grinder recipes, can be disabled inside configuration file. - * - * @param message String to be logged - */ - public static void grinder( @Nonnull final String message, final Object... params ) - { - if( AEConfig.instance().isFeatureEnabled( AEFeature.GRINDER_LOGGING ) ) - { - log( Level.DEBUG, "grinder: " + message, params ); - } - } + /** + * A specialized logging for grinder recipes, can be disabled inside configuration file. + * + * @param message String to be logged + */ + public static void grinder(@Nonnull final String message, final Object... params) { + if (AEConfig.instance().isFeatureEnabled(AEFeature.GRINDER_LOGGING)) { + log(Level.DEBUG, "grinder: " + message, params); + } + } - /** - * A specialized logging for mod integration errors, can be disabled inside configuration file. - * - * @param exception - */ - public static void integration( @Nonnull final Throwable exception ) - { - if( AEConfig.instance().isFeatureEnabled( AEFeature.INTEGRATION_LOGGING ) ) - { - debug( exception ); - } - } + /** + * A specialized logging for mod integration errors, can be disabled inside configuration file. + * + * @param exception + */ + public static void integration(@Nonnull final Throwable exception) { + if (AEConfig.instance().isFeatureEnabled(AEFeature.INTEGRATION_LOGGING)) { + debug(exception); + } + } - /** - * Logging of block updates. - * - * Off by default, can be enabled inside the configuration file. - * - * @see AELog#log(Level, String, Object...) - * @param pos - * @param aeBaseTile - */ - public static void blockUpdate( @Nonnull final BlockPos pos, @Nonnull final AEBaseTile aeBaseTile ) - { - if( AEConfig.instance().isFeatureEnabled( AEFeature.UPDATE_LOGGING ) ) - { - info( BLOCK_UPDATE, aeBaseTile.getClass().getName(), pos ); - } - } + /** + * Logging of block updates. + *

+ * Off by default, can be enabled inside the configuration file. + * + * @param pos + * @param aeBaseTile + * @see AELog#log(Level, String, Object...) + */ + public static void blockUpdate(@Nonnull final BlockPos pos, @Nonnull final AEBaseTile aeBaseTile) { + if (AEConfig.instance().isFeatureEnabled(AEFeature.UPDATE_LOGGING)) { + info(BLOCK_UPDATE, aeBaseTile.getClass().getName(), pos); + } + } - /** - * Use to check for an enabled crafting log. - * - * Can be used to prevent the execution of unneeded logic. - * - * @return true when the crafting log is enabled. - */ - public static boolean isCraftingLogEnabled() - { - return AEConfig.instance().isFeatureEnabled( AEFeature.CRAFTING_LOG ); - } + /** + * Use to check for an enabled crafting log. + *

+ * Can be used to prevent the execution of unneeded logic. + * + * @return true when the crafting log is enabled. + */ + public static boolean isCraftingLogEnabled() { + return AEConfig.instance().isFeatureEnabled(AEFeature.CRAFTING_LOG); + } - /** - * Logging for autocrafting. - * - * Off by default, can be enabled inside the configuration file. - * - * @see AELog#log(Level, String, Object...) - * @param message - * @param params - */ - public static void crafting( @Nonnull final String message, final Object... params ) - { - if( AELog.isCraftingLogEnabled() ) - { - log( Level.INFO, message, params ); - } - } + /** + * Logging for autocrafting. + *

+ * Off by default, can be enabled inside the configuration file. + * + * @param message + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void crafting(@Nonnull final String message, final Object... params) { + if (AELog.isCraftingLogEnabled()) { + log(Level.INFO, message, params); + } + } - /** - * Use to check for an enabled crafting debug log. - * - * Can be used to prevent the execution of unneeded logic. - * - * @return true when the crafting debug log is enabled. - */ - public static boolean isCraftingDebugLogEnabled() - { - return AEConfig.instance().isFeatureEnabled( AEFeature.CRAFTING_LOG ) && AEConfig.instance().isFeatureEnabled( AEFeature.DEBUG_LOGGING ); - } + /** + * Use to check for an enabled crafting debug log. + *

+ * Can be used to prevent the execution of unneeded logic. + * + * @return true when the crafting debug log is enabled. + */ + public static boolean isCraftingDebugLogEnabled() { + return AEConfig.instance().isFeatureEnabled(AEFeature.CRAFTING_LOG) && AEConfig.instance().isFeatureEnabled(AEFeature.DEBUG_LOGGING); + } - /** - * Debug logging for autocrafting. - * - * Off by default, can be enabled inside the configuration file. - * - * @see AELog#log(Level, String, Object...) - * @param message - * @param params - */ - public static void craftingDebug( @Nonnull final String message, final Object... params ) - { - if( AELog.isCraftingDebugLogEnabled() ) - { - log( Level.DEBUG, message, params ); - } - } + /** + * Debug logging for autocrafting. + *

+ * Off by default, can be enabled inside the configuration file. + * + * @param message + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void craftingDebug(@Nonnull final String message, final Object... params) { + if (AELog.isCraftingDebugLogEnabled()) { + log(Level.DEBUG, message, params); + } + } } diff --git a/src/main/java/appeng/core/Api.java b/src/main/java/appeng/core/Api.java index 53d7b274d..e5145b1d9 100644 --- a/src/main/java/appeng/core/Api.java +++ b/src/main/java/appeng/core/Api.java @@ -32,67 +32,58 @@ import appeng.core.features.registries.PartModels; import appeng.core.features.registries.RegistryContainer; -public final class Api implements IAppEngApi -{ - public static final Api INSTANCE = new Api(); +public final class Api implements IAppEngApi { + public static final Api INSTANCE = new Api(); - private final ApiPart partHelper; + private final ApiPart partHelper; - // private MovableTileRegistry MovableRegistry = new MovableTileRegistry(); - private final IRegistryContainer registryContainer; - private final IStorageHelper storageHelper; - private final IGridHelper networkHelper; - private final ApiDefinitions definitions; - private final IClientHelper client; + // private MovableTileRegistry MovableRegistry = new MovableTileRegistry(); + private final IRegistryContainer registryContainer; + private final IStorageHelper storageHelper; + private final IGridHelper networkHelper; + private final ApiDefinitions definitions; + private final IClientHelper client; - private Api() - { - this.storageHelper = new ApiStorage(); - this.networkHelper = new ApiGrid(); - this.registryContainer = new RegistryContainer(); - this.partHelper = new ApiPart(); - this.definitions = new ApiDefinitions( (PartModels) this.registryContainer.partModels() ); - this.client = new ApiClientHelper(); - } + private Api() { + this.storageHelper = new ApiStorage(); + this.networkHelper = new ApiGrid(); + this.registryContainer = new RegistryContainer(); + this.partHelper = new ApiPart(); + this.definitions = new ApiDefinitions((PartModels) this.registryContainer.partModels()); + this.client = new ApiClientHelper(); + } - public PartModels getPartModels() - { - return (PartModels) this.registryContainer.partModels(); - } + public PartModels getPartModels() { + return (PartModels) this.registryContainer.partModels(); + } - @Override - public IRegistryContainer registries() - { - return this.registryContainer; - } + @Override + public IRegistryContainer registries() { + return this.registryContainer; + } - @Override - public IStorageHelper storage() - { - return this.storageHelper; - } + @Override + public IStorageHelper storage() { + return this.storageHelper; + } - @Override - public IGridHelper grid() - { - return this.networkHelper; - } + @Override + public IGridHelper grid() { + return this.networkHelper; + } - @Override - public ApiPart partHelper() - { - return this.partHelper; - } + @Override + public ApiPart partHelper() { + return this.partHelper; + } - @Override - public ApiDefinitions definitions() - { - return this.definitions; - } + @Override + public ApiDefinitions definitions() { + return this.definitions; + } - @Override - public IClientHelper client() - { - return this.client; - } + @Override + public IClientHelper client() { + return this.client; + } } diff --git a/src/main/java/appeng/core/ApiDefinitions.java b/src/main/java/appeng/core/ApiDefinitions.java index 62e2ebda1..b6aeb3b48 100644 --- a/src/main/java/appeng/core/ApiDefinitions.java +++ b/src/main/java/appeng/core/ApiDefinitions.java @@ -31,60 +31,53 @@ import appeng.core.features.registries.PartModels; /** * Internal implementation of the definitions for the API */ -public final class ApiDefinitions implements IDefinitions -{ - // TODO : Check if this can be final again after the Register part. - private ApiBlocks blocks; - private ApiItems items; - private final ApiMaterials materials; - private final ApiParts parts; +public final class ApiDefinitions implements IDefinitions { + // TODO : Check if this can be final again after the Register part. + private final ApiBlocks blocks; + private final ApiItems items; + private final ApiMaterials materials; + private final ApiParts parts; - private final FeatureFactory registry = new FeatureFactory(); + private final FeatureFactory registry = new FeatureFactory(); - public ApiDefinitions( final PartModels partModels ) - { - this.blocks = new ApiBlocks( this.registry, partModels ); - this.items = new ApiItems( this.registry ); - this.materials = new ApiMaterials( this.registry ); - this.parts = new ApiParts( this.registry, partModels ); - } - // - // public void addBlocks( final PartModels partModels ) - // { - // this.blocks = new ApiBlocks( registry, partModels ); - // } - // - // public void addItems() - // { - // this.items = new ApiItems( registry ); - // } + public ApiDefinitions(final PartModels partModels) { + this.blocks = new ApiBlocks(this.registry, partModels); + this.items = new ApiItems(this.registry); + this.materials = new ApiMaterials(this.registry); + this.parts = new ApiParts(this.registry, partModels); + } + // + // public void addBlocks( final PartModels partModels ) + // { + // this.blocks = new ApiBlocks( registry, partModels ); + // } + // + // public void addItems() + // { + // this.items = new ApiItems( registry ); + // } - public FeatureFactory getRegistry() - { - return this.registry; - } + public FeatureFactory getRegistry() { + return this.registry; + } - @Override - public ApiBlocks blocks() - { - return this.blocks; - } + @Override + public ApiBlocks blocks() { + return this.blocks; + } - @Override - public ApiItems items() - { - return this.items; - } + @Override + public ApiItems items() { + return this.items; + } - @Override - public ApiMaterials materials() - { - return this.materials; - } + @Override + public ApiMaterials materials() { + return this.materials; + } - @Override - public ApiParts parts() - { - return this.parts; - } + @Override + public ApiParts parts() { + return this.parts; + } } diff --git a/src/main/java/appeng/core/AppEng.java b/src/main/java/appeng/core/AppEng.java index 8983f5228..5c847260e 100644 --- a/src/main/java/appeng/core/AppEng.java +++ b/src/main/java/appeng/core/AppEng.java @@ -19,37 +19,6 @@ package appeng.core; -import java.io.File; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nonnull; - -import appeng.helpers.NonBlockingItems; -import com.google.common.base.Stopwatch; -import com.google.common.collect.Lists; - -import net.minecraft.world.DimensionType; -import net.minecraft.world.biome.Biome; -import net.minecraftforge.common.ForgeVersion; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.common.Mod.EventHandler; -import net.minecraftforge.fml.common.SidedProxy; -import net.minecraftforge.fml.common.event.FMLInitializationEvent; -import net.minecraftforge.fml.common.event.FMLInterModComms; -import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; -import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.fml.common.event.FMLServerAboutToStartEvent; -import net.minecraftforge.fml.common.event.FMLServerStartingEvent; -import net.minecraftforge.fml.common.event.FMLServerStoppedEvent; -import net.minecraftforge.fml.common.event.FMLServerStoppingEvent; -import net.minecraftforge.fml.common.network.NetworkRegistry; - -import team.chisel.ctm.CTM; - import appeng.api.AEApi; import appeng.core.crash.CrashInfo; import appeng.core.crash.IntegrationCrashEnhancement; @@ -59,6 +28,7 @@ import appeng.core.stats.AdvancementTriggers; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.worlddata.WorldData; +import appeng.helpers.NonBlockingItems; import appeng.hooks.TickHandler; import appeng.integration.IntegrationRegistry; import appeng.integration.IntegrationType; @@ -69,214 +39,209 @@ import appeng.services.export.ExportProcess; import appeng.services.export.ForgeExportConfig; import appeng.services.version.VersionCheckerConfig; import appeng.util.Platform; +import com.google.common.base.Stopwatch; +import com.google.common.collect.Lists; +import net.minecraft.world.DimensionType; +import net.minecraft.world.biome.Biome; +import net.minecraftforge.common.ForgeVersion; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.Mod.EventHandler; +import net.minecraftforge.fml.common.SidedProxy; +import net.minecraftforge.fml.common.event.*; +import net.minecraftforge.fml.common.network.NetworkRegistry; +import team.chisel.ctm.CTM; + +import javax.annotation.Nonnull; +import java.io.File; +import java.util.List; +import java.util.concurrent.TimeUnit; -@Mod( modid = AppEng.MOD_ID, acceptedMinecraftVersions = "[1.12.2]", name = AppEng.MOD_NAME, version = AEConfig.VERSION, dependencies = AppEng.MOD_DEPENDENCIES, guiFactory = "appeng.client.gui.config.AEConfigGuiFactory", certificateFingerprint = "dfa4d3ac143316c6f32aa1a1beda1e34d42132e5" ) -public final class AppEng -{ - @SidedProxy( clientSide = "appeng.client.ClientHelper", serverSide = "appeng.server.ServerHelper", modId = AppEng.MOD_ID ) - public static CommonHelper proxy; +@Mod(modid = AppEng.MOD_ID, acceptedMinecraftVersions = "[1.12.2]", name = AppEng.MOD_NAME, version = AEConfig.VERSION, dependencies = AppEng.MOD_DEPENDENCIES, guiFactory = "appeng.client.gui.config.AEConfigGuiFactory", certificateFingerprint = "dfa4d3ac143316c6f32aa1a1beda1e34d42132e5") +public final class AppEng { + @SidedProxy(clientSide = "appeng.client.ClientHelper", serverSide = "appeng.server.ServerHelper", modId = AppEng.MOD_ID) + public static CommonHelper proxy; - public static final String MOD_ID = "appliedenergistics2"; - public static final String MOD_NAME = "Applied Energistics 2"; + public static final String MOD_ID = "appliedenergistics2"; + public static final String MOD_NAME = "Applied Energistics 2"; - public static final String ASSETS = "appliedenergistics2:"; + public static final String ASSETS = "appliedenergistics2:"; - private static final String FORGE_CURRENT_VERSION = ForgeVersion.majorVersion + "." + ForgeVersion.minorVersion + "." + ForgeVersion.revisionVersion + "." + ForgeVersion.buildVersion; - private static final String FORGE_MAX_VERSION = ( ForgeVersion.majorVersion + 1 ) + ".0.0.0"; - public static final String MOD_DEPENDENCIES = "required-after:forge@[" + FORGE_CURRENT_VERSION + "," + FORGE_MAX_VERSION + ");after:ctm@[" + CTM.VERSION + ",);"; + private static final String FORGE_CURRENT_VERSION = ForgeVersion.majorVersion + "." + ForgeVersion.minorVersion + "." + ForgeVersion.revisionVersion + "." + ForgeVersion.buildVersion; + private static final String FORGE_MAX_VERSION = (ForgeVersion.majorVersion + 1) + ".0.0.0"; + public static final String MOD_DEPENDENCIES = "required-after:forge@[" + FORGE_CURRENT_VERSION + "," + FORGE_MAX_VERSION + ");after:ctm@[" + CTM.VERSION + ",);"; - @Nonnull - private static final AppEng INSTANCE = new AppEng(); + @Nonnull + private static final AppEng INSTANCE = new AppEng(); - private final Registration registration; + private final Registration registration; - private File configDirectory; + private File configDirectory; - /** - * determined in pre-init but used in init - */ - private ExportConfig exportConfig; + /** + * determined in pre-init but used in init + */ + private ExportConfig exportConfig; - private AppEng() - { - FMLCommonHandler.instance().registerCrashCallable( new ModCrashEnhancement( CrashInfo.MOD_VERSION ) ); + private AppEng() { + FMLCommonHandler.instance().registerCrashCallable(new ModCrashEnhancement(CrashInfo.MOD_VERSION)); - this.registration = new Registration(); - MinecraftForge.EVENT_BUS.register( this.registration ); - } + this.registration = new Registration(); + MinecraftForge.EVENT_BUS.register(this.registration); + } - @Nonnull - @Mod.InstanceFactory - public static AppEng instance() - { - return INSTANCE; - } + @Nonnull + @Mod.InstanceFactory + public static AppEng instance() { + return INSTANCE; + } - public Biome getStorageBiome() - { - return this.registration.storageBiome; - } + public Biome getStorageBiome() { + return this.registration.storageBiome; + } - public DimensionType getStorageDimensionType() - { - return this.registration.storageDimensionType; - } + public DimensionType getStorageDimensionType() { + return this.registration.storageDimensionType; + } - public int getStorageDimensionID() - { - return this.registration.storageDimensionID; - } + public int getStorageDimensionID() { + return this.registration.storageDimensionID; + } - public AdvancementTriggers getAdvancementTriggers() - { - return this.registration.advancementTriggers; - } + public AdvancementTriggers getAdvancementTriggers() { + return this.registration.advancementTriggers; + } - @EventHandler - private void preInit( final FMLPreInitializationEvent event ) - { - final Stopwatch watch = Stopwatch.createStarted(); - this.configDirectory = new File( event.getModConfigurationDirectory().getPath(), "AppliedEnergistics2" ); + @EventHandler + private void preInit(final FMLPreInitializationEvent event) { + final Stopwatch watch = Stopwatch.createStarted(); + this.configDirectory = new File(event.getModConfigurationDirectory().getPath(), "AppliedEnergistics2"); - final File configFile = new File( this.configDirectory, "AppliedEnergistics2.cfg" ); - final File facadeFile = new File( this.configDirectory, "Facades.cfg" ); - final File versionFile = new File( this.configDirectory, "VersionChecker.cfg" ); - final File recipeFile = new File( this.configDirectory, "CustomRecipes.cfg" ); - final Configuration recipeConfiguration = new Configuration( recipeFile ); + final File configFile = new File(this.configDirectory, "AppliedEnergistics2.cfg"); + final File facadeFile = new File(this.configDirectory, "Facades.cfg"); + final File versionFile = new File(this.configDirectory, "VersionChecker.cfg"); + final File recipeFile = new File(this.configDirectory, "CustomRecipes.cfg"); + final Configuration recipeConfiguration = new Configuration(recipeFile); - AEConfig.init( configFile ); - FacadeConfig.init( facadeFile ); + AEConfig.init(configFile); + FacadeConfig.init(facadeFile); - final VersionCheckerConfig versionCheckerConfig = new VersionCheckerConfig( versionFile ); - this.exportConfig = new ForgeExportConfig( recipeConfiguration ); + final VersionCheckerConfig versionCheckerConfig = new VersionCheckerConfig(versionFile); + this.exportConfig = new ForgeExportConfig(recipeConfiguration); - AELog.info( "Pre Initialization ( started )" ); + AELog.info("Pre Initialization ( started )"); - CreativeTab.init(); - if( AEConfig.instance().isFeatureEnabled( AEFeature.FACADES ) ) - { - CreativeTabFacade.init(); - } + CreativeTab.init(); + if (AEConfig.instance().isFeatureEnabled(AEFeature.FACADES)) { + CreativeTabFacade.init(); + } - for( final IntegrationType type : IntegrationType.values() ) - { - IntegrationRegistry.INSTANCE.add( type ); - } + for (final IntegrationType type : IntegrationType.values()) { + IntegrationRegistry.INSTANCE.add(type); + } - this.registration.preInitialize( event ); + this.registration.preInitialize(event); - if( Platform.isClient() ) - { - AppEng.proxy.preinit(); - } + if (Platform.isClient()) { + AppEng.proxy.preinit(); + } - IntegrationRegistry.INSTANCE.preInit(); + IntegrationRegistry.INSTANCE.preInit(); - if( versionCheckerConfig.isVersionCheckingEnabled() ) - { - final VersionChecker versionChecker = new VersionChecker( versionCheckerConfig ); - final Thread versionCheckerThread = new Thread( versionChecker ); + if (versionCheckerConfig.isVersionCheckingEnabled()) { + final VersionChecker versionChecker = new VersionChecker(versionCheckerConfig); + final Thread versionCheckerThread = new Thread(versionChecker); - this.startService( "AE2 VersionChecker", versionCheckerThread ); - } + this.startService("AE2 VersionChecker", versionCheckerThread); + } - AELog.info( "Pre Initialization ( ended after " + watch.elapsed( TimeUnit.MILLISECONDS ) + "ms )" ); + AELog.info("Pre Initialization ( ended after " + watch.elapsed(TimeUnit.MILLISECONDS) + "ms )"); - // Instantiate all Plugins - List injectables = Lists.newArrayList( AEApi.instance() ); - new PluginLoader().loadPlugins( injectables, event.getAsmData() ); - } + // Instantiate all Plugins + List injectables = Lists.newArrayList(AEApi.instance()); + new PluginLoader().loadPlugins(injectables, event.getAsmData()); + } - private void startService( final String serviceName, final Thread thread ) - { - thread.setName( serviceName ); - thread.setPriority( Thread.MIN_PRIORITY ); + private void startService(final String serviceName, final Thread thread) { + thread.setName(serviceName); + thread.setPriority(Thread.MIN_PRIORITY); - AELog.info( "Starting " + serviceName ); - thread.start(); - } + AELog.info("Starting " + serviceName); + thread.start(); + } - @EventHandler - private void init( final FMLInitializationEvent event ) - { - final Stopwatch start = Stopwatch.createStarted(); - AELog.info( "Initialization ( started )" ); + @EventHandler + private void init(final FMLInitializationEvent event) { + final Stopwatch start = Stopwatch.createStarted(); + AELog.info("Initialization ( started )"); - AppEng.proxy.init(); + AppEng.proxy.init(); - if( this.exportConfig.isExportingItemNamesEnabled() ) - { - if( FMLCommonHandler.instance().getSide().isClient() ) - { - final ExportProcess process = new ExportProcess( this.configDirectory, this.exportConfig ); - final Thread exportProcessThread = new Thread( process ); + if (this.exportConfig.isExportingItemNamesEnabled()) { + if (FMLCommonHandler.instance().getSide().isClient()) { + final ExportProcess process = new ExportProcess(this.configDirectory, this.exportConfig); + final Thread exportProcessThread = new Thread(process); - this.startService( "AE2 CSV Export", exportProcessThread ); - } - else - { - AELog.info( "Disabling item.csv export for custom recipes, since creative tab information is only available on the client." ); - } - } + this.startService("AE2 CSV Export", exportProcessThread); + } else { + AELog.info("Disabling item.csv export for custom recipes, since creative tab information is only available on the client."); + } + } - this.registration.initialize( event, this.configDirectory ); - IntegrationRegistry.INSTANCE.init(); + this.registration.initialize(event, this.configDirectory); + IntegrationRegistry.INSTANCE.init(); - AELog.info( "Initialization ( ended after " + start.elapsed( TimeUnit.MILLISECONDS ) + "ms )" ); - } + AELog.info("Initialization ( ended after " + start.elapsed(TimeUnit.MILLISECONDS) + "ms )"); + } - @EventHandler - private void postInit( final FMLPostInitializationEvent event ) - { - final Stopwatch start = Stopwatch.createStarted(); - AELog.info( "Post Initialization ( started )" ); + @EventHandler + private void postInit(final FMLPostInitializationEvent event) { + final Stopwatch start = Stopwatch.createStarted(); + AELog.info("Post Initialization ( started )"); - this.registration.postInit( event ); - IntegrationRegistry.INSTANCE.postInit(); - FMLCommonHandler.instance().registerCrashCallable( new IntegrationCrashEnhancement() ); + this.registration.postInit(event); + IntegrationRegistry.INSTANCE.postInit(); + FMLCommonHandler.instance().registerCrashCallable(new IntegrationCrashEnhancement()); - AppEng.proxy.postInit(); - AEConfig.instance().save(); + AppEng.proxy.postInit(); + AEConfig.instance().save(); - NonBlockingItems.INSTANCE.init(); + NonBlockingItems.INSTANCE.init(); - NetworkRegistry.INSTANCE.registerGuiHandler( this, GuiBridge.GUI_Handler ); - NetworkHandler.init( "AE2" ); + NetworkRegistry.INSTANCE.registerGuiHandler(this, GuiBridge.GUI_Handler); + NetworkHandler.init("AE2"); - AELog.info( "Post Initialization ( ended after " + start.elapsed( TimeUnit.MILLISECONDS ) + "ms )" ); - } + AELog.info("Post Initialization ( ended after " + start.elapsed(TimeUnit.MILLISECONDS) + "ms )"); + } - @EventHandler - private void handleIMCEvent( final FMLInterModComms.IMCEvent event ) - { - final IMCHandler imcHandler = new IMCHandler(); + @EventHandler + private void handleIMCEvent(final FMLInterModComms.IMCEvent event) { + final IMCHandler imcHandler = new IMCHandler(); - imcHandler.handleIMCEvent( event ); - } + imcHandler.handleIMCEvent(event); + } - @EventHandler - private void serverAboutToStart( final FMLServerAboutToStartEvent evt ) - { - WorldData.onServerAboutToStart( evt.getServer() ); - } + @EventHandler + private void serverAboutToStart(final FMLServerAboutToStartEvent evt) { + WorldData.onServerAboutToStart(evt.getServer()); + } - @EventHandler - private void serverStopping( final FMLServerStoppingEvent event ) - { - WorldData.instance().onServerStopping(); - } + @EventHandler + private void serverStopping(final FMLServerStoppingEvent event) { + WorldData.instance().onServerStopping(); + } - @EventHandler - private void serverStopped( final FMLServerStoppedEvent event ) - { - WorldData.instance().onServerStoppped(); - TickHandler.INSTANCE.shutdown(); - } + @EventHandler + private void serverStopped(final FMLServerStoppedEvent event) { + WorldData.instance().onServerStoppped(); + TickHandler.INSTANCE.shutdown(); + } - @EventHandler - private void serverStarting( final FMLServerStartingEvent evt ) - { - evt.registerServerCommand( new AECommand( evt.getServer() ) ); - } + @EventHandler + private void serverStarting(final FMLServerStartingEvent evt) { + evt.registerServerCommand(new AECommand(evt.getServer())); + } } diff --git a/src/main/java/appeng/core/CommonHelper.java b/src/main/java/appeng/core/CommonHelper.java index bb0322af9..0cee1d43a 100644 --- a/src/main/java/appeng/core/CommonHelper.java +++ b/src/main/java/appeng/core/CommonHelper.java @@ -19,54 +19,51 @@ package appeng.core; -import java.util.List; -import java.util.Random; - -import javax.annotation.Nonnull; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.world.World; - import appeng.api.parts.CableRenderMode; import appeng.block.AEBaseBlock; import appeng.client.ActionKey; import appeng.client.EffectType; import appeng.core.sync.AppEngPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.world.World; + +import javax.annotation.Nonnull; +import java.util.List; +import java.util.Random; -public abstract class CommonHelper -{ +public abstract class CommonHelper { - public abstract void preinit(); + public abstract void preinit(); - public abstract void init(); + public abstract void init(); - public abstract World getWorld(); + public abstract World getWorld(); - public abstract void bindTileEntitySpecialRenderer( Class tile, AEBaseBlock blk ); + public abstract void bindTileEntitySpecialRenderer(Class tile, AEBaseBlock blk); - public abstract List getPlayers(); + public abstract List getPlayers(); - public abstract void sendToAllNearExcept( EntityPlayer p, double x, double y, double z, double dist, World w, AppEngPacket packet ); + public abstract void sendToAllNearExcept(EntityPlayer p, double x, double y, double z, double dist, World w, AppEngPacket packet); - public abstract void spawnEffect( EffectType effect, World world, double posX, double posY, double posZ, Object extra ); + public abstract void spawnEffect(EffectType effect, World world, double posX, double posY, double posZ, Object extra); - public abstract boolean shouldAddParticles( Random r ); + public abstract boolean shouldAddParticles(Random r); - public abstract RayTraceResult getRTR(); + public abstract RayTraceResult getRTR(); - public abstract void postInit(); + public abstract void postInit(); - public abstract CableRenderMode getRenderMode(); + public abstract CableRenderMode getRenderMode(); - public abstract void triggerUpdates(); + public abstract void triggerUpdates(); - public abstract void updateRenderMode( EntityPlayer player ); + public abstract void updateRenderMode(EntityPlayer player); - public abstract boolean isKeyPressed( @Nonnull final ActionKey key ); + public abstract boolean isKeyPressed(@Nonnull final ActionKey key); - public abstract boolean isActionKey( @Nonnull final ActionKey key, int pressedKeyCode ); + public abstract boolean isActionKey(@Nonnull final ActionKey key, int pressedKeyCode); } diff --git a/src/main/java/appeng/core/CreativeTab.java b/src/main/java/appeng/core/CreativeTab.java index 34fd4a036..f3cc61ca8 100644 --- a/src/main/java/appeng/core/CreativeTab.java +++ b/src/main/java/appeng/core/CreativeTab.java @@ -19,63 +19,50 @@ package appeng.core; -import java.util.Optional; - +import appeng.api.AEApi; +import appeng.api.definitions.*; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; -import appeng.api.AEApi; -import appeng.api.definitions.IBlocks; -import appeng.api.definitions.IDefinitions; -import appeng.api.definitions.IItemDefinition; -import appeng.api.definitions.IItems; -import appeng.api.definitions.IMaterials; +import java.util.Optional; -public final class CreativeTab extends CreativeTabs -{ - public static CreativeTab instance = null; +public final class CreativeTab extends CreativeTabs { + public static CreativeTab instance = null; - public CreativeTab() - { - super( "appliedenergistics2" ); - } + public CreativeTab() { + super("appliedenergistics2"); + } - static void init() - { - instance = new CreativeTab(); - } + static void init() { + instance = new CreativeTab(); + } - @Override - public ItemStack getTabIconItem() - { - return this.getIconItemStack(); - } + @Override + public ItemStack getTabIconItem() { + return this.getIconItemStack(); + } - @Override - public ItemStack getIconItemStack() - { - final IDefinitions definitions = AEApi.instance().definitions(); - final IBlocks blocks = definitions.blocks(); - final IItems items = definitions.items(); - final IMaterials materials = definitions.materials(); + @Override + public ItemStack getIconItemStack() { + final IDefinitions definitions = AEApi.instance().definitions(); + final IBlocks blocks = definitions.blocks(); + final IItems items = definitions.items(); + final IMaterials materials = definitions.materials(); - return this.findFirst( blocks.controller(), blocks.chest(), blocks.cellWorkbench(), blocks.fluixBlock(), items.cell1k(), items.networkTool(), - materials.fluixCrystal(), materials.certusQuartzCrystal(), materials.skyDust() ); - } + return this.findFirst(blocks.controller(), blocks.chest(), blocks.cellWorkbench(), blocks.fluixBlock(), items.cell1k(), items.networkTool(), + materials.fluixCrystal(), materials.certusQuartzCrystal(), materials.skyDust()); + } - private ItemStack findFirst( final IItemDefinition... choices ) - { - for( final IItemDefinition definition : choices ) - { - Optional maybeIs = definition.maybeStack( 1 ); - if( maybeIs.isPresent() ) - { - return maybeIs.get(); - } - } + private ItemStack findFirst(final IItemDefinition... choices) { + for (final IItemDefinition definition : choices) { + Optional maybeIs = definition.maybeStack(1); + if (maybeIs.isPresent()) { + return maybeIs.get(); + } + } - return new ItemStack( Blocks.CHEST ); - } + return new ItemStack(Blocks.CHEST); + } } \ No newline at end of file diff --git a/src/main/java/appeng/core/CreativeTabFacade.java b/src/main/java/appeng/core/CreativeTabFacade.java index a8dd45fec..44f8933ae 100644 --- a/src/main/java/appeng/core/CreativeTabFacade.java +++ b/src/main/java/appeng/core/CreativeTabFacade.java @@ -19,47 +19,40 @@ package appeng.core; -import java.util.Optional; - +import appeng.api.AEApi; +import appeng.items.parts.ItemFacade; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import appeng.api.AEApi; -import appeng.items.parts.ItemFacade; +import java.util.Optional; -public final class CreativeTabFacade extends CreativeTabs -{ +public final class CreativeTabFacade extends CreativeTabs { - public static CreativeTabFacade instance = null; + public static CreativeTabFacade instance = null; - public CreativeTabFacade() - { - super( "appliedenergistics2.facades" ); - } + public CreativeTabFacade() { + super("appliedenergistics2.facades"); + } - static void init() - { - instance = new CreativeTabFacade(); - } + static void init() { + instance = new CreativeTabFacade(); + } - @Override - public ItemStack getTabIconItem() - { - return this.getIconItemStack(); - } + @Override + public ItemStack getTabIconItem() { + return this.getIconItemStack(); + } - @Override - public ItemStack getIconItemStack() - { - final Optional maybeFacade = AEApi.instance().definitions().items().facade().maybeItem(); - if( maybeFacade.isPresent() ) - { - return ( (ItemFacade) maybeFacade.get() ).getCreativeTabIcon(); - } + @Override + public ItemStack getIconItemStack() { + final Optional maybeFacade = AEApi.instance().definitions().items().facade().maybeItem(); + if (maybeFacade.isPresent()) { + return ((ItemFacade) maybeFacade.get()).getCreativeTabIcon(); + } - return new ItemStack( Blocks.PLANKS ); - } + return new ItemStack(Blocks.PLANKS); + } } \ No newline at end of file diff --git a/src/main/java/appeng/core/FacadeConfig.java b/src/main/java/appeng/core/FacadeConfig.java index fe1212e83..308ce9ea6 100644 --- a/src/main/java/appeng/core/FacadeConfig.java +++ b/src/main/java/appeng/core/FacadeConfig.java @@ -19,11 +19,8 @@ package appeng.core; -import java.io.File; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - +import it.unimi.dsi.fastutil.objects.Object2IntArrayMap; +import it.unimi.dsi.fastutil.objects.Object2IntMap; import net.minecraft.block.Block; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.config.ConfigCategory; @@ -31,134 +28,121 @@ import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import net.minecraftforge.common.config.Property.Type; -import it.unimi.dsi.fastutil.objects.Object2IntArrayMap; -import it.unimi.dsi.fastutil.objects.Object2IntMap; +import java.io.File; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; -public class FacadeConfig -{ +public class FacadeConfig { - private static final String CONFIG_VERSION = "1"; - private static final String CONFIG_COMMON_KEY = "common"; - private static final String CONFIG_COMMON_COMMENT = "Settings applied to all facades.\n\n" // - + "By default full blocks with no tile entity and a model do not need whitelisting.\n"// - + "This will only be read once during client startup."; - private static final String CONFIG_COMMON_ALLOW_TILEENTITIES_KEY = "allowTileEntityFacades"; - private static final String CONFIG_COMMON_ALLOW_TILEENTITIES_COMMENT = "Unsupported: Allows whitelisting TileEntity as facades. Could work, have render issues, or corrupt your world. USE AT YOUR OWN RISK."; - private static final String CONFIG_FACADES_KEY = "facades"; - private static final String CONFIG_FACADES_COMMENT = "A way to explicitly handle certain blocks as facades.\n\n" // - + "Blocks can be added by their resource location under the following rules.\n" // - + " - One category per domain like minecraft or appliedenergistics2\n" // - + " - One key per id. E.g. glass in case of minecraft:glass\n" // - + " - An integer value ranging from 0 to 16 representing the metadata 0-15 and 16 as wildcard for all" // - + " - Multiple entries for the same id but different metadata are possible when needed"; + private static final String CONFIG_VERSION = "1"; + private static final String CONFIG_COMMON_KEY = "common"; + private static final String CONFIG_COMMON_COMMENT = "Settings applied to all facades.\n\n" // + + "By default full blocks with no tile entity and a model do not need whitelisting.\n"// + + "This will only be read once during client startup."; + private static final String CONFIG_COMMON_ALLOW_TILEENTITIES_KEY = "allowTileEntityFacades"; + private static final String CONFIG_COMMON_ALLOW_TILEENTITIES_COMMENT = "Unsupported: Allows whitelisting TileEntity as facades. Could work, have render issues, or corrupt your world. USE AT YOUR OWN RISK."; + private static final String CONFIG_FACADES_KEY = "facades"; + private static final String CONFIG_FACADES_COMMENT = "A way to explicitly handle certain blocks as facades.\n\n" // + + "Blocks can be added by their resource location under the following rules.\n" // + + " - One category per domain like minecraft or appliedenergistics2\n" // + + " - One key per id. E.g. glass in case of minecraft:glass\n" // + + " - An integer value ranging from 0 to 16 representing the metadata 0-15 and 16 as wildcard for all" // + + " - Multiple entries for the same id but different metadata are possible when needed"; - private static FacadeConfig instance; + private static FacadeConfig instance; - private final boolean allowTileEntityFacades; - private final Object2IntMap whiteList; + private final boolean allowTileEntityFacades; + private final Object2IntMap whiteList; - private FacadeConfig( boolean allowTileEntityFacades, Object2IntMap whiteList ) - { - this.allowTileEntityFacades = allowTileEntityFacades; - this.whiteList = whiteList; - } + private FacadeConfig(boolean allowTileEntityFacades, Object2IntMap whiteList) { + this.allowTileEntityFacades = allowTileEntityFacades; + this.whiteList = whiteList; + } - /** - * Creates a custom confuration based on a {@link Configuration}, but ultimately throws it away after reading it - * once to save a couple MB of memory. - * - * @param configFile - */ - public static void init( final File configFile ) - { - final Configuration configurartion = migrate( new Configuration( configFile, CONFIG_VERSION ) ); + /** + * Creates a custom confuration based on a {@link Configuration}, but ultimately throws it away after reading it + * once to save a couple MB of memory. + * + * @param configFile + */ + public static void init(final File configFile) { + final Configuration configurartion = migrate(new Configuration(configFile, CONFIG_VERSION)); - final boolean allowTileEntityFacades = configurartion - .get( CONFIG_COMMON_KEY, CONFIG_COMMON_ALLOW_TILEENTITIES_KEY, false, CONFIG_COMMON_ALLOW_TILEENTITIES_COMMENT ) - .setRequiresMcRestart( true ) - .setShowInGui( false ) - .getBoolean(); + final boolean allowTileEntityFacades = configurartion + .get(CONFIG_COMMON_KEY, CONFIG_COMMON_ALLOW_TILEENTITIES_KEY, false, CONFIG_COMMON_ALLOW_TILEENTITIES_COMMENT) + .setRequiresMcRestart(true) + .setShowInGui(false) + .getBoolean(); - final Object2IntMap configWhiteList = new Object2IntArrayMap<>(); + final Object2IntMap configWhiteList = new Object2IntArrayMap<>(); - final Set whitelist = configurartion.getCategory( CONFIG_FACADES_KEY ).getChildren(); - for( ConfigCategory configCategory : whitelist ) - { - final String domain = configCategory.getName(); - final Map values = configCategory.getValues(); + final Set whitelist = configurartion.getCategory(CONFIG_FACADES_KEY).getChildren(); + for (ConfigCategory configCategory : whitelist) { + final String domain = configCategory.getName(); + final Map values = configCategory.getValues(); - for( Entry entry : values.entrySet() ) - { - configWhiteList.put( new ResourceLocation( domain, entry.getKey() ), entry.getValue().getInt() ); - } - } + for (Entry entry : values.entrySet()) { + configWhiteList.put(new ResourceLocation(domain, entry.getKey()), entry.getValue().getInt()); + } + } - if( configurartion.hasChanged() ) - { - configurartion.save(); - } + if (configurartion.hasChanged()) { + configurartion.save(); + } - instance = new FacadeConfig( allowTileEntityFacades, configWhiteList ); - } + instance = new FacadeConfig(allowTileEntityFacades, configWhiteList); + } - private static Configuration migrate( Configuration configurartion ) - { - // Clear pre rv6 configs. - if( configurartion.getLoadedConfigVersion() == null ) - { - for( String category : configurartion.getCategoryNames() ) - { - final ConfigCategory c = configurartion.getCategory( category ); - configurartion.removeCategory( c ); - } - } + private static Configuration migrate(Configuration configurartion) { + // Clear pre rv6 configs. + if (configurartion.getLoadedConfigVersion() == null) { + for (String category : configurartion.getCategoryNames()) { + final ConfigCategory c = configurartion.getCategory(category); + configurartion.removeCategory(c); + } + } - // Create general category, if missing - if( !configurartion.hasCategory( CONFIG_COMMON_KEY ) ) - { - configurartion.getCategory( CONFIG_COMMON_KEY ).setComment( CONFIG_COMMON_COMMENT ); - } + // Create general category, if missing + if (!configurartion.hasCategory(CONFIG_COMMON_KEY)) { + configurartion.getCategory(CONFIG_COMMON_KEY).setComment(CONFIG_COMMON_COMMENT); + } - // Create whitelist, if missing - if( !configurartion.hasCategory( CONFIG_FACADES_KEY ) ) - { - final ConfigCategory category = configurartion.getCategory( CONFIG_FACADES_KEY ); - category.setComment( CONFIG_FACADES_COMMENT ); + // Create whitelist, if missing + if (!configurartion.hasCategory(CONFIG_FACADES_KEY)) { + final ConfigCategory category = configurartion.getCategory(CONFIG_FACADES_KEY); + category.setComment(CONFIG_FACADES_COMMENT); - // Whitelist some vanilla blocks like glass - final ConfigCategory minecraft = new ConfigCategory( "minecraft", category ); - minecraft.put( "glass", new Property( "glass", "16", Type.INTEGER ) ); - minecraft.put( "stained_glass", new Property( "stained_glass", "16", Type.INTEGER ) ); + // Whitelist some vanilla blocks like glass + final ConfigCategory minecraft = new ConfigCategory("minecraft", category); + minecraft.put("glass", new Property("glass", "16", Type.INTEGER)); + minecraft.put("stained_glass", new Property("stained_glass", "16", Type.INTEGER)); - // Whitelist some AE2 blocks like quartz glass - final ConfigCategory appliedenergistics = new ConfigCategory( "appliedenergistics2", category ); - appliedenergistics.put( "quartz_glass", new Property( "quartz_glass", "16", Type.INTEGER ) ); - appliedenergistics.put( "quartz_vibrant_glass", new Property( "quartz_vibrant_glass", "16", Type.INTEGER ) ); - } + // Whitelist some AE2 blocks like quartz glass + final ConfigCategory appliedenergistics = new ConfigCategory("appliedenergistics2", category); + appliedenergistics.put("quartz_glass", new Property("quartz_glass", "16", Type.INTEGER)); + appliedenergistics.put("quartz_vibrant_glass", new Property("quartz_vibrant_glass", "16", Type.INTEGER)); + } - return configurartion; - } + return configurartion; + } - public static FacadeConfig instance() - { - return instance; - } + public static FacadeConfig instance() { + return instance; + } - public boolean allowTileEntityFacades() - { - return this.allowTileEntityFacades; - } + public boolean allowTileEntityFacades() { + return this.allowTileEntityFacades; + } - public boolean isWhiteListed( final Block block, final int metadata ) - { - final Integer entry = this.whiteList.get( block.getRegistryName() ); + public boolean isWhiteListed(final Block block, final int metadata) { + final Integer entry = this.whiteList.get(block.getRegistryName()); - if( entry != null ) - { - return entry == metadata || entry == 16; - } + if (entry != null) { + return entry == metadata || entry == 16; + } - return false; - } + return false; + } } diff --git a/src/main/java/appeng/core/IMCHandler.java b/src/main/java/appeng/core/IMCHandler.java index 592da5cae..9294fd37d 100644 --- a/src/main/java/appeng/core/IMCHandler.java +++ b/src/main/java/appeng/core/IMCHandler.java @@ -19,20 +19,15 @@ package appeng.core; +import appeng.api.config.TunnelType; +import appeng.core.api.IIMCProcessor; +import appeng.core.api.imc.*; +import net.minecraftforge.fml.common.event.FMLInterModComms; + import java.util.HashMap; import java.util.Locale; import java.util.Map; -import net.minecraftforge.fml.common.event.FMLInterModComms; - -import appeng.api.config.TunnelType; -import appeng.core.api.IIMCProcessor; -import appeng.core.api.imc.IMCBlackListSpatial; -import appeng.core.api.imc.IMCGrinder; -import appeng.core.api.imc.IMCMatterCannon; -import appeng.core.api.imc.IMCP2PAttunement; -import appeng.core.api.imc.IMCSpatial; - /** * Handles the delegation of the corresponding IMC messages to the suitable IMC processors @@ -41,64 +36,53 @@ import appeng.core.api.imc.IMCSpatial; * @version rv3 - 10.08.2015 * @since rv1 */ -public class IMCHandler -{ - private static final int INITIAL_PROCESSORS_CAPACITY = 20; +public class IMCHandler { + private static final int INITIAL_PROCESSORS_CAPACITY = 20; - /** - * Contains the processors, - * - * is mutable, but write access only by the constructor - */ - private final Map processors; + /** + * Contains the processors, + *

+ * is mutable, but write access only by the constructor + */ + private final Map processors; - /** - * Initializes the processors - */ - public IMCHandler() - { - this.processors = new HashMap<>( INITIAL_PROCESSORS_CAPACITY ); + /** + * Initializes the processors + */ + public IMCHandler() { + this.processors = new HashMap<>(INITIAL_PROCESSORS_CAPACITY); - this.processors.put( "blacklist-block-spatial", new IMCBlackListSpatial() ); - this.processors.put( "whitelist-spatial", new IMCSpatial() ); - this.processors.put( "add-grindable", new IMCGrinder() ); - this.processors.put( "add-mattercannon-ammo", new IMCMatterCannon() ); + this.processors.put("blacklist-block-spatial", new IMCBlackListSpatial()); + this.processors.put("whitelist-spatial", new IMCSpatial()); + this.processors.put("add-grindable", new IMCGrinder()); + this.processors.put("add-mattercannon-ammo", new IMCMatterCannon()); - for( final TunnelType type : TunnelType.values() ) - { - this.processors.put( "add-p2p-attunement-" + type.name().replace( '_', '-' ).toLowerCase( Locale.ENGLISH ), new IMCP2PAttunement() ); - } - } + for (final TunnelType type : TunnelType.values()) { + this.processors.put("add-p2p-attunement-" + type.name().replace('_', '-').toLowerCase(Locale.ENGLISH), new IMCP2PAttunement()); + } + } - /** - * Tries to find every message matching the internal IMC keys. When found the corresponding handler will process the - * attached message. - * - * @param event Event carrying the identifier and message for the handlers - */ - void handleIMCEvent( final FMLInterModComms.IMCEvent event ) - { - for( final FMLInterModComms.IMCMessage message : event.getMessages() ) - { - final String key = message.key; + /** + * Tries to find every message matching the internal IMC keys. When found the corresponding handler will process the + * attached message. + * + * @param event Event carrying the identifier and message for the handlers + */ + void handleIMCEvent(final FMLInterModComms.IMCEvent event) { + for (final FMLInterModComms.IMCMessage message : event.getMessages()) { + final String key = message.key; - try - { - final IIMCProcessor handler = this.processors.get( key ); - if( handler != null ) - { - handler.process( message ); - } - else - { - throw new IllegalStateException( "Invalid IMC Called: " + key ); - } - } - catch( final Exception t ) - { - AELog.warn( "Problem detected when processing IMC " + key + " from " + message.getSender() ); - AELog.debug( t ); - } - } - } + try { + final IIMCProcessor handler = this.processors.get(key); + if (handler != null) { + handler.process(message); + } else { + throw new IllegalStateException("Invalid IMC Called: " + key); + } + } catch (final Exception t) { + AELog.warn("Problem detected when processing IMC " + key + " from " + message.getSender()); + AELog.debug(t); + } + } + } } diff --git a/src/main/java/appeng/core/PluginLoader.java b/src/main/java/appeng/core/PluginLoader.java index 916adb710..4a0a38a9e 100644 --- a/src/main/java/appeng/core/PluginLoader.java +++ b/src/main/java/appeng/core/PluginLoader.java @@ -19,6 +19,11 @@ package appeng.core; +import appeng.api.AEInjectable; +import appeng.api.AEPlugin; +import com.google.common.collect.ImmutableMap; +import net.minecraftforge.fml.common.discovery.ASMDataTable; + import java.lang.reflect.Constructor; import java.util.Collection; import java.util.HashSet; @@ -26,136 +31,105 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import com.google.common.collect.ImmutableMap; - -import net.minecraftforge.fml.common.discovery.ASMDataTable; - -import appeng.api.AEInjectable; -import appeng.api.AEPlugin; - /** * Loads AE plugins on startup and provides them with access to various components of the AE API. */ -class PluginLoader -{ +class PluginLoader { - public void loadPlugins( Collection injectables, ASMDataTable asmDataTable ) - { - Map, Object> injectableMap = mapInjectables( injectables ); - findAndInstantiatePlugins( asmDataTable, injectableMap ); - } + public void loadPlugins(Collection injectables, ASMDataTable asmDataTable) { + Map, Object> injectableMap = mapInjectables(injectables); + findAndInstantiatePlugins(asmDataTable, injectableMap); + } - private static void findAndInstantiatePlugins( ASMDataTable dataTable, Map, Object> injectableMap ) - { - Set allAnnotated = dataTable.getAll( AEPlugin.class.getCanonicalName() ); + private static void findAndInstantiatePlugins(ASMDataTable dataTable, Map, Object> injectableMap) { + Set allAnnotated = dataTable.getAll(AEPlugin.class.getCanonicalName()); - for( ASMDataTable.ASMData candidate : allAnnotated ) - { + for (ASMDataTable.ASMData candidate : allAnnotated) { - Class aClass; - try - { - aClass = Class.forName( candidate.getClassName() ); - } - catch( ClassNotFoundException e ) - { - AELog.error( e, "Couldn't find annotated AE plugin class " + candidate.getClassName() ); - throw new RuntimeException( "Couldn't find annotated AE plugin class " + candidate.getClassName(), e ); - } + Class aClass; + try { + aClass = Class.forName(candidate.getClassName()); + } catch (ClassNotFoundException e) { + AELog.error(e, "Couldn't find annotated AE plugin class " + candidate.getClassName()); + throw new RuntimeException("Couldn't find annotated AE plugin class " + candidate.getClassName(), e); + } - // Try instantiating the plugin - try - { - Object plugin = instantiatePlugin( aClass, injectableMap ); - AELog.info( "Loaded AE2 Plugin {}", plugin.getClass() ); - } - catch( Exception e ) - { - AELog.error( e, "Unable to instantiate AE plugin " + candidate.getClassName() ); - throw new RuntimeException( "Unable to instantiate AE plugin " + candidate.getClassName(), e ); - } - } - } + // Try instantiating the plugin + try { + Object plugin = instantiatePlugin(aClass, injectableMap); + AELog.info("Loaded AE2 Plugin {}", plugin.getClass()); + } catch (Exception e) { + AELog.error(e, "Unable to instantiate AE plugin " + candidate.getClassName()); + throw new RuntimeException("Unable to instantiate AE plugin " + candidate.getClassName(), e); + } + } + } - private static Object instantiatePlugin( Class aClass, Map, Object> injectableMap ) throws Exception - { + private static Object instantiatePlugin(Class aClass, Map, Object> injectableMap) throws Exception { - Constructor[] constructors = aClass.getDeclaredConstructors(); + Constructor[] constructors = aClass.getDeclaredConstructors(); - if( constructors.length == 0 ) - { - // This is the default no-arg constructor, although it seems pointless to instantiate anything but not take - // any AE dependencies as parameters - return aClass.newInstance(); - } - else if( constructors.length != 1 ) - { - throw new IllegalArgumentException( "Expected a single constructor, but found: " + constructors.length ); - } + if (constructors.length == 0) { + // This is the default no-arg constructor, although it seems pointless to instantiate anything but not take + // any AE dependencies as parameters + return aClass.newInstance(); + } else if (constructors.length != 1) { + throw new IllegalArgumentException("Expected a single constructor, but found: " + constructors.length); + } - Constructor constructor = constructors[0]; - constructor.setAccessible( true ); + Constructor constructor = constructors[0]; + constructor.setAccessible(true); - Object[] args = findInjectables( constructor, injectableMap ); + Object[] args = findInjectables(constructor, injectableMap); - return constructor.newInstance( args ); - } + return constructor.newInstance(args); + } - private static Object[] findInjectables( Constructor constructor, Map, Object> injectableMap ) - { + private static Object[] findInjectables(Constructor constructor, Map, Object> injectableMap) { - Class[] types = constructor.getParameterTypes(); - Object[] args = new Object[types.length]; + Class[] types = constructor.getParameterTypes(); + Object[] args = new Object[types.length]; - for( int i = 0; i < types.length; i++ ) - { - args[i] = injectableMap.get( types[i] ); - if( args[i] == null ) - { - throw new IllegalArgumentException( "Constructor has parameter of type " + types[i] + " which is not an injectable type." + " Please see the documentation for @AEPlugin." ); - } - } + for (int i = 0; i < types.length; i++) { + args[i] = injectableMap.get(types[i]); + if (args[i] == null) { + throw new IllegalArgumentException("Constructor has parameter of type " + types[i] + " which is not an injectable type." + " Please see the documentation for @AEPlugin."); + } + } - return args; - } + return args; + } - private static Map, Object> mapInjectables( Collection injectables ) - { - ImmutableMap.Builder, Object> builder = ImmutableMap.builder(); + private static Map, Object> mapInjectables(Collection injectables) { + ImmutableMap.Builder, Object> builder = ImmutableMap.builder(); - for( Object injectable : injectables ) - { - // Get all super-interfaces that were annotated with @AEInjectable - Set> injectableIfs = getInjectableInterfaces( injectable.getClass() ); - for( Class injectableIf : injectableIfs ) - { - builder.put( injectableIf, injectable ); - } - } + for (Object injectable : injectables) { + // Get all super-interfaces that were annotated with @AEInjectable + Set> injectableIfs = getInjectableInterfaces(injectable.getClass()); + for (Class injectableIf : injectableIfs) { + builder.put(injectableIf, injectable); + } + } - return builder.build(); - } + return builder.build(); + } - private static Set> getInjectableInterfaces( Class aClass ) - { - Set> hierarchy = new HashSet<>(); - getFullHierarchy( aClass, hierarchy ); + private static Set> getInjectableInterfaces(Class aClass) { + Set> hierarchy = new HashSet<>(); + getFullHierarchy(aClass, hierarchy); - return hierarchy.stream().filter( c -> c.getAnnotation( AEInjectable.class ) != null ).collect( Collectors.toSet() ); - } + return hierarchy.stream().filter(c -> c.getAnnotation(AEInjectable.class) != null).collect(Collectors.toSet()); + } - // Recursively gather all superclasses and superinterfaces of the given class and put them into the given collection - private static void getFullHierarchy( Class aClass, Set> classes ) - { - classes.add( aClass ); - for( Class anIf : aClass.getInterfaces() ) - { - getFullHierarchy( anIf, classes ); - } - if( aClass.getSuperclass() != null ) - { - getFullHierarchy( aClass.getSuperclass(), classes ); - } - } + // Recursively gather all superclasses and superinterfaces of the given class and put them into the given collection + private static void getFullHierarchy(Class aClass, Set> classes) { + classes.add(aClass); + for (Class anIf : aClass.getInterfaces()) { + getFullHierarchy(anIf, classes); + } + if (aClass.getSuperclass() != null) { + getFullHierarchy(aClass.getSuperclass(), classes); + } + } } diff --git a/src/main/java/appeng/core/Registration.java b/src/main/java/appeng/core/Registration.java index 4cdb7dd03..40ecd7901 100644 --- a/src/main/java/appeng/core/Registration.java +++ b/src/main/java/appeng/core/Registration.java @@ -19,16 +19,57 @@ package appeng.core; -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashSet; -import java.util.Set; - -import javax.annotation.Nonnull; - +import appeng.api.config.Upgrades; +import appeng.api.definitions.IBlocks; +import appeng.api.definitions.IItems; +import appeng.api.definitions.IParts; +import appeng.api.features.IRecipeHandlerRegistry; +import appeng.api.features.IRegistryContainer; +import appeng.api.features.IWirelessTermHandler; +import appeng.api.features.IWorldGen.WorldGenType; +import appeng.api.movable.IMovableRegistry; +import appeng.api.networking.IGridCacheRegistry; +import appeng.api.networking.crafting.ICraftingGrid; +import appeng.api.networking.energy.IEnergyGrid; +import appeng.api.networking.pathing.IPathingGrid; +import appeng.api.networking.security.ISecurityGrid; +import appeng.api.networking.spatial.ISpatialCache; +import appeng.api.networking.storage.IStorageGrid; +import appeng.api.networking.ticking.ITickManager; +import appeng.bootstrap.ICriterionTriggerRegistry; +import appeng.bootstrap.IModelRegistry; +import appeng.bootstrap.components.*; +import appeng.capabilities.Capabilities; +import appeng.core.features.AEFeature; +import appeng.core.features.registries.P2PTunnelRegistry; +import appeng.core.features.registries.cell.BasicCellHandler; +import appeng.core.features.registries.cell.BasicItemCellGuiHandler; +import appeng.core.features.registries.cell.CreativeCellHandler; +import appeng.core.localization.GuiText; +import appeng.core.localization.PlayerMessages; +import appeng.core.stats.AdvancementTriggers; +import appeng.core.stats.PartItemPredicate; +import appeng.core.stats.Stats; +import appeng.core.worlddata.SpatialDimensionManager; +import appeng.fluids.registries.BasicFluidCellGuiHandler; +import appeng.hooks.TickHandler; +import appeng.items.materials.ItemMaterial; +import appeng.items.parts.ItemFacade; +import appeng.items.parts.ItemPart; +import appeng.loot.ChestLoot; +import appeng.me.cache.*; +import appeng.parts.PartPlacement; +import appeng.recipes.AEItemResolver; +import appeng.recipes.AERecipeLoader; +import appeng.recipes.game.DisassembleRecipe; +import appeng.recipes.game.FacadeRecipe; +import appeng.recipes.ores.OreDictionaryHandler; +import appeng.spatial.BiomeGenStorage; +import appeng.spatial.StorageWorldProvider; +import appeng.tile.AEBaseTile; +import appeng.worldgen.MeteoriteWorldGen; +import appeng.worldgen.QuartzWorldGen; import com.google.common.base.Preconditions; - import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.advancements.ICriterionInstance; import net.minecraft.advancements.ICriterionTrigger; @@ -60,526 +101,426 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.registries.IForgeRegistry; -import appeng.api.config.Upgrades; -import appeng.api.definitions.IBlocks; -import appeng.api.definitions.IItems; -import appeng.api.definitions.IParts; -import appeng.api.features.IRecipeHandlerRegistry; -import appeng.api.features.IRegistryContainer; -import appeng.api.features.IWirelessTermHandler; -import appeng.api.features.IWorldGen.WorldGenType; -import appeng.api.movable.IMovableRegistry; -import appeng.api.networking.IGridCacheRegistry; -import appeng.api.networking.crafting.ICraftingGrid; -import appeng.api.networking.energy.IEnergyGrid; -import appeng.api.networking.pathing.IPathingGrid; -import appeng.api.networking.security.ISecurityGrid; -import appeng.api.networking.spatial.ISpatialCache; -import appeng.api.networking.storage.IStorageGrid; -import appeng.api.networking.ticking.ITickManager; -import appeng.bootstrap.ICriterionTriggerRegistry; -import appeng.bootstrap.IModelRegistry; -import appeng.bootstrap.components.IBlockRegistrationComponent; -import appeng.bootstrap.components.IEntityRegistrationComponent; -import appeng.bootstrap.components.IInitComponent; -import appeng.bootstrap.components.IItemRegistrationComponent; -import appeng.bootstrap.components.IModelRegistrationComponent; -import appeng.bootstrap.components.IOreDictComponent; -import appeng.bootstrap.components.IPostInitComponent; -import appeng.bootstrap.components.IPreInitComponent; -import appeng.bootstrap.components.IRecipeRegistrationComponent; -import appeng.capabilities.Capabilities; -import appeng.core.features.AEFeature; -import appeng.core.features.registries.P2PTunnelRegistry; -import appeng.core.features.registries.cell.BasicCellHandler; -import appeng.core.features.registries.cell.BasicItemCellGuiHandler; -import appeng.core.features.registries.cell.CreativeCellHandler; -import appeng.core.localization.GuiText; -import appeng.core.localization.PlayerMessages; -import appeng.core.stats.AdvancementTriggers; -import appeng.core.stats.PartItemPredicate; -import appeng.core.stats.Stats; -import appeng.core.worlddata.SpatialDimensionManager; -import appeng.fluids.registries.BasicFluidCellGuiHandler; -import appeng.hooks.TickHandler; -import appeng.items.materials.ItemMaterial; -import appeng.items.parts.ItemFacade; -import appeng.items.parts.ItemPart; -import appeng.loot.ChestLoot; -import appeng.me.cache.CraftingGridCache; -import appeng.me.cache.EnergyGridCache; -import appeng.me.cache.GridStorageCache; -import appeng.me.cache.P2PCache; -import appeng.me.cache.PathGridCache; -import appeng.me.cache.SecurityCache; -import appeng.me.cache.SpatialPylonCache; -import appeng.me.cache.TickManagerCache; -import appeng.parts.PartPlacement; -import appeng.recipes.AEItemResolver; -import appeng.recipes.AERecipeLoader; -import appeng.recipes.game.DisassembleRecipe; -import appeng.recipes.game.FacadeRecipe; -import appeng.recipes.ores.OreDictionaryHandler; -import appeng.spatial.BiomeGenStorage; -import appeng.spatial.StorageWorldProvider; -import appeng.tile.AEBaseTile; -import appeng.worldgen.MeteoriteWorldGen; -import appeng.worldgen.QuartzWorldGen; - - -final class Registration -{ - DimensionType storageDimensionType; - int storageDimensionID; - Biome storageBiome; - AdvancementTriggers advancementTriggers; - - void preInitialize( final FMLPreInitializationEvent event ) - { - Capabilities.register(); - - final Api api = Api.INSTANCE; - final IRecipeHandlerRegistry recipeRegistry = api.registries().recipes(); - this.registerCraftHandlers( recipeRegistry ); - - MinecraftForge.EVENT_BUS.register( OreDictionaryHandler.INSTANCE ); - - ApiDefinitions definitions = api.definitions(); - - // Register - definitions.getRegistry().getBootstrapComponents( IPreInitComponent.class ).forEachRemaining( b -> b.preInitialize( event.getSide() ) ); - } - - private void registerSpatialBiome( IForgeRegistry registry ) - { - if( !AEConfig.instance().isFeatureEnabled( AEFeature.SPATIAL_IO ) ) - { - return; - } - - if( this.storageBiome == null ) - { - this.storageBiome = new BiomeGenStorage(); - } - registry.register( this.storageBiome.setRegistryName( "appliedenergistics2:storage_biome" ) ); - } - - private void registerSpatialDimension() - { - final AEConfig config = AEConfig.instance(); - if( !config.isFeatureEnabled( AEFeature.SPATIAL_IO ) ) - { - return; - } - - if( config.getStorageProviderID() == -1 ) - { - final Set ids = new HashSet<>(); - for( DimensionType type : DimensionType.values() ) - { - ids.add( type.getId() ); - } - - int newId = -11; - while( ids.contains( newId ) ) - { - --newId; - } - config.setStorageProviderID( newId ); - config.save(); - } - - this.storageDimensionType = DimensionType.register( "Storage Cell", "_cell", config.getStorageProviderID(), StorageWorldProvider.class, true ); - - if( config.getStorageDimensionID() == -1 ) - { - config.setStorageDimensionID( DimensionManager.getNextFreeDimId() ); - config.save(); - } - this.storageDimensionID = config.getStorageDimensionID(); - - DimensionManager.registerDimension( this.storageDimensionID, this.storageDimensionType ); - } - - private void registerCraftHandlers( final IRecipeHandlerRegistry registry ) - { - registry.addNewSubItemResolver( new AEItemResolver() ); - } - - public void initialize( @Nonnull final FMLInitializationEvent event, @Nonnull final File recipeDirectory ) - { - Preconditions.checkNotNull( event ); - Preconditions.checkNotNull( recipeDirectory ); - Preconditions.checkArgument( !recipeDirectory.isFile() ); - - final Api api = Api.INSTANCE; - final IRegistryContainer registries = api.registries(); - - ApiDefinitions definitions = api.definitions(); - definitions.getRegistry().getBootstrapComponents( IInitComponent.class ).forEachRemaining( b -> b.initialize( event.getSide() ) ); - - MinecraftForge.EVENT_BUS.register( TickHandler.INSTANCE ); - - MinecraftForge.EVENT_BUS.register( new PartPlacement() ); - - if( AEConfig.instance().isFeatureEnabled( AEFeature.CHEST_LOOT ) ) - { - MinecraftForge.EVENT_BUS.register( new ChestLoot() ); - } - - final IGridCacheRegistry gcr = registries.gridCache(); - gcr.registerGridCache( ITickManager.class, TickManagerCache.class ); - gcr.registerGridCache( IEnergyGrid.class, EnergyGridCache.class ); - gcr.registerGridCache( IPathingGrid.class, PathGridCache.class ); - gcr.registerGridCache( IStorageGrid.class, GridStorageCache.class ); - gcr.registerGridCache( P2PCache.class, P2PCache.class ); - gcr.registerGridCache( ISpatialCache.class, SpatialPylonCache.class ); - gcr.registerGridCache( ISecurityGrid.class, SecurityCache.class ); - gcr.registerGridCache( ICraftingGrid.class, CraftingGridCache.class ); - - registries.cell().addCellHandler( new BasicCellHandler() ); - registries.cell().addCellHandler( new CreativeCellHandler() ); - registries.cell().addCellGuiHandler( new BasicItemCellGuiHandler() ); - registries.cell().addCellGuiHandler( new BasicFluidCellGuiHandler() ); - - api.definitions().materials().matterBall().maybeStack( 1 ).ifPresent( ammoStack -> - { - final double weight = 32; - - registries.matterCannon().registerAmmo( ammoStack, weight ); - } ); - - PartItemPredicate.register(); - Stats.register(); - this.advancementTriggers = new AdvancementTriggers( new CriterionTrigggerRegistry() ); - } - - @SubscribeEvent - public void registerBiomes( RegistryEvent.Register event ) - { - final IForgeRegistry registry = event.getRegistry(); - this.registerSpatialBiome( registry ); - } - - @SubscribeEvent - @SideOnly( Side.CLIENT ) - public void modelRegistryEvent( ModelRegistryEvent event ) - { - final ApiDefinitions definitions = Api.INSTANCE.definitions(); - final IModelRegistry registry = new ModelLoaderWrapper(); - final Side side = FMLCommonHandler.instance().getEffectiveSide(); - definitions.getRegistry().getBootstrapComponents( IModelRegistrationComponent.class ).forEachRemaining( b -> b.modelRegistration( side, registry ) ); - } - - @SubscribeEvent - public void registerBlocks( RegistryEvent.Register event ) - { - final IForgeRegistry registry = event.getRegistry(); - final ApiDefinitions definitions = Api.INSTANCE.definitions(); - final Side side = FMLCommonHandler.instance().getEffectiveSide(); - definitions.getRegistry().getBootstrapComponents( IBlockRegistrationComponent.class ).forEachRemaining( b -> b.blockRegistration( side, registry ) ); - } - - @SubscribeEvent - public void registerItems( RegistryEvent.Register event ) - { - final IForgeRegistry registry = event.getRegistry(); - final ApiDefinitions definitions = Api.INSTANCE.definitions(); - final Side side = FMLCommonHandler.instance().getEffectiveSide(); - definitions.getRegistry().getBootstrapComponents( IItemRegistrationComponent.class ).forEachRemaining( b -> b.itemRegistration( side, registry ) ); - // register oredicts - definitions.getRegistry().getBootstrapComponents( IOreDictComponent.class ).forEachRemaining( b -> b.oreRegistration( side ) ); - ItemMaterial.instance.registerOredicts(); - ItemPart.instance.registerOreDicts(); - } - - @SubscribeEvent - public void registerRecipes( RegistryEvent.Register event ) - { - final IForgeRegistry registry = event.getRegistry(); - - final Api api = Api.INSTANCE; - final ApiDefinitions definitions = api.definitions(); - final Side side = FMLCommonHandler.instance().getEffectiveSide(); - - if( AEConfig.instance().isFeatureEnabled( AEFeature.ENABLE_DISASSEMBLY_CRAFTING ) ) - { - DisassembleRecipe r = new DisassembleRecipe(); - registry.register( r.setRegistryName( AppEng.MOD_ID.toLowerCase(), "disassemble" ) ); - } - - if( AEConfig.instance().isFeatureEnabled( AEFeature.ENABLE_FACADE_CRAFTING ) ) - { - definitions.items().facade().maybeItem().ifPresent( facadeItem -> - { - FacadeRecipe f = new FacadeRecipe( (ItemFacade) facadeItem ); - registry.register( f.setRegistryName( AppEng.MOD_ID.toLowerCase(), "facade" ) ); - } ); - } - - definitions.getRegistry().getBootstrapComponents( IRecipeRegistrationComponent.class ).forEachRemaining( b -> b.recipeRegistration( side, registry ) ); - - final AERecipeLoader ldr = new AERecipeLoader(); - ldr.loadProcessingRecipes(); - } - - @SubscribeEvent - public void registerEntities( RegistryEvent.Register event ) - { - final IForgeRegistry registry = event.getRegistry(); - final ApiDefinitions definitions = Api.INSTANCE.definitions(); - definitions.getRegistry().getBootstrapComponents( IEntityRegistrationComponent.class ).forEachRemaining( b -> b.entityRegistration( registry ) ); - } - - @SubscribeEvent - public void attachSpatialDimensionManager( AttachCapabilitiesEvent event ) - { - if( AEConfig.instance() - .isFeatureEnabled( AEFeature.SPATIAL_IO ) && event.getObject() == DimensionManager.getWorld( AEConfig.instance().getStorageDimensionID() ) ) - { - event.addCapability( new ResourceLocation( "appliedenergistics2:spatial_dimension_manager" ), new SpatialDimensionManager( event.getObject() ) ); - } - } - - void postInit( final FMLPostInitializationEvent event ) - { - final IRegistryContainer registries = Api.INSTANCE.registries(); - ApiDefinitions definitions = Api.INSTANCE.definitions(); - final IParts parts = definitions.parts(); - final IBlocks blocks = definitions.blocks(); - final IItems items = definitions.items(); - - this.registerSpatialDimension(); - - // default settings.. - ( (P2PTunnelRegistry) registries.p2pTunnel() ).configure(); - - // add to localization.. - PlayerMessages.values(); - GuiText.values(); - - definitions.getRegistry().getBootstrapComponents( IPostInitComponent.class ).forEachRemaining( b -> b.postInitialize( event.getSide() ) ); - - // Interface - Upgrades.CRAFTING.registerItem( parts.iface(), 1 ); - Upgrades.CRAFTING.registerItem( blocks.iface(), 1 ); - Upgrades.PATTERN_EXPANSION.registerItem( parts.iface(), 3 ); - Upgrades.PATTERN_EXPANSION.registerItem( blocks.iface(), 3 ); - - // IO Port! - Upgrades.SPEED.registerItem( blocks.iOPort(), 3 ); - Upgrades.REDSTONE.registerItem( blocks.iOPort(), 1 ); - - // Level Emitter! - Upgrades.FUZZY.registerItem( parts.levelEmitter(), 1 ); - Upgrades.CRAFTING.registerItem( parts.levelEmitter(), 1 ); - - // Import Bus - Upgrades.FUZZY.registerItem( parts.importBus(), 1 ); - Upgrades.REDSTONE.registerItem( parts.importBus(), 1 ); - Upgrades.CAPACITY.registerItem( parts.importBus(), 2 ); - Upgrades.SPEED.registerItem( parts.importBus(), 4 ); - - // Fluid Import Bus - Upgrades.CAPACITY.registerItem( parts.fluidImportBus(), 2 ); - Upgrades.REDSTONE.registerItem( parts.fluidImportBus(), 1 ); - Upgrades.SPEED.registerItem( parts.fluidImportBus(), 4 ); - - // Export Bus - Upgrades.FUZZY.registerItem( parts.exportBus(), 1 ); - Upgrades.REDSTONE.registerItem( parts.exportBus(), 1 ); - Upgrades.CAPACITY.registerItem( parts.exportBus(), 2 ); - Upgrades.SPEED.registerItem( parts.exportBus(), 4 ); - Upgrades.CRAFTING.registerItem( parts.exportBus(), 1 ); - - // Fluid Export Bus - Upgrades.CAPACITY.registerItem( parts.fluidExportBus(), 2 ); - Upgrades.REDSTONE.registerItem( parts.fluidExportBus(), 1 ); - Upgrades.SPEED.registerItem( parts.fluidExportBus(), 4 ); - - // Storage Cells - Upgrades.FUZZY.registerItem( items.cell1k(), 1 ); - Upgrades.INVERTER.registerItem( items.cell1k(), 1 ); - - Upgrades.FUZZY.registerItem( items.cell4k(), 1 ); - Upgrades.INVERTER.registerItem( items.cell4k(), 1 ); - - Upgrades.FUZZY.registerItem( items.cell16k(), 1 ); - Upgrades.INVERTER.registerItem( items.cell16k(), 1 ); - - Upgrades.FUZZY.registerItem( items.cell64k(), 1 ); - Upgrades.INVERTER.registerItem( items.cell64k(), 1 ); - - Upgrades.FUZZY.registerItem( items.portableCell(), 1 ); - Upgrades.INVERTER.registerItem( items.portableCell(), 1 ); - - Upgrades.FUZZY.registerItem( items.viewCell(), 1 ); - Upgrades.INVERTER.registerItem( items.viewCell(), 1 ); - - // Storage Bus - Upgrades.FUZZY.registerItem( parts.storageBus(), 1 ); - Upgrades.INVERTER.registerItem( parts.storageBus(), 1 ); - Upgrades.CAPACITY.registerItem( parts.storageBus(), 5 ); - - // Storage Bus Fluids - Upgrades.INVERTER.registerItem( parts.fluidStorageBus(), 1 ); - Upgrades.CAPACITY.registerItem( parts.fluidStorageBus(), 5 ); - - // Formation Plane - Upgrades.FUZZY.registerItem( parts.formationPlane(), 1 ); - Upgrades.INVERTER.registerItem( parts.formationPlane(), 1 ); - Upgrades.CAPACITY.registerItem( parts.formationPlane(), 5 ); - - // Matter Cannon - Upgrades.FUZZY.registerItem( items.massCannon(), 1 ); - Upgrades.INVERTER.registerItem( items.massCannon(), 1 ); - Upgrades.SPEED.registerItem( items.massCannon(), 4 ); - - // Molecular Assembler - Upgrades.SPEED.registerItem( blocks.molecularAssembler(), 5 ); - - // Inscriber - Upgrades.SPEED.registerItem( blocks.inscriber(), 3 ); - - // Wireless Terminal Handler - items.wirelessTerminal().maybeItem().ifPresent( terminal -> registries.wireless().registerWirelessHandler( (IWirelessTermHandler) terminal ) ); - - // Charge Rates - items.chargedStaff().maybeItem().ifPresent( chargedStaff -> registries.charger().addChargeRate( chargedStaff, 320d ) ); - items.portableCell().maybeItem().ifPresent( chargedStaff -> registries.charger().addChargeRate( chargedStaff, 800d ) ); - items.colorApplicator().maybeItem().ifPresent( colorApplicator -> registries.charger().addChargeRate( colorApplicator, 800d ) ); - items.wirelessTerminal().maybeItem().ifPresent( terminal -> registries.charger().addChargeRate( terminal, 8000d ) ); - items.entropyManipulator().maybeItem().ifPresent( entropyManipulator -> registries.charger().addChargeRate( entropyManipulator, 8000d ) ); - items.massCannon().maybeItem().ifPresent( massCannon -> registries.charger().addChargeRate( massCannon, 8000d ) ); - blocks.energyCell().maybeItem().ifPresent( cell -> registries.charger().addChargeRate( cell, 8000d ) ); - blocks.energyCellDense().maybeItem().ifPresent( cell -> registries.charger().addChargeRate( cell, 16000d ) ); - - // add villager trading to black smiths for a few basic materials - if( AEConfig.instance().isFeatureEnabled( AEFeature.VILLAGER_TRADING ) ) - { - // TODO: VILLAGER TRADING - // VillagerRegistry.instance().getRegisteredVillagers().registerVillageTradeHandler( 3, new AETrading() ); - } - - if( AEConfig.instance().isFeatureEnabled( AEFeature.CERTUS_QUARTZ_WORLD_GEN ) ) - { - GameRegistry.registerWorldGenerator( new QuartzWorldGen(), 0 ); - } - - if( AEConfig.instance().isFeatureEnabled( AEFeature.METEORITE_WORLD_GEN ) ) - { - GameRegistry.registerWorldGenerator( new MeteoriteWorldGen(), 0 ); - } - - final IMovableRegistry mr = registries.movable(); - - /* - * You can't move bed rock. - */ - mr.blacklistBlock( net.minecraft.init.Blocks.BEDROCK ); - - /* - * White List Vanilla... - */ - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityBanner.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityBeacon.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityBrewingStand.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityChest.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityCommandBlock.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityComparator.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityDaylightDetector.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityDispenser.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityDropper.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityEnchantmentTable.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityEnderChest.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityEndPortal.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityFlowerPot.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityFurnace.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityHopper.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityMobSpawner.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityNote.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityPiston.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityShulkerBox.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntitySign.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntitySkull.class ); - - /* - * Whitelist AE2 - */ - mr.whiteListTileEntity( AEBaseTile.class ); - - /* - * world gen - */ - for( final WorldGenType type : WorldGenType.values() ) - { - registries.worldgen().disableWorldGenForProviderID( type, StorageWorldProvider.class ); - - // nether - registries.worldgen().disableWorldGenForDimension( type, -1 ); - - // end - registries.worldgen().disableWorldGenForDimension( type, 1 ); - } - - // whitelist from config - for( final int dimension : AEConfig.instance().getMeteoriteDimensionWhitelist() ) - { - registries.worldgen().enableWorldGenForDimension( WorldGenType.METEORITES, dimension ); - } - } - - private static class ModelLoaderWrapper implements IModelRegistry - { - - @Override - public void registerItemVariants( Item item, ResourceLocation... names ) - { - ModelLoader.registerItemVariants( item, names ); - } - - @Override - public void setCustomModelResourceLocation( Item item, int metadata, ModelResourceLocation model ) - { - ModelLoader.setCustomModelResourceLocation( item, metadata, model ); - } - - @Override - public void setCustomMeshDefinition( Item item, ItemMeshDefinition meshDefinition ) - { - ModelLoader.setCustomMeshDefinition( item, meshDefinition ); - } - - @Override - public void setCustomStateMapper( Block block, IStateMapper mapper ) - { - ModelLoader.setCustomStateMapper( block, mapper ); - } - } - - private static class CriterionTrigggerRegistry implements ICriterionTriggerRegistry - { - private Method method; - - CriterionTrigggerRegistry() - { - this.method = ReflectionHelper.findMethod( CriteriaTriggers.class, "register", "func_192118_a", ICriterionTrigger.class ); - this.method.setAccessible( true ); - } - - @Override - public void register( ICriterionTrigger trigger ) - { - try - { - this.method.invoke( null, trigger ); - } - catch( IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) - { - AELog.debug( e ); - } - } - - } +import javax.annotation.Nonnull; +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashSet; +import java.util.Set; + + +final class Registration { + DimensionType storageDimensionType; + int storageDimensionID; + Biome storageBiome; + AdvancementTriggers advancementTriggers; + + void preInitialize(final FMLPreInitializationEvent event) { + Capabilities.register(); + + final Api api = Api.INSTANCE; + final IRecipeHandlerRegistry recipeRegistry = api.registries().recipes(); + this.registerCraftHandlers(recipeRegistry); + + MinecraftForge.EVENT_BUS.register(OreDictionaryHandler.INSTANCE); + + ApiDefinitions definitions = api.definitions(); + + // Register + definitions.getRegistry().getBootstrapComponents(IPreInitComponent.class).forEachRemaining(b -> b.preInitialize(event.getSide())); + } + + private void registerSpatialBiome(IForgeRegistry registry) { + if (!AEConfig.instance().isFeatureEnabled(AEFeature.SPATIAL_IO)) { + return; + } + + if (this.storageBiome == null) { + this.storageBiome = new BiomeGenStorage(); + } + registry.register(this.storageBiome.setRegistryName("appliedenergistics2:storage_biome")); + } + + private void registerSpatialDimension() { + final AEConfig config = AEConfig.instance(); + if (!config.isFeatureEnabled(AEFeature.SPATIAL_IO)) { + return; + } + + if (config.getStorageProviderID() == -1) { + final Set ids = new HashSet<>(); + for (DimensionType type : DimensionType.values()) { + ids.add(type.getId()); + } + + int newId = -11; + while (ids.contains(newId)) { + --newId; + } + config.setStorageProviderID(newId); + config.save(); + } + + this.storageDimensionType = DimensionType.register("Storage Cell", "_cell", config.getStorageProviderID(), StorageWorldProvider.class, true); + + if (config.getStorageDimensionID() == -1) { + config.setStorageDimensionID(DimensionManager.getNextFreeDimId()); + config.save(); + } + this.storageDimensionID = config.getStorageDimensionID(); + + DimensionManager.registerDimension(this.storageDimensionID, this.storageDimensionType); + } + + private void registerCraftHandlers(final IRecipeHandlerRegistry registry) { + registry.addNewSubItemResolver(new AEItemResolver()); + } + + public void initialize(@Nonnull final FMLInitializationEvent event, @Nonnull final File recipeDirectory) { + Preconditions.checkNotNull(event); + Preconditions.checkNotNull(recipeDirectory); + Preconditions.checkArgument(!recipeDirectory.isFile()); + + final Api api = Api.INSTANCE; + final IRegistryContainer registries = api.registries(); + + ApiDefinitions definitions = api.definitions(); + definitions.getRegistry().getBootstrapComponents(IInitComponent.class).forEachRemaining(b -> b.initialize(event.getSide())); + + MinecraftForge.EVENT_BUS.register(TickHandler.INSTANCE); + + MinecraftForge.EVENT_BUS.register(new PartPlacement()); + + if (AEConfig.instance().isFeatureEnabled(AEFeature.CHEST_LOOT)) { + MinecraftForge.EVENT_BUS.register(new ChestLoot()); + } + + final IGridCacheRegistry gcr = registries.gridCache(); + gcr.registerGridCache(ITickManager.class, TickManagerCache.class); + gcr.registerGridCache(IEnergyGrid.class, EnergyGridCache.class); + gcr.registerGridCache(IPathingGrid.class, PathGridCache.class); + gcr.registerGridCache(IStorageGrid.class, GridStorageCache.class); + gcr.registerGridCache(P2PCache.class, P2PCache.class); + gcr.registerGridCache(ISpatialCache.class, SpatialPylonCache.class); + gcr.registerGridCache(ISecurityGrid.class, SecurityCache.class); + gcr.registerGridCache(ICraftingGrid.class, CraftingGridCache.class); + + registries.cell().addCellHandler(new BasicCellHandler()); + registries.cell().addCellHandler(new CreativeCellHandler()); + registries.cell().addCellGuiHandler(new BasicItemCellGuiHandler()); + registries.cell().addCellGuiHandler(new BasicFluidCellGuiHandler()); + + api.definitions().materials().matterBall().maybeStack(1).ifPresent(ammoStack -> + { + final double weight = 32; + + registries.matterCannon().registerAmmo(ammoStack, weight); + }); + + PartItemPredicate.register(); + Stats.register(); + this.advancementTriggers = new AdvancementTriggers(new CriterionTrigggerRegistry()); + } + + @SubscribeEvent + public void registerBiomes(RegistryEvent.Register event) { + final IForgeRegistry registry = event.getRegistry(); + this.registerSpatialBiome(registry); + } + + @SubscribeEvent + @SideOnly(Side.CLIENT) + public void modelRegistryEvent(ModelRegistryEvent event) { + final ApiDefinitions definitions = Api.INSTANCE.definitions(); + final IModelRegistry registry = new ModelLoaderWrapper(); + final Side side = FMLCommonHandler.instance().getEffectiveSide(); + definitions.getRegistry().getBootstrapComponents(IModelRegistrationComponent.class).forEachRemaining(b -> b.modelRegistration(side, registry)); + } + + @SubscribeEvent + public void registerBlocks(RegistryEvent.Register event) { + final IForgeRegistry registry = event.getRegistry(); + final ApiDefinitions definitions = Api.INSTANCE.definitions(); + final Side side = FMLCommonHandler.instance().getEffectiveSide(); + definitions.getRegistry().getBootstrapComponents(IBlockRegistrationComponent.class).forEachRemaining(b -> b.blockRegistration(side, registry)); + } + + @SubscribeEvent + public void registerItems(RegistryEvent.Register event) { + final IForgeRegistry registry = event.getRegistry(); + final ApiDefinitions definitions = Api.INSTANCE.definitions(); + final Side side = FMLCommonHandler.instance().getEffectiveSide(); + definitions.getRegistry().getBootstrapComponents(IItemRegistrationComponent.class).forEachRemaining(b -> b.itemRegistration(side, registry)); + // register oredicts + definitions.getRegistry().getBootstrapComponents(IOreDictComponent.class).forEachRemaining(b -> b.oreRegistration(side)); + ItemMaterial.instance.registerOredicts(); + ItemPart.instance.registerOreDicts(); + } + + @SubscribeEvent + public void registerRecipes(RegistryEvent.Register event) { + final IForgeRegistry registry = event.getRegistry(); + + final Api api = Api.INSTANCE; + final ApiDefinitions definitions = api.definitions(); + final Side side = FMLCommonHandler.instance().getEffectiveSide(); + + if (AEConfig.instance().isFeatureEnabled(AEFeature.ENABLE_DISASSEMBLY_CRAFTING)) { + DisassembleRecipe r = new DisassembleRecipe(); + registry.register(r.setRegistryName(AppEng.MOD_ID.toLowerCase(), "disassemble")); + } + + if (AEConfig.instance().isFeatureEnabled(AEFeature.ENABLE_FACADE_CRAFTING)) { + definitions.items().facade().maybeItem().ifPresent(facadeItem -> + { + FacadeRecipe f = new FacadeRecipe((ItemFacade) facadeItem); + registry.register(f.setRegistryName(AppEng.MOD_ID.toLowerCase(), "facade")); + }); + } + + definitions.getRegistry().getBootstrapComponents(IRecipeRegistrationComponent.class).forEachRemaining(b -> b.recipeRegistration(side, registry)); + + final AERecipeLoader ldr = new AERecipeLoader(); + ldr.loadProcessingRecipes(); + } + + @SubscribeEvent + public void registerEntities(RegistryEvent.Register event) { + final IForgeRegistry registry = event.getRegistry(); + final ApiDefinitions definitions = Api.INSTANCE.definitions(); + definitions.getRegistry().getBootstrapComponents(IEntityRegistrationComponent.class).forEachRemaining(b -> b.entityRegistration(registry)); + } + + @SubscribeEvent + public void attachSpatialDimensionManager(AttachCapabilitiesEvent event) { + if (AEConfig.instance() + .isFeatureEnabled(AEFeature.SPATIAL_IO) && event.getObject() == DimensionManager.getWorld(AEConfig.instance().getStorageDimensionID())) { + event.addCapability(new ResourceLocation("appliedenergistics2:spatial_dimension_manager"), new SpatialDimensionManager(event.getObject())); + } + } + + void postInit(final FMLPostInitializationEvent event) { + final IRegistryContainer registries = Api.INSTANCE.registries(); + ApiDefinitions definitions = Api.INSTANCE.definitions(); + final IParts parts = definitions.parts(); + final IBlocks blocks = definitions.blocks(); + final IItems items = definitions.items(); + + this.registerSpatialDimension(); + + // default settings.. + ((P2PTunnelRegistry) registries.p2pTunnel()).configure(); + + // add to localization.. + PlayerMessages.values(); + GuiText.values(); + + definitions.getRegistry().getBootstrapComponents(IPostInitComponent.class).forEachRemaining(b -> b.postInitialize(event.getSide())); + + // Interface + Upgrades.CRAFTING.registerItem(parts.iface(), 1); + Upgrades.CRAFTING.registerItem(blocks.iface(), 1); + Upgrades.PATTERN_EXPANSION.registerItem(parts.iface(), 3); + Upgrades.PATTERN_EXPANSION.registerItem(blocks.iface(), 3); + + // IO Port! + Upgrades.SPEED.registerItem(blocks.iOPort(), 3); + Upgrades.REDSTONE.registerItem(blocks.iOPort(), 1); + + // Level Emitter! + Upgrades.FUZZY.registerItem(parts.levelEmitter(), 1); + Upgrades.CRAFTING.registerItem(parts.levelEmitter(), 1); + + // Import Bus + Upgrades.FUZZY.registerItem(parts.importBus(), 1); + Upgrades.REDSTONE.registerItem(parts.importBus(), 1); + Upgrades.CAPACITY.registerItem(parts.importBus(), 2); + Upgrades.SPEED.registerItem(parts.importBus(), 4); + + // Fluid Import Bus + Upgrades.CAPACITY.registerItem(parts.fluidImportBus(), 2); + Upgrades.REDSTONE.registerItem(parts.fluidImportBus(), 1); + Upgrades.SPEED.registerItem(parts.fluidImportBus(), 4); + + // Export Bus + Upgrades.FUZZY.registerItem(parts.exportBus(), 1); + Upgrades.REDSTONE.registerItem(parts.exportBus(), 1); + Upgrades.CAPACITY.registerItem(parts.exportBus(), 2); + Upgrades.SPEED.registerItem(parts.exportBus(), 4); + Upgrades.CRAFTING.registerItem(parts.exportBus(), 1); + + // Fluid Export Bus + Upgrades.CAPACITY.registerItem(parts.fluidExportBus(), 2); + Upgrades.REDSTONE.registerItem(parts.fluidExportBus(), 1); + Upgrades.SPEED.registerItem(parts.fluidExportBus(), 4); + + // Storage Cells + Upgrades.FUZZY.registerItem(items.cell1k(), 1); + Upgrades.INVERTER.registerItem(items.cell1k(), 1); + + Upgrades.FUZZY.registerItem(items.cell4k(), 1); + Upgrades.INVERTER.registerItem(items.cell4k(), 1); + + Upgrades.FUZZY.registerItem(items.cell16k(), 1); + Upgrades.INVERTER.registerItem(items.cell16k(), 1); + + Upgrades.FUZZY.registerItem(items.cell64k(), 1); + Upgrades.INVERTER.registerItem(items.cell64k(), 1); + + Upgrades.FUZZY.registerItem(items.portableCell(), 1); + Upgrades.INVERTER.registerItem(items.portableCell(), 1); + + Upgrades.FUZZY.registerItem(items.viewCell(), 1); + Upgrades.INVERTER.registerItem(items.viewCell(), 1); + + // Storage Bus + Upgrades.FUZZY.registerItem(parts.storageBus(), 1); + Upgrades.INVERTER.registerItem(parts.storageBus(), 1); + Upgrades.CAPACITY.registerItem(parts.storageBus(), 5); + + // Storage Bus Fluids + Upgrades.INVERTER.registerItem(parts.fluidStorageBus(), 1); + Upgrades.CAPACITY.registerItem(parts.fluidStorageBus(), 5); + + // Formation Plane + Upgrades.FUZZY.registerItem(parts.formationPlane(), 1); + Upgrades.INVERTER.registerItem(parts.formationPlane(), 1); + Upgrades.CAPACITY.registerItem(parts.formationPlane(), 5); + + // Matter Cannon + Upgrades.FUZZY.registerItem(items.massCannon(), 1); + Upgrades.INVERTER.registerItem(items.massCannon(), 1); + Upgrades.SPEED.registerItem(items.massCannon(), 4); + + // Molecular Assembler + Upgrades.SPEED.registerItem(blocks.molecularAssembler(), 5); + + // Inscriber + Upgrades.SPEED.registerItem(blocks.inscriber(), 3); + + // Wireless Terminal Handler + items.wirelessTerminal().maybeItem().ifPresent(terminal -> registries.wireless().registerWirelessHandler((IWirelessTermHandler) terminal)); + + // Charge Rates + items.chargedStaff().maybeItem().ifPresent(chargedStaff -> registries.charger().addChargeRate(chargedStaff, 320d)); + items.portableCell().maybeItem().ifPresent(chargedStaff -> registries.charger().addChargeRate(chargedStaff, 800d)); + items.colorApplicator().maybeItem().ifPresent(colorApplicator -> registries.charger().addChargeRate(colorApplicator, 800d)); + items.wirelessTerminal().maybeItem().ifPresent(terminal -> registries.charger().addChargeRate(terminal, 8000d)); + items.entropyManipulator().maybeItem().ifPresent(entropyManipulator -> registries.charger().addChargeRate(entropyManipulator, 8000d)); + items.massCannon().maybeItem().ifPresent(massCannon -> registries.charger().addChargeRate(massCannon, 8000d)); + blocks.energyCell().maybeItem().ifPresent(cell -> registries.charger().addChargeRate(cell, 8000d)); + blocks.energyCellDense().maybeItem().ifPresent(cell -> registries.charger().addChargeRate(cell, 16000d)); + + // add villager trading to black smiths for a few basic materials + if (AEConfig.instance().isFeatureEnabled(AEFeature.VILLAGER_TRADING)) { + // TODO: VILLAGER TRADING + // VillagerRegistry.instance().getRegisteredVillagers().registerVillageTradeHandler( 3, new AETrading() ); + } + + if (AEConfig.instance().isFeatureEnabled(AEFeature.CERTUS_QUARTZ_WORLD_GEN)) { + GameRegistry.registerWorldGenerator(new QuartzWorldGen(), 0); + } + + if (AEConfig.instance().isFeatureEnabled(AEFeature.METEORITE_WORLD_GEN)) { + GameRegistry.registerWorldGenerator(new MeteoriteWorldGen(), 0); + } + + final IMovableRegistry mr = registries.movable(); + + /* + * You can't move bed rock. + */ + mr.blacklistBlock(net.minecraft.init.Blocks.BEDROCK); + + /* + * White List Vanilla... + */ + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityBanner.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityBeacon.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityBrewingStand.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityChest.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityCommandBlock.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityComparator.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityDaylightDetector.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityDispenser.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityDropper.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityEnchantmentTable.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityEnderChest.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityEndPortal.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityFlowerPot.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityFurnace.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityHopper.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityMobSpawner.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityNote.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityPiston.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityShulkerBox.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntitySign.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntitySkull.class); + + /* + * Whitelist AE2 + */ + mr.whiteListTileEntity(AEBaseTile.class); + + /* + * world gen + */ + for (final WorldGenType type : WorldGenType.values()) { + registries.worldgen().disableWorldGenForProviderID(type, StorageWorldProvider.class); + + // nether + registries.worldgen().disableWorldGenForDimension(type, -1); + + // end + registries.worldgen().disableWorldGenForDimension(type, 1); + } + + // whitelist from config + for (final int dimension : AEConfig.instance().getMeteoriteDimensionWhitelist()) { + registries.worldgen().enableWorldGenForDimension(WorldGenType.METEORITES, dimension); + } + } + + private static class ModelLoaderWrapper implements IModelRegistry { + + @Override + public void registerItemVariants(Item item, ResourceLocation... names) { + ModelLoader.registerItemVariants(item, names); + } + + @Override + public void setCustomModelResourceLocation(Item item, int metadata, ModelResourceLocation model) { + ModelLoader.setCustomModelResourceLocation(item, metadata, model); + } + + @Override + public void setCustomMeshDefinition(Item item, ItemMeshDefinition meshDefinition) { + ModelLoader.setCustomMeshDefinition(item, meshDefinition); + } + + @Override + public void setCustomStateMapper(Block block, IStateMapper mapper) { + ModelLoader.setCustomStateMapper(block, mapper); + } + } + + private static class CriterionTrigggerRegistry implements ICriterionTriggerRegistry { + private final Method method; + + CriterionTrigggerRegistry() { + this.method = ReflectionHelper.findMethod(CriteriaTriggers.class, "register", "func_192118_a", ICriterionTrigger.class); + this.method.setAccessible(true); + } + + @Override + public void register(ICriterionTrigger trigger) { + try { + this.method.invoke(null, trigger); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + AELog.debug(e); + } + } + + } } diff --git a/src/main/java/appeng/core/api/ApiClientHelper.java b/src/main/java/appeng/core/api/ApiClientHelper.java index d9db7bc9f..557fa62c3 100644 --- a/src/main/java/appeng/core/api/ApiClientHelper.java +++ b/src/main/java/appeng/core/api/ApiClientHelper.java @@ -1,9 +1,6 @@ - package appeng.core.api; -import java.util.List; - import appeng.api.config.IncludeExclude; import appeng.api.storage.ICellInventory; import appeng.api.storage.ICellInventoryHandler; @@ -11,41 +8,35 @@ import appeng.api.storage.data.IAEStack; import appeng.api.util.IClientHelper; import appeng.core.localization.GuiText; +import java.util.List; -public class ApiClientHelper implements IClientHelper -{ - @Override - public > void addCellInformation( ICellInventoryHandler handler, List lines ) - { - if( handler == null ) - { - return; - } - final ICellInventory cellInventory = handler.getCellInv(); +public class ApiClientHelper implements IClientHelper { + @Override + public > void addCellInformation(ICellInventoryHandler handler, List lines) { + if (handler == null) { + return; + } - if( cellInventory != null ) - { - lines.add( cellInventory.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cellInventory.getTotalBytes() + ' ' + GuiText.BytesUsed.getLocal() ); + final ICellInventory cellInventory = handler.getCellInv(); - lines.add( cellInventory.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cellInventory.getTotalItemTypes() + ' ' + GuiText.Types - .getLocal() ); - } + if (cellInventory != null) { + lines.add(cellInventory.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cellInventory.getTotalBytes() + ' ' + GuiText.BytesUsed.getLocal()); - if( handler.isPreformatted() ) - { - final String list = ( handler.getIncludeExcludeMode() == IncludeExclude.WHITELIST ? GuiText.Included : GuiText.Excluded ).getLocal(); + lines.add(cellInventory.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cellInventory.getTotalItemTypes() + ' ' + GuiText.Types + .getLocal()); + } - if( handler.isFuzzy() ) - { - lines.add( GuiText.Partitioned.getLocal() + " - " + list + ' ' + GuiText.Fuzzy.getLocal() ); - } - else - { - lines.add( GuiText.Partitioned.getLocal() + " - " + list + ' ' + GuiText.Precise.getLocal() ); - } - } + if (handler.isPreformatted()) { + final String list = (handler.getIncludeExcludeMode() == IncludeExclude.WHITELIST ? GuiText.Included : GuiText.Excluded).getLocal(); - } + if (handler.isFuzzy()) { + lines.add(GuiText.Partitioned.getLocal() + " - " + list + ' ' + GuiText.Fuzzy.getLocal()); + } else { + lines.add(GuiText.Partitioned.getLocal() + " - " + list + ' ' + GuiText.Precise.getLocal()); + } + } + + } } diff --git a/src/main/java/appeng/core/api/ApiGrid.java b/src/main/java/appeng/core/api/ApiGrid.java index b4cf311a3..b4ac14620 100644 --- a/src/main/java/appeng/core/api/ApiGrid.java +++ b/src/main/java/appeng/core/api/ApiGrid.java @@ -19,8 +19,6 @@ package appeng.core.api; -import com.google.common.base.Preconditions; - import appeng.api.exceptions.FailedConnectionException; import appeng.api.networking.IGridBlock; import appeng.api.networking.IGridConnection; @@ -30,6 +28,7 @@ import appeng.api.util.AEPartLocation; import appeng.me.GridConnection; import appeng.me.GridNode; import appeng.util.Platform; +import com.google.common.base.Preconditions; /** @@ -37,29 +36,25 @@ import appeng.util.Platform; * @version rv5 * @since rv5 */ -public class ApiGrid implements IGridHelper -{ +public class ApiGrid implements IGridHelper { - @Override - public IGridNode createGridNode( final IGridBlock blk ) - { - Preconditions.checkNotNull( blk ); + @Override + public IGridNode createGridNode(final IGridBlock blk) { + Preconditions.checkNotNull(blk); - if( Platform.isClient() ) - { - throw new IllegalStateException( "Grid features for " + blk + " are server side only." ); - } + if (Platform.isClient()) { + throw new IllegalStateException("Grid features for " + blk + " are server side only."); + } - return new GridNode( blk ); - } + return new GridNode(blk); + } - @Override - public IGridConnection createGridConnection( final IGridNode a, final IGridNode b ) throws FailedConnectionException - { - Preconditions.checkNotNull( a ); - Preconditions.checkNotNull( b ); + @Override + public IGridConnection createGridConnection(final IGridNode a, final IGridNode b) throws FailedConnectionException { + Preconditions.checkNotNull(a); + Preconditions.checkNotNull(b); - return GridConnection.create( a, b, AEPartLocation.INTERNAL ); - } + return GridConnection.create(a, b, AEPartLocation.INTERNAL); + } } diff --git a/src/main/java/appeng/core/api/ApiPart.java b/src/main/java/appeng/core/api/ApiPart.java index 1805edec1..5d3dacb08 100644 --- a/src/main/java/appeng/core/api/ApiPart.java +++ b/src/main/java/appeng/core/api/ApiPart.java @@ -19,20 +19,26 @@ package appeng.core.api; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - +import appeng.api.parts.CableRenderMode; +import appeng.api.parts.IPartHelper; +import appeng.api.parts.LayerBase; +import appeng.core.AELog; +import appeng.core.AppEng; +import appeng.parts.PartPlacement; +import appeng.tile.AEBaseTile; +import appeng.tile.networking.TileCableBus; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; - +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.commons.Remapper; @@ -42,365 +48,292 @@ import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import appeng.api.parts.CableRenderMode; -import appeng.api.parts.IPartHelper; -import appeng.api.parts.LayerBase; -import appeng.core.AELog; -import appeng.core.AppEng; -import appeng.parts.PartPlacement; -import appeng.tile.AEBaseTile; -import appeng.tile.networking.TileCableBus; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.util.*; -public class ApiPart implements IPartHelper -{ +public class ApiPart implements IPartHelper { - private final LoadingCache> cache = CacheBuilder.newBuilder() - .build( new CacheLoader>() - { - @Override - public Class load( CacheKey key ) throws Exception - { - return ApiPart.this.generateCombinedClass( key ); - } - } ); + private final LoadingCache> cache = CacheBuilder.newBuilder() + .build(new CacheLoader>() { + @Override + public Class load(CacheKey key) throws Exception { + return ApiPart.this.generateCombinedClass(key); + } + }); - private final Map, String> interfaces2Layer = new HashMap<>(); - private final List desc = new ArrayList<>(); + private final Map, String> interfaces2Layer = new HashMap<>(); + private final List desc = new ArrayList<>(); - /** - * Conceptually this method will build a new class hierarchy that is rooted at the given base class, and includes a - * chain of all registered layers. - *

- * To accomplish this, it takes the first registered layer, replaces it's inheritance from LayerBase with an - * inheritance from the given baseClass, - * and uses the resulting class as the parent class for the next registered layer, for which it repeats this - * process. This process is then repeated - * until a class hierarchy of all layers is formed. While janking out the inheritance from LayerBase, it'll make - * also sure that calls to that - * classes method will instead be forwarded to the superclass that was inserted as part of the described process. - *

- * Example: If layers A and B are registered, and TileCableBus is passed in as the baseClass, a synthetic class - * A_B_TileCableBus should be returned, - * which has A_B_TileCableBus -extends-> B_TileCableBus -extends-> TileCableBus as it's class hierarchy, where - * A_B_TileCableBus has been generated - * from A, and B_TileCableBus has been generated from B. - */ - public Class getCombinedInstance( final Class baseClass ) - { - if( this.desc.isEmpty() ) - { - // No layers registered... - return baseClass; - } + /** + * Conceptually this method will build a new class hierarchy that is rooted at the given base class, and includes a + * chain of all registered layers. + *

+ * To accomplish this, it takes the first registered layer, replaces it's inheritance from LayerBase with an + * inheritance from the given baseClass, + * and uses the resulting class as the parent class for the next registered layer, for which it repeats this + * process. This process is then repeated + * until a class hierarchy of all layers is formed. While janking out the inheritance from LayerBase, it'll make + * also sure that calls to that + * classes method will instead be forwarded to the superclass that was inserted as part of the described process. + *

+ * Example: If layers A and B are registered, and TileCableBus is passed in as the baseClass, a synthetic class + * A_B_TileCableBus should be returned, + * which has A_B_TileCableBus -extends-> B_TileCableBus -extends-> TileCableBus as it's class hierarchy, where + * A_B_TileCableBus has been generated + * from A, and B_TileCableBus has been generated from B. + */ + public Class getCombinedInstance(final Class baseClass) { + if (this.desc.isEmpty()) { + // No layers registered... + return baseClass; + } - return this.cache.getUnchecked( new CacheKey( baseClass, this.desc ) ); - } + return this.cache.getUnchecked(new CacheKey(baseClass, this.desc)); + } - private Class generateCombinedClass( CacheKey cacheKey ) - { - final Class parentClass; + private Class generateCombinedClass(CacheKey cacheKey) { + final Class parentClass; - // Get the list of interfaces that still need to be implemented beyond the current one - List remainingInterfaces = cacheKey.getInterfaces().subList( 1, cacheKey.getInterfaces().size() ); + // Get the list of interfaces that still need to be implemented beyond the current one + List remainingInterfaces = cacheKey.getInterfaces().subList(1, cacheKey.getInterfaces().size()); - // We are not at the root of the class hierarchy yet - if( !remainingInterfaces.isEmpty() ) - { - CacheKey parentKey = new CacheKey( cacheKey.getBaseClass(), remainingInterfaces ); - parentClass = this.cache.getUnchecked( parentKey ); - } - else - { - parentClass = cacheKey.getBaseClass(); - } + // We are not at the root of the class hierarchy yet + if (!remainingInterfaces.isEmpty()) { + CacheKey parentKey = new CacheKey(cacheKey.getBaseClass(), remainingInterfaces); + parentClass = this.cache.getUnchecked(parentKey); + } else { + parentClass = cacheKey.getBaseClass(); + } - // Which interface should be implemented in this layer? - String interfaceName = cacheKey.getInterfaces().get( 0 ); + // Which interface should be implemented in this layer? + String interfaceName = cacheKey.getInterfaces().get(0); - try - { - // This is the particular interface that this layer was registered for. Loading the class may fail if i.e. - // an API is broken or not present - // and in this case, the layer will be skipped! - Class interfaceClass = Class.forName( interfaceName ); - String layerImpl = this.interfaces2Layer.get( interfaceClass ); + try { + // This is the particular interface that this layer was registered for. Loading the class may fail if i.e. + // an API is broken or not present + // and in this case, the layer will be skipped! + Class interfaceClass = Class.forName(interfaceName); + String layerImpl = this.interfaces2Layer.get(interfaceClass); - return this.getClassByDesc( parentClass, layerImpl ); - } - catch( final Throwable t ) - { - AELog.warn( "Error loading " + interfaceName ); - AELog.debug( t ); - return parentClass; - } + return this.getClassByDesc(parentClass, layerImpl); + } catch (final Throwable t) { + AELog.warn("Error loading " + interfaceName); + AELog.debug(t); + return parentClass; + } - } + } - @SuppressWarnings( "unchecked" ) - private Class getClassByDesc( Class baseClass, final String next ) - { - final ClassWriter cw = new ClassWriter( ClassWriter.COMPUTE_MAXS ); - final ClassNode n = this.getReader( next ); - final String originalName = n.name; + @SuppressWarnings("unchecked") + private Class getClassByDesc(Class baseClass, final String next) { + final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + final ClassNode n = this.getReader(next); + final String originalName = n.name; - try - { - n.name = n.name + '_' + baseClass.getSimpleName(); - n.superName = baseClass.getName().replace( '.', '/' ); - } - catch( final Throwable t ) - { - AELog.debug( t ); - } + try { + n.name = n.name + '_' + baseClass.getSimpleName(); + n.superName = baseClass.getName().replace('.', '/'); + } catch (final Throwable t) { + AELog.debug(t); + } - for( final MethodNode mn : n.methods ) - { - final Iterator i = mn.instructions.iterator(); - while( i.hasNext() ) - { - this.processNode( i.next(), n.superName ); - } - } + for (final MethodNode mn : n.methods) { + final Iterator i = mn.instructions.iterator(); + while (i.hasNext()) { + this.processNode(i.next(), n.superName); + } + } - final DefaultPackageClassNameRemapper remapper = new DefaultPackageClassNameRemapper(); - remapper.inputOutput.put( "appeng/api/parts/LayerBase", n.superName ); - remapper.inputOutput.put( originalName, n.name ); - n.accept( new RemappingClassAdapter( cw, remapper ) ); - // n.accept( cw ); + final DefaultPackageClassNameRemapper remapper = new DefaultPackageClassNameRemapper(); + remapper.inputOutput.put("appeng/api/parts/LayerBase", n.superName); + remapper.inputOutput.put(originalName, n.name); + n.accept(new RemappingClassAdapter(cw, remapper)); + // n.accept( cw ); - // n.accept( new TraceClassVisitor( new PrintWriter( System.out ) ) ); - final byte[] byteArray = cw.toByteArray(); - final int size = byteArray.length; - final Class clazz = this.loadClass( n.name.replace( "/", "." ), byteArray ); + // n.accept( new TraceClassVisitor( new PrintWriter( System.out ) ) ); + final byte[] byteArray = cw.toByteArray(); + final int size = byteArray.length; + final Class clazz = this.loadClass(n.name.replace("/", "."), byteArray); - try - { - final Object fish = clazz.newInstance(); + try { + final Object fish = clazz.newInstance(); - boolean hasError = false; + boolean hasError = false; - if( !baseClass.isInstance( fish ) ) - { - hasError = true; - AELog.error( "Error, Expected layer to implement " + baseClass + " did not." ); - } + if (!baseClass.isInstance(fish)) { + hasError = true; + AELog.error("Error, Expected layer to implement " + baseClass + " did not."); + } - if( fish instanceof LayerBase ) - { - hasError = true; - AELog.error( "Error, Expected layer to NOT implement LayerBase but it DID." ); - } + if (fish instanceof LayerBase) { + hasError = true; + AELog.error("Error, Expected layer to NOT implement LayerBase but it DID."); + } - if( !( fish instanceof TileCableBus ) ) - { - hasError = true; - AELog.error( "Error, Expected layer to implement TileCableBus did not." ); - } + if (!(fish instanceof TileCableBus)) { + hasError = true; + AELog.error("Error, Expected layer to implement TileCableBus did not."); + } - if( !( fish instanceof TileEntity ) ) - { - hasError = true; - AELog.error( "Error, Expected layer to implement TileEntity did not." ); - } + if (!(fish instanceof TileEntity)) { + hasError = true; + AELog.error("Error, Expected layer to implement TileEntity did not."); + } - if( !hasError ) - { - AELog.info( "Layer: " + n.name + " loaded successfully - " + size + " bytes" ); - } - } - catch( final Throwable t ) - { - AELog.error( "Layer: " + n.name + " Failed." ); - AELog.debug( t ); - } + if (!hasError) { + AELog.info("Layer: " + n.name + " loaded successfully - " + size + " bytes"); + } + } catch (final Throwable t) { + AELog.error("Layer: " + n.name + " Failed."); + AELog.debug(t); + } - return clazz; - } + return clazz; + } - private ClassNode getReader( final String name ) - { - final String path = '/' + name.replace( ".", "/" ) + ".class"; - final InputStream is = this.getClass().getResourceAsStream( path ); - try - { - final ClassReader cr = new ClassReader( is ); + private ClassNode getReader(final String name) { + final String path = '/' + name.replace(".", "/") + ".class"; + final InputStream is = this.getClass().getResourceAsStream(path); + try { + final ClassReader cr = new ClassReader(is); - final ClassNode cn = new ClassNode(); - cr.accept( cn, ClassReader.EXPAND_FRAMES ); + final ClassNode cn = new ClassNode(); + cr.accept(cn, ClassReader.EXPAND_FRAMES); - return cn; - } - catch( final IOException e ) - { - throw new IllegalStateException( "Error loading " + name, e ); - } - } + return cn; + } catch (final IOException e) { + throw new IllegalStateException("Error loading " + name, e); + } + } - private void processNode( final AbstractInsnNode next, final String nePar ) - { - if( next instanceof MethodInsnNode ) - { - final MethodInsnNode min = (MethodInsnNode) next; - if( min.owner.equals( "appeng/api/parts/LayerBase" ) ) - { - min.owner = nePar; - } - } - } + private void processNode(final AbstractInsnNode next, final String nePar) { + if (next instanceof MethodInsnNode) { + final MethodInsnNode min = (MethodInsnNode) next; + if (min.owner.equals("appeng/api/parts/LayerBase")) { + min.owner = nePar; + } + } + } - private Class loadClass( final String name, byte[] b ) - { - // override classDefine (as it is protected) and define the class. - Class clazz = null; - try - { - final ClassLoader loader = this.getClass().getClassLoader();// ClassLoader.getSystemClassLoader(); - final Class root = ClassLoader.class; - final Class cls = loader.getClass(); - final Method defineClassMethod = root.getDeclaredMethod( "defineClass", String.class, byte[].class, int.class, int.class ); - final Method runTransformersMethod = cls.getDeclaredMethod( "runTransformers", String.class, String.class, byte[].class ); + private Class loadClass(final String name, byte[] b) { + // override classDefine (as it is protected) and define the class. + Class clazz = null; + try { + final ClassLoader loader = this.getClass().getClassLoader();// ClassLoader.getSystemClassLoader(); + final Class root = ClassLoader.class; + final Class cls = loader.getClass(); + final Method defineClassMethod = root.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class); + final Method runTransformersMethod = cls.getDeclaredMethod("runTransformers", String.class, String.class, byte[].class); - runTransformersMethod.setAccessible( true ); - defineClassMethod.setAccessible( true ); - try - { - final Object[] argsA = { - name, - name, - b - }; - b = (byte[]) runTransformersMethod.invoke( loader, argsA ); + runTransformersMethod.setAccessible(true); + defineClassMethod.setAccessible(true); + try { + final Object[] argsA = { + name, + name, + b + }; + b = (byte[]) runTransformersMethod.invoke(loader, argsA); - final Object[] args = { - name, - b, - 0, - b.length - }; - clazz = (Class) defineClassMethod.invoke( loader, args ); - } - finally - { - runTransformersMethod.setAccessible( false ); - defineClassMethod.setAccessible( false ); - } - } - catch( final Exception e ) - { - AELog.debug( e ); - throw new IllegalStateException( "Unable to manage part API.", e ); - } - return clazz; - } + final Object[] args = { + name, + b, + 0, + b.length + }; + clazz = (Class) defineClassMethod.invoke(loader, args); + } finally { + runTransformersMethod.setAccessible(false); + defineClassMethod.setAccessible(false); + } + } catch (final Exception e) { + AELog.debug(e); + throw new IllegalStateException("Unable to manage part API.", e); + } + return clazz; + } - @Override - public boolean registerNewLayer( final String layer, final String layerInterface ) - { - try - { - final Class layerInterfaceClass = Class.forName( layerInterface ); - if( this.interfaces2Layer.get( layerInterfaceClass ) == null ) - { - this.interfaces2Layer.put( layerInterfaceClass, layer ); - this.desc.add( layerInterface ); - return true; - } - else - { - AELog.info( "Layer " + layer + " not registered, " + layerInterface + " already has a layer." ); - } - } - catch( final Throwable ignored ) - { - } + @Override + public boolean registerNewLayer(final String layer, final String layerInterface) { + try { + final Class layerInterfaceClass = Class.forName(layerInterface); + if (this.interfaces2Layer.get(layerInterfaceClass) == null) { + this.interfaces2Layer.put(layerInterfaceClass, layer); + this.desc.add(layerInterface); + return true; + } else { + AELog.info("Layer " + layer + " not registered, " + layerInterface + " already has a layer."); + } + } catch (final Throwable ignored) { + } - return false; - } + return false; + } - @Override - public EnumActionResult placeBus( final ItemStack is, final BlockPos pos, final EnumFacing side, final EntityPlayer player, final EnumHand hand, final World w ) - { - return PartPlacement.place( is, pos, side, player, hand, w, PartPlacement.PlaceType.PLACE_ITEM, 0 ); - } + @Override + public EnumActionResult placeBus(final ItemStack is, final BlockPos pos, final EnumFacing side, final EntityPlayer player, final EnumHand hand, final World w) { + return PartPlacement.place(is, pos, side, player, hand, w, PartPlacement.PlaceType.PLACE_ITEM, 0); + } - @Override - public CableRenderMode getCableRenderMode() - { - return AppEng.proxy.getRenderMode(); - } + @Override + public CableRenderMode getCableRenderMode() { + return AppEng.proxy.getRenderMode(); + } - private static class DefaultPackageClassNameRemapper extends Remapper - { + private static class DefaultPackageClassNameRemapper extends Remapper { - private final HashMap inputOutput = new HashMap<>(); + private final HashMap inputOutput = new HashMap<>(); - @Override - public String map( final String typeName ) - { - final String o = this.inputOutput.get( typeName ); - if( o == null ) - { - return typeName; - } - return o; - } - } + @Override + public String map(final String typeName) { + final String o = this.inputOutput.get(typeName); + if (o == null) { + return typeName; + } + return o; + } + } - private static class CacheKey - { - private final Class baseClass; + private static class CacheKey { + private final Class baseClass; - private final List interfaces; + private final List interfaces; - private CacheKey( Class baseClass, List interfaces ) - { - this.baseClass = baseClass; - this.interfaces = ImmutableList.copyOf( interfaces ); - } + private CacheKey(Class baseClass, List interfaces) { + this.baseClass = baseClass; + this.interfaces = ImmutableList.copyOf(interfaces); + } - private Class getBaseClass() - { - return this.baseClass; - } + private Class getBaseClass() { + return this.baseClass; + } - private List getInterfaces() - { - return this.interfaces; - } + private List getInterfaces() { + return this.interfaces; + } - @Override - public boolean equals( Object o ) - { - if( this == o ) - { - return true; - } - if( o == null || this.getClass() != o.getClass() ) - { - return false; - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || this.getClass() != o.getClass()) { + return false; + } - CacheKey cacheKey = (CacheKey) o; + CacheKey cacheKey = (CacheKey) o; - return this.baseClass.equals( cacheKey.baseClass ) && this.interfaces.equals( cacheKey.interfaces ); - } + return this.baseClass.equals(cacheKey.baseClass) && this.interfaces.equals(cacheKey.interfaces); + } - @Override - public int hashCode() - { - int result = this.baseClass.hashCode(); - result = 31 * result + this.interfaces.hashCode(); - return result; - } - } + @Override + public int hashCode() { + int result = this.baseClass.hashCode(); + result = 31 * result + this.interfaces.hashCode(); + return result; + } + } } diff --git a/src/main/java/appeng/core/api/ApiStorage.java b/src/main/java/appeng/core/api/ApiStorage.java index 522926600..ffbd07daf 100644 --- a/src/main/java/appeng/core/api/ApiStorage.java +++ b/src/main/java/appeng/core/api/ApiStorage.java @@ -19,21 +19,6 @@ package appeng.core.api; -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ClassToInstanceMap; -import com.google.common.collect.MutableClassToInstanceMap; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; - import appeng.api.config.Actionable; import appeng.api.networking.crafting.ICraftingLink; import appeng.api.networking.crafting.ICraftingRequester; @@ -56,179 +41,164 @@ import appeng.fluids.util.FluidList; import appeng.util.Platform; import appeng.util.item.AEItemStack; import appeng.util.item.ItemList; +import com.google.common.base.Preconditions; +import com.google.common.collect.ClassToInstanceMap; +import com.google.common.collect.MutableClassToInstanceMap; +import io.netty.buffer.ByteBuf; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; + +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; -public class ApiStorage implements IStorageHelper -{ +public class ApiStorage implements IStorageHelper { - private final ClassToInstanceMap> channels; + private final ClassToInstanceMap> channels; - public ApiStorage() - { - this.channels = MutableClassToInstanceMap.create(); - this.registerStorageChannel( IItemStorageChannel.class, new ItemStorageChannel() ); - this.registerStorageChannel( IFluidStorageChannel.class, new FluidStorageChannel() ); - } + public ApiStorage() { + this.channels = MutableClassToInstanceMap.create(); + this.registerStorageChannel(IItemStorageChannel.class, new ItemStorageChannel()); + this.registerStorageChannel(IFluidStorageChannel.class, new FluidStorageChannel()); + } - @Override - public , C extends IStorageChannel> void registerStorageChannel( Class channel, C factory ) - { - Preconditions.checkNotNull( channel ); - Preconditions.checkNotNull( factory ); - Preconditions.checkArgument( channel.isInstance( factory ) ); - Preconditions.checkArgument( !this.channels.containsKey( channel ) ); + @Override + public , C extends IStorageChannel> void registerStorageChannel(Class channel, C factory) { + Preconditions.checkNotNull(channel); + Preconditions.checkNotNull(factory); + Preconditions.checkArgument(channel.isInstance(factory)); + Preconditions.checkArgument(!this.channels.containsKey(channel)); - this.channels.putInstance( channel, factory ); - } + this.channels.putInstance(channel, factory); + } - @Override - public , C extends IStorageChannel> C getStorageChannel( Class channel ) - { - Preconditions.checkNotNull( channel ); + @Override + public , C extends IStorageChannel> C getStorageChannel(Class channel) { + Preconditions.checkNotNull(channel); - final C type = this.channels.getInstance( channel ); + final C type = this.channels.getInstance(channel); - Preconditions.checkNotNull( type ); + Preconditions.checkNotNull(type); - return type; - } + return type; + } - @Override - public Collection>> storageChannels() - { - return Collections.unmodifiableCollection( this.channels.values() ); - } + @Override + public Collection>> storageChannels() { + return Collections.unmodifiableCollection(this.channels.values()); + } - @Override - public ICraftingLink loadCraftingLink( final NBTTagCompound data, final ICraftingRequester req ) - { - Preconditions.checkNotNull( data ); - Preconditions.checkNotNull( req ); + @Override + public ICraftingLink loadCraftingLink(final NBTTagCompound data, final ICraftingRequester req) { + Preconditions.checkNotNull(data); + Preconditions.checkNotNull(req); - return new CraftingLink( data, req ); - } + return new CraftingLink(data, req); + } - @Override - public > T poweredInsert( IEnergySource energy, IMEInventory inv, T input, IActionSource src, Actionable mode ) - { - return Platform.poweredInsert( energy, inv, input, src, mode ); - } + @Override + public > T poweredInsert(IEnergySource energy, IMEInventory inv, T input, IActionSource src, Actionable mode) { + return Platform.poweredInsert(energy, inv, input, src, mode); + } - @Override - public > T poweredExtraction( IEnergySource energy, IMEInventory inv, T request, IActionSource src, Actionable mode ) - { - return Platform.poweredExtraction( energy, inv, request, src, mode ); - } + @Override + public > T poweredExtraction(IEnergySource energy, IMEInventory inv, T request, IActionSource src, Actionable mode) { + return Platform.poweredExtraction(energy, inv, request, src, mode); + } - @Override - public void postChanges( IStorageGrid gs, ItemStack removedCell, ItemStack addedCell, IActionSource src ) - { - Preconditions.checkNotNull( gs ); - Preconditions.checkNotNull( removedCell ); - Preconditions.checkNotNull( addedCell ); - Preconditions.checkNotNull( src ); + @Override + public void postChanges(IStorageGrid gs, ItemStack removedCell, ItemStack addedCell, IActionSource src) { + Preconditions.checkNotNull(gs); + Preconditions.checkNotNull(removedCell); + Preconditions.checkNotNull(addedCell); + Preconditions.checkNotNull(src); - Platform.postChanges( gs, removedCell, addedCell, src ); - } + Platform.postChanges(gs, removedCell, addedCell, src); + } - private static final class ItemStorageChannel implements IItemStorageChannel - { + private static final class ItemStorageChannel implements IItemStorageChannel { - @Override - public IItemList createList() - { - return new ItemList(); - } + @Override + public IItemList createList() { + return new ItemList(); + } - @Override - public IAEItemStack createStack( Object input ) - { - Preconditions.checkNotNull( input ); + @Override + public IAEItemStack createStack(Object input) { + Preconditions.checkNotNull(input); - if( input instanceof ItemStack ) - { - return AEItemStack.fromItemStack( (ItemStack) input ); - } + if (input instanceof ItemStack) { + return AEItemStack.fromItemStack((ItemStack) input); + } - return null; - } + return null; + } - @Override - public IAEItemStack createFromNBT( NBTTagCompound nbt ) - { - Preconditions.checkNotNull( nbt ); - return AEItemStack.fromNBT( nbt ); - } + @Override + public IAEItemStack createFromNBT(NBTTagCompound nbt) { + Preconditions.checkNotNull(nbt); + return AEItemStack.fromNBT(nbt); + } - @Override - public IAEItemStack readFromPacket( ByteBuf input ) throws IOException - { - Preconditions.checkNotNull( input ); + @Override + public IAEItemStack readFromPacket(ByteBuf input) throws IOException { + Preconditions.checkNotNull(input); - return AEItemStack.fromPacket( input ); - } - } + return AEItemStack.fromPacket(input); + } + } - private static final class FluidStorageChannel implements IFluidStorageChannel - { + private static final class FluidStorageChannel implements IFluidStorageChannel { - @Override - public int transferFactor() - { - return 1000; - } + @Override + public int transferFactor() { + return 1000; + } - @Override - public int getUnitsPerByte() - { - return 8000; - } + @Override + public int getUnitsPerByte() { + return 8000; + } - @Override - public IItemList createList() - { - return new FluidList(); - } + @Override + public IItemList createList() { + return new FluidList(); + } - @Override - public IAEFluidStack createStack( Object input ) - { - Preconditions.checkNotNull( input ); + @Override + public IAEFluidStack createStack(Object input) { + Preconditions.checkNotNull(input); - if( input instanceof FluidStack ) - { - return AEFluidStack.fromFluidStack( (FluidStack) input ); - } - if( input instanceof ItemStack ) - { - final ItemStack is = (ItemStack) input; - if( is.getItem() instanceof FluidDummyItem ) - { - return AEFluidStack.fromFluidStack( ( (FluidDummyItem) is.getItem() ).getFluidStack( is ) ); - } - else - { - return AEFluidStack.fromFluidStack( FluidUtil.getFluidContained( is ) ); - } - } + if (input instanceof FluidStack) { + return AEFluidStack.fromFluidStack((FluidStack) input); + } + if (input instanceof ItemStack) { + final ItemStack is = (ItemStack) input; + if (is.getItem() instanceof FluidDummyItem) { + return AEFluidStack.fromFluidStack(((FluidDummyItem) is.getItem()).getFluidStack(is)); + } else { + return AEFluidStack.fromFluidStack(FluidUtil.getFluidContained(is)); + } + } - return null; - } + return null; + } - @Override - public IAEFluidStack readFromPacket( ByteBuf input ) throws IOException - { - Preconditions.checkNotNull( input ); + @Override + public IAEFluidStack readFromPacket(ByteBuf input) throws IOException { + Preconditions.checkNotNull(input); - return AEFluidStack.fromPacket( input ); - } + return AEFluidStack.fromPacket(input); + } - @Override - public IAEFluidStack createFromNBT( NBTTagCompound nbt ) - { - Preconditions.checkNotNull( nbt ); - return AEFluidStack.fromNBT( nbt ); - } - } + @Override + public IAEFluidStack createFromNBT(NBTTagCompound nbt) { + Preconditions.checkNotNull(nbt); + return AEFluidStack.fromNBT(nbt); + } + } } diff --git a/src/main/java/appeng/core/api/IIMCProcessor.java b/src/main/java/appeng/core/api/IIMCProcessor.java index 84ddcf2bb..661dae00e 100644 --- a/src/main/java/appeng/core/api/IIMCProcessor.java +++ b/src/main/java/appeng/core/api/IIMCProcessor.java @@ -22,7 +22,6 @@ package appeng.core.api; import net.minecraftforge.fml.common.event.FMLInterModComms.IMCMessage; -public interface IIMCProcessor -{ - void process( IMCMessage m ); +public interface IIMCProcessor { + void process(IMCMessage m); } diff --git a/src/main/java/appeng/core/api/definitions/ApiBlocks.java b/src/main/java/appeng/core/api/definitions/ApiBlocks.java index 08dfe0a3c..f9ab0f817 100644 --- a/src/main/java/appeng/core/api/definitions/ApiBlocks.java +++ b/src/main/java/appeng/core/api/definitions/ApiBlocks.java @@ -19,61 +19,18 @@ package appeng.core.api.definitions; -import com.google.common.base.Verify; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockDispenser; -import net.minecraft.block.BlockSlab; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemSlab; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.common.registry.EntityEntryBuilder; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; -import net.minecraftforge.oredict.OreDictionary; - import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IBlocks; import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.ITileDefinition; import appeng.block.AEBaseItemBlockChargeable; -import appeng.block.crafting.BlockCraftingMonitor; -import appeng.block.crafting.BlockCraftingStorage; -import appeng.block.crafting.BlockCraftingUnit; +import appeng.block.crafting.*; import appeng.block.crafting.BlockCraftingUnit.CraftingUnitType; -import appeng.block.crafting.BlockMolecularAssembler; -import appeng.block.crafting.ItemCraftingStorage; import appeng.block.grindstone.BlockCrank; import appeng.block.grindstone.BlockGrinder; import appeng.block.grindstone.CrankRendering; -import appeng.block.misc.BlockCellWorkbench; -import appeng.block.misc.BlockCharger; -import appeng.block.misc.BlockCondenser; -import appeng.block.misc.BlockInscriber; -import appeng.block.misc.BlockInterface; -import appeng.block.misc.BlockLightDetector; -import appeng.block.misc.BlockQuartzFixture; -import appeng.block.misc.BlockQuartzGrowthAccelerator; -import appeng.block.misc.BlockSecurityStation; -import appeng.block.misc.BlockSkyCompass; -import appeng.block.misc.BlockTinyTNT; -import appeng.block.misc.BlockVibrationChamber; -import appeng.block.misc.InscriberRendering; -import appeng.block.misc.SecurityStationRendering; -import appeng.block.misc.SkyCompassRendering; -import appeng.block.networking.BlockCableBus; -import appeng.block.networking.BlockController; -import appeng.block.networking.BlockCreativeEnergyCell; -import appeng.block.networking.BlockDenseEnergyCell; -import appeng.block.networking.BlockEnergyAcceptor; -import appeng.block.networking.BlockEnergyCell; -import appeng.block.networking.BlockEnergyCellRendering; -import appeng.block.networking.BlockWireless; -import appeng.block.networking.CableBusRendering; -import appeng.block.networking.ControllerRendering; -import appeng.block.networking.WirelessRendering; +import appeng.block.misc.*; +import appeng.block.networking.*; import appeng.block.paint.BlockPaint; import appeng.block.paint.PaintRendering; import appeng.block.qnb.BlockQuantumLinkChamber; @@ -82,14 +39,8 @@ import appeng.block.qnb.QuantumBridgeRendering; import appeng.block.spatial.BlockMatrixFrame; import appeng.block.spatial.BlockSpatialIOPort; import appeng.block.spatial.BlockSpatialPylon; -import appeng.block.storage.BlockChest; -import appeng.block.storage.BlockDrive; -import appeng.block.storage.BlockIOPort; -import appeng.block.storage.BlockSkyChest; +import appeng.block.storage.*; import appeng.block.storage.BlockSkyChest.SkyChestType; -import appeng.block.storage.ChestRendering; -import appeng.block.storage.DriveRendering; -import appeng.block.storage.SkyChestRenderingCustomizer; import appeng.bootstrap.BlockRenderingCustomizer; import appeng.bootstrap.FeatureFactory; import appeng.bootstrap.IBlockRendering; @@ -106,26 +57,9 @@ import appeng.core.AppEng; import appeng.core.features.AEFeature; import appeng.core.features.BlockDefinition; import appeng.core.features.registries.PartModels; -import appeng.debug.BlockChunkloader; -import appeng.debug.BlockCubeGenerator; -import appeng.debug.BlockEnergyGenerator; -import appeng.debug.BlockItemGen; -import appeng.debug.BlockPhantomNode; -import appeng.debug.TileChunkLoader; -import appeng.debug.TileCubeGenerator; -import appeng.debug.TileEnergyGenerator; -import appeng.debug.TileItemGen; -import appeng.debug.TilePhantomNode; +import appeng.debug.*; import appeng.decorative.slab.BlockSlabCommon; -import appeng.decorative.solid.BlockChargedQuartzOre; -import appeng.decorative.solid.BlockChiseledQuartz; -import appeng.decorative.solid.BlockFluix; -import appeng.decorative.solid.BlockQuartz; -import appeng.decorative.solid.BlockQuartzGlass; -import appeng.decorative.solid.BlockQuartzLamp; -import appeng.decorative.solid.BlockQuartzOre; -import appeng.decorative.solid.BlockQuartzPillar; -import appeng.decorative.solid.BlockSkyStone; +import appeng.decorative.solid.*; import appeng.decorative.solid.BlockSkyStone.SkystoneType; import appeng.decorative.stair.BlockStairCommon; import appeng.entity.EntityIds; @@ -139,23 +73,8 @@ import appeng.tile.crafting.TileCraftingTile; import appeng.tile.crafting.TileMolecularAssembler; import appeng.tile.grindstone.TileCrank; import appeng.tile.grindstone.TileGrinder; -import appeng.tile.misc.TileCellWorkbench; -import appeng.tile.misc.TileCharger; -import appeng.tile.misc.TileCondenser; -import appeng.tile.misc.TileInscriber; -import appeng.tile.misc.TileInterface; -import appeng.tile.misc.TileLightDetector; -import appeng.tile.misc.TilePaint; -import appeng.tile.misc.TileQuartzGrowthAccelerator; -import appeng.tile.misc.TileSecurityStation; -import appeng.tile.misc.TileSkyCompass; -import appeng.tile.misc.TileVibrationChamber; -import appeng.tile.networking.TileController; -import appeng.tile.networking.TileCreativeEnergyCell; -import appeng.tile.networking.TileDenseEnergyCell; -import appeng.tile.networking.TileEnergyAcceptor; -import appeng.tile.networking.TileEnergyCell; -import appeng.tile.networking.TileWireless; +import appeng.tile.misc.*; +import appeng.tile.networking.*; import appeng.tile.qnb.TileQuantumBridge; import appeng.tile.spatial.TileSpatialIOPort; import appeng.tile.spatial.TileSpatialPylon; @@ -163,918 +82,844 @@ import appeng.tile.storage.TileChest; import appeng.tile.storage.TileDrive; import appeng.tile.storage.TileIOPort; import appeng.tile.storage.TileSkyChest; +import com.google.common.base.Verify; +import net.minecraft.block.Block; +import net.minecraft.block.BlockDispenser; +import net.minecraft.block.BlockSlab; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemSlab; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.common.registry.EntityEntryBuilder; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.oredict.OreDictionary; /** * Internal implementation for the API blocks */ -public final class ApiBlocks implements IBlocks -{ - private final IBlockDefinition quartzOre; - private final IBlockDefinition quartzOreCharged; - private final IBlockDefinition matrixFrame; - private final IBlockDefinition quartzBlock; - private final IBlockDefinition quartzPillar; - private final IBlockDefinition chiseledQuartzBlock; - private final IBlockDefinition quartzGlass; - private final IBlockDefinition quartzVibrantGlass; - private final IBlockDefinition quartzFixture; - private final IBlockDefinition fluixBlock; - private final IBlockDefinition skyStoneBlock; - private final IBlockDefinition smoothSkyStoneBlock; - private final IBlockDefinition skyStoneBrick; - private final IBlockDefinition skyStoneSmallBrick; - private final IBlockDefinition skyStoneChest; - private final IBlockDefinition smoothSkyStoneChest; - private final IBlockDefinition skyCompass; - private final ITileDefinition grindstone; - private final ITileDefinition crank; - private final ITileDefinition inscriber; - private final ITileDefinition wirelessAccessPoint; - private final ITileDefinition charger; - private final IBlockDefinition tinyTNT; - private final ITileDefinition securityStation; - private final ITileDefinition quantumRing; - private final ITileDefinition quantumLink; - private final ITileDefinition spatialPylon; - private final ITileDefinition spatialIOPort; - private final ITileDefinition multiPart; - private final ITileDefinition controller; - private final ITileDefinition drive; - private final ITileDefinition chest; - private final ITileDefinition iface; - private final ITileDefinition fluidIface; - private final ITileDefinition cellWorkbench; - private final ITileDefinition iOPort; - private final ITileDefinition condenser; - private final ITileDefinition energyAcceptor; - private final ITileDefinition vibrationChamber; - private final ITileDefinition quartzGrowthAccelerator; - private final ITileDefinition energyCell; - private final ITileDefinition energyCellDense; - private final ITileDefinition energyCellCreative; - private final ITileDefinition craftingUnit; - private final ITileDefinition craftingAccelerator; - private final ITileDefinition craftingStorage1k; - private final ITileDefinition craftingStorage4k; - private final ITileDefinition craftingStorage16k; - private final ITileDefinition craftingStorage64k; - private final ITileDefinition craftingMonitor; - private final ITileDefinition molecularAssembler; - private final ITileDefinition lightDetector; - private final ITileDefinition paint; - private final IBlockDefinition skyStoneStairs; - private final IBlockDefinition smoothSkyStoneStairs; - private final IBlockDefinition skyStoneBrickStairs; - private final IBlockDefinition skyStoneSmallBrickStairs; - private final IBlockDefinition fluixStairs; - private final IBlockDefinition quartzStairs; - private final IBlockDefinition chiseledQuartzStairs; - private final IBlockDefinition quartzPillarStairs; - - private final IBlockDefinition skyStoneSlab; - private final IBlockDefinition smoothSkyStoneSlab; - private final IBlockDefinition skyStoneBrickSlab; - private final IBlockDefinition skyStoneSmallBrickSlab; - private final IBlockDefinition fluixSlab; - private final IBlockDefinition quartzSlab; - private final IBlockDefinition chiseledQuartzSlab; - private final IBlockDefinition quartzPillarSlab; - - private final IBlockDefinition itemGen; - private final IBlockDefinition chunkLoader; - private final IBlockDefinition phantomNode; - private final IBlockDefinition cubeGenerator; - private final IBlockDefinition energyGenerator; - - public ApiBlocks( FeatureFactory registry, PartModels partModels ) - { - // this.quartzOre = new BlockDefinition( "ore.quartz", new OreQuartz() ); - this.quartzOre = registry.block( "quartz_ore", BlockQuartzOre::new ) - .features( AEFeature.CERTUS_ORE ) - .bootstrap( ( block, item ) -> (IOreDictComponent) side -> OreDictionary.registerOre( "oreCertusQuartz", new ItemStack( block ) ) ) - .build(); - this.quartzOreCharged = registry.block( "charged_quartz_ore", BlockChargedQuartzOre::new ) - .features( AEFeature.CERTUS_ORE, AEFeature.CHARGED_CERTUS_ORE ) - .useCustomItemModel() - .bootstrap( ( block, item ) -> (IOreDictComponent) side -> - { - OreDictionary.registerOre( "oreCertusQuartz", new ItemStack( block ) ); - OreDictionary.registerOre( "oreChargedCertusQuartz", new ItemStack( block ) ); - } ) - .build(); - this.matrixFrame = registry.block( "matrix_frame", BlockMatrixFrame::new ).features( AEFeature.SPATIAL_IO ).build(); - - FeatureFactory deco = registry.features( AEFeature.DECORATIVE_BLOCKS ); - this.quartzBlock = deco.block( "quartz_block", BlockQuartz::new ).build(); - this.quartzPillar = deco.block( "quartz_pillar", BlockQuartzPillar::new ).build(); - this.chiseledQuartzBlock = deco.block( "chiseled_quartz_block", BlockChiseledQuartz::new ).build(); - - this.quartzGlass = registry.features( AEFeature.QUARTZ_GLASS ) - .block( "quartz_glass", BlockQuartzGlass::new ) - .useCustomItemModel() - .rendering( new BlockRenderingCustomizer() - { - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - rendering.builtInModel( "models/block/builtin/quartz_glass", new GlassModel() ); - } - } ) - .build(); - this.quartzVibrantGlass = deco.block( "quartz_vibrant_glass", BlockQuartzLamp::new ) - .addFeatures( AEFeature.DECORATIVE_LIGHTS, AEFeature.QUARTZ_GLASS ) - .useCustomItemModel() - .build(); - this.quartzFixture = registry.block( "quartz_fixture", BlockQuartzFixture::new ) - .features( AEFeature.DECORATIVE_LIGHTS ) - .useCustomItemModel() - .build(); - - this.fluixBlock = registry.features( AEFeature.FLUIX ).block( "fluix_block", BlockFluix::new ).build(); - - this.skyStoneBlock = registry.features( AEFeature.SKY_STONE ) - .block( "sky_stone_block", () -> new BlockSkyStone( SkystoneType.STONE ) ) - .build(); - this.smoothSkyStoneBlock = registry.features( AEFeature.SKY_STONE ) - .block( "smooth_sky_stone_block", () -> new BlockSkyStone( SkystoneType.BLOCK ) ) - .build(); - this.skyStoneBrick = deco.block( "sky_stone_brick", () -> new BlockSkyStone( SkystoneType.BRICK ) ) - .addFeatures( AEFeature.SKY_STONE ) - .build(); - this.skyStoneSmallBrick = deco.block( "sky_stone_small_brick", () -> new BlockSkyStone( SkystoneType.SMALL_BRICK ) ) - .addFeatures( AEFeature.SKY_STONE ) - .build(); - - this.skyStoneChest = registry.block( "sky_stone_chest", () -> new BlockSkyChest( SkyChestType.STONE ) ) - .features( AEFeature.SKY_STONE, AEFeature.SKY_STONE_CHESTS ) - .tileEntity( new TileEntityDefinition( TileSkyChest.class, "sky_stone_chest" ) ) - .rendering( new SkyChestRenderingCustomizer( SkyChestType.STONE ) ) - .build(); - this.smoothSkyStoneChest = registry.block( "smooth_sky_stone_chest", () -> new BlockSkyChest( SkyChestType.BLOCK ) ) - .features( AEFeature.SKY_STONE, AEFeature.SKY_STONE_CHESTS ) - .tileEntity( new TileEntityDefinition( TileSkyChest.class, "sky_stone_chest" ) ) - .rendering( new SkyChestRenderingCustomizer( SkyChestType.BLOCK ) ) - .build(); - - this.skyCompass = registry.block( "sky_compass", BlockSkyCompass::new ) - .features( AEFeature.METEORITE_COMPASS ) - .tileEntity( new TileEntityDefinition( TileSkyCompass.class ) ) - .rendering( new SkyCompassRendering() ) - .build(); - this.grindstone = registry.block( "grindstone", BlockGrinder::new ) - .features( AEFeature.GRIND_STONE ) - .tileEntity( new TileEntityDefinition( TileGrinder.class ) ) - .build(); - this.crank = registry.block( "crank", BlockCrank::new ) - .features( AEFeature.GRIND_STONE ) - .tileEntity( new TileEntityDefinition( TileCrank.class ) ) - .rendering( new CrankRendering() ) - .useCustomItemModel() - .build(); - this.inscriber = registry.block( "inscriber", BlockInscriber::new ) - .features( AEFeature.INSCRIBER ) - .tileEntity( new TileEntityDefinition( TileInscriber.class ) ) - .rendering( new InscriberRendering() ) - .build(); - this.wirelessAccessPoint = registry.block( "wireless_access_point", BlockWireless::new ) - .features( AEFeature.WIRELESS_ACCESS_TERMINAL ) - .tileEntity( new TileEntityDefinition( TileWireless.class ) ) - .rendering( new WirelessRendering() ) - .build(); - this.charger = registry.block( "charger", BlockCharger::new ) - .features( AEFeature.CHARGER ) - .tileEntity( new TileEntityDefinition( TileCharger.class ) ) - .rendering( new BlockRenderingCustomizer() - { - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - rendering.tesr( BlockCharger.createTesr() ); - } - } ) - .build(); - this.tinyTNT = registry.block( "tiny_tnt", BlockTinyTNT::new ) - .features( AEFeature.TINY_TNT ) - .bootstrap( ( block, item ) -> (IPreInitComponent) side -> BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject( item, - new DispenserBehaviorTinyTNT() ) ) - .bootstrap( ( block, item ) -> (IEntityRegistrationComponent) r -> - { - r.register( EntityEntryBuilder.create() - .entity( EntityTinyTNTPrimed.class ) - .id( new ResourceLocation( "appliedenergistics2", EntityTinyTNTPrimed.class.getName() ), - EntityIds.get( EntityTinyTNTPrimed.class ) ) - .name( "EntityTinyTNTPrimed" ) - .tracker( 16, 4, true ) - .build() ); - } ) - .build(); - this.securityStation = registry.block( "security_station", BlockSecurityStation::new ) - .features( AEFeature.SECURITY ) - .tileEntity( new TileEntityDefinition( TileSecurityStation.class ) ) - .rendering( new SecurityStationRendering() ) - .build(); - this.quantumRing = registry.block( "quantum_ring", BlockQuantumRing::new ) - .features( AEFeature.QUANTUM_NETWORK_BRIDGE ) - .tileEntity( new TileEntityDefinition( TileQuantumBridge.class, "quantum_ring" ) ) - .rendering( new QuantumBridgeRendering() ) - .build(); - this.quantumLink = registry.block( "quantum_link", BlockQuantumLinkChamber::new ) - .features( AEFeature.QUANTUM_NETWORK_BRIDGE ) - .tileEntity( new TileEntityDefinition( TileQuantumBridge.class, "quantum_ring" ) ) - .rendering( new QuantumBridgeRendering() ) - .build(); - this.spatialPylon = registry.block( "spatial_pylon", BlockSpatialPylon::new ) - .features( AEFeature.SPATIAL_IO ) - .tileEntity( new TileEntityDefinition( TileSpatialPylon.class ) ) - .useCustomItemModel() - .rendering( new SpatialPylonRendering() ) - .build(); - this.spatialIOPort = registry.block( "spatial_io_port", BlockSpatialIOPort::new ) - .features( AEFeature.SPATIAL_IO ) - .tileEntity( new TileEntityDefinition( TileSpatialIOPort.class ) ) - .build(); - this.controller = registry.block( "controller", BlockController::new ) - .tileEntity( new TileEntityDefinition( TileController.class ) ) - .useCustomItemModel() - .rendering( new ControllerRendering() ) - .build(); - this.drive = registry.block( "drive", BlockDrive::new ) - .features( AEFeature.STORAGE_CELLS, AEFeature.ME_DRIVE ) - .tileEntity( new TileEntityDefinition( TileDrive.class ) ) - .useCustomItemModel() - .rendering( new DriveRendering() ) - .build(); - this.chest = registry.block( "chest", BlockChest::new ) - .features( AEFeature.STORAGE_CELLS, AEFeature.ME_CHEST ) - .tileEntity( new TileEntityDefinition( TileChest.class ) ) - .useCustomItemModel() - .rendering( new ChestRendering() ) - .build(); - this.iface = registry.block( "interface", BlockInterface::new ) - .features( AEFeature.INTERFACE ) - .tileEntity( new TileEntityDefinition( TileInterface.class ) ) - .build(); - this.fluidIface = registry.block( "fluid_interface", BlockFluidInterface::new ) - .features( AEFeature.FLUID_INTERFACE ) - .tileEntity( new TileEntityDefinition( TileFluidInterface.class ) ) - .build(); - this.cellWorkbench = registry.block( "cell_workbench", BlockCellWorkbench::new ) - .features( AEFeature.STORAGE_CELLS ) - .tileEntity( new TileEntityDefinition( TileCellWorkbench.class ) ) - .build(); - this.iOPort = registry.block( "io_port", BlockIOPort::new ) - .features( AEFeature.STORAGE_CELLS, AEFeature.IO_PORT ) - .tileEntity( new TileEntityDefinition( TileIOPort.class ) ) - .build(); - this.condenser = registry.block( "condenser", BlockCondenser::new ) - .features( AEFeature.CONDENSER ) - .tileEntity( new TileEntityDefinition( TileCondenser.class ) ) - .build(); - this.energyAcceptor = registry.block( "energy_acceptor", BlockEnergyAcceptor::new ) - .features( AEFeature.ENERGY_ACCEPTOR ) - .tileEntity( new TileEntityDefinition( TileEnergyAcceptor.class ) ) - .build(); - this.vibrationChamber = registry.block( "vibration_chamber", BlockVibrationChamber::new ) - .features( AEFeature.POWER_GEN ) - .tileEntity( new TileEntityDefinition( TileVibrationChamber.class ) ) - .build(); - this.quartzGrowthAccelerator = registry.block( "quartz_growth_accelerator", BlockQuartzGrowthAccelerator::new ) - .tileEntity( new TileEntityDefinition( TileQuartzGrowthAccelerator.class ) ) - .features( AEFeature.CRYSTAL_GROWTH_ACCELERATOR ) - .build(); - this.energyCell = registry.block( "energy_cell", BlockEnergyCell::new ) - .features( AEFeature.ENERGY_CELLS ) - .item( AEBaseItemBlockChargeable::new ) - .tileEntity( new TileEntityDefinition( TileEnergyCell.class ) ) - .rendering( new BlockEnergyCellRendering( new ResourceLocation( AppEng.MOD_ID, "energy_cell" ) ) ) - .build(); - this.energyCellDense = registry.block( "dense_energy_cell", BlockDenseEnergyCell::new ) - .features( AEFeature.ENERGY_CELLS, AEFeature.DENSE_ENERGY_CELLS ) - .item( AEBaseItemBlockChargeable::new ) - .tileEntity( new TileEntityDefinition( TileDenseEnergyCell.class ) ) - .rendering( new BlockEnergyCellRendering( new ResourceLocation( AppEng.MOD_ID, "dense_energy_cell" ) ) ) - .build(); - this.energyCellCreative = registry.block( "creative_energy_cell", BlockCreativeEnergyCell::new ) - .features( AEFeature.CREATIVE ) - .tileEntity( new TileEntityDefinition( TileCreativeEnergyCell.class ) ) - .build(); - - FeatureFactory crafting = registry.features( AEFeature.CRAFTING_CPU ); - this.craftingUnit = crafting.block( "crafting_unit", () -> new BlockCraftingUnit( CraftingUnitType.UNIT ) ) - .rendering( new CraftingCubeRendering( "crafting_unit", CraftingUnitType.UNIT ) ) - .tileEntity( new TileEntityDefinition( TileCraftingTile.class, "crafting_unit" ) ) - .useCustomItemModel() - .build(); - this.craftingAccelerator = crafting.block( "crafting_accelerator", () -> new BlockCraftingUnit( CraftingUnitType.ACCELERATOR ) ) - .rendering( new CraftingCubeRendering( "crafting_accelerator", CraftingUnitType.ACCELERATOR ) ) - .tileEntity( new TileEntityDefinition( TileCraftingTile.class, "crafting_unit" ) ) - .useCustomItemModel() - .build(); - this.craftingStorage1k = crafting.block( "crafting_storage_1k", () -> new BlockCraftingStorage( CraftingUnitType.STORAGE_1K ) ) - .item( ItemCraftingStorage::new ) - .tileEntity( new TileEntityDefinition( TileCraftingStorageTile.class, "crafting_storage" ) ) - .rendering( new CraftingCubeRendering( "crafting_storage_1k", CraftingUnitType.STORAGE_1K ) ) - .useCustomItemModel() - .build(); - this.craftingStorage4k = crafting.block( "crafting_storage_4k", () -> new BlockCraftingStorage( CraftingUnitType.STORAGE_4K ) ) - .item( ItemCraftingStorage::new ) - .tileEntity( new TileEntityDefinition( TileCraftingStorageTile.class, "crafting_storage" ) ) - .rendering( new CraftingCubeRendering( "crafting_storage_4k", CraftingUnitType.STORAGE_4K ) ) - .useCustomItemModel() - .build(); - this.craftingStorage16k = crafting.block( "crafting_storage_16k", () -> new BlockCraftingStorage( CraftingUnitType.STORAGE_16K ) ) - .item( ItemCraftingStorage::new ) - .tileEntity( new TileEntityDefinition( TileCraftingStorageTile.class, "crafting_storage" ) ) - .rendering( new CraftingCubeRendering( "crafting_storage_16k", CraftingUnitType.STORAGE_16K ) ) - .useCustomItemModel() - .build(); - this.craftingStorage64k = crafting.block( "crafting_storage_64k", () -> new BlockCraftingStorage( CraftingUnitType.STORAGE_64K ) ) - .item( ItemCraftingStorage::new ) - .tileEntity( new TileEntityDefinition( TileCraftingStorageTile.class, "crafting_storage" ) ) - .rendering( new CraftingCubeRendering( "crafting_storage_64k", CraftingUnitType.STORAGE_64K ) ) - .useCustomItemModel() - .build(); - this.craftingMonitor = crafting.block( "crafting_monitor", BlockCraftingMonitor::new ) - .tileEntity( new TileEntityDefinition( TileCraftingMonitorTile.class ) ) - .rendering( new CraftingCubeRendering( "crafting_monitor", CraftingUnitType.MONITOR ) ) - .useCustomItemModel() - .build(); - - this.molecularAssembler = registry.block( "molecular_assembler", BlockMolecularAssembler::new ) - .features( AEFeature.MOLECULAR_ASSEMBLER ) - .tileEntity( new TileEntityDefinition( TileMolecularAssembler.class ) ) - .build(); - this.lightDetector = registry.block( "light_detector", BlockLightDetector::new ) - .features( AEFeature.LIGHT_DETECTOR ) - .tileEntity( new TileEntityDefinition( TileLightDetector.class ) ) - .useCustomItemModel() - .build(); - this.paint = registry.block( "paint", BlockPaint::new ) - .features( AEFeature.PAINT_BALLS ) - .tileEntity( new TileEntityDefinition( TilePaint.class ) ) - .rendering( new PaintRendering() ) - .build(); - - this.skyStoneStairs = makeStairs( "sky_stone_stairs", registry, this.skyStoneBlock() ); - this.smoothSkyStoneStairs = makeStairs( "smooth_sky_stone_stairs", registry, this.smoothSkyStoneBlock() ); - this.skyStoneBrickStairs = makeStairs( "sky_stone_brick_stairs", registry, this.skyStoneBrick() ); - this.skyStoneSmallBrickStairs = makeStairs( "sky_stone_small_brick_stairs", registry, this.skyStoneSmallBrick() ); - this.fluixStairs = makeStairs( "fluix_stairs", registry, this.fluixBlock() ); - this.quartzStairs = makeStairs( "quartz_stairs", registry, this.quartzBlock() ); - this.chiseledQuartzStairs = makeStairs( "chiseled_quartz_stairs", registry, this.chiseledQuartzBlock() ); - this.quartzPillarStairs = makeStairs( "quartz_pillar_stairs", registry, this.quartzPillar() ); - - this.multiPart = registry.block( "cable_bus", BlockCableBus::new ) - .rendering( new CableBusRendering( partModels ) ) - // (handled in BlockCableBus.java and its setupTile()) - // .tileEntity( TileCableBus.class ) - // TODO: why the custom registration? - .bootstrap( ( block, item ) -> (IPostInitComponent) side -> ( (BlockCableBus) block ).setupTile() ) - .build(); - - this.skyStoneSlab = makeSlab( "sky_stone_slab", "sky_stone_double_slab", registry, this.skyStoneBlock() ); - this.smoothSkyStoneSlab = makeSlab( "smooth_sky_stone_slab", "smooth_sky_stone_double_slab", registry, this.smoothSkyStoneBlock() ); - this.skyStoneBrickSlab = makeSlab( "sky_stone_brick_slab", "sky_stone_brick_double_slab", registry, this.skyStoneBrick() ); - this.skyStoneSmallBrickSlab = makeSlab( "sky_stone_small_brick_slab", "sky_stone_small_brick_double_slab", registry, this.skyStoneSmallBrick() ); - this.fluixSlab = makeSlab( "fluix_slab", "fluix_double_slab", registry, this.fluixBlock() ); - this.quartzSlab = makeSlab( "quartz_slab", "quartz_double_slab", registry, this.quartzBlock() ); - this.chiseledQuartzSlab = makeSlab( "chiseled_quartz_slab", "chiseled_quartz_double_slab", registry, this.chiseledQuartzBlock() ); - this.quartzPillarSlab = makeSlab( "quartz_pillar_slab", "quartz_pillar_double_slab", registry, this.quartzPillar() ); - - this.itemGen = registry.block( "debug_item_gen", BlockItemGen::new ) - .features( AEFeature.UNSUPPORTED_DEVELOPER_TOOLS, AEFeature.CREATIVE ) - .tileEntity( new TileEntityDefinition( TileItemGen.class ) ) - .useCustomItemModel() - .build(); - this.chunkLoader = registry.block( "debug_chunk_loader", BlockChunkloader::new ) - .features( AEFeature.UNSUPPORTED_DEVELOPER_TOOLS, AEFeature.CREATIVE ) - .tileEntity( new TileEntityDefinition( TileChunkLoader.class ) ) - .useCustomItemModel() - .build(); - this.phantomNode = registry.block( "debug_phantom_node", BlockPhantomNode::new ) - .features( AEFeature.UNSUPPORTED_DEVELOPER_TOOLS, AEFeature.CREATIVE ) - .tileEntity( new TileEntityDefinition( TilePhantomNode.class ) ) - .useCustomItemModel() - .build(); - this.cubeGenerator = registry.block( "debug_cube_gen", BlockCubeGenerator::new ) - .features( AEFeature.UNSUPPORTED_DEVELOPER_TOOLS, AEFeature.CREATIVE ) - .tileEntity( new TileEntityDefinition( TileCubeGenerator.class ) ) - .useCustomItemModel() - .build(); - this.energyGenerator = registry.block( "debug_energy_gen", BlockEnergyGenerator::new ) - .features( AEFeature.UNSUPPORTED_DEVELOPER_TOOLS, AEFeature.CREATIVE ) - .tileEntity( new TileEntityDefinition( TileEnergyGenerator.class ) ) - .useCustomItemModel() - .build(); - } - - private static IBlockDefinition makeSlab( String slabId, String doubleSlabId, FeatureFactory registry, IBlockDefinition blockDef ) - { - if( !blockDef.maybeBlock().isPresent() ) - { - return new BlockDefinition( slabId, null, null ); - } - - Block block = blockDef.maybeBlock().get(); - - IBlockDefinition slabDef = registry.block( slabId, () -> new BlockSlabCommon.Half( block ) ) - .features( AEFeature.DECORATIVE_BLOCKS ) - .disableItem() - .build(); - - if( !slabDef.maybeBlock().isPresent() ) - { - return new BlockDefinition( slabId, null, null ); - } - - BlockSlab slabBlock = (BlockSlab) slabDef.maybeBlock().get(); - - // Reigster the double slab variant as well - IBlockDefinition doubleSlabDef = registry.block( doubleSlabId, () -> new BlockSlabCommon.Double( slabBlock, block ) ) - .features( AEFeature.DECORATIVE_BLOCKS ) - .disableItem() - .build(); - - Verify.verify( doubleSlabDef.maybeBlock().isPresent() ); - - BlockSlab doubleSlabBlock = (BlockSlab) doubleSlabDef.maybeBlock().get(); - - // Make the slab item - IItemDefinition itemDef = registry.item( slabId, () -> new ItemSlab( slabBlock, slabBlock, doubleSlabBlock ) ) - .features( AEFeature.DECORATIVE_BLOCKS ) - .build(); - - Verify.verify( itemDef.maybeItem().isPresent() ); - - // Return a new composite block definition that combines the single slab block with the slab item - return new BlockDefinition( slabId, slabBlock, (ItemBlock) itemDef.maybeItem().get() ); - } - - private static IBlockDefinition makeStairs( String registryName, FeatureFactory registry, IBlockDefinition block ) - { - if( !block.maybeBlock().isPresent() ) - { - return new BlockDefinition( registryName, null, null ); - } - - IBlockDefinition stairs = registry.block( registryName, () -> new BlockStairCommon( block.maybeBlock().get(), block.identifier() ) ) - .features( AEFeature.DECORATIVE_BLOCKS ) - .rendering( new BlockRenderingCustomizer() - { - @Override - @SideOnly( Side.CLIENT ) - public void customize( IBlockRendering rendering, IItemRendering itemRendering ) - { - ModelResourceLocation model = new ModelResourceLocation( new ResourceLocation( AppEng.MOD_ID, registryName ), "facing=east,half=bottom,shape=straight" ); - itemRendering.model( model ); - } - } ) - .build(); - - Verify.verify( stairs.maybeBlock().isPresent() ); - - return stairs; - } - - @Override - public IBlockDefinition quartzOre() - { - return this.quartzOre; - } - - @Override - public IBlockDefinition quartzOreCharged() - { - return this.quartzOreCharged; - } - - @Override - public IBlockDefinition matrixFrame() - { - return this.matrixFrame; - } - - @Override - public IBlockDefinition quartzBlock() - { - return this.quartzBlock; - } - - @Override - public IBlockDefinition quartzPillar() - { - return this.quartzPillar; - } - - @Override - public IBlockDefinition chiseledQuartzBlock() - { - return this.chiseledQuartzBlock; - } - - @Override - public IBlockDefinition quartzGlass() - { - return this.quartzGlass; - } - - @Override - public IBlockDefinition quartzVibrantGlass() - { - return this.quartzVibrantGlass; - } - - @Override - public IBlockDefinition quartzFixture() - { - return this.quartzFixture; - } - - @Override - public IBlockDefinition fluixBlock() - { - return this.fluixBlock; - } - - @Override - public IBlockDefinition skyStoneBlock() - { - return this.skyStoneBlock; - } - - @Override - public IBlockDefinition smoothSkyStoneBlock() - { - return this.smoothSkyStoneBlock; - } - - @Override - public IBlockDefinition skyStoneBrick() - { - return this.skyStoneBrick; - } - - @Override - public IBlockDefinition skyStoneSmallBrick() - { - return this.skyStoneSmallBrick; - } - - @Override - public IBlockDefinition skyStoneChest() - { - return this.skyStoneChest; - } - - @Override - public IBlockDefinition smoothSkyStoneChest() - { - return this.smoothSkyStoneChest; - } - - @Override - public IBlockDefinition skyCompass() - { - return this.skyCompass; - } - - @Override - public IBlockDefinition skyStoneStairs() - { - return this.skyStoneStairs; - } - - @Override - public IBlockDefinition smoothSkyStoneStairs() - { - return this.smoothSkyStoneStairs; - } - - @Override - public IBlockDefinition skyStoneBrickStairs() - { - return this.skyStoneBrickStairs; - } - - @Override - public IBlockDefinition skyStoneSmallBrickStairs() - { - return this.skyStoneSmallBrickStairs; - } - - @Override - public IBlockDefinition fluixStairs() - { - return this.fluixStairs; - } - - @Override - public IBlockDefinition quartzStairs() - { - return this.quartzStairs; - } - - @Override - public IBlockDefinition chiseledQuartzStairs() - { - return this.chiseledQuartzStairs; - } - - @Override - public IBlockDefinition quartzPillarStairs() - { - return this.quartzPillarStairs; - } - - @Override - public IBlockDefinition skyStoneSlab() - { - return this.skyStoneSlab; - } - - @Override - public IBlockDefinition smoothSkyStoneSlab() - { - return this.smoothSkyStoneSlab; - } - - @Override - public IBlockDefinition skyStoneBrickSlab() - { - return this.skyStoneBrickSlab; - } - - @Override - public IBlockDefinition skyStoneSmallBrickSlab() - { - return this.skyStoneSmallBrickSlab; - } - - @Override - public IBlockDefinition fluixSlab() - { - return this.fluixSlab; - } - - @Override - public IBlockDefinition quartzSlab() - { - return this.quartzSlab; - } - - @Override - public IBlockDefinition chiseledQuartzSlab() - { - return this.chiseledQuartzSlab; - } - - @Override - public IBlockDefinition quartzPillarSlab() - { - return this.quartzPillarSlab; - } - - @Override - public ITileDefinition grindstone() - { - return this.grindstone; - } - - @Override - public ITileDefinition crank() - { - return this.crank; - } - - @Override - public ITileDefinition inscriber() - { - return this.inscriber; - } - - @Override - public ITileDefinition wirelessAccessPoint() - { - return this.wirelessAccessPoint; - } - - @Override - public ITileDefinition charger() - { - return this.charger; - } - - @Override - public IBlockDefinition tinyTNT() - { - return this.tinyTNT; - } - - @Override - public ITileDefinition securityStation() - { - return this.securityStation; - } - - @Override - public ITileDefinition quantumRing() - { - return this.quantumRing; - } - - @Override - public ITileDefinition quantumLink() - { - return this.quantumLink; - } - - @Override - public ITileDefinition spatialPylon() - { - return this.spatialPylon; - } - - @Override - public ITileDefinition spatialIOPort() - { - return this.spatialIOPort; - } - - @Override - public ITileDefinition multiPart() - { - return this.multiPart; - } - - @Override - public ITileDefinition controller() - { - return this.controller; - } - - @Override - public ITileDefinition drive() - { - return this.drive; - } - - @Override - public ITileDefinition chest() - { - return this.chest; - } - - @Override - public ITileDefinition iface() - { - return this.iface; - } - - @Override - public ITileDefinition fluidIface() - { - return this.fluidIface; - } - - @Override - public ITileDefinition cellWorkbench() - { - return this.cellWorkbench; - } - - @Override - public ITileDefinition iOPort() - { - return this.iOPort; - } - - @Override - public ITileDefinition condenser() - { - return this.condenser; - } - - @Override - public ITileDefinition energyAcceptor() - { - return this.energyAcceptor; - } - - @Override - public ITileDefinition vibrationChamber() - { - return this.vibrationChamber; - } - - @Override - public ITileDefinition quartzGrowthAccelerator() - { - return this.quartzGrowthAccelerator; - } - - @Override - public ITileDefinition energyCell() - { - return this.energyCell; - } - - @Override - public ITileDefinition energyCellDense() - { - return this.energyCellDense; - } - - @Override - public ITileDefinition energyCellCreative() - { - return this.energyCellCreative; - } - - @Override - public ITileDefinition craftingUnit() - { - return this.craftingUnit; - } - - @Override - public ITileDefinition craftingAccelerator() - { - return this.craftingAccelerator; - } - - @Override - public ITileDefinition craftingStorage1k() - { - return this.craftingStorage1k; - } - - @Override - public ITileDefinition craftingStorage4k() - { - return this.craftingStorage4k; - } - - @Override - public ITileDefinition craftingStorage16k() - { - return this.craftingStorage16k; - } - - @Override - public ITileDefinition craftingStorage64k() - { - return this.craftingStorage64k; - } - - @Override - public ITileDefinition craftingMonitor() - { - return this.craftingMonitor; - } - - @Override - public ITileDefinition molecularAssembler() - { - return this.molecularAssembler; - } - - @Override - public ITileDefinition lightDetector() - { - return this.lightDetector; - } - - @Override - public ITileDefinition paint() - { - return this.paint; - } - - public IBlockDefinition chunkLoader() - { - return this.chunkLoader; - } - - public IBlockDefinition itemGen() - { - return this.itemGen; - } - - public IBlockDefinition phantomNode() - { - return this.phantomNode; - } - - public IBlockDefinition cubeGenerator() - { - return this.cubeGenerator; - } - - public IBlockDefinition energyGenerator() - { - return this.energyGenerator; - } +public final class ApiBlocks implements IBlocks { + private final IBlockDefinition quartzOre; + private final IBlockDefinition quartzOreCharged; + private final IBlockDefinition matrixFrame; + private final IBlockDefinition quartzBlock; + private final IBlockDefinition quartzPillar; + private final IBlockDefinition chiseledQuartzBlock; + private final IBlockDefinition quartzGlass; + private final IBlockDefinition quartzVibrantGlass; + private final IBlockDefinition quartzFixture; + private final IBlockDefinition fluixBlock; + private final IBlockDefinition skyStoneBlock; + private final IBlockDefinition smoothSkyStoneBlock; + private final IBlockDefinition skyStoneBrick; + private final IBlockDefinition skyStoneSmallBrick; + private final IBlockDefinition skyStoneChest; + private final IBlockDefinition smoothSkyStoneChest; + private final IBlockDefinition skyCompass; + private final ITileDefinition grindstone; + private final ITileDefinition crank; + private final ITileDefinition inscriber; + private final ITileDefinition wirelessAccessPoint; + private final ITileDefinition charger; + private final IBlockDefinition tinyTNT; + private final ITileDefinition securityStation; + private final ITileDefinition quantumRing; + private final ITileDefinition quantumLink; + private final ITileDefinition spatialPylon; + private final ITileDefinition spatialIOPort; + private final ITileDefinition multiPart; + private final ITileDefinition controller; + private final ITileDefinition drive; + private final ITileDefinition chest; + private final ITileDefinition iface; + private final ITileDefinition fluidIface; + private final ITileDefinition cellWorkbench; + private final ITileDefinition iOPort; + private final ITileDefinition condenser; + private final ITileDefinition energyAcceptor; + private final ITileDefinition vibrationChamber; + private final ITileDefinition quartzGrowthAccelerator; + private final ITileDefinition energyCell; + private final ITileDefinition energyCellDense; + private final ITileDefinition energyCellCreative; + private final ITileDefinition craftingUnit; + private final ITileDefinition craftingAccelerator; + private final ITileDefinition craftingStorage1k; + private final ITileDefinition craftingStorage4k; + private final ITileDefinition craftingStorage16k; + private final ITileDefinition craftingStorage64k; + private final ITileDefinition craftingMonitor; + private final ITileDefinition molecularAssembler; + private final ITileDefinition lightDetector; + private final ITileDefinition paint; + private final IBlockDefinition skyStoneStairs; + private final IBlockDefinition smoothSkyStoneStairs; + private final IBlockDefinition skyStoneBrickStairs; + private final IBlockDefinition skyStoneSmallBrickStairs; + private final IBlockDefinition fluixStairs; + private final IBlockDefinition quartzStairs; + private final IBlockDefinition chiseledQuartzStairs; + private final IBlockDefinition quartzPillarStairs; + + private final IBlockDefinition skyStoneSlab; + private final IBlockDefinition smoothSkyStoneSlab; + private final IBlockDefinition skyStoneBrickSlab; + private final IBlockDefinition skyStoneSmallBrickSlab; + private final IBlockDefinition fluixSlab; + private final IBlockDefinition quartzSlab; + private final IBlockDefinition chiseledQuartzSlab; + private final IBlockDefinition quartzPillarSlab; + + private final IBlockDefinition itemGen; + private final IBlockDefinition chunkLoader; + private final IBlockDefinition phantomNode; + private final IBlockDefinition cubeGenerator; + private final IBlockDefinition energyGenerator; + + public ApiBlocks(FeatureFactory registry, PartModels partModels) { + // this.quartzOre = new BlockDefinition( "ore.quartz", new OreQuartz() ); + this.quartzOre = registry.block("quartz_ore", BlockQuartzOre::new) + .features(AEFeature.CERTUS_ORE) + .bootstrap((block, item) -> (IOreDictComponent) side -> OreDictionary.registerOre("oreCertusQuartz", new ItemStack(block))) + .build(); + this.quartzOreCharged = registry.block("charged_quartz_ore", BlockChargedQuartzOre::new) + .features(AEFeature.CERTUS_ORE, AEFeature.CHARGED_CERTUS_ORE) + .useCustomItemModel() + .bootstrap((block, item) -> (IOreDictComponent) side -> + { + OreDictionary.registerOre("oreCertusQuartz", new ItemStack(block)); + OreDictionary.registerOre("oreChargedCertusQuartz", new ItemStack(block)); + }) + .build(); + this.matrixFrame = registry.block("matrix_frame", BlockMatrixFrame::new).features(AEFeature.SPATIAL_IO).build(); + + FeatureFactory deco = registry.features(AEFeature.DECORATIVE_BLOCKS); + this.quartzBlock = deco.block("quartz_block", BlockQuartz::new).build(); + this.quartzPillar = deco.block("quartz_pillar", BlockQuartzPillar::new).build(); + this.chiseledQuartzBlock = deco.block("chiseled_quartz_block", BlockChiseledQuartz::new).build(); + + this.quartzGlass = registry.features(AEFeature.QUARTZ_GLASS) + .block("quartz_glass", BlockQuartzGlass::new) + .useCustomItemModel() + .rendering(new BlockRenderingCustomizer() { + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + rendering.builtInModel("models/block/builtin/quartz_glass", new GlassModel()); + } + }) + .build(); + this.quartzVibrantGlass = deco.block("quartz_vibrant_glass", BlockQuartzLamp::new) + .addFeatures(AEFeature.DECORATIVE_LIGHTS, AEFeature.QUARTZ_GLASS) + .useCustomItemModel() + .build(); + this.quartzFixture = registry.block("quartz_fixture", BlockQuartzFixture::new) + .features(AEFeature.DECORATIVE_LIGHTS) + .useCustomItemModel() + .build(); + + this.fluixBlock = registry.features(AEFeature.FLUIX).block("fluix_block", BlockFluix::new).build(); + + this.skyStoneBlock = registry.features(AEFeature.SKY_STONE) + .block("sky_stone_block", () -> new BlockSkyStone(SkystoneType.STONE)) + .build(); + this.smoothSkyStoneBlock = registry.features(AEFeature.SKY_STONE) + .block("smooth_sky_stone_block", () -> new BlockSkyStone(SkystoneType.BLOCK)) + .build(); + this.skyStoneBrick = deco.block("sky_stone_brick", () -> new BlockSkyStone(SkystoneType.BRICK)) + .addFeatures(AEFeature.SKY_STONE) + .build(); + this.skyStoneSmallBrick = deco.block("sky_stone_small_brick", () -> new BlockSkyStone(SkystoneType.SMALL_BRICK)) + .addFeatures(AEFeature.SKY_STONE) + .build(); + + this.skyStoneChest = registry.block("sky_stone_chest", () -> new BlockSkyChest(SkyChestType.STONE)) + .features(AEFeature.SKY_STONE, AEFeature.SKY_STONE_CHESTS) + .tileEntity(new TileEntityDefinition(TileSkyChest.class, "sky_stone_chest")) + .rendering(new SkyChestRenderingCustomizer(SkyChestType.STONE)) + .build(); + this.smoothSkyStoneChest = registry.block("smooth_sky_stone_chest", () -> new BlockSkyChest(SkyChestType.BLOCK)) + .features(AEFeature.SKY_STONE, AEFeature.SKY_STONE_CHESTS) + .tileEntity(new TileEntityDefinition(TileSkyChest.class, "sky_stone_chest")) + .rendering(new SkyChestRenderingCustomizer(SkyChestType.BLOCK)) + .build(); + + this.skyCompass = registry.block("sky_compass", BlockSkyCompass::new) + .features(AEFeature.METEORITE_COMPASS) + .tileEntity(new TileEntityDefinition(TileSkyCompass.class)) + .rendering(new SkyCompassRendering()) + .build(); + this.grindstone = registry.block("grindstone", BlockGrinder::new) + .features(AEFeature.GRIND_STONE) + .tileEntity(new TileEntityDefinition(TileGrinder.class)) + .build(); + this.crank = registry.block("crank", BlockCrank::new) + .features(AEFeature.GRIND_STONE) + .tileEntity(new TileEntityDefinition(TileCrank.class)) + .rendering(new CrankRendering()) + .useCustomItemModel() + .build(); + this.inscriber = registry.block("inscriber", BlockInscriber::new) + .features(AEFeature.INSCRIBER) + .tileEntity(new TileEntityDefinition(TileInscriber.class)) + .rendering(new InscriberRendering()) + .build(); + this.wirelessAccessPoint = registry.block("wireless_access_point", BlockWireless::new) + .features(AEFeature.WIRELESS_ACCESS_TERMINAL) + .tileEntity(new TileEntityDefinition(TileWireless.class)) + .rendering(new WirelessRendering()) + .build(); + this.charger = registry.block("charger", BlockCharger::new) + .features(AEFeature.CHARGER) + .tileEntity(new TileEntityDefinition(TileCharger.class)) + .rendering(new BlockRenderingCustomizer() { + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + rendering.tesr(BlockCharger.createTesr()); + } + }) + .build(); + this.tinyTNT = registry.block("tiny_tnt", BlockTinyTNT::new) + .features(AEFeature.TINY_TNT) + .bootstrap((block, item) -> (IPreInitComponent) side -> BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(item, + new DispenserBehaviorTinyTNT())) + .bootstrap((block, item) -> (IEntityRegistrationComponent) r -> + { + r.register(EntityEntryBuilder.create() + .entity(EntityTinyTNTPrimed.class) + .id(new ResourceLocation("appliedenergistics2", EntityTinyTNTPrimed.class.getName()), + EntityIds.get(EntityTinyTNTPrimed.class)) + .name("EntityTinyTNTPrimed") + .tracker(16, 4, true) + .build()); + }) + .build(); + this.securityStation = registry.block("security_station", BlockSecurityStation::new) + .features(AEFeature.SECURITY) + .tileEntity(new TileEntityDefinition(TileSecurityStation.class)) + .rendering(new SecurityStationRendering()) + .build(); + this.quantumRing = registry.block("quantum_ring", BlockQuantumRing::new) + .features(AEFeature.QUANTUM_NETWORK_BRIDGE) + .tileEntity(new TileEntityDefinition(TileQuantumBridge.class, "quantum_ring")) + .rendering(new QuantumBridgeRendering()) + .build(); + this.quantumLink = registry.block("quantum_link", BlockQuantumLinkChamber::new) + .features(AEFeature.QUANTUM_NETWORK_BRIDGE) + .tileEntity(new TileEntityDefinition(TileQuantumBridge.class, "quantum_ring")) + .rendering(new QuantumBridgeRendering()) + .build(); + this.spatialPylon = registry.block("spatial_pylon", BlockSpatialPylon::new) + .features(AEFeature.SPATIAL_IO) + .tileEntity(new TileEntityDefinition(TileSpatialPylon.class)) + .useCustomItemModel() + .rendering(new SpatialPylonRendering()) + .build(); + this.spatialIOPort = registry.block("spatial_io_port", BlockSpatialIOPort::new) + .features(AEFeature.SPATIAL_IO) + .tileEntity(new TileEntityDefinition(TileSpatialIOPort.class)) + .build(); + this.controller = registry.block("controller", BlockController::new) + .tileEntity(new TileEntityDefinition(TileController.class)) + .useCustomItemModel() + .rendering(new ControllerRendering()) + .build(); + this.drive = registry.block("drive", BlockDrive::new) + .features(AEFeature.STORAGE_CELLS, AEFeature.ME_DRIVE) + .tileEntity(new TileEntityDefinition(TileDrive.class)) + .useCustomItemModel() + .rendering(new DriveRendering()) + .build(); + this.chest = registry.block("chest", BlockChest::new) + .features(AEFeature.STORAGE_CELLS, AEFeature.ME_CHEST) + .tileEntity(new TileEntityDefinition(TileChest.class)) + .useCustomItemModel() + .rendering(new ChestRendering()) + .build(); + this.iface = registry.block("interface", BlockInterface::new) + .features(AEFeature.INTERFACE) + .tileEntity(new TileEntityDefinition(TileInterface.class)) + .build(); + this.fluidIface = registry.block("fluid_interface", BlockFluidInterface::new) + .features(AEFeature.FLUID_INTERFACE) + .tileEntity(new TileEntityDefinition(TileFluidInterface.class)) + .build(); + this.cellWorkbench = registry.block("cell_workbench", BlockCellWorkbench::new) + .features(AEFeature.STORAGE_CELLS) + .tileEntity(new TileEntityDefinition(TileCellWorkbench.class)) + .build(); + this.iOPort = registry.block("io_port", BlockIOPort::new) + .features(AEFeature.STORAGE_CELLS, AEFeature.IO_PORT) + .tileEntity(new TileEntityDefinition(TileIOPort.class)) + .build(); + this.condenser = registry.block("condenser", BlockCondenser::new) + .features(AEFeature.CONDENSER) + .tileEntity(new TileEntityDefinition(TileCondenser.class)) + .build(); + this.energyAcceptor = registry.block("energy_acceptor", BlockEnergyAcceptor::new) + .features(AEFeature.ENERGY_ACCEPTOR) + .tileEntity(new TileEntityDefinition(TileEnergyAcceptor.class)) + .build(); + this.vibrationChamber = registry.block("vibration_chamber", BlockVibrationChamber::new) + .features(AEFeature.POWER_GEN) + .tileEntity(new TileEntityDefinition(TileVibrationChamber.class)) + .build(); + this.quartzGrowthAccelerator = registry.block("quartz_growth_accelerator", BlockQuartzGrowthAccelerator::new) + .tileEntity(new TileEntityDefinition(TileQuartzGrowthAccelerator.class)) + .features(AEFeature.CRYSTAL_GROWTH_ACCELERATOR) + .build(); + this.energyCell = registry.block("energy_cell", BlockEnergyCell::new) + .features(AEFeature.ENERGY_CELLS) + .item(AEBaseItemBlockChargeable::new) + .tileEntity(new TileEntityDefinition(TileEnergyCell.class)) + .rendering(new BlockEnergyCellRendering(new ResourceLocation(AppEng.MOD_ID, "energy_cell"))) + .build(); + this.energyCellDense = registry.block("dense_energy_cell", BlockDenseEnergyCell::new) + .features(AEFeature.ENERGY_CELLS, AEFeature.DENSE_ENERGY_CELLS) + .item(AEBaseItemBlockChargeable::new) + .tileEntity(new TileEntityDefinition(TileDenseEnergyCell.class)) + .rendering(new BlockEnergyCellRendering(new ResourceLocation(AppEng.MOD_ID, "dense_energy_cell"))) + .build(); + this.energyCellCreative = registry.block("creative_energy_cell", BlockCreativeEnergyCell::new) + .features(AEFeature.CREATIVE) + .tileEntity(new TileEntityDefinition(TileCreativeEnergyCell.class)) + .build(); + + FeatureFactory crafting = registry.features(AEFeature.CRAFTING_CPU); + this.craftingUnit = crafting.block("crafting_unit", () -> new BlockCraftingUnit(CraftingUnitType.UNIT)) + .rendering(new CraftingCubeRendering("crafting_unit", CraftingUnitType.UNIT)) + .tileEntity(new TileEntityDefinition(TileCraftingTile.class, "crafting_unit")) + .useCustomItemModel() + .build(); + this.craftingAccelerator = crafting.block("crafting_accelerator", () -> new BlockCraftingUnit(CraftingUnitType.ACCELERATOR)) + .rendering(new CraftingCubeRendering("crafting_accelerator", CraftingUnitType.ACCELERATOR)) + .tileEntity(new TileEntityDefinition(TileCraftingTile.class, "crafting_unit")) + .useCustomItemModel() + .build(); + this.craftingStorage1k = crafting.block("crafting_storage_1k", () -> new BlockCraftingStorage(CraftingUnitType.STORAGE_1K)) + .item(ItemCraftingStorage::new) + .tileEntity(new TileEntityDefinition(TileCraftingStorageTile.class, "crafting_storage")) + .rendering(new CraftingCubeRendering("crafting_storage_1k", CraftingUnitType.STORAGE_1K)) + .useCustomItemModel() + .build(); + this.craftingStorage4k = crafting.block("crafting_storage_4k", () -> new BlockCraftingStorage(CraftingUnitType.STORAGE_4K)) + .item(ItemCraftingStorage::new) + .tileEntity(new TileEntityDefinition(TileCraftingStorageTile.class, "crafting_storage")) + .rendering(new CraftingCubeRendering("crafting_storage_4k", CraftingUnitType.STORAGE_4K)) + .useCustomItemModel() + .build(); + this.craftingStorage16k = crafting.block("crafting_storage_16k", () -> new BlockCraftingStorage(CraftingUnitType.STORAGE_16K)) + .item(ItemCraftingStorage::new) + .tileEntity(new TileEntityDefinition(TileCraftingStorageTile.class, "crafting_storage")) + .rendering(new CraftingCubeRendering("crafting_storage_16k", CraftingUnitType.STORAGE_16K)) + .useCustomItemModel() + .build(); + this.craftingStorage64k = crafting.block("crafting_storage_64k", () -> new BlockCraftingStorage(CraftingUnitType.STORAGE_64K)) + .item(ItemCraftingStorage::new) + .tileEntity(new TileEntityDefinition(TileCraftingStorageTile.class, "crafting_storage")) + .rendering(new CraftingCubeRendering("crafting_storage_64k", CraftingUnitType.STORAGE_64K)) + .useCustomItemModel() + .build(); + this.craftingMonitor = crafting.block("crafting_monitor", BlockCraftingMonitor::new) + .tileEntity(new TileEntityDefinition(TileCraftingMonitorTile.class)) + .rendering(new CraftingCubeRendering("crafting_monitor", CraftingUnitType.MONITOR)) + .useCustomItemModel() + .build(); + + this.molecularAssembler = registry.block("molecular_assembler", BlockMolecularAssembler::new) + .features(AEFeature.MOLECULAR_ASSEMBLER) + .tileEntity(new TileEntityDefinition(TileMolecularAssembler.class)) + .build(); + this.lightDetector = registry.block("light_detector", BlockLightDetector::new) + .features(AEFeature.LIGHT_DETECTOR) + .tileEntity(new TileEntityDefinition(TileLightDetector.class)) + .useCustomItemModel() + .build(); + this.paint = registry.block("paint", BlockPaint::new) + .features(AEFeature.PAINT_BALLS) + .tileEntity(new TileEntityDefinition(TilePaint.class)) + .rendering(new PaintRendering()) + .build(); + + this.skyStoneStairs = makeStairs("sky_stone_stairs", registry, this.skyStoneBlock()); + this.smoothSkyStoneStairs = makeStairs("smooth_sky_stone_stairs", registry, this.smoothSkyStoneBlock()); + this.skyStoneBrickStairs = makeStairs("sky_stone_brick_stairs", registry, this.skyStoneBrick()); + this.skyStoneSmallBrickStairs = makeStairs("sky_stone_small_brick_stairs", registry, this.skyStoneSmallBrick()); + this.fluixStairs = makeStairs("fluix_stairs", registry, this.fluixBlock()); + this.quartzStairs = makeStairs("quartz_stairs", registry, this.quartzBlock()); + this.chiseledQuartzStairs = makeStairs("chiseled_quartz_stairs", registry, this.chiseledQuartzBlock()); + this.quartzPillarStairs = makeStairs("quartz_pillar_stairs", registry, this.quartzPillar()); + + this.multiPart = registry.block("cable_bus", BlockCableBus::new) + .rendering(new CableBusRendering(partModels)) + // (handled in BlockCableBus.java and its setupTile()) + // .tileEntity( TileCableBus.class ) + // TODO: why the custom registration? + .bootstrap((block, item) -> (IPostInitComponent) side -> ((BlockCableBus) block).setupTile()) + .build(); + + this.skyStoneSlab = makeSlab("sky_stone_slab", "sky_stone_double_slab", registry, this.skyStoneBlock()); + this.smoothSkyStoneSlab = makeSlab("smooth_sky_stone_slab", "smooth_sky_stone_double_slab", registry, this.smoothSkyStoneBlock()); + this.skyStoneBrickSlab = makeSlab("sky_stone_brick_slab", "sky_stone_brick_double_slab", registry, this.skyStoneBrick()); + this.skyStoneSmallBrickSlab = makeSlab("sky_stone_small_brick_slab", "sky_stone_small_brick_double_slab", registry, this.skyStoneSmallBrick()); + this.fluixSlab = makeSlab("fluix_slab", "fluix_double_slab", registry, this.fluixBlock()); + this.quartzSlab = makeSlab("quartz_slab", "quartz_double_slab", registry, this.quartzBlock()); + this.chiseledQuartzSlab = makeSlab("chiseled_quartz_slab", "chiseled_quartz_double_slab", registry, this.chiseledQuartzBlock()); + this.quartzPillarSlab = makeSlab("quartz_pillar_slab", "quartz_pillar_double_slab", registry, this.quartzPillar()); + + this.itemGen = registry.block("debug_item_gen", BlockItemGen::new) + .features(AEFeature.UNSUPPORTED_DEVELOPER_TOOLS, AEFeature.CREATIVE) + .tileEntity(new TileEntityDefinition(TileItemGen.class)) + .useCustomItemModel() + .build(); + this.chunkLoader = registry.block("debug_chunk_loader", BlockChunkloader::new) + .features(AEFeature.UNSUPPORTED_DEVELOPER_TOOLS, AEFeature.CREATIVE) + .tileEntity(new TileEntityDefinition(TileChunkLoader.class)) + .useCustomItemModel() + .build(); + this.phantomNode = registry.block("debug_phantom_node", BlockPhantomNode::new) + .features(AEFeature.UNSUPPORTED_DEVELOPER_TOOLS, AEFeature.CREATIVE) + .tileEntity(new TileEntityDefinition(TilePhantomNode.class)) + .useCustomItemModel() + .build(); + this.cubeGenerator = registry.block("debug_cube_gen", BlockCubeGenerator::new) + .features(AEFeature.UNSUPPORTED_DEVELOPER_TOOLS, AEFeature.CREATIVE) + .tileEntity(new TileEntityDefinition(TileCubeGenerator.class)) + .useCustomItemModel() + .build(); + this.energyGenerator = registry.block("debug_energy_gen", BlockEnergyGenerator::new) + .features(AEFeature.UNSUPPORTED_DEVELOPER_TOOLS, AEFeature.CREATIVE) + .tileEntity(new TileEntityDefinition(TileEnergyGenerator.class)) + .useCustomItemModel() + .build(); + } + + private static IBlockDefinition makeSlab(String slabId, String doubleSlabId, FeatureFactory registry, IBlockDefinition blockDef) { + if (!blockDef.maybeBlock().isPresent()) { + return new BlockDefinition(slabId, null, null); + } + + Block block = blockDef.maybeBlock().get(); + + IBlockDefinition slabDef = registry.block(slabId, () -> new BlockSlabCommon.Half(block)) + .features(AEFeature.DECORATIVE_BLOCKS) + .disableItem() + .build(); + + if (!slabDef.maybeBlock().isPresent()) { + return new BlockDefinition(slabId, null, null); + } + + BlockSlab slabBlock = (BlockSlab) slabDef.maybeBlock().get(); + + // Reigster the double slab variant as well + IBlockDefinition doubleSlabDef = registry.block(doubleSlabId, () -> new BlockSlabCommon.Double(slabBlock, block)) + .features(AEFeature.DECORATIVE_BLOCKS) + .disableItem() + .build(); + + Verify.verify(doubleSlabDef.maybeBlock().isPresent()); + + BlockSlab doubleSlabBlock = (BlockSlab) doubleSlabDef.maybeBlock().get(); + + // Make the slab item + IItemDefinition itemDef = registry.item(slabId, () -> new ItemSlab(slabBlock, slabBlock, doubleSlabBlock)) + .features(AEFeature.DECORATIVE_BLOCKS) + .build(); + + Verify.verify(itemDef.maybeItem().isPresent()); + + // Return a new composite block definition that combines the single slab block with the slab item + return new BlockDefinition(slabId, slabBlock, (ItemBlock) itemDef.maybeItem().get()); + } + + private static IBlockDefinition makeStairs(String registryName, FeatureFactory registry, IBlockDefinition block) { + if (!block.maybeBlock().isPresent()) { + return new BlockDefinition(registryName, null, null); + } + + IBlockDefinition stairs = registry.block(registryName, () -> new BlockStairCommon(block.maybeBlock().get(), block.identifier())) + .features(AEFeature.DECORATIVE_BLOCKS) + .rendering(new BlockRenderingCustomizer() { + @Override + @SideOnly(Side.CLIENT) + public void customize(IBlockRendering rendering, IItemRendering itemRendering) { + ModelResourceLocation model = new ModelResourceLocation(new ResourceLocation(AppEng.MOD_ID, registryName), "facing=east,half=bottom,shape=straight"); + itemRendering.model(model); + } + }) + .build(); + + Verify.verify(stairs.maybeBlock().isPresent()); + + return stairs; + } + + @Override + public IBlockDefinition quartzOre() { + return this.quartzOre; + } + + @Override + public IBlockDefinition quartzOreCharged() { + return this.quartzOreCharged; + } + + @Override + public IBlockDefinition matrixFrame() { + return this.matrixFrame; + } + + @Override + public IBlockDefinition quartzBlock() { + return this.quartzBlock; + } + + @Override + public IBlockDefinition quartzPillar() { + return this.quartzPillar; + } + + @Override + public IBlockDefinition chiseledQuartzBlock() { + return this.chiseledQuartzBlock; + } + + @Override + public IBlockDefinition quartzGlass() { + return this.quartzGlass; + } + + @Override + public IBlockDefinition quartzVibrantGlass() { + return this.quartzVibrantGlass; + } + + @Override + public IBlockDefinition quartzFixture() { + return this.quartzFixture; + } + + @Override + public IBlockDefinition fluixBlock() { + return this.fluixBlock; + } + + @Override + public IBlockDefinition skyStoneBlock() { + return this.skyStoneBlock; + } + + @Override + public IBlockDefinition smoothSkyStoneBlock() { + return this.smoothSkyStoneBlock; + } + + @Override + public IBlockDefinition skyStoneBrick() { + return this.skyStoneBrick; + } + + @Override + public IBlockDefinition skyStoneSmallBrick() { + return this.skyStoneSmallBrick; + } + + @Override + public IBlockDefinition skyStoneChest() { + return this.skyStoneChest; + } + + @Override + public IBlockDefinition smoothSkyStoneChest() { + return this.smoothSkyStoneChest; + } + + @Override + public IBlockDefinition skyCompass() { + return this.skyCompass; + } + + @Override + public IBlockDefinition skyStoneStairs() { + return this.skyStoneStairs; + } + + @Override + public IBlockDefinition smoothSkyStoneStairs() { + return this.smoothSkyStoneStairs; + } + + @Override + public IBlockDefinition skyStoneBrickStairs() { + return this.skyStoneBrickStairs; + } + + @Override + public IBlockDefinition skyStoneSmallBrickStairs() { + return this.skyStoneSmallBrickStairs; + } + + @Override + public IBlockDefinition fluixStairs() { + return this.fluixStairs; + } + + @Override + public IBlockDefinition quartzStairs() { + return this.quartzStairs; + } + + @Override + public IBlockDefinition chiseledQuartzStairs() { + return this.chiseledQuartzStairs; + } + + @Override + public IBlockDefinition quartzPillarStairs() { + return this.quartzPillarStairs; + } + + @Override + public IBlockDefinition skyStoneSlab() { + return this.skyStoneSlab; + } + + @Override + public IBlockDefinition smoothSkyStoneSlab() { + return this.smoothSkyStoneSlab; + } + + @Override + public IBlockDefinition skyStoneBrickSlab() { + return this.skyStoneBrickSlab; + } + + @Override + public IBlockDefinition skyStoneSmallBrickSlab() { + return this.skyStoneSmallBrickSlab; + } + + @Override + public IBlockDefinition fluixSlab() { + return this.fluixSlab; + } + + @Override + public IBlockDefinition quartzSlab() { + return this.quartzSlab; + } + + @Override + public IBlockDefinition chiseledQuartzSlab() { + return this.chiseledQuartzSlab; + } + + @Override + public IBlockDefinition quartzPillarSlab() { + return this.quartzPillarSlab; + } + + @Override + public ITileDefinition grindstone() { + return this.grindstone; + } + + @Override + public ITileDefinition crank() { + return this.crank; + } + + @Override + public ITileDefinition inscriber() { + return this.inscriber; + } + + @Override + public ITileDefinition wirelessAccessPoint() { + return this.wirelessAccessPoint; + } + + @Override + public ITileDefinition charger() { + return this.charger; + } + + @Override + public IBlockDefinition tinyTNT() { + return this.tinyTNT; + } + + @Override + public ITileDefinition securityStation() { + return this.securityStation; + } + + @Override + public ITileDefinition quantumRing() { + return this.quantumRing; + } + + @Override + public ITileDefinition quantumLink() { + return this.quantumLink; + } + + @Override + public ITileDefinition spatialPylon() { + return this.spatialPylon; + } + + @Override + public ITileDefinition spatialIOPort() { + return this.spatialIOPort; + } + + @Override + public ITileDefinition multiPart() { + return this.multiPart; + } + + @Override + public ITileDefinition controller() { + return this.controller; + } + + @Override + public ITileDefinition drive() { + return this.drive; + } + + @Override + public ITileDefinition chest() { + return this.chest; + } + + @Override + public ITileDefinition iface() { + return this.iface; + } + + @Override + public ITileDefinition fluidIface() { + return this.fluidIface; + } + + @Override + public ITileDefinition cellWorkbench() { + return this.cellWorkbench; + } + + @Override + public ITileDefinition iOPort() { + return this.iOPort; + } + + @Override + public ITileDefinition condenser() { + return this.condenser; + } + + @Override + public ITileDefinition energyAcceptor() { + return this.energyAcceptor; + } + + @Override + public ITileDefinition vibrationChamber() { + return this.vibrationChamber; + } + + @Override + public ITileDefinition quartzGrowthAccelerator() { + return this.quartzGrowthAccelerator; + } + + @Override + public ITileDefinition energyCell() { + return this.energyCell; + } + + @Override + public ITileDefinition energyCellDense() { + return this.energyCellDense; + } + + @Override + public ITileDefinition energyCellCreative() { + return this.energyCellCreative; + } + + @Override + public ITileDefinition craftingUnit() { + return this.craftingUnit; + } + + @Override + public ITileDefinition craftingAccelerator() { + return this.craftingAccelerator; + } + + @Override + public ITileDefinition craftingStorage1k() { + return this.craftingStorage1k; + } + + @Override + public ITileDefinition craftingStorage4k() { + return this.craftingStorage4k; + } + + @Override + public ITileDefinition craftingStorage16k() { + return this.craftingStorage16k; + } + + @Override + public ITileDefinition craftingStorage64k() { + return this.craftingStorage64k; + } + + @Override + public ITileDefinition craftingMonitor() { + return this.craftingMonitor; + } + + @Override + public ITileDefinition molecularAssembler() { + return this.molecularAssembler; + } + + @Override + public ITileDefinition lightDetector() { + return this.lightDetector; + } + + @Override + public ITileDefinition paint() { + return this.paint; + } + + public IBlockDefinition chunkLoader() { + return this.chunkLoader; + } + + public IBlockDefinition itemGen() { + return this.itemGen; + } + + public IBlockDefinition phantomNode() { + return this.phantomNode; + } + + public IBlockDefinition cubeGenerator() { + return this.cubeGenerator; + } + + public IBlockDefinition energyGenerator() { + return this.energyGenerator; + } } diff --git a/src/main/java/appeng/core/api/definitions/ApiItems.java b/src/main/java/appeng/core/api/definitions/ApiItems.java index e69d39eea..103806e7e 100644 --- a/src/main/java/appeng/core/api/definitions/ApiItems.java +++ b/src/main/java/appeng/core/api/definitions/ApiItems.java @@ -19,11 +19,6 @@ package appeng.core.api.definitions; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.common.registry.EntityEntryBuilder; -import net.minecraftforge.oredict.OreDictionary; - import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.IItems; import appeng.api.util.AEColoredItemDefinition; @@ -45,520 +40,455 @@ import appeng.fluids.items.FluidDummyItemRendering; import appeng.hooks.DispenserBlockTool; import appeng.hooks.DispenserMatterCannon; import appeng.items.materials.MaterialType; -import appeng.items.misc.ItemCrystalSeed; -import appeng.items.misc.ItemCrystalSeedRendering; -import appeng.items.misc.ItemEncodedPattern; -import appeng.items.misc.ItemPaintBall; -import appeng.items.misc.ItemPaintBallRendering; +import appeng.items.misc.*; import appeng.items.parts.FacadeRendering; import appeng.items.parts.ItemFacade; import appeng.items.storage.BasicItemStorageCell; import appeng.items.storage.ItemCreativeStorageCell; import appeng.items.storage.ItemSpatialStorageCell; import appeng.items.storage.ItemViewCell; -import appeng.items.tools.ToolBiometricCard; -import appeng.items.tools.ToolBiometricCardRendering; -import appeng.items.tools.ToolMemoryCard; -import appeng.items.tools.ToolMemoryCardRendering; -import appeng.items.tools.ToolNetworkTool; -import appeng.items.tools.powered.ToolChargedStaff; -import appeng.items.tools.powered.ToolColorApplicator; -import appeng.items.tools.powered.ToolColorApplicatorRendering; -import appeng.items.tools.powered.ToolEntropyManipulator; -import appeng.items.tools.powered.ToolMatterCannon; -import appeng.items.tools.powered.ToolPortableCell; -import appeng.items.tools.powered.ToolWirelessTerminal; -import appeng.items.tools.quartz.ToolQuartzAxe; -import appeng.items.tools.quartz.ToolQuartzCuttingKnife; -import appeng.items.tools.quartz.ToolQuartzHoe; -import appeng.items.tools.quartz.ToolQuartzPickaxe; -import appeng.items.tools.quartz.ToolQuartzSpade; -import appeng.items.tools.quartz.ToolQuartzSword; -import appeng.items.tools.quartz.ToolQuartzWrench; +import appeng.items.tools.*; +import appeng.items.tools.powered.*; +import appeng.items.tools.quartz.*; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.common.registry.EntityEntryBuilder; +import net.minecraftforge.oredict.OreDictionary; /** * Internal implementation for the API items */ -public final class ApiItems implements IItems -{ - private final IItemDefinition certusQuartzAxe; - private final IItemDefinition certusQuartzHoe; - private final IItemDefinition certusQuartzShovel; - private final IItemDefinition certusQuartzPick; - private final IItemDefinition certusQuartzSword; - private final IItemDefinition certusQuartzWrench; - private final IItemDefinition certusQuartzKnife; - - private final IItemDefinition netherQuartzAxe; - private final IItemDefinition netherQuartzHoe; - private final IItemDefinition netherQuartzShovel; - private final IItemDefinition netherQuartzPick; - private final IItemDefinition netherQuartzSword; - private final IItemDefinition netherQuartzWrench; - private final IItemDefinition netherQuartzKnife; - - private final IItemDefinition entropyManipulator; - private final IItemDefinition wirelessTerminal; - private final IItemDefinition biometricCard; - private final IItemDefinition chargedStaff; - private final IItemDefinition massCannon; - private final IItemDefinition memoryCard; - private final IItemDefinition networkTool; - private final IItemDefinition portableCell; - - private final IItemDefinition cellCreative; - private final IItemDefinition viewCell; - - private final IItemDefinition cell1k; - private final IItemDefinition cell4k; - private final IItemDefinition cell16k; - private final IItemDefinition cell64k; - - private final IItemDefinition fluidCell1k; - private final IItemDefinition fluidCell4k; - private final IItemDefinition fluidCell16k; - private final IItemDefinition fluidCell64k; - - private final IItemDefinition spatialCell2; - private final IItemDefinition spatialCell16; - private final IItemDefinition spatialCell128; - - private final IItemDefinition facade; - private final IItemDefinition crystalSeed; - - // rv1 - private final IItemDefinition encodedPattern; - private final IItemDefinition colorApplicator; - - private final IItemDefinition paintBall; - private final AEColoredItemDefinition coloredPaintBall; - private final AEColoredItemDefinition coloredLumenPaintBall; - - // unsupported dev tools - private final IItemDefinition toolEraser; - private final IItemDefinition toolMeteoritePlacer; - private final IItemDefinition toolDebugCard; - private final IItemDefinition toolReplicatorCard; - - private final IItemDefinition dummyFluidItem; - - public ApiItems( FeatureFactory registry ) - { - FeatureFactory certusTools = registry.features( AEFeature.CERTUS_QUARTZ_TOOLS ); - this.certusQuartzAxe = certusTools.item( "certus_quartz_axe", () -> new ToolQuartzAxe( AEFeature.CERTUS_QUARTZ_TOOLS ) ) - .addFeatures( AEFeature.QUARTZ_AXE ) - .build(); - this.certusQuartzHoe = certusTools.item( "certus_quartz_hoe", () -> new ToolQuartzHoe( AEFeature.CERTUS_QUARTZ_TOOLS ) ) - .addFeatures( AEFeature.QUARTZ_HOE ) - .build(); - this.certusQuartzShovel = certusTools.item( "certus_quartz_spade", () -> new ToolQuartzSpade( AEFeature.CERTUS_QUARTZ_TOOLS ) ) - .addFeatures( AEFeature.QUARTZ_SPADE ) - .build(); - this.certusQuartzPick = certusTools.item( "certus_quartz_pickaxe", () -> new ToolQuartzPickaxe( AEFeature.CERTUS_QUARTZ_TOOLS ) ) - .addFeatures( AEFeature.QUARTZ_PICKAXE ) - .build(); - this.certusQuartzSword = certusTools.item( "certus_quartz_sword", () -> new ToolQuartzSword( AEFeature.CERTUS_QUARTZ_TOOLS ) ) - .addFeatures( AEFeature.QUARTZ_SWORD ) - .build(); - this.certusQuartzWrench = certusTools.item( "certus_quartz_wrench", ToolQuartzWrench::new ) - .addFeatures( AEFeature.QUARTZ_WRENCH ) - .bootstrap( item -> (IOreDictComponent) side -> OreDictionary.registerOre( "itemQuartzWrench", new ItemStack( item ) ) ) - .build(); - this.certusQuartzKnife = certusTools.item( "certus_quartz_cutting_knife", () -> new ToolQuartzCuttingKnife( AEFeature.CERTUS_QUARTZ_TOOLS ) ) - .addFeatures( AEFeature.QUARTZ_KNIFE ) - .bootstrap( item -> (IOreDictComponent) side -> OreDictionary.registerOre( "itemQuartzKnife", new ItemStack( item ) ) ) - .build(); - - FeatureFactory netherTools = registry.features( AEFeature.NETHER_QUARTZ_TOOLS ); - this.netherQuartzAxe = netherTools.item( "nether_quartz_axe", () -> new ToolQuartzAxe( AEFeature.NETHER_QUARTZ_TOOLS ) ) - .addFeatures( AEFeature.QUARTZ_AXE ) - .build(); - this.netherQuartzHoe = netherTools.item( "nether_quartz_hoe", () -> new ToolQuartzHoe( AEFeature.NETHER_QUARTZ_TOOLS ) ) - .addFeatures( AEFeature.QUARTZ_HOE ) - .build(); - this.netherQuartzShovel = netherTools.item( "nether_quartz_spade", () -> new ToolQuartzSpade( AEFeature.NETHER_QUARTZ_TOOLS ) ) - .addFeatures( AEFeature.QUARTZ_SPADE ) - .build(); - this.netherQuartzPick = netherTools.item( "nether_quartz_pickaxe", () -> new ToolQuartzPickaxe( AEFeature.NETHER_QUARTZ_TOOLS ) ) - .addFeatures( AEFeature.QUARTZ_PICKAXE ) - .build(); - this.netherQuartzSword = netherTools.item( "nether_quartz_sword", () -> new ToolQuartzSword( AEFeature.NETHER_QUARTZ_TOOLS ) ) - .addFeatures( AEFeature.QUARTZ_SWORD ) - .build(); - this.netherQuartzWrench = netherTools.item( "nether_quartz_wrench", ToolQuartzWrench::new ) - .addFeatures( AEFeature.QUARTZ_WRENCH ) - .bootstrap( item -> (IOreDictComponent) side -> OreDictionary.registerOre( "itemQuartzWrench", new ItemStack( item ) ) ) - .build(); - this.netherQuartzKnife = netherTools.item( "nether_quartz_cutting_knife", () -> new ToolQuartzCuttingKnife( AEFeature.NETHER_QUARTZ_TOOLS ) ) - .addFeatures( AEFeature.QUARTZ_KNIFE ) - .bootstrap( item -> (IOreDictComponent) side -> OreDictionary.registerOre( "itemQuartzKnife", new ItemStack( item ) ) ) - .build(); - - FeatureFactory powerTools = registry.features( AEFeature.POWERED_TOOLS ); - this.entropyManipulator = powerTools.item( "entropy_manipulator", ToolEntropyManipulator::new ) - .addFeatures( AEFeature.ENTROPY_MANIPULATOR ) - .dispenserBehavior( DispenserBlockTool::new ) - .build(); - this.wirelessTerminal = powerTools.item( "wireless_terminal", ToolWirelessTerminal::new ).addFeatures( AEFeature.WIRELESS_ACCESS_TERMINAL ).build(); - this.chargedStaff = powerTools.item( "charged_staff", ToolChargedStaff::new ).addFeatures( AEFeature.CHARGED_STAFF ).build(); - this.massCannon = powerTools.item( "matter_cannon", ToolMatterCannon::new ) - .addFeatures( AEFeature.MATTER_CANNON ) - .dispenserBehavior( DispenserMatterCannon::new ) - .build(); - this.portableCell = powerTools.item( "portable_cell", ToolPortableCell::new ).addFeatures( AEFeature.PORTABLE_CELL, AEFeature.STORAGE_CELLS ).build(); - this.colorApplicator = powerTools.item( "color_applicator", ToolColorApplicator::new ) - .addFeatures( AEFeature.COLOR_APPLICATOR ) - .dispenserBehavior( DispenserBlockTool::new ) - .rendering( new ToolColorApplicatorRendering() ) - .build(); - - this.biometricCard = registry.item( "biometric_card", ToolBiometricCard::new ) - .rendering( new ToolBiometricCardRendering() ) - .features( AEFeature.SECURITY ) - .build(); - this.memoryCard = registry.item( "memory_card", ToolMemoryCard::new ) - .rendering( new ToolMemoryCardRendering() ) - .features( AEFeature.MEMORY_CARD ) - .build(); - this.networkTool = registry.item( "network_tool", ToolNetworkTool::new ).features( AEFeature.NETWORK_TOOL ).build(); - - this.cellCreative = registry.item( "creative_storage_cell", ItemCreativeStorageCell::new ) - .features( AEFeature.STORAGE_CELLS, AEFeature.CREATIVE ) - .build(); - this.viewCell = registry.item( "view_cell", ItemViewCell::new ).features( AEFeature.VIEW_CELL ).build(); - - FeatureFactory storageCells = registry.features( AEFeature.STORAGE_CELLS ); - this.cell1k = storageCells.item( "storage_cell_1k", () -> new BasicItemStorageCell( MaterialType.CELL1K_PART, 1 ) ).build(); - this.cell4k = storageCells.item( "storage_cell_4k", () -> new BasicItemStorageCell( MaterialType.CELL4K_PART, 4 ) ).build(); - this.cell16k = storageCells.item( "storage_cell_16k", () -> new BasicItemStorageCell( MaterialType.CELL16K_PART, 16 ) ).build(); - this.cell64k = storageCells.item( "storage_cell_64k", () -> new BasicItemStorageCell( MaterialType.CELL64K_PART, 64 ) ).build(); - - this.fluidCell1k = storageCells.item( "fluid_storage_cell_1k", () -> new BasicFluidStorageCell( MaterialType.FLUID_CELL1K_PART, 1 ) ).build(); - this.fluidCell4k = storageCells.item( "fluid_storage_cell_4k", () -> new BasicFluidStorageCell( MaterialType.FLUID_CELL4K_PART, 4 ) ).build(); - this.fluidCell16k = storageCells.item( "fluid_storage_cell_16k", () -> new BasicFluidStorageCell( MaterialType.FLUID_CELL16K_PART, 16 ) ).build(); - this.fluidCell64k = storageCells.item( "fluid_storage_cell_64k", () -> new BasicFluidStorageCell( MaterialType.FLUID_CELL64K_PART, 64 ) ).build(); - - FeatureFactory spatialCells = registry.features( AEFeature.SPATIAL_IO ); - this.spatialCell2 = spatialCells.item( "spatial_storage_cell_2_cubed", () -> new ItemSpatialStorageCell( 2 ) ).build(); - this.spatialCell16 = spatialCells.item( "spatial_storage_cell_16_cubed", () -> new ItemSpatialStorageCell( 16 ) ).build(); - this.spatialCell128 = spatialCells.item( "spatial_storage_cell_128_cubed", () -> new ItemSpatialStorageCell( 128 ) ).build(); - - this.facade = registry.item( "facade", ItemFacade::new ) - .features( AEFeature.FACADES ) - .creativeTab( CreativeTabFacade.instance ) - .rendering( new FacadeRendering() ) - .build(); - this.crystalSeed = registry.item( "crystal_seed", ItemCrystalSeed::new ) - .features( AEFeature.CRYSTAL_SEEDS ) - .rendering( new ItemCrystalSeedRendering() ) - .bootstrap( item -> (IEntityRegistrationComponent) r -> - { - r.register( EntityEntryBuilder.create() - .entity( EntityGrowingCrystal.class ) - .id( new ResourceLocation( "appliedenergistics2", EntityGrowingCrystal.class.getName() ), - EntityIds.get( EntityGrowingCrystal.class ) ) - .name( EntityGrowingCrystal.class.getSimpleName() ) - .tracker( 16, 4, true ) - .build() ); - } ) - .build(); - - // rv1 - this.encodedPattern = registry.item( "encoded_pattern", ItemEncodedPattern::new ) - .features( AEFeature.PATTERNS ) - .rendering( new ItemEncodedPatternRendering() ) - .build(); - - this.paintBall = registry.item( "paint_ball", ItemPaintBall::new ) - .features( AEFeature.PAINT_BALLS ) - .rendering( new ItemPaintBallRendering() ) - .build(); - this.coloredPaintBall = registry.colored( this.paintBall, 0 ); - this.coloredLumenPaintBall = registry.colored( this.paintBall, 20 ); - - FeatureFactory debugTools = registry.features( AEFeature.UNSUPPORTED_DEVELOPER_TOOLS, AEFeature.CREATIVE ); - this.toolEraser = debugTools.item( "debug_eraser", ToolEraser::new ).build(); - this.toolMeteoritePlacer = debugTools.item( "debug_meteorite_placer", ToolMeteoritePlacer::new ).build(); - this.toolDebugCard = debugTools.item( "debug_card", ToolDebugCard::new ).build(); - this.toolReplicatorCard = debugTools.item( "debug_replicator_card", ToolReplicatorCard::new ).build(); - - this.dummyFluidItem = registry.item( "dummy_fluid_item", FluidDummyItem::new ).rendering( new FluidDummyItemRendering() ).build(); - } - - @Override - public IItemDefinition certusQuartzAxe() - { - return this.certusQuartzAxe; - } - - @Override - public IItemDefinition certusQuartzHoe() - { - return this.certusQuartzHoe; - } - - @Override - public IItemDefinition certusQuartzShovel() - { - return this.certusQuartzShovel; - } - - @Override - public IItemDefinition certusQuartzPick() - { - return this.certusQuartzPick; - } - - @Override - public IItemDefinition certusQuartzSword() - { - return this.certusQuartzSword; - } - - @Override - public IItemDefinition certusQuartzWrench() - { - return this.certusQuartzWrench; - } - - @Override - public IItemDefinition certusQuartzKnife() - { - return this.certusQuartzKnife; - } - - @Override - public IItemDefinition netherQuartzAxe() - { - return this.netherQuartzAxe; - } - - @Override - public IItemDefinition netherQuartzHoe() - { - return this.netherQuartzHoe; - } - - @Override - public IItemDefinition netherQuartzShovel() - { - return this.netherQuartzShovel; - } - - @Override - public IItemDefinition netherQuartzPick() - { - return this.netherQuartzPick; - } - - @Override - public IItemDefinition netherQuartzSword() - { - return this.netherQuartzSword; - } - - @Override - public IItemDefinition netherQuartzWrench() - { - return this.netherQuartzWrench; - } - - @Override - public IItemDefinition netherQuartzKnife() - { - return this.netherQuartzKnife; - } - - @Override - public IItemDefinition entropyManipulator() - { - return this.entropyManipulator; - } - - @Override - public IItemDefinition wirelessTerminal() - { - return this.wirelessTerminal; - } - - @Override - public IItemDefinition biometricCard() - { - return this.biometricCard; - } - - @Override - public IItemDefinition chargedStaff() - { - return this.chargedStaff; - } - - @Override - public IItemDefinition massCannon() - { - return this.massCannon; - } - - @Override - public IItemDefinition memoryCard() - { - return this.memoryCard; - } - - @Override - public IItemDefinition networkTool() - { - return this.networkTool; - } - - @Override - public IItemDefinition portableCell() - { - return this.portableCell; - } - - @Override - public IItemDefinition cellCreative() - { - return this.cellCreative; - } - - @Override - public IItemDefinition viewCell() - { - return this.viewCell; - } - - @Override - public IItemDefinition cell1k() - { - return this.cell1k; - } - - @Override - public IItemDefinition cell4k() - { - return this.cell4k; - } - - @Override - public IItemDefinition cell16k() - { - return this.cell16k; - } - - @Override - public IItemDefinition cell64k() - { - return this.cell64k; - } - - @Override - public IItemDefinition fluidCell1k() - { - return this.fluidCell1k; - } - - @Override - public IItemDefinition fluidCell4k() - { - return this.fluidCell4k; - } - - @Override - public IItemDefinition fluidCell16k() - { - return this.fluidCell16k; - } - - @Override - public IItemDefinition fluidCell64k() - { - return this.fluidCell64k; - } - - @Override - public IItemDefinition spatialCell2() - { - return this.spatialCell2; - } - - @Override - public IItemDefinition spatialCell16() - { - return this.spatialCell16; - } - - @Override - public IItemDefinition spatialCell128() - { - return this.spatialCell128; - } - - @Override - public IItemDefinition facade() - { - return this.facade; - } - - @Override - public IItemDefinition crystalSeed() - { - return this.crystalSeed; - } - - @Override - public IItemDefinition encodedPattern() - { - return this.encodedPattern; - } - - @Override - public IItemDefinition colorApplicator() - { - return this.colorApplicator; - } - - @Override - public AEColoredItemDefinition coloredPaintBall() - { - return this.coloredPaintBall; - } - - @Override - public AEColoredItemDefinition coloredLumenPaintBall() - { - return this.coloredLumenPaintBall; - } - - public IItemDefinition paintBall() - { - return this.paintBall; - } - - public IItemDefinition toolEraser() - { - return this.toolEraser; - } - - public IItemDefinition toolMeteoritePlacer() - { - return this.toolMeteoritePlacer; - } - - public IItemDefinition toolDebugCard() - { - return this.toolDebugCard; - } - - public IItemDefinition toolReplicatorCard() - { - return this.toolReplicatorCard; - } - - public IItemDefinition dummyFluidItem() - { - return this.dummyFluidItem; - } +public final class ApiItems implements IItems { + private final IItemDefinition certusQuartzAxe; + private final IItemDefinition certusQuartzHoe; + private final IItemDefinition certusQuartzShovel; + private final IItemDefinition certusQuartzPick; + private final IItemDefinition certusQuartzSword; + private final IItemDefinition certusQuartzWrench; + private final IItemDefinition certusQuartzKnife; + + private final IItemDefinition netherQuartzAxe; + private final IItemDefinition netherQuartzHoe; + private final IItemDefinition netherQuartzShovel; + private final IItemDefinition netherQuartzPick; + private final IItemDefinition netherQuartzSword; + private final IItemDefinition netherQuartzWrench; + private final IItemDefinition netherQuartzKnife; + + private final IItemDefinition entropyManipulator; + private final IItemDefinition wirelessTerminal; + private final IItemDefinition biometricCard; + private final IItemDefinition chargedStaff; + private final IItemDefinition massCannon; + private final IItemDefinition memoryCard; + private final IItemDefinition networkTool; + private final IItemDefinition portableCell; + + private final IItemDefinition cellCreative; + private final IItemDefinition viewCell; + + private final IItemDefinition cell1k; + private final IItemDefinition cell4k; + private final IItemDefinition cell16k; + private final IItemDefinition cell64k; + + private final IItemDefinition fluidCell1k; + private final IItemDefinition fluidCell4k; + private final IItemDefinition fluidCell16k; + private final IItemDefinition fluidCell64k; + + private final IItemDefinition spatialCell2; + private final IItemDefinition spatialCell16; + private final IItemDefinition spatialCell128; + + private final IItemDefinition facade; + private final IItemDefinition crystalSeed; + + // rv1 + private final IItemDefinition encodedPattern; + private final IItemDefinition colorApplicator; + + private final IItemDefinition paintBall; + private final AEColoredItemDefinition coloredPaintBall; + private final AEColoredItemDefinition coloredLumenPaintBall; + + // unsupported dev tools + private final IItemDefinition toolEraser; + private final IItemDefinition toolMeteoritePlacer; + private final IItemDefinition toolDebugCard; + private final IItemDefinition toolReplicatorCard; + + private final IItemDefinition dummyFluidItem; + + public ApiItems(FeatureFactory registry) { + FeatureFactory certusTools = registry.features(AEFeature.CERTUS_QUARTZ_TOOLS); + this.certusQuartzAxe = certusTools.item("certus_quartz_axe", () -> new ToolQuartzAxe(AEFeature.CERTUS_QUARTZ_TOOLS)) + .addFeatures(AEFeature.QUARTZ_AXE) + .build(); + this.certusQuartzHoe = certusTools.item("certus_quartz_hoe", () -> new ToolQuartzHoe(AEFeature.CERTUS_QUARTZ_TOOLS)) + .addFeatures(AEFeature.QUARTZ_HOE) + .build(); + this.certusQuartzShovel = certusTools.item("certus_quartz_spade", () -> new ToolQuartzSpade(AEFeature.CERTUS_QUARTZ_TOOLS)) + .addFeatures(AEFeature.QUARTZ_SPADE) + .build(); + this.certusQuartzPick = certusTools.item("certus_quartz_pickaxe", () -> new ToolQuartzPickaxe(AEFeature.CERTUS_QUARTZ_TOOLS)) + .addFeatures(AEFeature.QUARTZ_PICKAXE) + .build(); + this.certusQuartzSword = certusTools.item("certus_quartz_sword", () -> new ToolQuartzSword(AEFeature.CERTUS_QUARTZ_TOOLS)) + .addFeatures(AEFeature.QUARTZ_SWORD) + .build(); + this.certusQuartzWrench = certusTools.item("certus_quartz_wrench", ToolQuartzWrench::new) + .addFeatures(AEFeature.QUARTZ_WRENCH) + .bootstrap(item -> (IOreDictComponent) side -> OreDictionary.registerOre("itemQuartzWrench", new ItemStack(item))) + .build(); + this.certusQuartzKnife = certusTools.item("certus_quartz_cutting_knife", () -> new ToolQuartzCuttingKnife(AEFeature.CERTUS_QUARTZ_TOOLS)) + .addFeatures(AEFeature.QUARTZ_KNIFE) + .bootstrap(item -> (IOreDictComponent) side -> OreDictionary.registerOre("itemQuartzKnife", new ItemStack(item))) + .build(); + + FeatureFactory netherTools = registry.features(AEFeature.NETHER_QUARTZ_TOOLS); + this.netherQuartzAxe = netherTools.item("nether_quartz_axe", () -> new ToolQuartzAxe(AEFeature.NETHER_QUARTZ_TOOLS)) + .addFeatures(AEFeature.QUARTZ_AXE) + .build(); + this.netherQuartzHoe = netherTools.item("nether_quartz_hoe", () -> new ToolQuartzHoe(AEFeature.NETHER_QUARTZ_TOOLS)) + .addFeatures(AEFeature.QUARTZ_HOE) + .build(); + this.netherQuartzShovel = netherTools.item("nether_quartz_spade", () -> new ToolQuartzSpade(AEFeature.NETHER_QUARTZ_TOOLS)) + .addFeatures(AEFeature.QUARTZ_SPADE) + .build(); + this.netherQuartzPick = netherTools.item("nether_quartz_pickaxe", () -> new ToolQuartzPickaxe(AEFeature.NETHER_QUARTZ_TOOLS)) + .addFeatures(AEFeature.QUARTZ_PICKAXE) + .build(); + this.netherQuartzSword = netherTools.item("nether_quartz_sword", () -> new ToolQuartzSword(AEFeature.NETHER_QUARTZ_TOOLS)) + .addFeatures(AEFeature.QUARTZ_SWORD) + .build(); + this.netherQuartzWrench = netherTools.item("nether_quartz_wrench", ToolQuartzWrench::new) + .addFeatures(AEFeature.QUARTZ_WRENCH) + .bootstrap(item -> (IOreDictComponent) side -> OreDictionary.registerOre("itemQuartzWrench", new ItemStack(item))) + .build(); + this.netherQuartzKnife = netherTools.item("nether_quartz_cutting_knife", () -> new ToolQuartzCuttingKnife(AEFeature.NETHER_QUARTZ_TOOLS)) + .addFeatures(AEFeature.QUARTZ_KNIFE) + .bootstrap(item -> (IOreDictComponent) side -> OreDictionary.registerOre("itemQuartzKnife", new ItemStack(item))) + .build(); + + FeatureFactory powerTools = registry.features(AEFeature.POWERED_TOOLS); + this.entropyManipulator = powerTools.item("entropy_manipulator", ToolEntropyManipulator::new) + .addFeatures(AEFeature.ENTROPY_MANIPULATOR) + .dispenserBehavior(DispenserBlockTool::new) + .build(); + this.wirelessTerminal = powerTools.item("wireless_terminal", ToolWirelessTerminal::new).addFeatures(AEFeature.WIRELESS_ACCESS_TERMINAL).build(); + this.chargedStaff = powerTools.item("charged_staff", ToolChargedStaff::new).addFeatures(AEFeature.CHARGED_STAFF).build(); + this.massCannon = powerTools.item("matter_cannon", ToolMatterCannon::new) + .addFeatures(AEFeature.MATTER_CANNON) + .dispenserBehavior(DispenserMatterCannon::new) + .build(); + this.portableCell = powerTools.item("portable_cell", ToolPortableCell::new).addFeatures(AEFeature.PORTABLE_CELL, AEFeature.STORAGE_CELLS).build(); + this.colorApplicator = powerTools.item("color_applicator", ToolColorApplicator::new) + .addFeatures(AEFeature.COLOR_APPLICATOR) + .dispenserBehavior(DispenserBlockTool::new) + .rendering(new ToolColorApplicatorRendering()) + .build(); + + this.biometricCard = registry.item("biometric_card", ToolBiometricCard::new) + .rendering(new ToolBiometricCardRendering()) + .features(AEFeature.SECURITY) + .build(); + this.memoryCard = registry.item("memory_card", ToolMemoryCard::new) + .rendering(new ToolMemoryCardRendering()) + .features(AEFeature.MEMORY_CARD) + .build(); + this.networkTool = registry.item("network_tool", ToolNetworkTool::new).features(AEFeature.NETWORK_TOOL).build(); + + this.cellCreative = registry.item("creative_storage_cell", ItemCreativeStorageCell::new) + .features(AEFeature.STORAGE_CELLS, AEFeature.CREATIVE) + .build(); + this.viewCell = registry.item("view_cell", ItemViewCell::new).features(AEFeature.VIEW_CELL).build(); + + FeatureFactory storageCells = registry.features(AEFeature.STORAGE_CELLS); + this.cell1k = storageCells.item("storage_cell_1k", () -> new BasicItemStorageCell(MaterialType.CELL1K_PART, 1)).build(); + this.cell4k = storageCells.item("storage_cell_4k", () -> new BasicItemStorageCell(MaterialType.CELL4K_PART, 4)).build(); + this.cell16k = storageCells.item("storage_cell_16k", () -> new BasicItemStorageCell(MaterialType.CELL16K_PART, 16)).build(); + this.cell64k = storageCells.item("storage_cell_64k", () -> new BasicItemStorageCell(MaterialType.CELL64K_PART, 64)).build(); + + this.fluidCell1k = storageCells.item("fluid_storage_cell_1k", () -> new BasicFluidStorageCell(MaterialType.FLUID_CELL1K_PART, 1)).build(); + this.fluidCell4k = storageCells.item("fluid_storage_cell_4k", () -> new BasicFluidStorageCell(MaterialType.FLUID_CELL4K_PART, 4)).build(); + this.fluidCell16k = storageCells.item("fluid_storage_cell_16k", () -> new BasicFluidStorageCell(MaterialType.FLUID_CELL16K_PART, 16)).build(); + this.fluidCell64k = storageCells.item("fluid_storage_cell_64k", () -> new BasicFluidStorageCell(MaterialType.FLUID_CELL64K_PART, 64)).build(); + + FeatureFactory spatialCells = registry.features(AEFeature.SPATIAL_IO); + this.spatialCell2 = spatialCells.item("spatial_storage_cell_2_cubed", () -> new ItemSpatialStorageCell(2)).build(); + this.spatialCell16 = spatialCells.item("spatial_storage_cell_16_cubed", () -> new ItemSpatialStorageCell(16)).build(); + this.spatialCell128 = spatialCells.item("spatial_storage_cell_128_cubed", () -> new ItemSpatialStorageCell(128)).build(); + + this.facade = registry.item("facade", ItemFacade::new) + .features(AEFeature.FACADES) + .creativeTab(CreativeTabFacade.instance) + .rendering(new FacadeRendering()) + .build(); + this.crystalSeed = registry.item("crystal_seed", ItemCrystalSeed::new) + .features(AEFeature.CRYSTAL_SEEDS) + .rendering(new ItemCrystalSeedRendering()) + .bootstrap(item -> (IEntityRegistrationComponent) r -> + { + r.register(EntityEntryBuilder.create() + .entity(EntityGrowingCrystal.class) + .id(new ResourceLocation("appliedenergistics2", EntityGrowingCrystal.class.getName()), + EntityIds.get(EntityGrowingCrystal.class)) + .name(EntityGrowingCrystal.class.getSimpleName()) + .tracker(16, 4, true) + .build()); + }) + .build(); + + // rv1 + this.encodedPattern = registry.item("encoded_pattern", ItemEncodedPattern::new) + .features(AEFeature.PATTERNS) + .rendering(new ItemEncodedPatternRendering()) + .build(); + + this.paintBall = registry.item("paint_ball", ItemPaintBall::new) + .features(AEFeature.PAINT_BALLS) + .rendering(new ItemPaintBallRendering()) + .build(); + this.coloredPaintBall = registry.colored(this.paintBall, 0); + this.coloredLumenPaintBall = registry.colored(this.paintBall, 20); + + FeatureFactory debugTools = registry.features(AEFeature.UNSUPPORTED_DEVELOPER_TOOLS, AEFeature.CREATIVE); + this.toolEraser = debugTools.item("debug_eraser", ToolEraser::new).build(); + this.toolMeteoritePlacer = debugTools.item("debug_meteorite_placer", ToolMeteoritePlacer::new).build(); + this.toolDebugCard = debugTools.item("debug_card", ToolDebugCard::new).build(); + this.toolReplicatorCard = debugTools.item("debug_replicator_card", ToolReplicatorCard::new).build(); + + this.dummyFluidItem = registry.item("dummy_fluid_item", FluidDummyItem::new).rendering(new FluidDummyItemRendering()).build(); + } + + @Override + public IItemDefinition certusQuartzAxe() { + return this.certusQuartzAxe; + } + + @Override + public IItemDefinition certusQuartzHoe() { + return this.certusQuartzHoe; + } + + @Override + public IItemDefinition certusQuartzShovel() { + return this.certusQuartzShovel; + } + + @Override + public IItemDefinition certusQuartzPick() { + return this.certusQuartzPick; + } + + @Override + public IItemDefinition certusQuartzSword() { + return this.certusQuartzSword; + } + + @Override + public IItemDefinition certusQuartzWrench() { + return this.certusQuartzWrench; + } + + @Override + public IItemDefinition certusQuartzKnife() { + return this.certusQuartzKnife; + } + + @Override + public IItemDefinition netherQuartzAxe() { + return this.netherQuartzAxe; + } + + @Override + public IItemDefinition netherQuartzHoe() { + return this.netherQuartzHoe; + } + + @Override + public IItemDefinition netherQuartzShovel() { + return this.netherQuartzShovel; + } + + @Override + public IItemDefinition netherQuartzPick() { + return this.netherQuartzPick; + } + + @Override + public IItemDefinition netherQuartzSword() { + return this.netherQuartzSword; + } + + @Override + public IItemDefinition netherQuartzWrench() { + return this.netherQuartzWrench; + } + + @Override + public IItemDefinition netherQuartzKnife() { + return this.netherQuartzKnife; + } + + @Override + public IItemDefinition entropyManipulator() { + return this.entropyManipulator; + } + + @Override + public IItemDefinition wirelessTerminal() { + return this.wirelessTerminal; + } + + @Override + public IItemDefinition biometricCard() { + return this.biometricCard; + } + + @Override + public IItemDefinition chargedStaff() { + return this.chargedStaff; + } + + @Override + public IItemDefinition massCannon() { + return this.massCannon; + } + + @Override + public IItemDefinition memoryCard() { + return this.memoryCard; + } + + @Override + public IItemDefinition networkTool() { + return this.networkTool; + } + + @Override + public IItemDefinition portableCell() { + return this.portableCell; + } + + @Override + public IItemDefinition cellCreative() { + return this.cellCreative; + } + + @Override + public IItemDefinition viewCell() { + return this.viewCell; + } + + @Override + public IItemDefinition cell1k() { + return this.cell1k; + } + + @Override + public IItemDefinition cell4k() { + return this.cell4k; + } + + @Override + public IItemDefinition cell16k() { + return this.cell16k; + } + + @Override + public IItemDefinition cell64k() { + return this.cell64k; + } + + @Override + public IItemDefinition fluidCell1k() { + return this.fluidCell1k; + } + + @Override + public IItemDefinition fluidCell4k() { + return this.fluidCell4k; + } + + @Override + public IItemDefinition fluidCell16k() { + return this.fluidCell16k; + } + + @Override + public IItemDefinition fluidCell64k() { + return this.fluidCell64k; + } + + @Override + public IItemDefinition spatialCell2() { + return this.spatialCell2; + } + + @Override + public IItemDefinition spatialCell16() { + return this.spatialCell16; + } + + @Override + public IItemDefinition spatialCell128() { + return this.spatialCell128; + } + + @Override + public IItemDefinition facade() { + return this.facade; + } + + @Override + public IItemDefinition crystalSeed() { + return this.crystalSeed; + } + + @Override + public IItemDefinition encodedPattern() { + return this.encodedPattern; + } + + @Override + public IItemDefinition colorApplicator() { + return this.colorApplicator; + } + + @Override + public AEColoredItemDefinition coloredPaintBall() { + return this.coloredPaintBall; + } + + @Override + public AEColoredItemDefinition coloredLumenPaintBall() { + return this.coloredLumenPaintBall; + } + + public IItemDefinition paintBall() { + return this.paintBall; + } + + public IItemDefinition toolEraser() { + return this.toolEraser; + } + + public IItemDefinition toolMeteoritePlacer() { + return this.toolMeteoritePlacer; + } + + public IItemDefinition toolDebugCard() { + return this.toolDebugCard; + } + + public IItemDefinition toolReplicatorCard() { + return this.toolReplicatorCard; + } + + public IItemDefinition dummyFluidItem() { + return this.dummyFluidItem; + } } diff --git a/src/main/java/appeng/core/api/definitions/ApiMaterials.java b/src/main/java/appeng/core/api/definitions/ApiMaterials.java index 9d29dd152..d2f55074e 100644 --- a/src/main/java/appeng/core/api/definitions/ApiMaterials.java +++ b/src/main/java/appeng/core/api/definitions/ApiMaterials.java @@ -19,14 +19,6 @@ package appeng.core.api.definitions; -import java.util.Arrays; -import java.util.stream.Collectors; - -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.common.registry.EntityEntryBuilder; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.IMaterials; import appeng.bootstrap.FeatureFactory; @@ -39,555 +31,503 @@ import appeng.entity.EntityIds; import appeng.entity.EntitySingularity; import appeng.items.materials.ItemMaterial; import appeng.items.materials.MaterialType; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.common.registry.EntityEntryBuilder; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import java.util.Arrays; +import java.util.stream.Collectors; /** * Internal implementation for the API materials */ -public final class ApiMaterials implements IMaterials -{ - private final IItemDefinition cell2SpatialPart; - private final IItemDefinition cell16SpatialPart; - private final IItemDefinition cell128SpatialPart; - - private final IItemDefinition silicon; - private final IItemDefinition skyDust; - - private final IItemDefinition calcProcessorPress; - private final IItemDefinition engProcessorPress; - private final IItemDefinition logicProcessorPress; - - private final IItemDefinition calcProcessorPrint; - private final IItemDefinition engProcessorPrint; - private final IItemDefinition logicProcessorPrint; - - private final IItemDefinition siliconPress; - private final IItemDefinition siliconPrint; - - private final IItemDefinition namePress; - - private final IItemDefinition logicProcessor; - private final IItemDefinition calcProcessor; - private final IItemDefinition engProcessor; - - private final IItemDefinition basicCard; - private final IItemDefinition advCard; - - private final IItemDefinition purifiedCertusQuartzCrystal; - private final IItemDefinition purifiedNetherQuartzCrystal; - private final IItemDefinition purifiedFluixCrystal; - - private final IItemDefinition cell1kPart; - private final IItemDefinition cell4kPart; - private final IItemDefinition cell16kPart; - private final IItemDefinition cell64kPart; - private final IItemDefinition emptyStorageCell; - - private final IItemDefinition cardRedstone; - private final IItemDefinition cardSpeed; - private final IItemDefinition cardCapacity; - private final IItemDefinition cardPatternExpansion; - private final IItemDefinition cardFuzzy; - private final IItemDefinition cardInverter; - private final IItemDefinition cardCrafting; - - private final IItemDefinition enderDust; - private final IItemDefinition flour; - private final IItemDefinition goldDust; - private final IItemDefinition ironDust; - private final IItemDefinition fluixDust; - private final IItemDefinition certusQuartzDust; - private final IItemDefinition netherQuartzDust; - - private final IItemDefinition matterBall; - - private final IItemDefinition certusQuartzCrystal; - private final IItemDefinition certusQuartzCrystalCharged; - private final IItemDefinition fluixCrystal; - private final IItemDefinition fluixPearl; - - private final IItemDefinition woodenGear; - - private final IItemDefinition wirelessReceiver; - private final IItemDefinition wirelessBooster; - - private final IItemDefinition annihilationCore; - private final IItemDefinition formationCore; - - private final IItemDefinition singularity; - private final IItemDefinition qESingularity; - private final IItemDefinition blankPattern; - - private final IItemDefinition fluidCell1kPart; - private final IItemDefinition fluidCell4kPart; - private final IItemDefinition fluidCell16kPart; - private final IItemDefinition fluidCell64kPart; - - public ApiMaterials( FeatureFactory registry ) - { - final ItemMaterial materials = new ItemMaterial(); - registry.item( "material", () -> materials ) - .rendering( new ItemRenderingCustomizer() - { - @Override - @SideOnly( Side.CLIENT ) - public void customize( IItemRendering rendering ) - { - rendering.meshDefinition( is -> materials.getTypeByStack( is ).getModel() ); - // Register a resource location for every material type - rendering.variants( Arrays.stream( MaterialType.values() ) - .map( MaterialType::getModel ) - .collect( Collectors.toList() ) ); - } - } ) - .bootstrap( item -> (IEntityRegistrationComponent) r -> - { - r.register( EntityEntryBuilder.create() - .entity( EntitySingularity.class ) - .id( new ResourceLocation( "appliedenergistics2", EntitySingularity.class.getName() ), EntityIds.get( EntitySingularity.class ) ) - .name( EntitySingularity.class.getSimpleName() ) - .tracker( 16, 4, true ) - .build() ); - r.register( EntityEntryBuilder.create() - .entity( EntityChargedQuartz.class ) - .id( new ResourceLocation( "appliedenergistics2", EntityChargedQuartz.class.getName() ), - EntityIds.get( EntityChargedQuartz.class ) ) - .name( EntityChargedQuartz.class.getSimpleName() ) - .tracker( 16, 4, true ) - .build() ); - } ) - .build(); - - this.cell2SpatialPart = new DamagedItemDefinition( "material.cell.spatial.2", materials.createMaterial( MaterialType.CELL2_SPATIAL_PART ) ); - this.cell16SpatialPart = new DamagedItemDefinition( "material.cell.spatial.16", materials.createMaterial( MaterialType.CELL16_SPATIAL_PART ) ); - this.cell128SpatialPart = new DamagedItemDefinition( "material.cell.spatial.128", materials.createMaterial( MaterialType.CELL128_SPATIAL_PART ) ); - - this.silicon = new DamagedItemDefinition( "material.silicon", materials.createMaterial( MaterialType.SILICON ) ); - this.skyDust = new DamagedItemDefinition( "material.dust.sky_stone", materials.createMaterial( MaterialType.SKY_DUST ) ); - - this.calcProcessorPress = new DamagedItemDefinition( "material.press.processor.calculation", materials - .createMaterial( MaterialType.CALCULATION_PROCESSOR_PRESS ) ); - this.engProcessorPress = new DamagedItemDefinition( "material.press.processor.engineering", materials - .createMaterial( MaterialType.ENGINEERING_PROCESSOR_PRESS ) ); - this.logicProcessorPress = new DamagedItemDefinition( "material.press.processor.logic", materials - .createMaterial( MaterialType.LOGIC_PROCESSOR_PRESS ) ); - this.siliconPress = new DamagedItemDefinition( "material.press.silicon", materials.createMaterial( MaterialType.SILICON_PRESS ) ); - this.namePress = new DamagedItemDefinition( "material.press.name", materials.createMaterial( MaterialType.NAME_PRESS ) ); - - this.calcProcessorPrint = new DamagedItemDefinition( "material.print.processor.calculation", materials - .createMaterial( MaterialType.CALCULATION_PROCESSOR_PRINT ) ); - this.engProcessorPrint = new DamagedItemDefinition( "material.print.processor.engineering", materials - .createMaterial( MaterialType.ENGINEERING_PROCESSOR_PRINT ) ); - this.logicProcessorPrint = new DamagedItemDefinition( "material.print.processor.logic", materials - .createMaterial( MaterialType.LOGIC_PROCESSOR_PRINT ) ); - this.siliconPrint = new DamagedItemDefinition( "material.print.silicon", materials.createMaterial( MaterialType.SILICON_PRINT ) ); - - this.logicProcessor = new DamagedItemDefinition( "material.processor.logic", materials.createMaterial( MaterialType.LOGIC_PROCESSOR ) ); - this.calcProcessor = new DamagedItemDefinition( "material.processor.calculation", materials.createMaterial( MaterialType.CALCULATION_PROCESSOR ) ); - this.engProcessor = new DamagedItemDefinition( "material.processor.engineering", materials.createMaterial( MaterialType.ENGINEERING_PROCESSOR ) ); - - this.basicCard = new DamagedItemDefinition( "material.card.basic", materials.createMaterial( MaterialType.BASIC_CARD ) ); - this.advCard = new DamagedItemDefinition( "material.card.advanced", materials.createMaterial( MaterialType.ADVANCED_CARD ) ); - - this.purifiedCertusQuartzCrystal = new DamagedItemDefinition( "material.crystal.quartz.certus.purified", materials - .createMaterial( MaterialType.PURIFIED_CERTUS_QUARTZ_CRYSTAL ) ); - this.purifiedNetherQuartzCrystal = new DamagedItemDefinition( "material.crystal.quartz.nether.purified", materials - .createMaterial( MaterialType.PURIFIED_NETHER_QUARTZ_CRYSTAL ) ); - this.purifiedFluixCrystal = new DamagedItemDefinition( "material.crystal.fluix.purified", materials - .createMaterial( MaterialType.PURIFIED_FLUIX_CRYSTAL ) ); - - this.cell1kPart = new DamagedItemDefinition( "material.cell.storage.1k", materials.createMaterial( MaterialType.CELL1K_PART ) ); - this.cell4kPart = new DamagedItemDefinition( "material.cell.storage.4k", materials.createMaterial( MaterialType.CELL4K_PART ) ); - this.cell16kPart = new DamagedItemDefinition( "material.cell.storage.16k", materials.createMaterial( MaterialType.CELL16K_PART ) ); - this.cell64kPart = new DamagedItemDefinition( "material.cell.storage.64k", materials.createMaterial( MaterialType.CELL64K_PART ) ); - this.emptyStorageCell = new DamagedItemDefinition( "material.cell.storage.empty", materials.createMaterial( MaterialType.EMPTY_STORAGE_CELL ) ); - - this.cardRedstone = new DamagedItemDefinition( "material.card.redstone", materials.createMaterial( MaterialType.CARD_REDSTONE ) ); - this.cardSpeed = new DamagedItemDefinition( "material.card.acceleration", materials.createMaterial( MaterialType.CARD_SPEED ) ); - this.cardCapacity = new DamagedItemDefinition( "material.card.capacity", materials.createMaterial( MaterialType.CARD_CAPACITY ) ); - this.cardPatternExpansion = new DamagedItemDefinition( "material.card.pattern.expansion", materials.createMaterial(MaterialType.CARD_PATTERN_EXPANSION) ); - this.cardFuzzy = new DamagedItemDefinition( "material.card.fuzzy", materials.createMaterial( MaterialType.CARD_FUZZY ) ); - this.cardInverter = new DamagedItemDefinition( "material.card.inverter", materials.createMaterial( MaterialType.CARD_INVERTER ) ); - this.cardCrafting = new DamagedItemDefinition( "material.card.crafting", materials.createMaterial( MaterialType.CARD_CRAFTING ) ); - - this.enderDust = new DamagedItemDefinition( "material.dust.ender", materials.createMaterial( MaterialType.ENDER_DUST ) ); - this.flour = new DamagedItemDefinition( "material.flour", materials.createMaterial( MaterialType.FLOUR ) ); - this.goldDust = new DamagedItemDefinition( "material.dust.gold", materials.createMaterial( MaterialType.GOLD_DUST ) ); - this.ironDust = new DamagedItemDefinition( "material.dust.iron", materials.createMaterial( MaterialType.IRON_DUST ) ); - this.fluixDust = new DamagedItemDefinition( "material.dust.fluix", materials.createMaterial( MaterialType.FLUIX_DUST ) ); - this.certusQuartzDust = new DamagedItemDefinition( "material.dust.quartz.certus", materials.createMaterial( MaterialType.CERTUS_QUARTZ_DUST ) ); - this.netherQuartzDust = new DamagedItemDefinition( "material.dust.quartz.nether", materials.createMaterial( MaterialType.NETHER_QUARTZ_DUST ) ); - - this.matterBall = new DamagedItemDefinition( "material.ammo.matter_ball", materials.createMaterial( MaterialType.MATTER_BALL ) ); - - this.certusQuartzCrystal = new DamagedItemDefinition( "material.crystal.quartz.certus", materials - .createMaterial( MaterialType.CERTUS_QUARTZ_CRYSTAL ) ); - this.certusQuartzCrystalCharged = new DamagedItemDefinition( "material.crystal.quartz.certus.charged", materials - .createMaterial( MaterialType.CERTUS_QUARTZ_CRYSTAL_CHARGED ) ); - this.fluixCrystal = new DamagedItemDefinition( "material.crystal.fluix", materials.createMaterial( MaterialType.FLUIX_CRYSTAL ) ); - this.fluixPearl = new DamagedItemDefinition( "material.pearl.fluix", materials.createMaterial( MaterialType.FLUIX_PEARL ) ); - - this.woodenGear = new DamagedItemDefinition( "material.gear.wooden", materials.createMaterial( MaterialType.WOODEN_GEAR ) ); - - this.wirelessReceiver = new DamagedItemDefinition( "material.wireless.receiver", materials.createMaterial( MaterialType.WIRELESS ) ); - this.wirelessBooster = new DamagedItemDefinition( "material.wireless.booster", materials.createMaterial( MaterialType.WIRELESS_BOOSTER ) ); - - this.annihilationCore = new DamagedItemDefinition( "material.core.annihilation", materials.createMaterial( MaterialType.ANNIHILATION_CORE ) ); - this.formationCore = new DamagedItemDefinition( "material.core.formation", materials.createMaterial( MaterialType.FORMATION_CORE ) ); - - this.singularity = new DamagedItemDefinition( "material.singularity", materials.createMaterial( MaterialType.SINGULARITY ) ); - this.qESingularity = new DamagedItemDefinition( "material.singularity.entangled.quantum", materials - .createMaterial( MaterialType.QUANTUM_ENTANGLED_SINGULARITY ) ); - this.blankPattern = new DamagedItemDefinition( "material.pattern.blank", materials.createMaterial( MaterialType.BLANK_PATTERN ) ); - - this.fluidCell1kPart = new DamagedItemDefinition( "material.cell.storage.1k", materials.createMaterial( MaterialType.FLUID_CELL1K_PART ) ); - this.fluidCell4kPart = new DamagedItemDefinition( "material.cell.storage.4k", materials.createMaterial( MaterialType.FLUID_CELL4K_PART ) ); - this.fluidCell16kPart = new DamagedItemDefinition( "material.cell.storage.16k", materials.createMaterial( MaterialType.FLUID_CELL16K_PART ) ); - this.fluidCell64kPart = new DamagedItemDefinition( "material.cell.storage.64k", materials.createMaterial( MaterialType.FLUID_CELL64K_PART ) ); - } - - @Override - public IItemDefinition cell2SpatialPart() - { - return this.cell2SpatialPart; - } - - @Override - public IItemDefinition cell16SpatialPart() - { - return this.cell16SpatialPart; - } - - @Override - public IItemDefinition cell128SpatialPart() - { - return this.cell128SpatialPart; - } - - @Override - public IItemDefinition silicon() - { - return this.silicon; - } - - @Override - public IItemDefinition skyDust() - { - return this.skyDust; - } - - @Override - public IItemDefinition calcProcessorPress() - { - return this.calcProcessorPress; - } - - @Override - public IItemDefinition engProcessorPress() - { - return this.engProcessorPress; - } - - @Override - public IItemDefinition logicProcessorPress() - { - return this.logicProcessorPress; - } - - @Override - public IItemDefinition calcProcessorPrint() - { - return this.calcProcessorPrint; - } - - @Override - public IItemDefinition engProcessorPrint() - { - return this.engProcessorPrint; - } - - @Override - public IItemDefinition logicProcessorPrint() - { - return this.logicProcessorPrint; - } - - @Override - public IItemDefinition siliconPress() - { - return this.siliconPress; - } - - @Override - public IItemDefinition siliconPrint() - { - return this.siliconPrint; - } - - @Override - public IItemDefinition namePress() - { - return this.namePress; - } - - @Override - public IItemDefinition logicProcessor() - { - return this.logicProcessor; - } - - @Override - public IItemDefinition calcProcessor() - { - return this.calcProcessor; - } - - @Override - public IItemDefinition engProcessor() - { - return this.engProcessor; - } - - @Override - public IItemDefinition basicCard() - { - return this.basicCard; - } - - @Override - public IItemDefinition advCard() - { - return this.advCard; - } - - @Override - public IItemDefinition purifiedCertusQuartzCrystal() - { - return this.purifiedCertusQuartzCrystal; - } - - @Override - public IItemDefinition purifiedNetherQuartzCrystal() - { - return this.purifiedNetherQuartzCrystal; - } - - @Override - public IItemDefinition purifiedFluixCrystal() - { - return this.purifiedFluixCrystal; - } - - @Override - public IItemDefinition cell1kPart() - { - return this.cell1kPart; - } - - @Override - public IItemDefinition cell4kPart() - { - return this.cell4kPart; - } - - @Override - public IItemDefinition cell16kPart() - { - return this.cell16kPart; - } - - @Override - public IItemDefinition cell64kPart() - { - return this.cell64kPart; - } - - @Override - public IItemDefinition emptyStorageCell() - { - return this.emptyStorageCell; - } - - @Override - public IItemDefinition cardRedstone() - { - return this.cardRedstone; - } - - @Override - public IItemDefinition cardSpeed() - { - return this.cardSpeed; - } - - @Override - public IItemDefinition cardCapacity() - { - return this.cardCapacity; - } - - @Override - public IItemDefinition cardPatternExpansion(){ return this.cardPatternExpansion;} - - @Override - public IItemDefinition cardFuzzy() - { - return this.cardFuzzy; - } - - @Override - public IItemDefinition cardInverter() - { - return this.cardInverter; - } - - @Override - public IItemDefinition cardCrafting() - { - return this.cardCrafting; - } - - @Override - public IItemDefinition enderDust() - { - return this.enderDust; - } - - @Override - public IItemDefinition flour() - { - return this.flour; - } - - @Override - public IItemDefinition goldDust() - { - return this.goldDust; - } - - @Override - public IItemDefinition ironDust() - { - return this.ironDust; - } - - @Override - public IItemDefinition fluixDust() - { - return this.fluixDust; - } - - @Override - public IItemDefinition certusQuartzDust() - { - return this.certusQuartzDust; - } - - @Override - public IItemDefinition netherQuartzDust() - { - return this.netherQuartzDust; - } - - @Override - public IItemDefinition matterBall() - { - return this.matterBall; - } - - @Override - public IItemDefinition certusQuartzCrystal() - { - return this.certusQuartzCrystal; - } - - @Override - public IItemDefinition certusQuartzCrystalCharged() - { - return this.certusQuartzCrystalCharged; - } - - @Override - public IItemDefinition fluixCrystal() - { - return this.fluixCrystal; - } - - @Override - public IItemDefinition fluixPearl() - { - return this.fluixPearl; - } - - @Override - public IItemDefinition woodenGear() - { - return this.woodenGear; - } - - @Override - public IItemDefinition wirelessReceiver() - { - return this.wirelessReceiver; - } - - @Override - public IItemDefinition wirelessBooster() - { - return this.wirelessBooster; - } - - @Override - public IItemDefinition annihilationCore() - { - return this.annihilationCore; - } - - @Override - public IItemDefinition formationCore() - { - return this.formationCore; - } - - @Override - public IItemDefinition singularity() - { - return this.singularity; - } - - @Override - public IItemDefinition qESingularity() - { - return this.qESingularity; - } - - @Override - public IItemDefinition blankPattern() - { - return this.blankPattern; - } - - @Override - public IItemDefinition fluidCell1kPart() - { - return this.fluidCell1kPart; - } - - @Override - public IItemDefinition fluidCell4kPart() - { - return this.fluidCell4kPart; - } - - @Override - public IItemDefinition fluidCell16kPart() - { - return this.fluidCell16kPart; - } - - @Override - public IItemDefinition fluidCell64kPart() - { - return this.fluidCell64kPart; - } +public final class ApiMaterials implements IMaterials { + private final IItemDefinition cell2SpatialPart; + private final IItemDefinition cell16SpatialPart; + private final IItemDefinition cell128SpatialPart; + + private final IItemDefinition silicon; + private final IItemDefinition skyDust; + + private final IItemDefinition calcProcessorPress; + private final IItemDefinition engProcessorPress; + private final IItemDefinition logicProcessorPress; + + private final IItemDefinition calcProcessorPrint; + private final IItemDefinition engProcessorPrint; + private final IItemDefinition logicProcessorPrint; + + private final IItemDefinition siliconPress; + private final IItemDefinition siliconPrint; + + private final IItemDefinition namePress; + + private final IItemDefinition logicProcessor; + private final IItemDefinition calcProcessor; + private final IItemDefinition engProcessor; + + private final IItemDefinition basicCard; + private final IItemDefinition advCard; + + private final IItemDefinition purifiedCertusQuartzCrystal; + private final IItemDefinition purifiedNetherQuartzCrystal; + private final IItemDefinition purifiedFluixCrystal; + + private final IItemDefinition cell1kPart; + private final IItemDefinition cell4kPart; + private final IItemDefinition cell16kPart; + private final IItemDefinition cell64kPart; + private final IItemDefinition emptyStorageCell; + + private final IItemDefinition cardRedstone; + private final IItemDefinition cardSpeed; + private final IItemDefinition cardCapacity; + private final IItemDefinition cardPatternExpansion; + private final IItemDefinition cardFuzzy; + private final IItemDefinition cardInverter; + private final IItemDefinition cardCrafting; + + private final IItemDefinition enderDust; + private final IItemDefinition flour; + private final IItemDefinition goldDust; + private final IItemDefinition ironDust; + private final IItemDefinition fluixDust; + private final IItemDefinition certusQuartzDust; + private final IItemDefinition netherQuartzDust; + + private final IItemDefinition matterBall; + + private final IItemDefinition certusQuartzCrystal; + private final IItemDefinition certusQuartzCrystalCharged; + private final IItemDefinition fluixCrystal; + private final IItemDefinition fluixPearl; + + private final IItemDefinition woodenGear; + + private final IItemDefinition wirelessReceiver; + private final IItemDefinition wirelessBooster; + + private final IItemDefinition annihilationCore; + private final IItemDefinition formationCore; + + private final IItemDefinition singularity; + private final IItemDefinition qESingularity; + private final IItemDefinition blankPattern; + + private final IItemDefinition fluidCell1kPart; + private final IItemDefinition fluidCell4kPart; + private final IItemDefinition fluidCell16kPart; + private final IItemDefinition fluidCell64kPart; + + public ApiMaterials(FeatureFactory registry) { + final ItemMaterial materials = new ItemMaterial(); + registry.item("material", () -> materials) + .rendering(new ItemRenderingCustomizer() { + @Override + @SideOnly(Side.CLIENT) + public void customize(IItemRendering rendering) { + rendering.meshDefinition(is -> materials.getTypeByStack(is).getModel()); + // Register a resource location for every material type + rendering.variants(Arrays.stream(MaterialType.values()) + .map(MaterialType::getModel) + .collect(Collectors.toList())); + } + }) + .bootstrap(item -> (IEntityRegistrationComponent) r -> + { + r.register(EntityEntryBuilder.create() + .entity(EntitySingularity.class) + .id(new ResourceLocation("appliedenergistics2", EntitySingularity.class.getName()), EntityIds.get(EntitySingularity.class)) + .name(EntitySingularity.class.getSimpleName()) + .tracker(16, 4, true) + .build()); + r.register(EntityEntryBuilder.create() + .entity(EntityChargedQuartz.class) + .id(new ResourceLocation("appliedenergistics2", EntityChargedQuartz.class.getName()), + EntityIds.get(EntityChargedQuartz.class)) + .name(EntityChargedQuartz.class.getSimpleName()) + .tracker(16, 4, true) + .build()); + }) + .build(); + + this.cell2SpatialPart = new DamagedItemDefinition("material.cell.spatial.2", materials.createMaterial(MaterialType.CELL2_SPATIAL_PART)); + this.cell16SpatialPart = new DamagedItemDefinition("material.cell.spatial.16", materials.createMaterial(MaterialType.CELL16_SPATIAL_PART)); + this.cell128SpatialPart = new DamagedItemDefinition("material.cell.spatial.128", materials.createMaterial(MaterialType.CELL128_SPATIAL_PART)); + + this.silicon = new DamagedItemDefinition("material.silicon", materials.createMaterial(MaterialType.SILICON)); + this.skyDust = new DamagedItemDefinition("material.dust.sky_stone", materials.createMaterial(MaterialType.SKY_DUST)); + + this.calcProcessorPress = new DamagedItemDefinition("material.press.processor.calculation", materials + .createMaterial(MaterialType.CALCULATION_PROCESSOR_PRESS)); + this.engProcessorPress = new DamagedItemDefinition("material.press.processor.engineering", materials + .createMaterial(MaterialType.ENGINEERING_PROCESSOR_PRESS)); + this.logicProcessorPress = new DamagedItemDefinition("material.press.processor.logic", materials + .createMaterial(MaterialType.LOGIC_PROCESSOR_PRESS)); + this.siliconPress = new DamagedItemDefinition("material.press.silicon", materials.createMaterial(MaterialType.SILICON_PRESS)); + this.namePress = new DamagedItemDefinition("material.press.name", materials.createMaterial(MaterialType.NAME_PRESS)); + + this.calcProcessorPrint = new DamagedItemDefinition("material.print.processor.calculation", materials + .createMaterial(MaterialType.CALCULATION_PROCESSOR_PRINT)); + this.engProcessorPrint = new DamagedItemDefinition("material.print.processor.engineering", materials + .createMaterial(MaterialType.ENGINEERING_PROCESSOR_PRINT)); + this.logicProcessorPrint = new DamagedItemDefinition("material.print.processor.logic", materials + .createMaterial(MaterialType.LOGIC_PROCESSOR_PRINT)); + this.siliconPrint = new DamagedItemDefinition("material.print.silicon", materials.createMaterial(MaterialType.SILICON_PRINT)); + + this.logicProcessor = new DamagedItemDefinition("material.processor.logic", materials.createMaterial(MaterialType.LOGIC_PROCESSOR)); + this.calcProcessor = new DamagedItemDefinition("material.processor.calculation", materials.createMaterial(MaterialType.CALCULATION_PROCESSOR)); + this.engProcessor = new DamagedItemDefinition("material.processor.engineering", materials.createMaterial(MaterialType.ENGINEERING_PROCESSOR)); + + this.basicCard = new DamagedItemDefinition("material.card.basic", materials.createMaterial(MaterialType.BASIC_CARD)); + this.advCard = new DamagedItemDefinition("material.card.advanced", materials.createMaterial(MaterialType.ADVANCED_CARD)); + + this.purifiedCertusQuartzCrystal = new DamagedItemDefinition("material.crystal.quartz.certus.purified", materials + .createMaterial(MaterialType.PURIFIED_CERTUS_QUARTZ_CRYSTAL)); + this.purifiedNetherQuartzCrystal = new DamagedItemDefinition("material.crystal.quartz.nether.purified", materials + .createMaterial(MaterialType.PURIFIED_NETHER_QUARTZ_CRYSTAL)); + this.purifiedFluixCrystal = new DamagedItemDefinition("material.crystal.fluix.purified", materials + .createMaterial(MaterialType.PURIFIED_FLUIX_CRYSTAL)); + + this.cell1kPart = new DamagedItemDefinition("material.cell.storage.1k", materials.createMaterial(MaterialType.CELL1K_PART)); + this.cell4kPart = new DamagedItemDefinition("material.cell.storage.4k", materials.createMaterial(MaterialType.CELL4K_PART)); + this.cell16kPart = new DamagedItemDefinition("material.cell.storage.16k", materials.createMaterial(MaterialType.CELL16K_PART)); + this.cell64kPart = new DamagedItemDefinition("material.cell.storage.64k", materials.createMaterial(MaterialType.CELL64K_PART)); + this.emptyStorageCell = new DamagedItemDefinition("material.cell.storage.empty", materials.createMaterial(MaterialType.EMPTY_STORAGE_CELL)); + + this.cardRedstone = new DamagedItemDefinition("material.card.redstone", materials.createMaterial(MaterialType.CARD_REDSTONE)); + this.cardSpeed = new DamagedItemDefinition("material.card.acceleration", materials.createMaterial(MaterialType.CARD_SPEED)); + this.cardCapacity = new DamagedItemDefinition("material.card.capacity", materials.createMaterial(MaterialType.CARD_CAPACITY)); + this.cardPatternExpansion = new DamagedItemDefinition("material.card.pattern.expansion", materials.createMaterial(MaterialType.CARD_PATTERN_EXPANSION)); + this.cardFuzzy = new DamagedItemDefinition("material.card.fuzzy", materials.createMaterial(MaterialType.CARD_FUZZY)); + this.cardInverter = new DamagedItemDefinition("material.card.inverter", materials.createMaterial(MaterialType.CARD_INVERTER)); + this.cardCrafting = new DamagedItemDefinition("material.card.crafting", materials.createMaterial(MaterialType.CARD_CRAFTING)); + + this.enderDust = new DamagedItemDefinition("material.dust.ender", materials.createMaterial(MaterialType.ENDER_DUST)); + this.flour = new DamagedItemDefinition("material.flour", materials.createMaterial(MaterialType.FLOUR)); + this.goldDust = new DamagedItemDefinition("material.dust.gold", materials.createMaterial(MaterialType.GOLD_DUST)); + this.ironDust = new DamagedItemDefinition("material.dust.iron", materials.createMaterial(MaterialType.IRON_DUST)); + this.fluixDust = new DamagedItemDefinition("material.dust.fluix", materials.createMaterial(MaterialType.FLUIX_DUST)); + this.certusQuartzDust = new DamagedItemDefinition("material.dust.quartz.certus", materials.createMaterial(MaterialType.CERTUS_QUARTZ_DUST)); + this.netherQuartzDust = new DamagedItemDefinition("material.dust.quartz.nether", materials.createMaterial(MaterialType.NETHER_QUARTZ_DUST)); + + this.matterBall = new DamagedItemDefinition("material.ammo.matter_ball", materials.createMaterial(MaterialType.MATTER_BALL)); + + this.certusQuartzCrystal = new DamagedItemDefinition("material.crystal.quartz.certus", materials + .createMaterial(MaterialType.CERTUS_QUARTZ_CRYSTAL)); + this.certusQuartzCrystalCharged = new DamagedItemDefinition("material.crystal.quartz.certus.charged", materials + .createMaterial(MaterialType.CERTUS_QUARTZ_CRYSTAL_CHARGED)); + this.fluixCrystal = new DamagedItemDefinition("material.crystal.fluix", materials.createMaterial(MaterialType.FLUIX_CRYSTAL)); + this.fluixPearl = new DamagedItemDefinition("material.pearl.fluix", materials.createMaterial(MaterialType.FLUIX_PEARL)); + + this.woodenGear = new DamagedItemDefinition("material.gear.wooden", materials.createMaterial(MaterialType.WOODEN_GEAR)); + + this.wirelessReceiver = new DamagedItemDefinition("material.wireless.receiver", materials.createMaterial(MaterialType.WIRELESS)); + this.wirelessBooster = new DamagedItemDefinition("material.wireless.booster", materials.createMaterial(MaterialType.WIRELESS_BOOSTER)); + + this.annihilationCore = new DamagedItemDefinition("material.core.annihilation", materials.createMaterial(MaterialType.ANNIHILATION_CORE)); + this.formationCore = new DamagedItemDefinition("material.core.formation", materials.createMaterial(MaterialType.FORMATION_CORE)); + + this.singularity = new DamagedItemDefinition("material.singularity", materials.createMaterial(MaterialType.SINGULARITY)); + this.qESingularity = new DamagedItemDefinition("material.singularity.entangled.quantum", materials + .createMaterial(MaterialType.QUANTUM_ENTANGLED_SINGULARITY)); + this.blankPattern = new DamagedItemDefinition("material.pattern.blank", materials.createMaterial(MaterialType.BLANK_PATTERN)); + + this.fluidCell1kPart = new DamagedItemDefinition("material.cell.storage.1k", materials.createMaterial(MaterialType.FLUID_CELL1K_PART)); + this.fluidCell4kPart = new DamagedItemDefinition("material.cell.storage.4k", materials.createMaterial(MaterialType.FLUID_CELL4K_PART)); + this.fluidCell16kPart = new DamagedItemDefinition("material.cell.storage.16k", materials.createMaterial(MaterialType.FLUID_CELL16K_PART)); + this.fluidCell64kPart = new DamagedItemDefinition("material.cell.storage.64k", materials.createMaterial(MaterialType.FLUID_CELL64K_PART)); + } + + @Override + public IItemDefinition cell2SpatialPart() { + return this.cell2SpatialPart; + } + + @Override + public IItemDefinition cell16SpatialPart() { + return this.cell16SpatialPart; + } + + @Override + public IItemDefinition cell128SpatialPart() { + return this.cell128SpatialPart; + } + + @Override + public IItemDefinition silicon() { + return this.silicon; + } + + @Override + public IItemDefinition skyDust() { + return this.skyDust; + } + + @Override + public IItemDefinition calcProcessorPress() { + return this.calcProcessorPress; + } + + @Override + public IItemDefinition engProcessorPress() { + return this.engProcessorPress; + } + + @Override + public IItemDefinition logicProcessorPress() { + return this.logicProcessorPress; + } + + @Override + public IItemDefinition calcProcessorPrint() { + return this.calcProcessorPrint; + } + + @Override + public IItemDefinition engProcessorPrint() { + return this.engProcessorPrint; + } + + @Override + public IItemDefinition logicProcessorPrint() { + return this.logicProcessorPrint; + } + + @Override + public IItemDefinition siliconPress() { + return this.siliconPress; + } + + @Override + public IItemDefinition siliconPrint() { + return this.siliconPrint; + } + + @Override + public IItemDefinition namePress() { + return this.namePress; + } + + @Override + public IItemDefinition logicProcessor() { + return this.logicProcessor; + } + + @Override + public IItemDefinition calcProcessor() { + return this.calcProcessor; + } + + @Override + public IItemDefinition engProcessor() { + return this.engProcessor; + } + + @Override + public IItemDefinition basicCard() { + return this.basicCard; + } + + @Override + public IItemDefinition advCard() { + return this.advCard; + } + + @Override + public IItemDefinition purifiedCertusQuartzCrystal() { + return this.purifiedCertusQuartzCrystal; + } + + @Override + public IItemDefinition purifiedNetherQuartzCrystal() { + return this.purifiedNetherQuartzCrystal; + } + + @Override + public IItemDefinition purifiedFluixCrystal() { + return this.purifiedFluixCrystal; + } + + @Override + public IItemDefinition cell1kPart() { + return this.cell1kPart; + } + + @Override + public IItemDefinition cell4kPart() { + return this.cell4kPart; + } + + @Override + public IItemDefinition cell16kPart() { + return this.cell16kPart; + } + + @Override + public IItemDefinition cell64kPart() { + return this.cell64kPart; + } + + @Override + public IItemDefinition emptyStorageCell() { + return this.emptyStorageCell; + } + + @Override + public IItemDefinition cardRedstone() { + return this.cardRedstone; + } + + @Override + public IItemDefinition cardSpeed() { + return this.cardSpeed; + } + + @Override + public IItemDefinition cardCapacity() { + return this.cardCapacity; + } + + @Override + public IItemDefinition cardPatternExpansion() { + return this.cardPatternExpansion; + } + + @Override + public IItemDefinition cardFuzzy() { + return this.cardFuzzy; + } + + @Override + public IItemDefinition cardInverter() { + return this.cardInverter; + } + + @Override + public IItemDefinition cardCrafting() { + return this.cardCrafting; + } + + @Override + public IItemDefinition enderDust() { + return this.enderDust; + } + + @Override + public IItemDefinition flour() { + return this.flour; + } + + @Override + public IItemDefinition goldDust() { + return this.goldDust; + } + + @Override + public IItemDefinition ironDust() { + return this.ironDust; + } + + @Override + public IItemDefinition fluixDust() { + return this.fluixDust; + } + + @Override + public IItemDefinition certusQuartzDust() { + return this.certusQuartzDust; + } + + @Override + public IItemDefinition netherQuartzDust() { + return this.netherQuartzDust; + } + + @Override + public IItemDefinition matterBall() { + return this.matterBall; + } + + @Override + public IItemDefinition certusQuartzCrystal() { + return this.certusQuartzCrystal; + } + + @Override + public IItemDefinition certusQuartzCrystalCharged() { + return this.certusQuartzCrystalCharged; + } + + @Override + public IItemDefinition fluixCrystal() { + return this.fluixCrystal; + } + + @Override + public IItemDefinition fluixPearl() { + return this.fluixPearl; + } + + @Override + public IItemDefinition woodenGear() { + return this.woodenGear; + } + + @Override + public IItemDefinition wirelessReceiver() { + return this.wirelessReceiver; + } + + @Override + public IItemDefinition wirelessBooster() { + return this.wirelessBooster; + } + + @Override + public IItemDefinition annihilationCore() { + return this.annihilationCore; + } + + @Override + public IItemDefinition formationCore() { + return this.formationCore; + } + + @Override + public IItemDefinition singularity() { + return this.singularity; + } + + @Override + public IItemDefinition qESingularity() { + return this.qESingularity; + } + + @Override + public IItemDefinition blankPattern() { + return this.blankPattern; + } + + @Override + public IItemDefinition fluidCell1kPart() { + return this.fluidCell1kPart; + } + + @Override + public IItemDefinition fluidCell4kPart() { + return this.fluidCell4kPart; + } + + @Override + public IItemDefinition fluidCell16kPart() { + return this.fluidCell16kPart; + } + + @Override + public IItemDefinition fluidCell64kPart() { + return this.fluidCell64kPart; + } } diff --git a/src/main/java/appeng/core/api/definitions/ApiParts.java b/src/main/java/appeng/core/api/definitions/ApiParts.java index 3a1f984c7..626232226 100644 --- a/src/main/java/appeng/core/api/definitions/ApiParts.java +++ b/src/main/java/appeng/core/api/definitions/ApiParts.java @@ -37,433 +37,380 @@ import appeng.items.parts.PartType; /** * Internal implementation for the API parts */ -public final class ApiParts implements IParts -{ - private final AEColoredItemDefinition cableSmart; - private final AEColoredItemDefinition cableCovered; - private final AEColoredItemDefinition cableGlass; - private final AEColoredItemDefinition cableDenseCovered; - private final AEColoredItemDefinition cableDenseSmart; - // private final AEColoredItemDefinition lumenCableSmart; - // private final AEColoredItemDefinition lumenCableCovered; - // private final AEColoredItemDefinition lumenCableGlass; - // private final AEColoredItemDefinition lumenCableDense; - private final IItemDefinition quartzFiber; - private final IItemDefinition toggleBus; - private final IItemDefinition invertedToggleBus; - private final IItemDefinition storageBus; - private final IItemDefinition oreDictStorageBus; - private final IItemDefinition importBus; - private final IItemDefinition exportBus; - private final IItemDefinition iface; - private final IItemDefinition fluidIface; - private final IItemDefinition levelEmitter; - private final IItemDefinition fluidLevelEmitter; - private final IItemDefinition annihilationPlane; - private final IItemDefinition identityAnnihilationPlane; - private final IItemDefinition fluidAnnihilationPlane; - private final IItemDefinition formationPlane; - private final IItemDefinition fluidFormationPlane; - private final IItemDefinition p2PTunnelME; - private final IItemDefinition p2PTunnelRedstone; - private final IItemDefinition p2PTunnelItems; - private final IItemDefinition p2PTunnelFluids; - private final IItemDefinition p2PTunnelEU; - private final IItemDefinition p2PTunnelFE; - private final IItemDefinition p2PTunnelGTEU; - private final IItemDefinition p2PTunnelLight; - // private final IItemDefinition p2PTunnelOpenComputers; - private final IItemDefinition cableAnchor; - private final IItemDefinition monitor; - private final IItemDefinition semiDarkMonitor; - private final IItemDefinition darkMonitor; - private final IItemDefinition interfaceTerminal; - private final IItemDefinition patternTerminal; - private final IItemDefinition expandedProcessingPatternTerminal; - private final IItemDefinition interfaceConfigurationTerminal; - private final IItemDefinition craftingTerminal; - private final IItemDefinition terminal; - private final IItemDefinition storageMonitor; - private final IItemDefinition conversionMonitor; - private final IItemDefinition fluidImportBus; - private final IItemDefinition fluidExportBus; - private final IItemDefinition fluidTerminal; - private final IItemDefinition fluidStorageBus; +public final class ApiParts implements IParts { + private final AEColoredItemDefinition cableSmart; + private final AEColoredItemDefinition cableCovered; + private final AEColoredItemDefinition cableGlass; + private final AEColoredItemDefinition cableDenseCovered; + private final AEColoredItemDefinition cableDenseSmart; + // private final AEColoredItemDefinition lumenCableSmart; + // private final AEColoredItemDefinition lumenCableCovered; + // private final AEColoredItemDefinition lumenCableGlass; + // private final AEColoredItemDefinition lumenCableDense; + private final IItemDefinition quartzFiber; + private final IItemDefinition toggleBus; + private final IItemDefinition invertedToggleBus; + private final IItemDefinition storageBus; + private final IItemDefinition oreDictStorageBus; + private final IItemDefinition importBus; + private final IItemDefinition exportBus; + private final IItemDefinition iface; + private final IItemDefinition fluidIface; + private final IItemDefinition levelEmitter; + private final IItemDefinition fluidLevelEmitter; + private final IItemDefinition annihilationPlane; + private final IItemDefinition identityAnnihilationPlane; + private final IItemDefinition fluidAnnihilationPlane; + private final IItemDefinition formationPlane; + private final IItemDefinition fluidFormationPlane; + private final IItemDefinition p2PTunnelME; + private final IItemDefinition p2PTunnelRedstone; + private final IItemDefinition p2PTunnelItems; + private final IItemDefinition p2PTunnelFluids; + private final IItemDefinition p2PTunnelEU; + private final IItemDefinition p2PTunnelFE; + private final IItemDefinition p2PTunnelGTEU; + private final IItemDefinition p2PTunnelLight; + // private final IItemDefinition p2PTunnelOpenComputers; + private final IItemDefinition cableAnchor; + private final IItemDefinition monitor; + private final IItemDefinition semiDarkMonitor; + private final IItemDefinition darkMonitor; + private final IItemDefinition interfaceTerminal; + private final IItemDefinition patternTerminal; + private final IItemDefinition expandedProcessingPatternTerminal; + private final IItemDefinition interfaceConfigurationTerminal; + private final IItemDefinition craftingTerminal; + private final IItemDefinition terminal; + private final IItemDefinition storageMonitor; + private final IItemDefinition conversionMonitor; + private final IItemDefinition fluidImportBus; + private final IItemDefinition fluidExportBus; + private final IItemDefinition fluidTerminal; + private final IItemDefinition fluidStorageBus; - public ApiParts( FeatureFactory registry, PartModels partModels ) - { - final ItemPart itemPart = new ItemPart(); - registry.item( "part", () -> itemPart ).rendering( new ItemPartRendering( partModels, itemPart ) ).build(); + public ApiParts(FeatureFactory registry, PartModels partModels) { + final ItemPart itemPart = new ItemPart(); + registry.item("part", () -> itemPart).rendering(new ItemPartRendering(partModels, itemPart)).build(); - // Register all part models - for( PartType partType : PartType.values() ) - { - partModels.registerModels( partType.getModels() ); - } + // Register all part models + for (PartType partType : PartType.values()) { + partModels.registerModels(partType.getModels()); + } - this.cableSmart = constructColoredDefinition( itemPart, PartType.CABLE_SMART ); - this.cableCovered = constructColoredDefinition( itemPart, PartType.CABLE_COVERED ); - this.cableGlass = constructColoredDefinition( itemPart, PartType.CABLE_GLASS ); - this.cableDenseCovered = constructColoredDefinition( itemPart, PartType.CABLE_DENSE_COVERED ); - this.cableDenseSmart = constructColoredDefinition( itemPart, PartType.CABLE_DENSE_SMART ); - // this.lumenCableSmart = Optional.absent(); // has yet to be implemented, no PartType defined for it yet - // this.lumenCableCovered = Optional.absent(); // has yet to be implemented, no PartType defined for it yet - // this.lumenCableGlass = Optional.absent(); // has yet to be implemented, no PartType defined for it yet - // this.lumenCableDense = Optional.absent(); // has yet to be implemented, no PartType defined for it yet - this.quartzFiber = new DamagedItemDefinition( "part.quartz_fiber", itemPart.createPart( PartType.QUARTZ_FIBER ) ); - this.toggleBus = new DamagedItemDefinition( "part.toggle_bus", itemPart.createPart( PartType.TOGGLE_BUS ) ); - this.invertedToggleBus = new DamagedItemDefinition( "part.toggle_bus.inverted", itemPart.createPart( PartType.INVERTED_TOGGLE_BUS ) ); - this.storageBus = new DamagedItemDefinition( "part.bus.storage", itemPart.createPart( PartType.STORAGE_BUS ) ); - this.oreDictStorageBus = new DamagedItemDefinition( "part.bus.oredict_storage", itemPart.createPart( PartType.OREDICT_STORAGE_BUS ) ); - this.importBus = new DamagedItemDefinition( "part.bus.import", itemPart.createPart( PartType.IMPORT_BUS ) ); - this.exportBus = new DamagedItemDefinition( "part.bus.export", itemPart.createPart( PartType.EXPORT_BUS ) ); - this.iface = new DamagedItemDefinition( "part.interface", itemPart.createPart( PartType.INTERFACE ) ); - this.fluidIface = new DamagedItemDefinition( "part.fluid_interface", itemPart.createPart( PartType.FLUID_INTERFACE ) ); - this.levelEmitter = new DamagedItemDefinition( "part.level_emitter", itemPart.createPart( PartType.LEVEL_EMITTER ) ); - this.fluidLevelEmitter = new DamagedItemDefinition( "part.fluid_level_emitter", itemPart.createPart( PartType.FLUID_LEVEL_EMITTER ) ); - this.annihilationPlane = new DamagedItemDefinition( "part.plane.annihilation", itemPart.createPart( PartType.ANNIHILATION_PLANE ) ); - this.identityAnnihilationPlane = new DamagedItemDefinition( "part.plane.annihiliation.identity", itemPart.createPart( PartType.IDENTITY_ANNIHILATION_PLANE ) ); - this.fluidAnnihilationPlane = new DamagedItemDefinition( "part.plane.fluid_annihilation", itemPart.createPart( PartType.FLUID_ANNIHILATION_PLANE ) ); - this.formationPlane = new DamagedItemDefinition( "part.plane.formation", itemPart.createPart( PartType.FORMATION_PLANE ) ); - this.fluidFormationPlane = new DamagedItemDefinition( "part.plane.fluid_formation", itemPart.createPart( PartType.FLUID_FORMATION_PLANE ) ); - this.p2PTunnelME = new DamagedItemDefinition( "part.tunnel.me", itemPart.createPart( PartType.P2P_TUNNEL_ME ) ); - this.p2PTunnelRedstone = new DamagedItemDefinition( "part.tunnel.redstone", itemPart.createPart( PartType.P2P_TUNNEL_REDSTONE ) ); - this.p2PTunnelItems = new DamagedItemDefinition( "part.tunnel.item", itemPart.createPart( PartType.P2P_TUNNEL_ITEMS ) ); - this.p2PTunnelFluids = new DamagedItemDefinition( "part.tunnel.fluid", itemPart.createPart( PartType.P2P_TUNNEL_FLUIDS ) ); - this.p2PTunnelEU = new DamagedItemDefinition( "part.tunnel.eu", itemPart.createPart( PartType.P2P_TUNNEL_IC2 ) ); - this.p2PTunnelFE = new DamagedItemDefinition( "part.tunnel.fe", itemPart.createPart( PartType.P2P_TUNNEL_FE ) ); - this.p2PTunnelGTEU = new DamagedItemDefinition( "part.tunnel.gteu", itemPart.createPart( PartType.P2P_TUNNEL_GTEU ) ); - this.p2PTunnelLight = new DamagedItemDefinition( "part.tunnel.light", itemPart.createPart( PartType.P2P_TUNNEL_LIGHT ) ); - // this.p2PTunnelOpenComputers = new DamagedItemDefinition( itemMultiPart.createPart( - // PartType.P2PTunnelOpenComputers ) ); - this.cableAnchor = new DamagedItemDefinition( "part.cable_anchor", itemPart.createPart( PartType.CABLE_ANCHOR ) ); - this.monitor = new DamagedItemDefinition( "part.monitor", itemPart.createPart( PartType.MONITOR ) ); - this.semiDarkMonitor = new DamagedItemDefinition( "part.monitor.semi_dark", itemPart.createPart( PartType.SEMI_DARK_MONITOR ) ); - this.darkMonitor = new DamagedItemDefinition( "part.monitor.dark", itemPart.createPart( PartType.DARK_MONITOR ) ); - this.interfaceTerminal = new DamagedItemDefinition( "part.terminal.interface", itemPart.createPart( PartType.INTERFACE_TERMINAL ) ); - this.patternTerminal = new DamagedItemDefinition( "part.terminal.pattern", itemPart.createPart( PartType.PATTERN_TERMINAL ) ); - this.expandedProcessingPatternTerminal = new DamagedItemDefinition( "part.terminal.expanded_processing_pattern", itemPart.createPart( PartType.EXPANDED_PROCESSING_PATTERN_TERMINAL ) ); - this.interfaceConfigurationTerminal = new DamagedItemDefinition( "part.terminal.interface_configuration_terminal", itemPart.createPart( PartType.INTERFACE_CONFIGURATION_TERMINAL ) ); - this.craftingTerminal = new DamagedItemDefinition( "part.terminal.crafting", itemPart.createPart( PartType.CRAFTING_TERMINAL ) ); - this.terminal = new DamagedItemDefinition( "part.terminal", itemPart.createPart( PartType.TERMINAL ) ); - this.storageMonitor = new DamagedItemDefinition( "part.monitor.storage", itemPart.createPart( PartType.STORAGE_MONITOR ) ); - this.conversionMonitor = new DamagedItemDefinition( "part.monitor.conversion", itemPart.createPart( PartType.CONVERSION_MONITOR ) ); - this.fluidImportBus = new DamagedItemDefinition( "part.bus.import.fluid", itemPart.createPart( PartType.FLUID_IMPORT_BUS ) ); - this.fluidExportBus = new DamagedItemDefinition( "part.bus.export.fluid", itemPart.createPart( PartType.FLUID_EXPORT_BUS ) ); - this.fluidTerminal = new DamagedItemDefinition( "part.terminal.fluid", itemPart.createPart( PartType.FLUID_TERMINAL ) ); - this.fluidStorageBus = new DamagedItemDefinition( "part.bus.storage.fluid", itemPart.createPart( PartType.FLUID_STORAGE_BUS ) ); - } + this.cableSmart = constructColoredDefinition(itemPart, PartType.CABLE_SMART); + this.cableCovered = constructColoredDefinition(itemPart, PartType.CABLE_COVERED); + this.cableGlass = constructColoredDefinition(itemPart, PartType.CABLE_GLASS); + this.cableDenseCovered = constructColoredDefinition(itemPart, PartType.CABLE_DENSE_COVERED); + this.cableDenseSmart = constructColoredDefinition(itemPart, PartType.CABLE_DENSE_SMART); + // this.lumenCableSmart = Optional.absent(); // has yet to be implemented, no PartType defined for it yet + // this.lumenCableCovered = Optional.absent(); // has yet to be implemented, no PartType defined for it yet + // this.lumenCableGlass = Optional.absent(); // has yet to be implemented, no PartType defined for it yet + // this.lumenCableDense = Optional.absent(); // has yet to be implemented, no PartType defined for it yet + this.quartzFiber = new DamagedItemDefinition("part.quartz_fiber", itemPart.createPart(PartType.QUARTZ_FIBER)); + this.toggleBus = new DamagedItemDefinition("part.toggle_bus", itemPart.createPart(PartType.TOGGLE_BUS)); + this.invertedToggleBus = new DamagedItemDefinition("part.toggle_bus.inverted", itemPart.createPart(PartType.INVERTED_TOGGLE_BUS)); + this.storageBus = new DamagedItemDefinition("part.bus.storage", itemPart.createPart(PartType.STORAGE_BUS)); + this.oreDictStorageBus = new DamagedItemDefinition("part.bus.oredict_storage", itemPart.createPart(PartType.OREDICT_STORAGE_BUS)); + this.importBus = new DamagedItemDefinition("part.bus.import", itemPart.createPart(PartType.IMPORT_BUS)); + this.exportBus = new DamagedItemDefinition("part.bus.export", itemPart.createPart(PartType.EXPORT_BUS)); + this.iface = new DamagedItemDefinition("part.interface", itemPart.createPart(PartType.INTERFACE)); + this.fluidIface = new DamagedItemDefinition("part.fluid_interface", itemPart.createPart(PartType.FLUID_INTERFACE)); + this.levelEmitter = new DamagedItemDefinition("part.level_emitter", itemPart.createPart(PartType.LEVEL_EMITTER)); + this.fluidLevelEmitter = new DamagedItemDefinition("part.fluid_level_emitter", itemPart.createPart(PartType.FLUID_LEVEL_EMITTER)); + this.annihilationPlane = new DamagedItemDefinition("part.plane.annihilation", itemPart.createPart(PartType.ANNIHILATION_PLANE)); + this.identityAnnihilationPlane = new DamagedItemDefinition("part.plane.annihiliation.identity", itemPart.createPart(PartType.IDENTITY_ANNIHILATION_PLANE)); + this.fluidAnnihilationPlane = new DamagedItemDefinition("part.plane.fluid_annihilation", itemPart.createPart(PartType.FLUID_ANNIHILATION_PLANE)); + this.formationPlane = new DamagedItemDefinition("part.plane.formation", itemPart.createPart(PartType.FORMATION_PLANE)); + this.fluidFormationPlane = new DamagedItemDefinition("part.plane.fluid_formation", itemPart.createPart(PartType.FLUID_FORMATION_PLANE)); + this.p2PTunnelME = new DamagedItemDefinition("part.tunnel.me", itemPart.createPart(PartType.P2P_TUNNEL_ME)); + this.p2PTunnelRedstone = new DamagedItemDefinition("part.tunnel.redstone", itemPart.createPart(PartType.P2P_TUNNEL_REDSTONE)); + this.p2PTunnelItems = new DamagedItemDefinition("part.tunnel.item", itemPart.createPart(PartType.P2P_TUNNEL_ITEMS)); + this.p2PTunnelFluids = new DamagedItemDefinition("part.tunnel.fluid", itemPart.createPart(PartType.P2P_TUNNEL_FLUIDS)); + this.p2PTunnelEU = new DamagedItemDefinition("part.tunnel.eu", itemPart.createPart(PartType.P2P_TUNNEL_IC2)); + this.p2PTunnelFE = new DamagedItemDefinition("part.tunnel.fe", itemPart.createPart(PartType.P2P_TUNNEL_FE)); + this.p2PTunnelGTEU = new DamagedItemDefinition("part.tunnel.gteu", itemPart.createPart(PartType.P2P_TUNNEL_GTEU)); + this.p2PTunnelLight = new DamagedItemDefinition("part.tunnel.light", itemPart.createPart(PartType.P2P_TUNNEL_LIGHT)); + // this.p2PTunnelOpenComputers = new DamagedItemDefinition( itemMultiPart.createPart( + // PartType.P2PTunnelOpenComputers ) ); + this.cableAnchor = new DamagedItemDefinition("part.cable_anchor", itemPart.createPart(PartType.CABLE_ANCHOR)); + this.monitor = new DamagedItemDefinition("part.monitor", itemPart.createPart(PartType.MONITOR)); + this.semiDarkMonitor = new DamagedItemDefinition("part.monitor.semi_dark", itemPart.createPart(PartType.SEMI_DARK_MONITOR)); + this.darkMonitor = new DamagedItemDefinition("part.monitor.dark", itemPart.createPart(PartType.DARK_MONITOR)); + this.interfaceTerminal = new DamagedItemDefinition("part.terminal.interface", itemPart.createPart(PartType.INTERFACE_TERMINAL)); + this.patternTerminal = new DamagedItemDefinition("part.terminal.pattern", itemPart.createPart(PartType.PATTERN_TERMINAL)); + this.expandedProcessingPatternTerminal = new DamagedItemDefinition("part.terminal.expanded_processing_pattern", itemPart.createPart(PartType.EXPANDED_PROCESSING_PATTERN_TERMINAL)); + this.interfaceConfigurationTerminal = new DamagedItemDefinition("part.terminal.interface_configuration_terminal", itemPart.createPart(PartType.INTERFACE_CONFIGURATION_TERMINAL)); + this.craftingTerminal = new DamagedItemDefinition("part.terminal.crafting", itemPart.createPart(PartType.CRAFTING_TERMINAL)); + this.terminal = new DamagedItemDefinition("part.terminal", itemPart.createPart(PartType.TERMINAL)); + this.storageMonitor = new DamagedItemDefinition("part.monitor.storage", itemPart.createPart(PartType.STORAGE_MONITOR)); + this.conversionMonitor = new DamagedItemDefinition("part.monitor.conversion", itemPart.createPart(PartType.CONVERSION_MONITOR)); + this.fluidImportBus = new DamagedItemDefinition("part.bus.import.fluid", itemPart.createPart(PartType.FLUID_IMPORT_BUS)); + this.fluidExportBus = new DamagedItemDefinition("part.bus.export.fluid", itemPart.createPart(PartType.FLUID_EXPORT_BUS)); + this.fluidTerminal = new DamagedItemDefinition("part.terminal.fluid", itemPart.createPart(PartType.FLUID_TERMINAL)); + this.fluidStorageBus = new DamagedItemDefinition("part.bus.storage.fluid", itemPart.createPart(PartType.FLUID_STORAGE_BUS)); + } - private static AEColoredItemDefinition constructColoredDefinition( final ItemPart target, final PartType type ) - { - final ColoredItemDefinition definition = new ColoredItemDefinition(); + private static AEColoredItemDefinition constructColoredDefinition(final ItemPart target, final PartType type) { + final ColoredItemDefinition definition = new ColoredItemDefinition(); - for( final AEColor color : AEColor.values() ) - { - final ItemStackSrc multiPartSource = target.createPart( type, color ); + for (final AEColor color : AEColor.values()) { + final ItemStackSrc multiPartSource = target.createPart(type, color); - definition.add( color, multiPartSource ); - } + definition.add(color, multiPartSource); + } - return definition; - } + return definition; + } - @Override - public AEColoredItemDefinition cableSmart() - { - return this.cableSmart; - } + @Override + public AEColoredItemDefinition cableSmart() { + return this.cableSmart; + } - @Override - public AEColoredItemDefinition cableCovered() - { - return this.cableCovered; - } + @Override + public AEColoredItemDefinition cableCovered() { + return this.cableCovered; + } - @Override - public AEColoredItemDefinition cableGlass() - { - return this.cableGlass; - } + @Override + public AEColoredItemDefinition cableGlass() { + return this.cableGlass; + } - @Override - public AEColoredItemDefinition cableDenseCovered() - { - return this.cableDenseCovered; - } + @Override + public AEColoredItemDefinition cableDenseCovered() { + return this.cableDenseCovered; + } - @Override - public AEColoredItemDefinition cableDenseSmart() - { - return this.cableDenseSmart; - } + @Override + public AEColoredItemDefinition cableDenseSmart() { + return this.cableDenseSmart; + } - @Override - public AEColoredItemDefinition lumenCableSmart() - { - throw new MissingDefinitionException( "Lumen Smart Cable has yet to be implemented." ); - // return this.lumenCableSmart; - } + @Override + public AEColoredItemDefinition lumenCableSmart() { + throw new MissingDefinitionException("Lumen Smart Cable has yet to be implemented."); + // return this.lumenCableSmart; + } - @Override - public AEColoredItemDefinition lumenCableCovered() - { - throw new MissingDefinitionException( "Lumen Covered Cable has yet to be implemented." ); - // return this.lumenCableCovered; - } + @Override + public AEColoredItemDefinition lumenCableCovered() { + throw new MissingDefinitionException("Lumen Covered Cable has yet to be implemented."); + // return this.lumenCableCovered; + } - @Override - public AEColoredItemDefinition lumenCableGlass() - { - throw new MissingDefinitionException( "Lumen Glass Cable has yet to be implemented." ); - // return this.lumenCableGlass; - } + @Override + public AEColoredItemDefinition lumenCableGlass() { + throw new MissingDefinitionException("Lumen Glass Cable has yet to be implemented."); + // return this.lumenCableGlass; + } - @Override - public AEColoredItemDefinition lumenDenseCableSmart() - { - throw new MissingDefinitionException( "Lumen Dense Cable has yet to be implemented." ); - // return this.lumenCableDense; - } + @Override + public AEColoredItemDefinition lumenDenseCableSmart() { + throw new MissingDefinitionException("Lumen Dense Cable has yet to be implemented."); + // return this.lumenCableDense; + } - @Override - public IItemDefinition quartzFiber() - { - return this.quartzFiber; - } + @Override + public IItemDefinition quartzFiber() { + return this.quartzFiber; + } - @Override - public IItemDefinition toggleBus() - { - return this.toggleBus; - } + @Override + public IItemDefinition toggleBus() { + return this.toggleBus; + } - @Override - public IItemDefinition invertedToggleBus() - { - return this.invertedToggleBus; - } + @Override + public IItemDefinition invertedToggleBus() { + return this.invertedToggleBus; + } - @Override - public IItemDefinition storageBus() - { - return this.storageBus; - } + @Override + public IItemDefinition storageBus() { + return this.storageBus; + } - @Override - public IItemDefinition oreDictStorageBus() - { - return this.oreDictStorageBus; - } + @Override + public IItemDefinition oreDictStorageBus() { + return this.oreDictStorageBus; + } - @Override - public IItemDefinition importBus() - { - return this.importBus; - } + @Override + public IItemDefinition importBus() { + return this.importBus; + } - @Override - public IItemDefinition exportBus() - { - return this.exportBus; - } + @Override + public IItemDefinition exportBus() { + return this.exportBus; + } - @Override - public IItemDefinition iface() - { - return this.iface; - } + @Override + public IItemDefinition iface() { + return this.iface; + } - @Override - public IItemDefinition fluidIface() - { - return this.fluidIface; - } + @Override + public IItemDefinition fluidIface() { + return this.fluidIface; + } - @Override - public IItemDefinition levelEmitter() - { - return this.levelEmitter; - } + @Override + public IItemDefinition levelEmitter() { + return this.levelEmitter; + } - @Override - public IItemDefinition annihilationPlane() - { - return this.annihilationPlane; - } + @Override + public IItemDefinition annihilationPlane() { + return this.annihilationPlane; + } - @Override - public IItemDefinition identityAnnihilationPlane() - { - return this.identityAnnihilationPlane; - } + @Override + public IItemDefinition identityAnnihilationPlane() { + return this.identityAnnihilationPlane; + } - @Override - public IItemDefinition formationPlane() - { - return this.formationPlane; - } + @Override + public IItemDefinition formationPlane() { + return this.formationPlane; + } - @Override - public IItemDefinition p2PTunnelME() - { - return this.p2PTunnelME; - } + @Override + public IItemDefinition p2PTunnelME() { + return this.p2PTunnelME; + } - @Override - public IItemDefinition p2PTunnelRedstone() - { - return this.p2PTunnelRedstone; - } + @Override + public IItemDefinition p2PTunnelRedstone() { + return this.p2PTunnelRedstone; + } - @Override - public IItemDefinition p2PTunnelItems() - { - return this.p2PTunnelItems; - } + @Override + public IItemDefinition p2PTunnelItems() { + return this.p2PTunnelItems; + } - @Override - public IItemDefinition p2PTunnelFluids() - { - return this.p2PTunnelFluids; - } + @Override + public IItemDefinition p2PTunnelFluids() { + return this.p2PTunnelFluids; + } - @Override - public IItemDefinition p2PTunnelEU() - { - return this.p2PTunnelEU; - } + @Override + public IItemDefinition p2PTunnelEU() { + return this.p2PTunnelEU; + } - @Override - public IItemDefinition p2PTunnelFE() - { - return this.p2PTunnelFE; - } + @Override + public IItemDefinition p2PTunnelFE() { + return this.p2PTunnelFE; + } - public IItemDefinition p2PTunnelGTEU() - { - return this.p2PTunnelGTEU; - } + public IItemDefinition p2PTunnelGTEU() { + return this.p2PTunnelGTEU; + } - @Override - public IItemDefinition p2PTunnelLight() - { - return this.p2PTunnelLight; - } + @Override + public IItemDefinition p2PTunnelLight() { + return this.p2PTunnelLight; + } - /* - * @Override - * public IItemDefinition p2PTunnelOpenComputers() - * { - * return this.p2PTunnelOpenComputers; - * } - */ + /* + * @Override + * public IItemDefinition p2PTunnelOpenComputers() + * { + * return this.p2PTunnelOpenComputers; + * } + */ - @Override - public IItemDefinition cableAnchor() - { - return this.cableAnchor; - } + @Override + public IItemDefinition cableAnchor() { + return this.cableAnchor; + } - @Override - public IItemDefinition monitor() - { - return this.monitor; - } + @Override + public IItemDefinition monitor() { + return this.monitor; + } - @Override - public IItemDefinition semiDarkMonitor() - { - return this.semiDarkMonitor; - } + @Override + public IItemDefinition semiDarkMonitor() { + return this.semiDarkMonitor; + } - @Override - public IItemDefinition darkMonitor() - { - return this.darkMonitor; - } + @Override + public IItemDefinition darkMonitor() { + return this.darkMonitor; + } - @Override - public IItemDefinition interfaceTerminal() - { - return this.interfaceTerminal; - } + @Override + public IItemDefinition interfaceTerminal() { + return this.interfaceTerminal; + } - @Override - public IItemDefinition patternTerminal() - { - return this.patternTerminal; - } + @Override + public IItemDefinition patternTerminal() { + return this.patternTerminal; + } - @Override - public IItemDefinition expandedProcessingPatternTerminal() - { - return this.expandedProcessingPatternTerminal; - } + @Override + public IItemDefinition expandedProcessingPatternTerminal() { + return this.expandedProcessingPatternTerminal; + } - @Override - public IItemDefinition craftingTerminal() - { - return this.craftingTerminal; - } + @Override + public IItemDefinition craftingTerminal() { + return this.craftingTerminal; + } - @Override - public IItemDefinition terminal() - { - return this.terminal; - } + @Override + public IItemDefinition terminal() { + return this.terminal; + } - @Override - public IItemDefinition storageMonitor() - { - return this.storageMonitor; - } + @Override + public IItemDefinition storageMonitor() { + return this.storageMonitor; + } - @Override - public IItemDefinition conversionMonitor() - { - return this.conversionMonitor; - } + @Override + public IItemDefinition conversionMonitor() { + return this.conversionMonitor; + } - @Override - public IItemDefinition fluidTerminal() - { - return this.fluidTerminal; - } + @Override + public IItemDefinition fluidTerminal() { + return this.fluidTerminal; + } - @Override - public IItemDefinition fluidImportBus() - { - return this.fluidImportBus; - } + @Override + public IItemDefinition fluidImportBus() { + return this.fluidImportBus; + } - @Override - public IItemDefinition fluidExportBus() - { - return this.fluidExportBus; - } + @Override + public IItemDefinition fluidExportBus() { + return this.fluidExportBus; + } - @Override - public IItemDefinition fluidStorageBus() - { - return this.fluidStorageBus; - } + @Override + public IItemDefinition fluidStorageBus() { + return this.fluidStorageBus; + } - @Override - public IItemDefinition fluidLevelEmitter() - { - return this.fluidLevelEmitter; - } + @Override + public IItemDefinition fluidLevelEmitter() { + return this.fluidLevelEmitter; + } - @Override - public IItemDefinition fluidAnnihilationPlane() - { - return this.fluidAnnihilationPlane; - } + @Override + public IItemDefinition fluidAnnihilationPlane() { + return this.fluidAnnihilationPlane; + } - @Override - public IItemDefinition fluidFormationnPlane() - { - return this.fluidFormationPlane; - } + @Override + public IItemDefinition fluidFormationnPlane() { + return this.fluidFormationPlane; + } } diff --git a/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java b/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java index 984d7bed4..ecbf9977f 100644 --- a/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java +++ b/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java @@ -19,34 +19,29 @@ package appeng.core.api.imc; +import appeng.api.AEApi; +import appeng.core.AELog; +import appeng.core.api.IIMCProcessor; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.event.FMLInterModComms.IMCMessage; -import appeng.api.AEApi; -import appeng.core.AELog; -import appeng.core.api.IIMCProcessor; +public class IMCBlackListSpatial implements IIMCProcessor { -public class IMCBlackListSpatial implements IIMCProcessor -{ + @Override + public void process(final IMCMessage m) { - @Override - public void process( final IMCMessage m ) - { + final ItemStack is = m.getItemStackValue(); + if (!is.isEmpty()) { + final Block blk = Block.getBlockFromItem(is.getItem()); + if (blk != Blocks.AIR) { + AEApi.instance().registries().movable().blacklistBlock(blk); + return; + } + } - final ItemStack is = m.getItemStackValue(); - if( !is.isEmpty() ) - { - final Block blk = Block.getBlockFromItem( is.getItem() ); - if( blk != Blocks.AIR ) - { - AEApi.instance().registries().movable().blacklistBlock( blk ); - return; - } - } - - AELog.info( "Bad Block blacklisted by " + m.getSender() ); - } + AELog.info("Bad Block blacklisted by " + m.getSender()); + } } diff --git a/src/main/java/appeng/core/api/imc/IMCGrinder.java b/src/main/java/appeng/core/api/imc/IMCGrinder.java index 69a327647..7de25298f 100644 --- a/src/main/java/appeng/core/api/imc/IMCGrinder.java +++ b/src/main/java/appeng/core/api/imc/IMCGrinder.java @@ -53,72 +53,63 @@ package appeng.core.api.imc; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fml.common.event.FMLInterModComms.IMCMessage; - import appeng.api.AEApi; import appeng.api.features.IGrinderRecipe; import appeng.api.features.IGrinderRecipeBuilder; import appeng.api.features.IGrinderRegistry; import appeng.core.api.IIMCProcessor; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fml.common.event.FMLInterModComms.IMCMessage; -public class IMCGrinder implements IIMCProcessor -{ - @Override - public void process( final IMCMessage m ) - { - final NBTTagCompound msg = m.getNBTValue(); - final NBTTagCompound inTag = (NBTTagCompound) msg.getTag( "in" ); - final NBTTagCompound outTag = (NBTTagCompound) msg.getTag( "out" ); +public class IMCGrinder implements IIMCProcessor { + @Override + public void process(final IMCMessage m) { + final NBTTagCompound msg = m.getNBTValue(); + final NBTTagCompound inTag = (NBTTagCompound) msg.getTag("in"); + final NBTTagCompound outTag = (NBTTagCompound) msg.getTag("out"); - final ItemStack in = new ItemStack( inTag ); - final ItemStack out = new ItemStack( outTag ); + final ItemStack in = new ItemStack(inTag); + final ItemStack out = new ItemStack(outTag); - final int turns = msg.getInteger( "turns" ); + final int turns = msg.getInteger("turns"); - if( in.isEmpty() ) - { - throw new IllegalStateException( "invalid input" ); - } + if (in.isEmpty()) { + throw new IllegalStateException("invalid input"); + } - if( out.isEmpty() ) - { - throw new IllegalStateException( "invalid output" ); - } + if (out.isEmpty()) { + throw new IllegalStateException("invalid output"); + } - if( msg.hasKey( "optional" ) ) - { - final NBTTagCompound optionalTag = (NBTTagCompound) msg.getTag( "optional" ); - final ItemStack optional = new ItemStack( optionalTag ); + if (msg.hasKey("optional")) { + final NBTTagCompound optionalTag = (NBTTagCompound) msg.getTag("optional"); + final ItemStack optional = new ItemStack(optionalTag); - if( optional.isEmpty() ) - { - throw new IllegalStateException( "invalid optional" ); - } + if (optional.isEmpty()) { + throw new IllegalStateException("invalid optional"); + } - final float chance = msg.getFloat( "chance" ); - final IGrinderRegistry grinderRegistry = AEApi.instance().registries().grinder(); - final IGrinderRecipeBuilder builder = grinderRegistry.builder(); - final IGrinderRecipe grinderRecipe = builder.withInput( in ) - .withOutput( out ) - .withFirstOptional( optional, chance ) - .withTurns( turns ) - .build(); + final float chance = msg.getFloat("chance"); + final IGrinderRegistry grinderRegistry = AEApi.instance().registries().grinder(); + final IGrinderRecipeBuilder builder = grinderRegistry.builder(); + final IGrinderRecipe grinderRecipe = builder.withInput(in) + .withOutput(out) + .withFirstOptional(optional, chance) + .withTurns(turns) + .build(); - grinderRegistry.addRecipe( grinderRecipe ); - } - else - { - final IGrinderRegistry grinderRegistry = AEApi.instance().registries().grinder(); - final IGrinderRecipeBuilder builder = grinderRegistry.builder(); - final IGrinderRecipe grinderRecipe = builder.withInput( in ) - .withOutput( out ) - .withTurns( turns ) - .build(); + grinderRegistry.addRecipe(grinderRecipe); + } else { + final IGrinderRegistry grinderRegistry = AEApi.instance().registries().grinder(); + final IGrinderRecipeBuilder builder = grinderRegistry.builder(); + final IGrinderRecipe grinderRecipe = builder.withInput(in) + .withOutput(out) + .withTurns(turns) + .build(); - grinderRegistry.addRecipe( grinderRecipe ); - } - } + grinderRegistry.addRecipe(grinderRecipe); + } + } } diff --git a/src/main/java/appeng/core/api/imc/IMCMatterCannon.java b/src/main/java/appeng/core/api/imc/IMCMatterCannon.java index cf81d9d47..c51399398 100644 --- a/src/main/java/appeng/core/api/imc/IMCMatterCannon.java +++ b/src/main/java/appeng/core/api/imc/IMCMatterCannon.java @@ -32,31 +32,27 @@ package appeng.core.api.imc; +import appeng.api.AEApi; +import appeng.core.api.IIMCProcessor; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fml.common.event.FMLInterModComms.IMCMessage; -import appeng.api.AEApi; -import appeng.core.api.IIMCProcessor; +public class IMCMatterCannon implements IIMCProcessor { -public class IMCMatterCannon implements IIMCProcessor -{ + @Override + public void process(final IMCMessage m) { + final NBTTagCompound msg = m.getNBTValue(); + final NBTTagCompound item = (NBTTagCompound) msg.getTag("item"); - @Override - public void process( final IMCMessage m ) - { - final NBTTagCompound msg = m.getNBTValue(); - final NBTTagCompound item = (NBTTagCompound) msg.getTag( "item" ); + final ItemStack ammo = new ItemStack(item); + final double weight = msg.getDouble("weight"); - final ItemStack ammo = new ItemStack( item ); - final double weight = msg.getDouble( "weight" ); + if (ammo.isEmpty()) { + throw new IllegalStateException("invalid item in message " + m); + } - if( ammo.isEmpty() ) - { - throw new IllegalStateException( "invalid item in message " + m ); - } - - AEApi.instance().registries().matterCannon().registerAmmo( ammo, weight ); - } + AEApi.instance().registries().matterCannon().registerAmmo(ammo, weight); + } } diff --git a/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java b/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java index 870a71d43..66b3db0da 100644 --- a/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java +++ b/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java @@ -30,42 +30,33 @@ package appeng.core.api.imc; -import java.util.Arrays; -import java.util.Locale; - -import net.minecraft.item.ItemStack; -import net.minecraftforge.fml.common.event.FMLInterModComms.IMCMessage; - import appeng.api.AEApi; import appeng.api.config.TunnelType; import appeng.core.api.IIMCProcessor; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fml.common.event.FMLInterModComms.IMCMessage; + +import java.util.Arrays; +import java.util.Locale; -public class IMCP2PAttunement implements IIMCProcessor -{ +public class IMCP2PAttunement implements IIMCProcessor { - @Override - public void process( final IMCMessage m ) - { - final String key = m.key.substring( "add-p2p-attunement-".length() ).replace( '-', '_' ).toUpperCase( Locale.ENGLISH ); + @Override + public void process(final IMCMessage m) { + final String key = m.key.substring("add-p2p-attunement-".length()).replace('-', '_').toUpperCase(Locale.ENGLISH); - final TunnelType type = TunnelType.valueOf( key ); + final TunnelType type = TunnelType.valueOf(key); - if( type != null ) - { - final ItemStack is = m.getItemStackValue(); - if( !is.isEmpty() ) - { - AEApi.instance().registries().p2pTunnel().addNewAttunement( is, type ); - } - else - { - throw new IllegalStateException( "invalid item in message " + m ); - } - } - else - { - throw new IllegalStateException( "invalid type in message " + m + " is not contained in " + Arrays.toString( TunnelType.values() ) ); - } - } + if (type != null) { + final ItemStack is = m.getItemStackValue(); + if (!is.isEmpty()) { + AEApi.instance().registries().p2pTunnel().addNewAttunement(is, type); + } else { + throw new IllegalStateException("invalid item in message " + m); + } + } else { + throw new IllegalStateException("invalid type in message " + m + " is not contained in " + Arrays.toString(TunnelType.values())); + } + } } diff --git a/src/main/java/appeng/core/api/imc/IMCSpatial.java b/src/main/java/appeng/core/api/imc/IMCSpatial.java index 1a5cf0c31..af6ea75c2 100644 --- a/src/main/java/appeng/core/api/imc/IMCSpatial.java +++ b/src/main/java/appeng/core/api/imc/IMCSpatial.java @@ -25,28 +25,22 @@ package appeng.core.api.imc; -import net.minecraftforge.fml.common.event.FMLInterModComms.IMCMessage; - import appeng.api.AEApi; import appeng.core.AELog; import appeng.core.api.IIMCProcessor; +import net.minecraftforge.fml.common.event.FMLInterModComms.IMCMessage; -public class IMCSpatial implements IIMCProcessor -{ +public class IMCSpatial implements IIMCProcessor { - @Override - public void process( final IMCMessage m ) - { + @Override + public void process(final IMCMessage m) { - try - { - final Class classInstance = Class.forName( m.getStringValue() ); - AEApi.instance().registries().movable().whiteListTileEntity( classInstance ); - } - catch( final ClassNotFoundException e ) - { - AELog.info( "Bad Class Registered: " + m.getStringValue() + " by " + m.getSender() ); - } - } + try { + final Class classInstance = Class.forName(m.getStringValue()); + AEApi.instance().registries().movable().whiteListTileEntity(classInstance); + } catch (final ClassNotFoundException e) { + AELog.info("Bad Class Registered: " + m.getStringValue() + " by " + m.getSender()); + } + } } diff --git a/src/main/java/appeng/core/crash/BaseCrashEnhancement.java b/src/main/java/appeng/core/crash/BaseCrashEnhancement.java index 07f899ce8..5a08387ce 100644 --- a/src/main/java/appeng/core/crash/BaseCrashEnhancement.java +++ b/src/main/java/appeng/core/crash/BaseCrashEnhancement.java @@ -22,26 +22,22 @@ package appeng.core.crash; import net.minecraftforge.fml.common.ICrashCallable; -abstract class BaseCrashEnhancement implements ICrashCallable -{ - private final String name; - private final String value; +abstract class BaseCrashEnhancement implements ICrashCallable { + private final String name; + private final String value; - public BaseCrashEnhancement( final String name, final String value ) - { - this.name = name; - this.value = value; - } + public BaseCrashEnhancement(final String name, final String value) { + this.name = name; + this.value = value; + } - @Override - public final String call() throws Exception - { - return this.value; - } + @Override + public final String call() throws Exception { + return this.value; + } - @Override - public final String getLabel() - { - return this.name; - } + @Override + public final String getLabel() { + return this.name; + } } diff --git a/src/main/java/appeng/core/crash/CrashInfo.java b/src/main/java/appeng/core/crash/CrashInfo.java index 7a25618f1..6d9a197a5 100644 --- a/src/main/java/appeng/core/crash/CrashInfo.java +++ b/src/main/java/appeng/core/crash/CrashInfo.java @@ -19,7 +19,6 @@ package appeng.core.crash; -public enum CrashInfo -{ - MOD_VERSION, INTEGRATION +public enum CrashInfo { + MOD_VERSION, INTEGRATION } diff --git a/src/main/java/appeng/core/crash/IntegrationCrashEnhancement.java b/src/main/java/appeng/core/crash/IntegrationCrashEnhancement.java index 6db8d3b0c..a18c6b537 100644 --- a/src/main/java/appeng/core/crash/IntegrationCrashEnhancement.java +++ b/src/main/java/appeng/core/crash/IntegrationCrashEnhancement.java @@ -22,10 +22,8 @@ package appeng.core.crash; import appeng.integration.IntegrationRegistry; -public class IntegrationCrashEnhancement extends BaseCrashEnhancement -{ - public IntegrationCrashEnhancement() - { - super( "AE2 Integration", IntegrationRegistry.INSTANCE.getStatus() ); - } +public class IntegrationCrashEnhancement extends BaseCrashEnhancement { + public IntegrationCrashEnhancement() { + super("AE2 Integration", IntegrationRegistry.INSTANCE.getStatus()); + } } diff --git a/src/main/java/appeng/core/crash/ModCrashEnhancement.java b/src/main/java/appeng/core/crash/ModCrashEnhancement.java index 1dde2cb83..3deedcda8 100644 --- a/src/main/java/appeng/core/crash/ModCrashEnhancement.java +++ b/src/main/java/appeng/core/crash/ModCrashEnhancement.java @@ -22,16 +22,14 @@ package appeng.core.crash; import appeng.core.AEConfig; -public class ModCrashEnhancement extends BaseCrashEnhancement -{ - private static final String MOD_VERSION = AEConfig.CHANNEL + ' ' + AEConfig.VERSION + " for Forge " + // WHAT? - net.minecraftforge.common.ForgeVersion.majorVersion + '.' // majorVersion - + net.minecraftforge.common.ForgeVersion.minorVersion + '.' // minorVersion - + net.minecraftforge.common.ForgeVersion.revisionVersion + '.' // revisionVersion - + net.minecraftforge.common.ForgeVersion.buildVersion; +public class ModCrashEnhancement extends BaseCrashEnhancement { + private static final String MOD_VERSION = AEConfig.CHANNEL + ' ' + AEConfig.VERSION + " for Forge " + // WHAT? + net.minecraftforge.common.ForgeVersion.majorVersion + '.' // majorVersion + + net.minecraftforge.common.ForgeVersion.minorVersion + '.' // minorVersion + + net.minecraftforge.common.ForgeVersion.revisionVersion + '.' // revisionVersion + + net.minecraftforge.common.ForgeVersion.buildVersion; - public ModCrashEnhancement( final CrashInfo output ) - { - super( "AE2 Version", MOD_VERSION ); - } + public ModCrashEnhancement(final CrashInfo output) { + super("AE2 Version", MOD_VERSION); + } } diff --git a/src/main/java/appeng/core/features/AEFeature.java b/src/main/java/appeng/core/features/AEFeature.java index d13a857e0..be47fd423 100644 --- a/src/main/java/appeng/core/features/AEFeature.java +++ b/src/main/java/appeng/core/features/AEFeature.java @@ -19,257 +19,244 @@ package appeng.core.features; -public enum AEFeature -{ - // stuff that has no reason for ever being turned off, or that - // is just flat out required by tons of - // important stuff. - CORE( "Core", null ) - { - @Override - public boolean isVisible() - { - return false; - } - }, +public enum AEFeature { + // stuff that has no reason for ever being turned off, or that + // is just flat out required by tons of + // important stuff. + CORE("Core", null) { + @Override + public boolean isVisible() { + return false; + } + }, - CERTUS_QUARTZ_WORLD_GEN( "CertusQuartzWorldGen", Constants.CATEGORY_WORLD ), - METEORITE_WORLD_GEN( "MeteoriteWorldGen", Constants.CATEGORY_WORLD ), - DECORATIVE_LIGHTS( "DecorativeLights", Constants.CATEGORY_WORLD ), - DECORATIVE_BLOCKS( "DecorativeBlocks", Constants.CATEGORY_WORLD, "Blocks that are not used in any essential recipes, also slabs and stairs." ), - SKY_STONE_CHESTS( "SkyStoneChests", Constants.CATEGORY_WORLD ), - SPAWN_PRESSES_IN_METEORITES( "SpawnPressesInMeteorites", Constants.CATEGORY_WORLD ), - FLOUR( "Flour", Constants.CATEGORY_WORLD ), - CHEST_LOOT( "ChestLoot", Constants.CATEGORY_WORLD ), - VILLAGER_TRADING( "VillagerTrading", Constants.CATEGORY_WORLD ), - TINY_TNT( "TinyTNT", Constants.CATEGORY_WORLD ), - CERTUS_ORE( "CertusOre", Constants.CATEGORY_WORLD ), - CHARGED_CERTUS_ORE( "ChargedCertusOre", Constants.CATEGORY_WORLD ), + CERTUS_QUARTZ_WORLD_GEN("CertusQuartzWorldGen", Constants.CATEGORY_WORLD), + METEORITE_WORLD_GEN("MeteoriteWorldGen", Constants.CATEGORY_WORLD), + DECORATIVE_LIGHTS("DecorativeLights", Constants.CATEGORY_WORLD), + DECORATIVE_BLOCKS("DecorativeBlocks", Constants.CATEGORY_WORLD, "Blocks that are not used in any essential recipes, also slabs and stairs."), + SKY_STONE_CHESTS("SkyStoneChests", Constants.CATEGORY_WORLD), + SPAWN_PRESSES_IN_METEORITES("SpawnPressesInMeteorites", Constants.CATEGORY_WORLD), + FLOUR("Flour", Constants.CATEGORY_WORLD), + CHEST_LOOT("ChestLoot", Constants.CATEGORY_WORLD), + VILLAGER_TRADING("VillagerTrading", Constants.CATEGORY_WORLD), + TINY_TNT("TinyTNT", Constants.CATEGORY_WORLD), + CERTUS_ORE("CertusOre", Constants.CATEGORY_WORLD), + CHARGED_CERTUS_ORE("ChargedCertusOre", Constants.CATEGORY_WORLD), - GRIND_STONE( "GrindStone", Constants.CATEGORY_MACHINES ), - INSCRIBER( "Inscriber", Constants.CATEGORY_MACHINES ), - CHARGER( "Charger", Constants.CATEGORY_MACHINES ), - CRYSTAL_GROWTH_ACCELERATOR( "CrystalGrowthAccelerator", Constants.CATEGORY_MACHINES ), - POWER_GEN( "VibrationChamber", Constants.CATEGORY_MACHINES ), + GRIND_STONE("GrindStone", Constants.CATEGORY_MACHINES), + INSCRIBER("Inscriber", Constants.CATEGORY_MACHINES), + CHARGER("Charger", Constants.CATEGORY_MACHINES), + CRYSTAL_GROWTH_ACCELERATOR("CrystalGrowthAccelerator", Constants.CATEGORY_MACHINES), + POWER_GEN("VibrationChamber", Constants.CATEGORY_MACHINES), - POWERED_TOOLS( "PoweredTools", Constants.CATEGORY_TOOLS_CLASSIFICATIONS ), - CERTUS_QUARTZ_TOOLS( "CertusQuartzTools", Constants.CATEGORY_TOOLS_CLASSIFICATIONS ), - NETHER_QUARTZ_TOOLS( "NetherQuartzTools", Constants.CATEGORY_TOOLS_CLASSIFICATIONS ), + POWERED_TOOLS("PoweredTools", Constants.CATEGORY_TOOLS_CLASSIFICATIONS), + CERTUS_QUARTZ_TOOLS("CertusQuartzTools", Constants.CATEGORY_TOOLS_CLASSIFICATIONS), + NETHER_QUARTZ_TOOLS("NetherQuartzTools", Constants.CATEGORY_TOOLS_CLASSIFICATIONS), - QUARTZ_HOE( "QuartzHoe", Constants.CATEGORY_TOOLS ), - QUARTZ_SPADE( "QuartzSpade", Constants.CATEGORY_TOOLS ), - QUARTZ_SWORD( "QuartzSword", Constants.CATEGORY_TOOLS ), - QUARTZ_PICKAXE( "QuartzPickaxe", Constants.CATEGORY_TOOLS ), - QUARTZ_AXE( "QuartzAxe", Constants.CATEGORY_TOOLS ), - QUARTZ_KNIFE( "QuartzKnife", Constants.CATEGORY_TOOLS ), - QUARTZ_WRENCH( "QuartzWrench", Constants.CATEGORY_TOOLS ), - CHARGED_STAFF( "ChargedStaff", Constants.CATEGORY_TOOLS ), - ENTROPY_MANIPULATOR( "EntropyManipulator", Constants.CATEGORY_TOOLS ), - MATTER_CANNON( "MatterCannon", Constants.CATEGORY_TOOLS ), - WIRELESS_ACCESS_TERMINAL( "WirelessAccessTerminal", Constants.CATEGORY_TOOLS ), - COLOR_APPLICATOR( "ColorApplicator", Constants.CATEGORY_TOOLS ), - METEORITE_COMPASS( "MeteoriteCompass", Constants.CATEGORY_TOOLS ), + QUARTZ_HOE("QuartzHoe", Constants.CATEGORY_TOOLS), + QUARTZ_SPADE("QuartzSpade", Constants.CATEGORY_TOOLS), + QUARTZ_SWORD("QuartzSword", Constants.CATEGORY_TOOLS), + QUARTZ_PICKAXE("QuartzPickaxe", Constants.CATEGORY_TOOLS), + QUARTZ_AXE("QuartzAxe", Constants.CATEGORY_TOOLS), + QUARTZ_KNIFE("QuartzKnife", Constants.CATEGORY_TOOLS), + QUARTZ_WRENCH("QuartzWrench", Constants.CATEGORY_TOOLS), + CHARGED_STAFF("ChargedStaff", Constants.CATEGORY_TOOLS), + ENTROPY_MANIPULATOR("EntropyManipulator", Constants.CATEGORY_TOOLS), + MATTER_CANNON("MatterCannon", Constants.CATEGORY_TOOLS), + WIRELESS_ACCESS_TERMINAL("WirelessAccessTerminal", Constants.CATEGORY_TOOLS), + COLOR_APPLICATOR("ColorApplicator", Constants.CATEGORY_TOOLS), + METEORITE_COMPASS("MeteoriteCompass", Constants.CATEGORY_TOOLS), - SECURITY( "Security", Constants.CATEGORY_NETWORK_FEATURES ), - SPATIAL_IO( "SpatialIO", Constants.CATEGORY_NETWORK_FEATURES ), - QUANTUM_NETWORK_BRIDGE( "QuantumNetworkBridge", Constants.CATEGORY_NETWORK_FEATURES ), - CHANNELS( "Channels", Constants.CATEGORY_NETWORK_FEATURES ), + SECURITY("Security", Constants.CATEGORY_NETWORK_FEATURES), + SPATIAL_IO("SpatialIO", Constants.CATEGORY_NETWORK_FEATURES), + QUANTUM_NETWORK_BRIDGE("QuantumNetworkBridge", Constants.CATEGORY_NETWORK_FEATURES), + CHANNELS("Channels", Constants.CATEGORY_NETWORK_FEATURES), - INTERFACE( "Interface", Constants.CATEGORY_NETWORK_BUSES ), - FLUID_INTERFACE( "FluidInterface", Constants.CATEGORY_NETWORK_BUSES ), - LEVEL_EMITTER( "LevelEmitter", Constants.CATEGORY_NETWORK_BUSES ), - FLUID_LEVEL_EMITTER( "FluidLevelEmitter", Constants.CATEGORY_NETWORK_BUSES ), - FLUID_TERMINAL( "FluidTerminal", Constants.CATEGORY_NETWORK_BUSES ), - CRAFTING_TERMINAL( "CraftingTerminal", Constants.CATEGORY_NETWORK_BUSES ), - TERMINAL( "Terminal", Constants.CATEGORY_NETWORK_BUSES ), - STORAGE_MONITOR( "StorageMonitor", Constants.CATEGORY_NETWORK_BUSES ), - P2P_TUNNEL( "P2PTunnel", Constants.CATEGORY_NETWORK_BUSES ), - FORMATION_PLANE( "FormationPlane", Constants.CATEGORY_NETWORK_BUSES ), - FLUID_FORMATION_PLANE( "FluidFormationPlane", Constants.CATEGORY_NETWORK_BUSES ), - ANNIHILATION_PLANE( "AnnihilationPlane", Constants.CATEGORY_NETWORK_BUSES ), - IDENTITY_ANNIHILATION_PLANE( "IdentityAnnihilationPlane", Constants.CATEGORY_NETWORK_BUSES ), - FLUID_ANNIHILATION_PLANE( "FluidAnnihilationPlane", Constants.CATEGORY_NETWORK_BUSES ), - IMPORT_BUS( "ImportBus", Constants.CATEGORY_NETWORK_BUSES ), - FLUID_IMPORT_BUS( "FluidImportBus", Constants.CATEGORY_NETWORK_BUSES ), - EXPORT_BUS( "ExportBus", Constants.CATEGORY_NETWORK_BUSES ), - FLUID_EXPORT_BUS( "FluidExportBus", Constants.CATEGORY_NETWORK_BUSES ), - STORAGE_BUS( "StorageBus", Constants.CATEGORY_NETWORK_BUSES ), - FLUID_STORAGE_BUS( "FluidStorageBus", Constants.CATEGORY_NETWORK_BUSES ), - PART_CONVERSION_MONITOR( "PartConversionMonitor", Constants.CATEGORY_NETWORK_BUSES ), - TOGGLE_BUS( "ToggleBus", Constants.CATEGORY_NETWORK_BUSES ), - PANELS( "Panels", Constants.CATEGORY_NETWORK_BUSES ), - QUARTZ_FIBER( "QuartzFiber", Constants.CATEGORY_NETWORK_BUSES ), - CABLE_ANCHOR( "CableAnchor", Constants.CATEGORY_NETWORK_BUSES ), + INTERFACE("Interface", Constants.CATEGORY_NETWORK_BUSES), + FLUID_INTERFACE("FluidInterface", Constants.CATEGORY_NETWORK_BUSES), + LEVEL_EMITTER("LevelEmitter", Constants.CATEGORY_NETWORK_BUSES), + FLUID_LEVEL_EMITTER("FluidLevelEmitter", Constants.CATEGORY_NETWORK_BUSES), + FLUID_TERMINAL("FluidTerminal", Constants.CATEGORY_NETWORK_BUSES), + CRAFTING_TERMINAL("CraftingTerminal", Constants.CATEGORY_NETWORK_BUSES), + TERMINAL("Terminal", Constants.CATEGORY_NETWORK_BUSES), + STORAGE_MONITOR("StorageMonitor", Constants.CATEGORY_NETWORK_BUSES), + P2P_TUNNEL("P2PTunnel", Constants.CATEGORY_NETWORK_BUSES), + FORMATION_PLANE("FormationPlane", Constants.CATEGORY_NETWORK_BUSES), + FLUID_FORMATION_PLANE("FluidFormationPlane", Constants.CATEGORY_NETWORK_BUSES), + ANNIHILATION_PLANE("AnnihilationPlane", Constants.CATEGORY_NETWORK_BUSES), + IDENTITY_ANNIHILATION_PLANE("IdentityAnnihilationPlane", Constants.CATEGORY_NETWORK_BUSES), + FLUID_ANNIHILATION_PLANE("FluidAnnihilationPlane", Constants.CATEGORY_NETWORK_BUSES), + IMPORT_BUS("ImportBus", Constants.CATEGORY_NETWORK_BUSES), + FLUID_IMPORT_BUS("FluidImportBus", Constants.CATEGORY_NETWORK_BUSES), + EXPORT_BUS("ExportBus", Constants.CATEGORY_NETWORK_BUSES), + FLUID_EXPORT_BUS("FluidExportBus", Constants.CATEGORY_NETWORK_BUSES), + STORAGE_BUS("StorageBus", Constants.CATEGORY_NETWORK_BUSES), + FLUID_STORAGE_BUS("FluidStorageBus", Constants.CATEGORY_NETWORK_BUSES), + PART_CONVERSION_MONITOR("PartConversionMonitor", Constants.CATEGORY_NETWORK_BUSES), + TOGGLE_BUS("ToggleBus", Constants.CATEGORY_NETWORK_BUSES), + PANELS("Panels", Constants.CATEGORY_NETWORK_BUSES), + QUARTZ_FIBER("QuartzFiber", Constants.CATEGORY_NETWORK_BUSES), + CABLE_ANCHOR("CableAnchor", Constants.CATEGORY_NETWORK_BUSES), - PORTABLE_CELL( "PortableCell", Constants.CATEGORY_PORTABLE_CELL ), + PORTABLE_CELL("PortableCell", Constants.CATEGORY_PORTABLE_CELL), - STORAGE_CELLS( "StorageCells", Constants.CATEGORY_STORAGE ), - ME_CHEST( "MEChest", Constants.CATEGORY_STORAGE ), - ME_DRIVE( "MEDrive", Constants.CATEGORY_STORAGE ), - IO_PORT( "IOPort", Constants.CATEGORY_STORAGE ), - CONDENSER( "Condenser", Constants.CATEGORY_STORAGE ), + STORAGE_CELLS("StorageCells", Constants.CATEGORY_STORAGE), + ME_CHEST("MEChest", Constants.CATEGORY_STORAGE), + ME_DRIVE("MEDrive", Constants.CATEGORY_STORAGE), + IO_PORT("IOPort", Constants.CATEGORY_STORAGE), + CONDENSER("Condenser", Constants.CATEGORY_STORAGE), - NETWORK_TOOL( "NetworkTool", Constants.CATEGORY_NETWORK_TOOL ), - MEMORY_CARD( "MemoryCard", Constants.CATEGORY_NETWORK_TOOL ), + NETWORK_TOOL("NetworkTool", Constants.CATEGORY_NETWORK_TOOL), + MEMORY_CARD("MemoryCard", Constants.CATEGORY_NETWORK_TOOL), - GLASS_CABLES( "GlassCables", Constants.CATEGORY_CABLES ), - COVERED_CABLES( "CoveredCables", Constants.CATEGORY_CABLES ), - SMART_CABLES( "SmartCables", Constants.CATEGORY_CABLES ), - DENSE_CABLES( "DenseCables", Constants.CATEGORY_CABLES ), + GLASS_CABLES("GlassCables", Constants.CATEGORY_CABLES), + COVERED_CABLES("CoveredCables", Constants.CATEGORY_CABLES), + SMART_CABLES("SmartCables", Constants.CATEGORY_CABLES), + DENSE_CABLES("DenseCables", Constants.CATEGORY_CABLES), - ENERGY_CELLS( "EnergyCells", Constants.CATEGORY_ENERGY ), - ENERGY_ACCEPTOR( "EnergyAcceptor", Constants.CATEGORY_ENERGY ), - DENSE_ENERGY_CELLS( "DenseEnergyCells", Constants.CATEGORY_ENERGY ), + ENERGY_CELLS("EnergyCells", Constants.CATEGORY_ENERGY), + ENERGY_ACCEPTOR("EnergyAcceptor", Constants.CATEGORY_ENERGY), + DENSE_ENERGY_CELLS("DenseEnergyCells", Constants.CATEGORY_ENERGY), - P2P_TUNNEL_ME( "P2PTunnelME", Constants.CATEGORY_P2P_TUNNELS ), - P2P_TUNNEL_ITEMS( "P2PTunnelItems", Constants.CATEGORY_P2P_TUNNELS ), - P2P_TUNNEL_REDSTONE( "P2PTunnelRedstone", Constants.CATEGORY_P2P_TUNNELS ), - P2P_TUNNEL_EU( "P2PTunnelEU", Constants.CATEGORY_P2P_TUNNELS ), - P2P_TUNNEL_FE( "P2PTunnelFE", Constants.CATEGORY_P2P_TUNNELS ), - P2P_TUNNEL_GTEU( "P2PTunnelGTEU", Constants.CATEGORY_P2P_TUNNELS ), - P2P_TUNNEL_FLUIDS( "P2PTunnelFluids", Constants.CATEGORY_P2P_TUNNELS ), - P2P_TUNNEL_LIGHT( "P2PTunnelLight", Constants.CATEGORY_P2P_TUNNELS ), - P2P_TUNNEL_OPEN_COMPUTERS( "P2PTunnelOpenComputers", Constants.CATEGORY_P2P_TUNNELS ), - P2P_TUNNEL_PRESSURE( "P2PTunnelPressure", Constants.CATEGORY_P2P_TUNNELS ), + P2P_TUNNEL_ME("P2PTunnelME", Constants.CATEGORY_P2P_TUNNELS), + P2P_TUNNEL_ITEMS("P2PTunnelItems", Constants.CATEGORY_P2P_TUNNELS), + P2P_TUNNEL_REDSTONE("P2PTunnelRedstone", Constants.CATEGORY_P2P_TUNNELS), + P2P_TUNNEL_EU("P2PTunnelEU", Constants.CATEGORY_P2P_TUNNELS), + P2P_TUNNEL_FE("P2PTunnelFE", Constants.CATEGORY_P2P_TUNNELS), + P2P_TUNNEL_GTEU("P2PTunnelGTEU", Constants.CATEGORY_P2P_TUNNELS), + P2P_TUNNEL_FLUIDS("P2PTunnelFluids", Constants.CATEGORY_P2P_TUNNELS), + P2P_TUNNEL_LIGHT("P2PTunnelLight", Constants.CATEGORY_P2P_TUNNELS), + P2P_TUNNEL_OPEN_COMPUTERS("P2PTunnelOpenComputers", Constants.CATEGORY_P2P_TUNNELS), + P2P_TUNNEL_PRESSURE("P2PTunnelPressure", Constants.CATEGORY_P2P_TUNNELS), - MASS_CANNON_BLOCK_DAMAGE( "MassCannonBlockDamage", Constants.CATEGORY_BLOCK_FEATURES ), - TINY_TNT_BLOCK_DAMAGE( "TinyTNTBlockDamage", Constants.CATEGORY_BLOCK_FEATURES ), + MASS_CANNON_BLOCK_DAMAGE("MassCannonBlockDamage", Constants.CATEGORY_BLOCK_FEATURES), + TINY_TNT_BLOCK_DAMAGE("TinyTNTBlockDamage", Constants.CATEGORY_BLOCK_FEATURES), - FACADES( "Facades", Constants.CATEGORY_FACADES ), + FACADES("Facades", Constants.CATEGORY_FACADES), - UNSUPPORTED_DEVELOPER_TOOLS( "UnsupportedDeveloperTools", Constants.CATEGORY_MISC, false ), - CREATIVE( "Creative", Constants.CATEGORY_MISC ), - GRINDER_LOGGING( "GrinderLogging", Constants.CATEGORY_MISC, false ), - LOGGING( "Logging", Constants.CATEGORY_MISC ), - INTEGRATION_LOGGING( "IntegrationLogging", Constants.CATEGORY_MISC, false ), - WEBSITE_RECIPES( "WebsiteRecipes", Constants.CATEGORY_MISC, false ), - LOG_SECURITY_AUDITS( "LogSecurityAudits", Constants.CATEGORY_MISC, false ), - ACHIEVEMENTS( "Achievements", Constants.CATEGORY_MISC ), - UPDATE_LOGGING( "UpdateLogging", Constants.CATEGORY_MISC, false ), - PACKET_LOGGING( "PacketLogging", Constants.CATEGORY_MISC, false ), - CRAFTING_LOG( "CraftingLog", Constants.CATEGORY_MISC, false ), - LIGHT_DETECTOR( "LightDetector", Constants.CATEGORY_MISC ), - DEBUG_LOGGING( "DebugLogging", Constants.CATEGORY_MISC, false ), + UNSUPPORTED_DEVELOPER_TOOLS("UnsupportedDeveloperTools", Constants.CATEGORY_MISC, false), + CREATIVE("Creative", Constants.CATEGORY_MISC), + GRINDER_LOGGING("GrinderLogging", Constants.CATEGORY_MISC, false), + LOGGING("Logging", Constants.CATEGORY_MISC), + INTEGRATION_LOGGING("IntegrationLogging", Constants.CATEGORY_MISC, false), + WEBSITE_RECIPES("WebsiteRecipes", Constants.CATEGORY_MISC, false), + LOG_SECURITY_AUDITS("LogSecurityAudits", Constants.CATEGORY_MISC, false), + ACHIEVEMENTS("Achievements", Constants.CATEGORY_MISC), + UPDATE_LOGGING("UpdateLogging", Constants.CATEGORY_MISC, false), + PACKET_LOGGING("PacketLogging", Constants.CATEGORY_MISC, false), + CRAFTING_LOG("CraftingLog", Constants.CATEGORY_MISC, false), + LIGHT_DETECTOR("LightDetector", Constants.CATEGORY_MISC), + DEBUG_LOGGING("DebugLogging", Constants.CATEGORY_MISC, false), - ENABLE_FACADE_CRAFTING( "EnableFacadeCrafting", Constants.CATEGORY_CRAFTING ), - IN_WORLD_SINGULARITY( "InWorldSingularity", Constants.CATEGORY_CRAFTING ), - IN_WORLD_FLUIX( "InWorldFluix", Constants.CATEGORY_CRAFTING ), - IN_WORLD_PURIFICATION( "InWorldPurification", Constants.CATEGORY_CRAFTING ), - INTERFACE_TERMINAL( "InterfaceTerminal", Constants.CATEGORY_CRAFTING ), - ENABLE_DISASSEMBLY_CRAFTING( "EnableDisassemblyCrafting", Constants.CATEGORY_CRAFTING ), + ENABLE_FACADE_CRAFTING("EnableFacadeCrafting", Constants.CATEGORY_CRAFTING), + IN_WORLD_SINGULARITY("InWorldSingularity", Constants.CATEGORY_CRAFTING), + IN_WORLD_FLUIX("InWorldFluix", Constants.CATEGORY_CRAFTING), + IN_WORLD_PURIFICATION("InWorldPurification", Constants.CATEGORY_CRAFTING), + INTERFACE_TERMINAL("InterfaceTerminal", Constants.CATEGORY_CRAFTING), + ENABLE_DISASSEMBLY_CRAFTING("EnableDisassemblyCrafting", Constants.CATEGORY_CRAFTING), - ALPHA_PASS( "AlphaPass", Constants.CATEGORY_RENDERING ), - PAINT_BALLS( "PaintBalls", Constants.CATEGORY_TOOLS ), + ALPHA_PASS("AlphaPass", Constants.CATEGORY_RENDERING), + PAINT_BALLS("PaintBalls", Constants.CATEGORY_TOOLS), - MOLECULAR_ASSEMBLER( "MolecularAssembler", Constants.CATEGORY_CRAFTING_FEATURES ), - PATTERNS( "Patterns", Constants.CATEGORY_CRAFTING_FEATURES ), - CRAFTING_CPU( "CraftingCPU", Constants.CATEGORY_CRAFTING_FEATURES ), + MOLECULAR_ASSEMBLER("MolecularAssembler", Constants.CATEGORY_CRAFTING_FEATURES), + PATTERNS("Patterns", Constants.CATEGORY_CRAFTING_FEATURES), + CRAFTING_CPU("CraftingCPU", Constants.CATEGORY_CRAFTING_FEATURES), - BASIC_CARDS( "BasicCards", Constants.CATEGORY_UPGRADES ), - ADVANCED_CARDS( "AdvancedCards", Constants.CATEGORY_UPGRADES ), - VIEW_CELL( "ViewCell", Constants.CATEGORY_UPGRADES ), + BASIC_CARDS("BasicCards", Constants.CATEGORY_UPGRADES), + ADVANCED_CARDS("AdvancedCards", Constants.CATEGORY_UPGRADES), + VIEW_CELL("ViewCell", Constants.CATEGORY_UPGRADES), - CRYSTAL_SEEDS( "CrystalSeeds", Constants.CATEGORY_MATERIALS ), - PURE_CRYSTALS( "PureCrystals", Constants.CATEGORY_MATERIALS ), - CERTUS( "Certus", Constants.CATEGORY_MATERIALS ), - FLUIX( "Fluix", Constants.CATEGORY_MATERIALS ), - SILICON( "Silicon", Constants.CATEGORY_MATERIALS ), - DUSTS( "Dusts", Constants.CATEGORY_MATERIALS ), - NUGGETS( "Nuggets", Constants.CATEGORY_MATERIALS ), - QUARTZ_GLASS( "QuartzGlass", Constants.CATEGORY_MATERIALS ), - SKY_STONE( "SkyStone", Constants.CATEGORY_MATERIALS ), + CRYSTAL_SEEDS("CrystalSeeds", Constants.CATEGORY_MATERIALS), + PURE_CRYSTALS("PureCrystals", Constants.CATEGORY_MATERIALS), + CERTUS("Certus", Constants.CATEGORY_MATERIALS), + FLUIX("Fluix", Constants.CATEGORY_MATERIALS), + SILICON("Silicon", Constants.CATEGORY_MATERIALS), + DUSTS("Dusts", Constants.CATEGORY_MATERIALS), + NUGGETS("Nuggets", Constants.CATEGORY_MATERIALS), + QUARTZ_GLASS("QuartzGlass", Constants.CATEGORY_MATERIALS), + SKY_STONE("SkyStone", Constants.CATEGORY_MATERIALS), - PROCESSORS( "Processors", Constants.CATEGORY_COMPONENTS ), - PRINTED_CIRCUITS( "PrintedCircuits", Constants.CATEGORY_COMPONENTS ), - PRESSES( "Presses", Constants.CATEGORY_COMPONENTS ), - MATTER_BALL( "MatterBall", Constants.CATEGORY_COMPONENTS ), - CORES( "Cores", Constants.CATEGORY_COMPONENTS ), + PROCESSORS("Processors", Constants.CATEGORY_COMPONENTS), + PRINTED_CIRCUITS("PrintedCircuits", Constants.CATEGORY_COMPONENTS), + PRESSES("Presses", Constants.CATEGORY_COMPONENTS), + MATTER_BALL("MatterBall", Constants.CATEGORY_COMPONENTS), + CORES("Cores", Constants.CATEGORY_COMPONENTS), - CHUNK_LOGGER_TRACE( "ChunkLoggerTrace", Constants.CATEGORY_COMMANDS, false ); + CHUNK_LOGGER_TRACE("ChunkLoggerTrace", Constants.CATEGORY_COMMANDS, false); - private final String key; - private final String category; - private final boolean enabled; - private final String comment; + private final String key; + private final String category; + private final boolean enabled; + private final String comment; - AEFeature( final String key, final String cat ) - { - this( key, cat, true ); - } + AEFeature(final String key, final String cat) { + this(key, cat, true); + } - AEFeature( final String key, final String cat, final String comment ) - { - this( key, cat, true, comment ); - } + AEFeature(final String key, final String cat, final String comment) { + this(key, cat, true, comment); + } - AEFeature( final String key, final String cat, final boolean enabled ) - { - this( key, cat, enabled, null ); - } + AEFeature(final String key, final String cat, final boolean enabled) { + this(key, cat, enabled, null); + } - AEFeature( final String key, final String cat, final boolean enabled, final String comment ) - { - this.key = key; - this.category = cat; - this.enabled = enabled; - this.comment = comment; - } + AEFeature(final String key, final String cat, final boolean enabled, final String comment) { + this.key = key; + this.category = cat; + this.enabled = enabled; + this.comment = comment; + } - /** - * override to set visibility - * - * @return default true - */ - public boolean isVisible() - { - return true; - } + /** + * override to set visibility + * + * @return default true + */ + public boolean isVisible() { + return true; + } - public String key() - { - return this.key; - } + public String key() { + return this.key; + } - public String category() - { - return this.category; - } + public String category() { + return this.category; + } - public boolean isEnabled() - { - return this.enabled; - } + public boolean isEnabled() { + return this.enabled; + } - public String comment() - { - return this.comment; - } + public String comment() { + return this.comment; + } - private enum Constants - { - ; + private enum Constants { + ; - private static final String CATEGORY_MISC = "Misc"; - private static final String CATEGORY_CRAFTING = "Crafting"; - private static final String CATEGORY_WORLD = "World"; - private static final String CATEGORY_MACHINES = "Machines"; - private static final String CATEGORY_TOOLS = "Tools"; - private static final String CATEGORY_TOOLS_CLASSIFICATIONS = "ToolsClassifications"; - private static final String CATEGORY_NETWORK_BUSES = "NetworkBuses"; - private static final String CATEGORY_P2P_TUNNELS = "P2PTunnels"; - private static final String CATEGORY_BLOCK_FEATURES = "BlockFeatures"; - private static final String CATEGORY_CRAFTING_FEATURES = "CraftingFeatures"; - private static final String CATEGORY_STORAGE = "Storage"; - private static final String CATEGORY_CABLES = "Cables"; - private static final String CATEGORY_NETWORK_FEATURES = "NetworkFeatures"; - private static final String CATEGORY_COMMANDS = "Commands"; - private static final String CATEGORY_RENDERING = "Rendering"; - private static final String CATEGORY_FACADES = "Facades"; - private static final String CATEGORY_NETWORK_TOOL = "NetworkTool"; - private static final String CATEGORY_PORTABLE_CELL = "PortableCell"; - private static final String CATEGORY_ENERGY = "Energy"; - private static final String CATEGORY_UPGRADES = "Upgrades"; - private static final String CATEGORY_MATERIALS = "Materials"; - private static final String CATEGORY_COMPONENTS = "CraftingComponents"; - } + private static final String CATEGORY_MISC = "Misc"; + private static final String CATEGORY_CRAFTING = "Crafting"; + private static final String CATEGORY_WORLD = "World"; + private static final String CATEGORY_MACHINES = "Machines"; + private static final String CATEGORY_TOOLS = "Tools"; + private static final String CATEGORY_TOOLS_CLASSIFICATIONS = "ToolsClassifications"; + private static final String CATEGORY_NETWORK_BUSES = "NetworkBuses"; + private static final String CATEGORY_P2P_TUNNELS = "P2PTunnels"; + private static final String CATEGORY_BLOCK_FEATURES = "BlockFeatures"; + private static final String CATEGORY_CRAFTING_FEATURES = "CraftingFeatures"; + private static final String CATEGORY_STORAGE = "Storage"; + private static final String CATEGORY_CABLES = "Cables"; + private static final String CATEGORY_NETWORK_FEATURES = "NetworkFeatures"; + private static final String CATEGORY_COMMANDS = "Commands"; + private static final String CATEGORY_RENDERING = "Rendering"; + private static final String CATEGORY_FACADES = "Facades"; + private static final String CATEGORY_NETWORK_TOOL = "NetworkTool"; + private static final String CATEGORY_PORTABLE_CELL = "PortableCell"; + private static final String CATEGORY_ENERGY = "Energy"; + private static final String CATEGORY_UPGRADES = "Upgrades"; + private static final String CATEGORY_MATERIALS = "Materials"; + private static final String CATEGORY_COMPONENTS = "CraftingComponents"; + } } diff --git a/src/main/java/appeng/core/features/ActivityState.java b/src/main/java/appeng/core/features/ActivityState.java index 0cc74f7b3..0bb8f22ea 100644 --- a/src/main/java/appeng/core/features/ActivityState.java +++ b/src/main/java/appeng/core/features/ActivityState.java @@ -19,19 +19,14 @@ package appeng.core.features; -public enum ActivityState -{ - Enabled, Disabled; +public enum ActivityState { + Enabled, Disabled; - public static ActivityState from( final boolean enabled ) - { - if( enabled ) - { - return ActivityState.Enabled; - } - else - { - return ActivityState.Disabled; - } - } + public static ActivityState from(final boolean enabled) { + if (enabled) { + return ActivityState.Enabled; + } else { + return ActivityState.Disabled; + } + } } diff --git a/src/main/java/appeng/core/features/BlockDefinition.java b/src/main/java/appeng/core/features/BlockDefinition.java index d08d1bf3b..0130db1ce 100644 --- a/src/main/java/appeng/core/features/BlockDefinition.java +++ b/src/main/java/appeng/core/features/BlockDefinition.java @@ -19,52 +19,44 @@ package appeng.core.features; -import java.util.Optional; - +import appeng.api.definitions.IBlockDefinition; import com.google.common.base.Preconditions; - import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; -import appeng.api.definitions.IBlockDefinition; +import java.util.Optional; -public class BlockDefinition extends ItemDefinition implements IBlockDefinition -{ - private final Optional block; +public class BlockDefinition extends ItemDefinition implements IBlockDefinition { + private final Optional block; - public BlockDefinition( String registryName, Block block, ItemBlock item ) - { - super( registryName, item ); - this.block = Optional.ofNullable( block ); - } + public BlockDefinition(String registryName, Block block, ItemBlock item) { + super(registryName, item); + this.block = Optional.ofNullable(block); + } - @Override - public final Optional maybeBlock() - { - return this.block; - } + @Override + public final Optional maybeBlock() { + return this.block; + } - @Override - public final Optional maybeItemBlock() - { - return this.block.map( ItemBlock::new ); - } + @Override + public final Optional maybeItemBlock() { + return this.block.map(ItemBlock::new); + } - @Override - public final Optional maybeStack( int stackSize ) - { - Preconditions.checkArgument( stackSize > 0 ); + @Override + public final Optional maybeStack(int stackSize) { + Preconditions.checkArgument(stackSize > 0); - return this.block.map( b -> new ItemStack( b, stackSize ) ); - } + return this.block.map(b -> new ItemStack(b, stackSize)); + } - @Override - public final boolean isSameAs( final IBlockAccess world, final BlockPos pos ) - { - return this.block.isPresent() && world.getBlockState( pos ).getBlock() == this.block.get(); - } + @Override + public final boolean isSameAs(final IBlockAccess world, final BlockPos pos) { + return this.block.isPresent() && world.getBlockState(pos).getBlock() == this.block.get(); + } } diff --git a/src/main/java/appeng/core/features/BlockStackSrc.java b/src/main/java/appeng/core/features/BlockStackSrc.java index 60f1279fe..31643c15c 100644 --- a/src/main/java/appeng/core/features/BlockStackSrc.java +++ b/src/main/java/appeng/core/features/BlockStackSrc.java @@ -19,56 +19,49 @@ package appeng.core.features; -import javax.annotation.Nullable; - import com.google.common.base.Preconditions; - import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import javax.annotation.Nullable; -public class BlockStackSrc implements IStackSrc -{ - private final Block block; - private final int damage; - private final boolean enabled; +public class BlockStackSrc implements IStackSrc { - public BlockStackSrc( final Block block, final int damage, final ActivityState state ) - { - Preconditions.checkNotNull( block ); - Preconditions.checkArgument( damage >= 0 ); - Preconditions.checkNotNull( state ); - Preconditions.checkArgument( state == ActivityState.Enabled || state == ActivityState.Disabled ); + private final Block block; + private final int damage; + private final boolean enabled; - this.block = block; - this.damage = damage; - this.enabled = state == ActivityState.Enabled; - } + public BlockStackSrc(final Block block, final int damage, final ActivityState state) { + Preconditions.checkNotNull(block); + Preconditions.checkArgument(damage >= 0); + Preconditions.checkNotNull(state); + Preconditions.checkArgument(state == ActivityState.Enabled || state == ActivityState.Disabled); - @Nullable - @Override - public ItemStack stack( final int i ) - { - return new ItemStack( this.block, i, this.damage ); - } + this.block = block; + this.damage = damage; + this.enabled = state == ActivityState.Enabled; + } - @Override - public Item getItem() - { - return null; - } + @Nullable + @Override + public ItemStack stack(final int i) { + return new ItemStack(this.block, i, this.damage); + } - @Override - public int getDamage() - { - return this.damage; - } + @Override + public Item getItem() { + return null; + } - @Override - public boolean isEnabled() - { - return this.enabled; - } + @Override + public int getDamage() { + return this.damage; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } } diff --git a/src/main/java/appeng/core/features/ColoredItemDefinition.java b/src/main/java/appeng/core/features/ColoredItemDefinition.java index 61d5cf876..994d6cf1f 100644 --- a/src/main/java/appeng/core/features/ColoredItemDefinition.java +++ b/src/main/java/appeng/core/features/ColoredItemDefinition.java @@ -19,84 +19,71 @@ package appeng.core.features; +import appeng.api.util.AEColor; +import appeng.api.util.AEColoredItemDefinition; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import appeng.api.util.AEColor; -import appeng.api.util.AEColoredItemDefinition; +public final class ColoredItemDefinition implements AEColoredItemDefinition { -public final class ColoredItemDefinition implements AEColoredItemDefinition -{ + private final ItemStackSrc[] colors = new ItemStackSrc[17]; - private final ItemStackSrc[] colors = new ItemStackSrc[17]; + public void add(final AEColor v, final ItemStackSrc is) { + this.colors[v.ordinal()] = is; + } - public void add( final AEColor v, final ItemStackSrc is ) - { - this.colors[v.ordinal()] = is; - } + @Override + public Block block(final AEColor color) { + return null; + } - @Override - public Block block( final AEColor color ) - { - return null; - } + @Override + public Item item(final AEColor color) { + final ItemStackSrc is = this.colors[color.ordinal()]; - @Override - public Item item( final AEColor color ) - { - final ItemStackSrc is = this.colors[color.ordinal()]; + if (is == null) { + return null; + } - if( is == null ) - { - return null; - } + return is.getItem(); + } - return is.getItem(); - } + @Override + public Class entity(final AEColor color) { + return null; + } - @Override - public Class entity( final AEColor color ) - { - return null; - } + @Override + public ItemStack stack(final AEColor color, final int stackSize) { + final ItemStackSrc is = this.colors[color.ordinal()]; - @Override - public ItemStack stack( final AEColor color, final int stackSize ) - { - final ItemStackSrc is = this.colors[color.ordinal()]; + if (is == null) { + return ItemStack.EMPTY; + } - if( is == null ) - { - return ItemStack.EMPTY; - } + return is.stack(stackSize); + } - return is.stack( stackSize ); - } + @Override + public ItemStack[] allStacks(final int stackSize) { + final ItemStack[] is = new ItemStack[this.colors.length]; + for (int x = 0; x < is.length; x++) { + is[x] = this.colors[x].stack(1); + } + return is; + } - @Override - public ItemStack[] allStacks( final int stackSize ) - { - final ItemStack[] is = new ItemStack[this.colors.length]; - for( int x = 0; x < is.length; x++ ) - { - is[x] = this.colors[x].stack( 1 ); - } - return is; - } + @Override + public boolean sameAs(final AEColor color, final ItemStack comparableItem) { + final ItemStackSrc is = this.colors[color.ordinal()]; - @Override - public boolean sameAs( final AEColor color, final ItemStack comparableItem ) - { - final ItemStackSrc is = this.colors[color.ordinal()]; + if (comparableItem.isEmpty() || is == null) { + return false; + } - if( comparableItem.isEmpty() || is == null ) - { - return false; - } - - return comparableItem.getItem() == is.getItem() && comparableItem.getItemDamage() == is.getDamage(); - } + return comparableItem.getItem() == is.getItem() && comparableItem.getItemDamage() == is.getDamage(); + } } diff --git a/src/main/java/appeng/core/features/DamagedItemDefinition.java b/src/main/java/appeng/core/features/DamagedItemDefinition.java index d025927ac..3f3998391 100644 --- a/src/main/java/appeng/core/features/DamagedItemDefinition.java +++ b/src/main/java/appeng/core/features/DamagedItemDefinition.java @@ -19,72 +19,58 @@ package appeng.core.features; -import java.util.Optional; - -import javax.annotation.Nonnull; - +import appeng.api.definitions.IItemDefinition; import com.google.common.base.Preconditions; - import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import appeng.api.definitions.IItemDefinition; +import javax.annotation.Nonnull; +import java.util.Optional; -public final class DamagedItemDefinition implements IItemDefinition -{ - private final String identifier; - private final Optional source; +public final class DamagedItemDefinition implements IItemDefinition { + private final String identifier; + private final Optional source; - public DamagedItemDefinition( @Nonnull final String identifier, @Nonnull final IStackSrc source ) - { - this.identifier = Preconditions.checkNotNull( identifier ); - Preconditions.checkNotNull( source ); + public DamagedItemDefinition(@Nonnull final String identifier, @Nonnull final IStackSrc source) { + this.identifier = Preconditions.checkNotNull(identifier); + Preconditions.checkNotNull(source); - if( source.isEnabled() ) - { - this.source = Optional.of( source ); - } - else - { - this.source = Optional.empty(); - } - } + if (source.isEnabled()) { + this.source = Optional.of(source); + } else { + this.source = Optional.empty(); + } + } - @Nonnull - @Override - public String identifier() - { - return this.identifier; - } + @Nonnull + @Override + public String identifier() { + return this.identifier; + } - @Override - public Optional maybeItem() - { - return this.source.map( IStackSrc::getItem ); - } + @Override + public Optional maybeItem() { + return this.source.map(IStackSrc::getItem); + } - @Override - public Optional maybeStack( final int stackSize ) - { - return this.source.map( input -> input.stack( stackSize ) ); - } + @Override + public Optional maybeStack(final int stackSize) { + return this.source.map(input -> input.stack(stackSize)); + } - @Override - public boolean isEnabled() - { - return this.source.isPresent(); - } + @Override + public boolean isEnabled() { + return this.source.isPresent(); + } - @Override - public boolean isSameAs( final ItemStack comparableStack ) - { - if( comparableStack.isEmpty() ) - { - return false; - } + @Override + public boolean isSameAs(final ItemStack comparableStack) { + if (comparableStack.isEmpty()) { + return false; + } - return this.isEnabled() && comparableStack.getItem() == this.source.get().getItem() && comparableStack.getItemDamage() == this.source.get().getDamage(); - } + return this.isEnabled() && comparableStack.getItem() == this.source.get().getItem() && comparableStack.getItemDamage() == this.source.get().getDamage(); + } } diff --git a/src/main/java/appeng/core/features/IStackSrc.java b/src/main/java/appeng/core/features/IStackSrc.java index cc7e1aa24..97f97efc1 100644 --- a/src/main/java/appeng/core/features/IStackSrc.java +++ b/src/main/java/appeng/core/features/IStackSrc.java @@ -23,14 +23,13 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -public interface IStackSrc -{ +public interface IStackSrc { - ItemStack stack( int i ); + ItemStack stack(int i); - Item getItem(); + Item getItem(); - int getDamage(); + int getDamage(); - boolean isEnabled(); + boolean isEnabled(); } diff --git a/src/main/java/appeng/core/features/ItemDefinition.java b/src/main/java/appeng/core/features/ItemDefinition.java index b074906a0..defb97ec0 100644 --- a/src/main/java/appeng/core/features/ItemDefinition.java +++ b/src/main/java/appeng/core/features/ItemDefinition.java @@ -19,61 +19,51 @@ package appeng.core.features; -import java.util.Optional; - -import javax.annotation.Nonnull; - +import appeng.api.definitions.IItemDefinition; +import appeng.util.Platform; import com.google.common.base.Preconditions; import com.google.common.base.Strings; - import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import appeng.api.definitions.IItemDefinition; -import appeng.util.Platform; +import javax.annotation.Nonnull; +import java.util.Optional; -public class ItemDefinition implements IItemDefinition -{ - private final String identifier; - private final Optional item; +public class ItemDefinition implements IItemDefinition { + private final String identifier; + private final Optional item; - public ItemDefinition( String registryName, Item item ) - { - Preconditions.checkArgument( !Strings.isNullOrEmpty( registryName ), "registryName" ); - this.identifier = registryName; - this.item = Optional.ofNullable( item ); - } + public ItemDefinition(String registryName, Item item) { + Preconditions.checkArgument(!Strings.isNullOrEmpty(registryName), "registryName"); + this.identifier = registryName; + this.item = Optional.ofNullable(item); + } - @Nonnull - @Override - public String identifier() - { - return this.identifier; - } + @Nonnull + @Override + public String identifier() { + return this.identifier; + } - @Override - public final Optional maybeItem() - { - return this.item; - } + @Override + public final Optional maybeItem() { + return this.item; + } - @Override - public Optional maybeStack( final int stackSize ) - { - return this.item.map( item -> new ItemStack( item, stackSize ) ); - } + @Override + public Optional maybeStack(final int stackSize) { + return this.item.map(item -> new ItemStack(item, stackSize)); + } - @Override - public boolean isEnabled() - { - return this.item.isPresent(); - } + @Override + public boolean isEnabled() { + return this.item.isPresent(); + } - @Override - public final boolean isSameAs( final ItemStack comparableStack ) - { - return this.isEnabled() && Platform.itemComparisons().isEqualItemType( comparableStack, this.maybeStack( 1 ).get() ); - } + @Override + public final boolean isSameAs(final ItemStack comparableStack) { + return this.isEnabled() && Platform.itemComparisons().isEqualItemType(comparableStack, this.maybeStack(1).get()); + } } diff --git a/src/main/java/appeng/core/features/ItemStackSrc.java b/src/main/java/appeng/core/features/ItemStackSrc.java index c263d40d1..885bfe1ec 100644 --- a/src/main/java/appeng/core/features/ItemStackSrc.java +++ b/src/main/java/appeng/core/features/ItemStackSrc.java @@ -19,55 +19,48 @@ package appeng.core.features; -import javax.annotation.Nullable; - import com.google.common.base.Preconditions; - import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import javax.annotation.Nullable; -public class ItemStackSrc implements IStackSrc -{ - private final Item item; - private final int damage; - private final boolean enabled; +public class ItemStackSrc implements IStackSrc { - public ItemStackSrc( final Item item, final int damage, final ActivityState state ) - { - Preconditions.checkNotNull( item ); - Preconditions.checkArgument( damage >= 0 ); - Preconditions.checkNotNull( state ); - Preconditions.checkArgument( state == ActivityState.Enabled || state == ActivityState.Disabled ); + private final Item item; + private final int damage; + private final boolean enabled; - this.item = item; - this.damage = damage; - this.enabled = state == ActivityState.Enabled; - } + public ItemStackSrc(final Item item, final int damage, final ActivityState state) { + Preconditions.checkNotNull(item); + Preconditions.checkArgument(damage >= 0); + Preconditions.checkNotNull(state); + Preconditions.checkArgument(state == ActivityState.Enabled || state == ActivityState.Disabled); - @Nullable - @Override - public ItemStack stack( final int i ) - { - return new ItemStack( this.item, i, this.damage ); - } + this.item = item; + this.damage = damage; + this.enabled = state == ActivityState.Enabled; + } - @Override - public Item getItem() - { - return this.item; - } + @Nullable + @Override + public ItemStack stack(final int i) { + return new ItemStack(this.item, i, this.damage); + } - @Override - public int getDamage() - { - return this.damage; - } + @Override + public Item getItem() { + return this.item; + } - @Override - public boolean isEnabled() - { - return this.enabled; - } + @Override + public int getDamage() { + return this.damage; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } } diff --git a/src/main/java/appeng/core/features/MaterialStackSrc.java b/src/main/java/appeng/core/features/MaterialStackSrc.java index 294211f52..ddf6dd18d 100644 --- a/src/main/java/appeng/core/features/MaterialStackSrc.java +++ b/src/main/java/appeng/core/features/MaterialStackSrc.java @@ -19,48 +19,40 @@ package appeng.core.features; +import appeng.items.materials.MaterialType; import com.google.common.base.Preconditions; - import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import appeng.items.materials.MaterialType; +public class MaterialStackSrc implements IStackSrc { + private final MaterialType src; + private final boolean enabled; -public class MaterialStackSrc implements IStackSrc -{ - private final MaterialType src; - private final boolean enabled; + public MaterialStackSrc(final MaterialType src, boolean enabled) { + Preconditions.checkNotNull(src); - public MaterialStackSrc( final MaterialType src, boolean enabled ) - { - Preconditions.checkNotNull( src ); + this.src = src; + this.enabled = enabled; + } - this.src = src; - this.enabled = enabled; - } + @Override + public ItemStack stack(final int stackSize) { + return this.src.stack(stackSize); + } - @Override - public ItemStack stack( final int stackSize ) - { - return this.src.stack( stackSize ); - } + @Override + public Item getItem() { + return this.src.getItemInstance(); + } - @Override - public Item getItem() - { - return this.src.getItemInstance(); - } + @Override + public int getDamage() { + return this.src.getDamageValue(); + } - @Override - public int getDamage() - { - return this.src.getDamageValue(); - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } + @Override + public boolean isEnabled() { + return this.enabled; + } } diff --git a/src/main/java/appeng/core/features/TileDefinition.java b/src/main/java/appeng/core/features/TileDefinition.java index 50d803707..596f43695 100644 --- a/src/main/java/appeng/core/features/TileDefinition.java +++ b/src/main/java/appeng/core/features/TileDefinition.java @@ -19,31 +19,26 @@ package appeng.core.features; -import java.util.Optional; - -import javax.annotation.Nonnull; - +import appeng.api.definitions.ITileDefinition; +import appeng.block.AEBaseTileBlock; import net.minecraft.item.ItemBlock; import net.minecraft.tileentity.TileEntity; -import appeng.api.definitions.ITileDefinition; -import appeng.block.AEBaseTileBlock; +import javax.annotation.Nonnull; +import java.util.Optional; -public final class TileDefinition extends BlockDefinition implements ITileDefinition -{ +public final class TileDefinition extends BlockDefinition implements ITileDefinition { - private final Optional block; + private final Optional block; - public TileDefinition( @Nonnull String registryName, AEBaseTileBlock block, ItemBlock item ) - { - super( registryName, block, item ); - this.block = Optional.ofNullable( block ); - } + public TileDefinition(@Nonnull String registryName, AEBaseTileBlock block, ItemBlock item) { + super(registryName, block, item); + this.block = Optional.ofNullable(block); + } - @Override - public Optional> maybeEntity() - { - return this.block.map( AEBaseTileBlock::getTileEntityClass ); - } + @Override + public Optional> maybeEntity() { + return this.block.map(AEBaseTileBlock::getTileEntityClass); + } } diff --git a/src/main/java/appeng/core/features/registries/GridCacheRegistry.java b/src/main/java/appeng/core/features/registries/GridCacheRegistry.java index 4135c1dd9..39c17fdc3 100644 --- a/src/main/java/appeng/core/features/registries/GridCacheRegistry.java +++ b/src/main/java/appeng/core/features/registries/GridCacheRegistry.java @@ -19,68 +19,52 @@ package appeng.core.features.registries; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Map; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridCache; import appeng.api.networking.IGridCacheRegistry; import appeng.core.AELog; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; -public final class GridCacheRegistry implements IGridCacheRegistry -{ - private final Map, Class> caches = new HashMap<>(); - @Override - public void registerGridCache( final Class iface, final Class implementation ) - { - if( iface.isAssignableFrom( implementation ) ) - { - this.caches.put( iface, implementation ); - } - else - { - throw new IllegalArgumentException( "Invalid setup, grid cache must either be the same class, or an interface that the implementation implements. Gotten: " + iface + " and " + implementation ); - } - } +public final class GridCacheRegistry implements IGridCacheRegistry { + private final Map, Class> caches = new HashMap<>(); - @Override - public HashMap, IGridCache> createCacheInstance( final IGrid g ) - { - final HashMap, IGridCache> map = new HashMap<>(); + @Override + public void registerGridCache(final Class iface, final Class implementation) { + if (iface.isAssignableFrom(implementation)) { + this.caches.put(iface, implementation); + } else { + throw new IllegalArgumentException("Invalid setup, grid cache must either be the same class, or an interface that the implementation implements. Gotten: " + iface + " and " + implementation); + } + } - for( final Class iface : this.caches.keySet() ) - { - try - { - final Constructor c = this.caches.get( iface ).getConstructor( IGrid.class ); - map.put( iface, c.newInstance( g ) ); - } - catch( final NoSuchMethodException e ) - { - AELog.error( "Grid Caches must have a constructor with IGrid as the single param." ); - throw new IllegalArgumentException( e ); - } - catch( final InvocationTargetException e ) - { - AELog.error( "Grid Caches must have a constructor with IGrid as the single param." ); - throw new IllegalStateException( e ); - } - catch( final InstantiationException e ) - { - AELog.error( "Grid Caches must have a constructor with IGrid as the single param." ); - throw new IllegalStateException( e ); - } - catch( final IllegalAccessException e ) - { - AELog.error( "Grid Caches must have a constructor with IGrid as the single param." ); - throw new IllegalStateException( e ); - } - } + @Override + public HashMap, IGridCache> createCacheInstance(final IGrid g) { + final HashMap, IGridCache> map = new HashMap<>(); - return map; - } + for (final Class iface : this.caches.keySet()) { + try { + final Constructor c = this.caches.get(iface).getConstructor(IGrid.class); + map.put(iface, c.newInstance(g)); + } catch (final NoSuchMethodException e) { + AELog.error("Grid Caches must have a constructor with IGrid as the single param."); + throw new IllegalArgumentException(e); + } catch (final InvocationTargetException e) { + AELog.error("Grid Caches must have a constructor with IGrid as the single param."); + throw new IllegalStateException(e); + } catch (final InstantiationException e) { + AELog.error("Grid Caches must have a constructor with IGrid as the single param."); + throw new IllegalStateException(e); + } catch (final IllegalAccessException e) { + AELog.error("Grid Caches must have a constructor with IGrid as the single param."); + throw new IllegalStateException(e); + } + } + + return map; + } } diff --git a/src/main/java/appeng/core/features/registries/LocatableRegistry.java b/src/main/java/appeng/core/features/registries/LocatableRegistry.java index c82244643..a2657d672 100644 --- a/src/main/java/appeng/core/features/registries/LocatableRegistry.java +++ b/src/main/java/appeng/core/features/registries/LocatableRegistry.java @@ -19,50 +19,41 @@ package appeng.core.features.registries; -import java.util.HashMap; -import java.util.Map; - -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; - import appeng.api.events.LocatableEventAnnounce; import appeng.api.events.LocatableEventAnnounce.LocatableEvent; import appeng.api.features.ILocatable; import appeng.api.features.ILocatableRegistry; import appeng.util.Platform; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; + +import java.util.HashMap; +import java.util.Map; -public final class LocatableRegistry implements ILocatableRegistry -{ - private final Map set; +public final class LocatableRegistry implements ILocatableRegistry { + private final Map set; - public LocatableRegistry() - { - this.set = new HashMap<>(); - MinecraftForge.EVENT_BUS.register( this ); - } + public LocatableRegistry() { + this.set = new HashMap<>(); + MinecraftForge.EVENT_BUS.register(this); + } - @SubscribeEvent - public void updateLocatable( final LocatableEventAnnounce e ) - { - if( Platform.isClient() ) - { - return; // IGNORE! - } + @SubscribeEvent + public void updateLocatable(final LocatableEventAnnounce e) { + if (Platform.isClient()) { + return; // IGNORE! + } - if( e.change == LocatableEvent.REGISTER ) - { - this.set.put( e.target.getLocatableSerial(), e.target ); - } - else if( e.change == LocatableEvent.UNREGISTER ) - { - this.set.remove( e.target.getLocatableSerial() ); - } - } + if (e.change == LocatableEvent.REGISTER) { + this.set.put(e.target.getLocatableSerial(), e.target); + } else if (e.change == LocatableEvent.UNREGISTER) { + this.set.remove(e.target.getLocatableSerial()); + } + } - @Override - public ILocatable getLocatableBy( final long serial ) - { - return this.set.get( serial ); - } + @Override + public ILocatable getLocatableBy(final long serial) { + return this.set.get(serial); + } } diff --git a/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java b/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java index 24e0ce52b..d1f0f78ff 100644 --- a/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java +++ b/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java @@ -19,132 +19,121 @@ package appeng.core.features.registries; -import java.util.HashMap; - -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - import appeng.api.features.IMatterCannonAmmoRegistry; import appeng.recipes.ores.IOreListener; import appeng.recipes.ores.OreDictionaryHandler; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; + +import java.util.HashMap; -public class MatterCannonAmmoRegistry implements IOreListener, IMatterCannonAmmoRegistry -{ +public class MatterCannonAmmoRegistry implements IOreListener, IMatterCannonAmmoRegistry { - private final HashMap DamageModifiers = new HashMap<>(); + private final HashMap DamageModifiers = new HashMap<>(); - public MatterCannonAmmoRegistry() - { - OreDictionaryHandler.INSTANCE.observe( this ); - this.registerAmmo( new ItemStack( Items.GOLD_NUGGET ), 196.96655 ); - } + public MatterCannonAmmoRegistry() { + OreDictionaryHandler.INSTANCE.observe(this); + this.registerAmmo(new ItemStack(Items.GOLD_NUGGET), 196.96655); + } - @Override - public void registerAmmo( final ItemStack ammo, final double weight ) - { - this.DamageModifiers.put( ammo, weight ); - } + @Override + public void registerAmmo(final ItemStack ammo, final double weight) { + this.DamageModifiers.put(ammo, weight); + } - @Override - public float getPenetration( final ItemStack is ) - { - for( final ItemStack o : this.DamageModifiers.keySet() ) - { - if( ItemStack.areItemsEqual( o, is ) ) - { - return this.DamageModifiers.get( o ).floatValue(); - } - } - return 0; - } + @Override + public float getPenetration(final ItemStack is) { + for (final ItemStack o : this.DamageModifiers.keySet()) { + if (ItemStack.areItemsEqual(o, is)) { + return this.DamageModifiers.get(o).floatValue(); + } + } + return 0; + } - @Override - public void oreRegistered( final String name, final ItemStack item ) - { - if( !( name.startsWith( "berry" ) || name.startsWith( "nugget" ) ) ) - { - return; - } + @Override + public void oreRegistered(final String name, final ItemStack item) { + if (!(name.startsWith("berry") || name.startsWith("nugget"))) { + return; + } - // addNugget( "Cobble", 18 ); // ? - this.considerItem( name, item, "MeatRaw", 32 ); - this.considerItem( name, item, "MeatCooked", 32 ); - this.considerItem( name, item, "Meat", 32 ); - this.considerItem( name, item, "Chicken", 32 ); - this.considerItem( name, item, "Beef", 32 ); - this.considerItem( name, item, "Sheep", 32 ); - this.considerItem( name, item, "Fish", 32 ); + // addNugget( "Cobble", 18 ); // ? + this.considerItem(name, item, "MeatRaw", 32); + this.considerItem(name, item, "MeatCooked", 32); + this.considerItem(name, item, "Meat", 32); + this.considerItem(name, item, "Chicken", 32); + this.considerItem(name, item, "Beef", 32); + this.considerItem(name, item, "Sheep", 32); + this.considerItem(name, item, "Fish", 32); - // real world... - this.considerItem( name, item, "Lithium", 6.941 ); - this.considerItem( name, item, "Beryllium", 9.0122 ); - this.considerItem( name, item, "Boron", 10.811 ); - this.considerItem( name, item, "Carbon", 12.0107 ); - this.considerItem( name, item, "Coal", 12.0107 ); - this.considerItem( name, item, "Charcoal", 12.0107 ); - this.considerItem( name, item, "Sodium", 22.9897 ); - this.considerItem( name, item, "Magnesium", 24.305 ); - this.considerItem( name, item, "Aluminum", 26.9815 ); - this.considerItem( name, item, "SILICON", 28.0855 ); - this.considerItem( name, item, "Phosphorus", 30.9738 ); - this.considerItem( name, item, "Sulfur", 32.065 ); - this.considerItem( name, item, "Potassium", 39.0983 ); - this.considerItem( name, item, "Calcium", 40.078 ); - this.considerItem( name, item, "Scandium", 44.9559 ); - this.considerItem( name, item, "Titanium", 47.867 ); - this.considerItem( name, item, "Vanadium", 50.9415 ); - this.considerItem( name, item, "Manganese", 54.938 ); - this.considerItem( name, item, "Iron", 55.845 ); - this.considerItem( name, item, "Nickel", 58.6934 ); - this.considerItem( name, item, "Cobalt", 58.9332 ); - this.considerItem( name, item, "Copper", 63.546 ); - this.considerItem( name, item, "Zinc", 65.39 ); - this.considerItem( name, item, "Gallium", 69.723 ); - this.considerItem( name, item, "Germanium", 72.64 ); - this.considerItem( name, item, "Bromine", 79.904 ); - this.considerItem( name, item, "Krypton", 83.8 ); - this.considerItem( name, item, "Rubidium", 85.4678 ); - this.considerItem( name, item, "Strontium", 87.62 ); - this.considerItem( name, item, "Yttrium", 88.9059 ); - this.considerItem( name, item, "Zirconiumm", 91.224 ); - this.considerItem( name, item, "Niobiumm", 92.9064 ); - this.considerItem( name, item, "Technetium", 98 ); - this.considerItem( name, item, "Ruthenium", 101.07 ); - this.considerItem( name, item, "Rhodium", 102.9055 ); - this.considerItem( name, item, "Palladium", 106.42 ); - this.considerItem( name, item, "Silver", 107.8682 ); - this.considerItem( name, item, "Cadmium", 112.411 ); - this.considerItem( name, item, "Indium", 114.818 ); - this.considerItem( name, item, "Tin", 118.71 ); - this.considerItem( name, item, "Antimony", 121.76 ); - this.considerItem( name, item, "Iodine", 126.9045 ); - this.considerItem( name, item, "Tellurium", 127.6 ); - this.considerItem( name, item, "Xenon", 131.293 ); - this.considerItem( name, item, "Cesium", 132.9055 ); - this.considerItem( name, item, "Barium", 137.327 ); - this.considerItem( name, item, "Lanthanum", 138.9055 ); - this.considerItem( name, item, "Cerium", 140.116 ); - this.considerItem( name, item, "Tantalum", 180.9479 ); - this.considerItem( name, item, "Tungsten", 183.84 ); - this.considerItem( name, item, "Osmium", 190.23 ); - this.considerItem( name, item, "Iridium", 192.217 ); - this.considerItem( name, item, "Platinum", 195.078 ); - this.considerItem( name, item, "Lead", 207.2 ); - this.considerItem( name, item, "Bismuth", 208.9804 ); - this.considerItem( name, item, "Uranium", 238.0289 ); - this.considerItem( name, item, "Plutonium", 244 ); + // real world... + this.considerItem(name, item, "Lithium", 6.941); + this.considerItem(name, item, "Beryllium", 9.0122); + this.considerItem(name, item, "Boron", 10.811); + this.considerItem(name, item, "Carbon", 12.0107); + this.considerItem(name, item, "Coal", 12.0107); + this.considerItem(name, item, "Charcoal", 12.0107); + this.considerItem(name, item, "Sodium", 22.9897); + this.considerItem(name, item, "Magnesium", 24.305); + this.considerItem(name, item, "Aluminum", 26.9815); + this.considerItem(name, item, "SILICON", 28.0855); + this.considerItem(name, item, "Phosphorus", 30.9738); + this.considerItem(name, item, "Sulfur", 32.065); + this.considerItem(name, item, "Potassium", 39.0983); + this.considerItem(name, item, "Calcium", 40.078); + this.considerItem(name, item, "Scandium", 44.9559); + this.considerItem(name, item, "Titanium", 47.867); + this.considerItem(name, item, "Vanadium", 50.9415); + this.considerItem(name, item, "Manganese", 54.938); + this.considerItem(name, item, "Iron", 55.845); + this.considerItem(name, item, "Nickel", 58.6934); + this.considerItem(name, item, "Cobalt", 58.9332); + this.considerItem(name, item, "Copper", 63.546); + this.considerItem(name, item, "Zinc", 65.39); + this.considerItem(name, item, "Gallium", 69.723); + this.considerItem(name, item, "Germanium", 72.64); + this.considerItem(name, item, "Bromine", 79.904); + this.considerItem(name, item, "Krypton", 83.8); + this.considerItem(name, item, "Rubidium", 85.4678); + this.considerItem(name, item, "Strontium", 87.62); + this.considerItem(name, item, "Yttrium", 88.9059); + this.considerItem(name, item, "Zirconiumm", 91.224); + this.considerItem(name, item, "Niobiumm", 92.9064); + this.considerItem(name, item, "Technetium", 98); + this.considerItem(name, item, "Ruthenium", 101.07); + this.considerItem(name, item, "Rhodium", 102.9055); + this.considerItem(name, item, "Palladium", 106.42); + this.considerItem(name, item, "Silver", 107.8682); + this.considerItem(name, item, "Cadmium", 112.411); + this.considerItem(name, item, "Indium", 114.818); + this.considerItem(name, item, "Tin", 118.71); + this.considerItem(name, item, "Antimony", 121.76); + this.considerItem(name, item, "Iodine", 126.9045); + this.considerItem(name, item, "Tellurium", 127.6); + this.considerItem(name, item, "Xenon", 131.293); + this.considerItem(name, item, "Cesium", 132.9055); + this.considerItem(name, item, "Barium", 137.327); + this.considerItem(name, item, "Lanthanum", 138.9055); + this.considerItem(name, item, "Cerium", 140.116); + this.considerItem(name, item, "Tantalum", 180.9479); + this.considerItem(name, item, "Tungsten", 183.84); + this.considerItem(name, item, "Osmium", 190.23); + this.considerItem(name, item, "Iridium", 192.217); + this.considerItem(name, item, "Platinum", 195.078); + this.considerItem(name, item, "Lead", 207.2); + this.considerItem(name, item, "Bismuth", 208.9804); + this.considerItem(name, item, "Uranium", 238.0289); + this.considerItem(name, item, "Plutonium", 244); - // TE stuff... - this.considerItem( name, item, "Invar", ( 58.6934 + 55.845 + 55.845 ) / 3.0 ); - this.considerItem( name, item, "Electrum", ( 107.8682 + 196.96655 ) / 2.0 ); - } + // TE stuff... + this.considerItem(name, item, "Invar", (58.6934 + 55.845 + 55.845) / 3.0); + this.considerItem(name, item, "Electrum", (107.8682 + 196.96655) / 2.0); + } - private void considerItem( final String ore, final ItemStack item, final String name, final double weight ) - { - if( ore.equals( "berry" + name ) || ore.equals( "nugget" + name ) ) - { - this.registerAmmo( item, weight ); - } - } + private void considerItem(final String ore, final ItemStack item, final String name, final double weight) { + if (ore.equals("berry" + name) || ore.equals("nugget" + name)) { + this.registerAmmo(item, weight); + } + } } diff --git a/src/main/java/appeng/core/features/registries/MovableTileRegistry.java b/src/main/java/appeng/core/features/registries/MovableTileRegistry.java index e0359c0cc..261ae1917 100644 --- a/src/main/java/appeng/core/features/registries/MovableTileRegistry.java +++ b/src/main/java/appeng/core/features/registries/MovableTileRegistry.java @@ -19,150 +19,128 @@ package appeng.core.features.registries; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.tileentity.TileEntity; - import appeng.api.exceptions.AppEngException; import appeng.api.movable.IMovableHandler; import appeng.api.movable.IMovableRegistry; import appeng.api.movable.IMovableTile; import appeng.spatial.DefaultSpatialHandler; +import net.minecraft.block.Block; +import net.minecraft.tileentity.TileEntity; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; -public class MovableTileRegistry implements IMovableRegistry -{ +public class MovableTileRegistry implements IMovableRegistry { - private final HashSet blacklisted = new HashSet<>(); + private final HashSet blacklisted = new HashSet<>(); - private final HashMap, IMovableHandler> Valid = new HashMap<>(); - private final List> test = new ArrayList<>(); - private final List handlers = new ArrayList<>(); - private final DefaultSpatialHandler dsh = new DefaultSpatialHandler(); + private final HashMap, IMovableHandler> Valid = new HashMap<>(); + private final List> test = new ArrayList<>(); + private final List handlers = new ArrayList<>(); + private final DefaultSpatialHandler dsh = new DefaultSpatialHandler(); - private final IMovableHandler nullHandler = new DefaultSpatialHandler(); + private final IMovableHandler nullHandler = new DefaultSpatialHandler(); - @Override - public void blacklistBlock( final Block blk ) - { - this.blacklisted.add( blk ); - } + @Override + public void blacklistBlock(final Block blk) { + this.blacklisted.add(blk); + } - @Override - public void whiteListTileEntity( final Class c ) - { - if( c.getName().equals( TileEntity.class.getName() ) ) - { - throw new IllegalArgumentException( new AppEngException( "Someone tried to make all tiles movable with " + c + ", this is a clear violation of the purpose of the white list." ) ); - } + @Override + public void whiteListTileEntity(final Class c) { + if (c.getName().equals(TileEntity.class.getName())) { + throw new IllegalArgumentException(new AppEngException("Someone tried to make all tiles movable with " + c + ", this is a clear violation of the purpose of the white list.")); + } - this.test.add( c ); - } + this.test.add(c); + } - @Override - public boolean askToMove( final TileEntity te ) - { - final Class myClass = te.getClass(); - IMovableHandler canMove = this.Valid.get( myClass ); + @Override + public boolean askToMove(final TileEntity te) { + final Class myClass = te.getClass(); + IMovableHandler canMove = this.Valid.get(myClass); - if( canMove == null ) - { - canMove = this.testClass( myClass, te ); - } + if (canMove == null) { + canMove = this.testClass(myClass, te); + } - if( canMove != this.nullHandler ) - { - if( te instanceof IMovableTile ) - { - ( (IMovableTile) te ).prepareToMove(); - } + if (canMove != this.nullHandler) { + if (te instanceof IMovableTile) { + ((IMovableTile) te).prepareToMove(); + } - te.invalidate(); - return true; - } + te.invalidate(); + return true; + } - return false; - } + return false; + } - private IMovableHandler testClass( final Class myClass, final TileEntity te ) - { - IMovableHandler handler = null; + private IMovableHandler testClass(final Class myClass, final TileEntity te) { + IMovableHandler handler = null; - // ask handlers... - for( final IMovableHandler han : this.handlers ) - { - if( han.canHandle( myClass, te ) ) - { - handler = han; - break; - } - } + // ask handlers... + for (final IMovableHandler han : this.handlers) { + if (han.canHandle(myClass, te)) { + handler = han; + break; + } + } - // if you have a handler your opted in - if( handler != null ) - { - this.Valid.put( myClass, handler ); - return handler; - } + // if you have a handler your opted in + if (handler != null) { + this.Valid.put(myClass, handler); + return handler; + } - // if your movable our opted in - if( te instanceof IMovableTile ) - { - this.Valid.put( myClass, this.dsh ); - return this.dsh; - } + // if your movable our opted in + if (te instanceof IMovableTile) { + this.Valid.put(myClass, this.dsh); + return this.dsh; + } - // if you are on the white list your opted in. - for( final Class testClass : this.test ) - { - if( testClass.isAssignableFrom( myClass ) ) - { - this.Valid.put( myClass, this.dsh ); - return this.dsh; - } - } + // if you are on the white list your opted in. + for (final Class testClass : this.test) { + if (testClass.isAssignableFrom(myClass)) { + this.Valid.put(myClass, this.dsh); + return this.dsh; + } + } - this.Valid.put( myClass, this.nullHandler ); - return this.nullHandler; - } + this.Valid.put(myClass, this.nullHandler); + return this.nullHandler; + } - @Override - public void doneMoving( final TileEntity te ) - { - if( te instanceof IMovableTile ) - { - final IMovableTile mt = (IMovableTile) te; - mt.doneMoving(); - } - } + @Override + public void doneMoving(final TileEntity te) { + if (te instanceof IMovableTile) { + final IMovableTile mt = (IMovableTile) te; + mt.doneMoving(); + } + } - @Override - public void addHandler( final IMovableHandler han ) - { - this.handlers.add( han ); - } + @Override + public void addHandler(final IMovableHandler han) { + this.handlers.add(han); + } - @Override - public IMovableHandler getHandler( final TileEntity te ) - { - final Class myClass = te.getClass(); - final IMovableHandler h = this.Valid.get( myClass ); - return h == null ? this.dsh : h; - } + @Override + public IMovableHandler getHandler(final TileEntity te) { + final Class myClass = te.getClass(); + final IMovableHandler h = this.Valid.get(myClass); + return h == null ? this.dsh : h; + } - @Override - public IMovableHandler getDefaultHandler() - { - return this.dsh; - } + @Override + public IMovableHandler getDefaultHandler() { + return this.dsh; + } - @Override - public boolean isBlacklisted( final Block blk ) - { - return this.blacklisted.contains( blk ); - } + @Override + public boolean isBlacklisted(final Block blk) { + return this.blacklisted.contains(blk); + } } diff --git a/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java b/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java index b82219ccd..55a9e1fdd 100644 --- a/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java +++ b/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java @@ -19,13 +19,15 @@ package appeng.core.features.registries; -import java.util.*; -import java.util.Map.Entry; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import appeng.core.AELog; +import appeng.api.AEApi; +import appeng.api.config.TunnelType; +import appeng.api.definitions.IBlocks; +import appeng.api.definitions.IDefinitions; +import appeng.api.definitions.IItemDefinition; +import appeng.api.definitions.IParts; +import appeng.api.features.IP2PTunnelRegistry; +import appeng.api.util.AEColor; +import appeng.capabilities.Capabilities; import appeng.util.item.OreHelper; import net.minecraft.init.Blocks; import net.minecraft.init.Items; @@ -36,271 +38,243 @@ import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.oredict.OreDictionary; -import appeng.api.AEApi; -import appeng.api.config.TunnelType; -import appeng.api.definitions.IBlocks; -import appeng.api.definitions.IDefinitions; -import appeng.api.definitions.IItemDefinition; -import appeng.api.definitions.IParts; -import appeng.api.features.IP2PTunnelRegistry; -import appeng.api.util.AEColor; -import appeng.capabilities.Capabilities; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; +import java.util.Map.Entry; -public final class P2PTunnelRegistry implements IP2PTunnelRegistry -{ - private static final int INITIAL_CAPACITY = 40; +public final class P2PTunnelRegistry implements IP2PTunnelRegistry { + private static final int INITIAL_CAPACITY = 40; - private final Map tunnels = new HashMap<>( INITIAL_CAPACITY ); - private final Map modIdTunnels = new HashMap<>( INITIAL_CAPACITY ); - private final Map, TunnelType> capTunnels = new HashMap<>( INITIAL_CAPACITY ); + private final Map tunnels = new HashMap<>(INITIAL_CAPACITY); + private final Map modIdTunnels = new HashMap<>(INITIAL_CAPACITY); + private final Map, TunnelType> capTunnels = new HashMap<>(INITIAL_CAPACITY); - public void configure() - { + public void configure() { - final IDefinitions definitions = AEApi.instance().definitions(); - final IBlocks blocks = definitions.blocks(); - final IParts parts = definitions.parts(); + final IDefinitions definitions = AEApi.instance().definitions(); + final IBlocks blocks = definitions.blocks(); + final IParts parts = definitions.parts(); - /** - * light! - */ - this.addNewAttunement( new ItemStack( Blocks.TORCH ), TunnelType.LIGHT ); - this.addNewAttunement( new ItemStack( Blocks.GLOWSTONE ), TunnelType.LIGHT ); + /** + * light! + */ + this.addNewAttunement(new ItemStack(Blocks.TORCH), TunnelType.LIGHT); + this.addNewAttunement(new ItemStack(Blocks.GLOWSTONE), TunnelType.LIGHT); - List gtceOreDict = new ArrayList<>(); - gtceOreDict.add( "wireGtHex" ); - gtceOreDict.add( "wireGtOctal" ); - gtceOreDict.add( "wireGtQuadruple" ); - gtceOreDict.add( "wireGtDouble" ); - gtceOreDict.add( "wireGtSingle" ); - gtceOreDict.add( "cableGtHex" ); - gtceOreDict.add( "cableGtOctal" ); - gtceOreDict.add( "cableGtQuadruple" ); - gtceOreDict.add( "cableGtDouble" ); - gtceOreDict.add( "cableGtSingle" ); + List gtceOreDict = new ArrayList<>(); + gtceOreDict.add("wireGtHex"); + gtceOreDict.add("wireGtOctal"); + gtceOreDict.add("wireGtQuadruple"); + gtceOreDict.add("wireGtDouble"); + gtceOreDict.add("wireGtSingle"); + gtceOreDict.add("cableGtHex"); + gtceOreDict.add("cableGtOctal"); + gtceOreDict.add("cableGtQuadruple"); + gtceOreDict.add("cableGtDouble"); + gtceOreDict.add("cableGtSingle"); - for( String oreDict : gtceOreDict ) - { - Arrays.stream( OreDictionary.getOreNames() ).filter( oreName -> oreName.startsWith( oreDict ) ).forEach( oreName -> { - OreHelper.INSTANCE.getCachedOres( oreName ).forEach( stack -> this.addNewAttunement( stack, TunnelType.GTEU_POWER ) ); - } ); - } + for (String oreDict : gtceOreDict) { + Arrays.stream(OreDictionary.getOreNames()).filter(oreName -> oreName.startsWith(oreDict)).forEach(oreName -> { + OreHelper.INSTANCE.getCachedOres(oreName).forEach(stack -> this.addNewAttunement(stack, TunnelType.GTEU_POWER)); + }); + } - /** - * Forge energy tunnel items - */ + /** + * Forge energy tunnel items + */ - this.addNewAttunement( blocks.energyCellDense(), TunnelType.FE_POWER ); - this.addNewAttunement( blocks.energyAcceptor(), TunnelType.FE_POWER ); - this.addNewAttunement( blocks.energyCell(), TunnelType.FE_POWER ); - this.addNewAttunement( blocks.energyCellCreative(), TunnelType.FE_POWER ); + this.addNewAttunement(blocks.energyCellDense(), TunnelType.FE_POWER); + this.addNewAttunement(blocks.energyAcceptor(), TunnelType.FE_POWER); + this.addNewAttunement(blocks.energyCell(), TunnelType.FE_POWER); + this.addNewAttunement(blocks.energyCellCreative(), TunnelType.FE_POWER); - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_0", 0 ), TunnelType.FE_POWER ); - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_0", 1 ), TunnelType.FE_POWER ); - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_0", 2 ), TunnelType.FE_POWER ); - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_0", 3 ), TunnelType.FE_POWER ); - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_0", 4 ), TunnelType.FE_POWER ); - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_0", 5 ), TunnelType.FE_POWER ); + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_0", 0), TunnelType.FE_POWER); + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_0", 1), TunnelType.FE_POWER); + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_0", 2), TunnelType.FE_POWER); + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_0", 3), TunnelType.FE_POWER); + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_0", 4), TunnelType.FE_POWER); + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_0", 5), TunnelType.FE_POWER); - /** - * EU tunnel items - */ + /** + * EU tunnel items + */ - this.addNewAttunement( this.getModItem( "ic2", "cable", 0 ), TunnelType.IC2_POWER ); // Copper cable - this.addNewAttunement( this.getModItem( "ic2", "cable", 1 ), TunnelType.IC2_POWER ); // Glass fibre cable - this.addNewAttunement( this.getModItem( "ic2", "cable", 2 ), TunnelType.IC2_POWER ); // Gold cable - this.addNewAttunement( this.getModItem( "ic2", "cable", 3 ), TunnelType.IC2_POWER ); // HV cable - this.addNewAttunement( this.getModItem( "ic2", "cable", 4 ), TunnelType.IC2_POWER ); // Tin cable + this.addNewAttunement(this.getModItem("ic2", "cable", 0), TunnelType.IC2_POWER); // Copper cable + this.addNewAttunement(this.getModItem("ic2", "cable", 1), TunnelType.IC2_POWER); // Glass fibre cable + this.addNewAttunement(this.getModItem("ic2", "cable", 2), TunnelType.IC2_POWER); // Gold cable + this.addNewAttunement(this.getModItem("ic2", "cable", 3), TunnelType.IC2_POWER); // HV cable + this.addNewAttunement(this.getModItem("ic2", "cable", 4), TunnelType.IC2_POWER); // Tin cable - /** - * attune based on most redstone base items. - */ - this.addNewAttunement( new ItemStack( Items.REDSTONE ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Items.REPEATER ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.REDSTONE_LAMP ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.UNPOWERED_COMPARATOR ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.POWERED_COMPARATOR ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.POWERED_REPEATER ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.UNPOWERED_REPEATER ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.DAYLIGHT_DETECTOR ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.REDSTONE_WIRE ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.REDSTONE_BLOCK ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.LEVER ), TunnelType.REDSTONE ); - this.addNewAttunement( this.getModItem( "enderio", "itemredstoneconduit", OreDictionary.WILDCARD_VALUE ), TunnelType.REDSTONE ); + /** + * attune based on most redstone base items. + */ + this.addNewAttunement(new ItemStack(Items.REDSTONE), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Items.REPEATER), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.REDSTONE_LAMP), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.UNPOWERED_COMPARATOR), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.POWERED_COMPARATOR), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.POWERED_REPEATER), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.UNPOWERED_REPEATER), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.DAYLIGHT_DETECTOR), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.REDSTONE_WIRE), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.REDSTONE_BLOCK), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.LEVER), TunnelType.REDSTONE); + this.addNewAttunement(this.getModItem("enderio", "itemredstoneconduit", OreDictionary.WILDCARD_VALUE), TunnelType.REDSTONE); - /** - * attune based on lots of random item related stuff - */ + /** + * attune based on lots of random item related stuff + */ - this.addNewAttunement( blocks.iface(), TunnelType.ITEM ); - this.addNewAttunement( parts.iface(), TunnelType.ITEM ); - this.addNewAttunement( parts.storageBus(), TunnelType.ITEM ); - this.addNewAttunement( parts.importBus(), TunnelType.ITEM ); - this.addNewAttunement( parts.exportBus(), TunnelType.ITEM ); + this.addNewAttunement(blocks.iface(), TunnelType.ITEM); + this.addNewAttunement(parts.iface(), TunnelType.ITEM); + this.addNewAttunement(parts.storageBus(), TunnelType.ITEM); + this.addNewAttunement(parts.importBus(), TunnelType.ITEM); + this.addNewAttunement(parts.exportBus(), TunnelType.ITEM); - this.addNewAttunement( new ItemStack( Blocks.HOPPER ), TunnelType.ITEM ); - this.addNewAttunement( new ItemStack( Blocks.CHEST ), TunnelType.ITEM ); - this.addNewAttunement( new ItemStack( Blocks.TRAPPED_CHEST ), TunnelType.ITEM ); - this.addNewAttunement( this.getModItem( "extrautilities", "extractor_base", 0 ), TunnelType.ITEM ); - this.addNewAttunement( this.getModItem( "mekanism", "parttransmitter", 9 ), TunnelType.ITEM ); - this.addNewAttunement( this.getModItem( "enderio", "itemitemconduit", OreDictionary.WILDCARD_VALUE ), TunnelType.ITEM ); - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_32", 0 ), TunnelType.ITEM ); // itemduct - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_32", 1 ), TunnelType.ITEM ); // itemduct - // (opaque) - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_32", 2 ), TunnelType.ITEM ); // impulse - // itemduct - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_32", 3 ), TunnelType.ITEM ); // impulse - // itemduct - // (opaque) + this.addNewAttunement(new ItemStack(Blocks.HOPPER), TunnelType.ITEM); + this.addNewAttunement(new ItemStack(Blocks.CHEST), TunnelType.ITEM); + this.addNewAttunement(new ItemStack(Blocks.TRAPPED_CHEST), TunnelType.ITEM); + this.addNewAttunement(this.getModItem("extrautilities", "extractor_base", 0), TunnelType.ITEM); + this.addNewAttunement(this.getModItem("mekanism", "parttransmitter", 9), TunnelType.ITEM); + this.addNewAttunement(this.getModItem("enderio", "itemitemconduit", OreDictionary.WILDCARD_VALUE), TunnelType.ITEM); + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_32", 0), TunnelType.ITEM); // itemduct + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_32", 1), TunnelType.ITEM); // itemduct + // (opaque) + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_32", 2), TunnelType.ITEM); // impulse + // itemduct + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_32", 3), TunnelType.ITEM); // impulse + // itemduct + // (opaque) - /** - * attune based on lots of random item related stuff - */ - this.addNewAttunement( new ItemStack( Items.BUCKET ), TunnelType.FLUID ); - this.addNewAttunement( new ItemStack( Items.LAVA_BUCKET ), TunnelType.FLUID ); - this.addNewAttunement( new ItemStack( Items.MILK_BUCKET ), TunnelType.FLUID ); - this.addNewAttunement( new ItemStack( Items.WATER_BUCKET ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "mekanism", "machineblock2", 11 ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "mekanism", "parttransmitter", 4 ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "extrautilities", "extractor_base", 6 ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "extrautilities", "drum", OreDictionary.WILDCARD_VALUE ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "enderio", "itemliquidconduit", OreDictionary.WILDCARD_VALUE ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_16", 0 ), TunnelType.FLUID ); // fluiduct - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_16", 1 ), TunnelType.FLUID ); // fluiduct - // (opaque) - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_16", 2 ), TunnelType.FLUID ); // fluiduct - // hardened - this.addNewAttunement( this.getModItem( "thermaldynamics", "duct_16", 3 ), TunnelType.FLUID ); // fluiduct - // hardened - // (opaque) + /** + * attune based on lots of random item related stuff + */ + this.addNewAttunement(new ItemStack(Items.BUCKET), TunnelType.FLUID); + this.addNewAttunement(new ItemStack(Items.LAVA_BUCKET), TunnelType.FLUID); + this.addNewAttunement(new ItemStack(Items.MILK_BUCKET), TunnelType.FLUID); + this.addNewAttunement(new ItemStack(Items.WATER_BUCKET), TunnelType.FLUID); + this.addNewAttunement(this.getModItem("mekanism", "machineblock2", 11), TunnelType.FLUID); + this.addNewAttunement(this.getModItem("mekanism", "parttransmitter", 4), TunnelType.FLUID); + this.addNewAttunement(this.getModItem("extrautilities", "extractor_base", 6), TunnelType.FLUID); + this.addNewAttunement(this.getModItem("extrautilities", "drum", OreDictionary.WILDCARD_VALUE), TunnelType.FLUID); + this.addNewAttunement(this.getModItem("enderio", "itemliquidconduit", OreDictionary.WILDCARD_VALUE), TunnelType.FLUID); + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_16", 0), TunnelType.FLUID); // fluiduct + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_16", 1), TunnelType.FLUID); // fluiduct + // (opaque) + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_16", 2), TunnelType.FLUID); // fluiduct + // hardened + this.addNewAttunement(this.getModItem("thermaldynamics", "duct_16", 3), TunnelType.FLUID); // fluiduct + // hardened + // (opaque) - for( final AEColor c : AEColor.values() ) - { - this.addNewAttunement( parts.cableGlass().stack( c, 1 ), TunnelType.ME ); - this.addNewAttunement( parts.cableCovered().stack( c, 1 ), TunnelType.ME ); - this.addNewAttunement( parts.cableSmart().stack( c, 1 ), TunnelType.ME ); - this.addNewAttunement( parts.cableDenseSmart().stack( c, 1 ), TunnelType.ME ); - } + for (final AEColor c : AEColor.values()) { + this.addNewAttunement(parts.cableGlass().stack(c, 1), TunnelType.ME); + this.addNewAttunement(parts.cableCovered().stack(c, 1), TunnelType.ME); + this.addNewAttunement(parts.cableSmart().stack(c, 1), TunnelType.ME); + this.addNewAttunement(parts.cableDenseSmart().stack(c, 1), TunnelType.ME); + } - /** - * attune based caps - */ - this.addNewAttunement( Capabilities.FORGE_ENERGY, TunnelType.FE_POWER ); - this.addNewAttunement( CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, TunnelType.FLUID ); + /** + * attune based caps + */ + this.addNewAttunement(Capabilities.FORGE_ENERGY, TunnelType.FE_POWER); + this.addNewAttunement(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, TunnelType.FLUID); - /** - * attune based on the ItemStack's modId - */ + /** + * attune based on the ItemStack's modId + */ - this.addNewAttunement( "thermaldynamics", TunnelType.FE_POWER ); - this.addNewAttunement( "thermalexpansion", TunnelType.FE_POWER ); - this.addNewAttunement( "thermalfoundation", TunnelType.FE_POWER ); - // TODO: Remove when confirmed that the official 1.12 version of EnderIO will support FE. - this.addNewAttunement( "enderio", TunnelType.FE_POWER ); - // TODO: Remove when confirmed that the official 1.12 version of Mekanism will support FE. - this.addNewAttunement( "mekanism", TunnelType.FE_POWER ); - // TODO: Remove when support for RFTools' Powercells support is added - this.addNewAttunement( "rftools", TunnelType.FE_POWER ); - this.addNewAttunement( "ic2", TunnelType.IC2_POWER ); + this.addNewAttunement("thermaldynamics", TunnelType.FE_POWER); + this.addNewAttunement("thermalexpansion", TunnelType.FE_POWER); + this.addNewAttunement("thermalfoundation", TunnelType.FE_POWER); + // TODO: Remove when confirmed that the official 1.12 version of EnderIO will support FE. + this.addNewAttunement("enderio", TunnelType.FE_POWER); + // TODO: Remove when confirmed that the official 1.12 version of Mekanism will support FE. + this.addNewAttunement("mekanism", TunnelType.FE_POWER); + // TODO: Remove when support for RFTools' Powercells support is added + this.addNewAttunement("rftools", TunnelType.FE_POWER); + this.addNewAttunement("ic2", TunnelType.IC2_POWER); - } + } - @Override - public void addNewAttunement( @Nonnull final String modId, @Nullable final TunnelType type ) - { - if( type == null || modId == null ) - { - return; - } - this.modIdTunnels.put( modId, type ); - } + @Override + public void addNewAttunement(@Nonnull final String modId, @Nullable final TunnelType type) { + if (type == null || modId == null) { + return; + } + this.modIdTunnels.put(modId, type); + } - @Override - public void addNewAttunement( @Nonnull final Capability cap, @Nullable final TunnelType type ) - { - if( type == null || cap == null ) - { - return; - } - this.capTunnels.put( cap, type ); - } + @Override + public void addNewAttunement(@Nonnull final Capability cap, @Nullable final TunnelType type) { + if (type == null || cap == null) { + return; + } + this.capTunnels.put(cap, type); + } - @Override - public void addNewAttunement( @Nonnull final ItemStack trigger, @Nullable final TunnelType type ) - { - if( type == null || trigger.isEmpty() ) - { - return; - } + @Override + public void addNewAttunement(@Nonnull final ItemStack trigger, @Nullable final TunnelType type) { + if (type == null || trigger.isEmpty()) { + return; + } - this.tunnels.put( trigger, type ); - } + this.tunnels.put(trigger, type); + } - @Nullable - @Override - public TunnelType getTunnelTypeByItem( final ItemStack trigger ) - { - if( !trigger.isEmpty() ) - { - // First match exact items - for( final Entry entry : this.tunnels.entrySet() ) - { - final ItemStack is = entry.getKey(); + @Nullable + @Override + public TunnelType getTunnelTypeByItem(final ItemStack trigger) { + if (!trigger.isEmpty()) { + // First match exact items + for (final Entry entry : this.tunnels.entrySet()) { + final ItemStack is = entry.getKey(); - if( is.getItem() == trigger.getItem() && is.getItemDamage() == OreDictionary.WILDCARD_VALUE ) - { - return entry.getValue(); - } + if (is.getItem() == trigger.getItem() && is.getItemDamage() == OreDictionary.WILDCARD_VALUE) { + return entry.getValue(); + } - if( ItemStack.areItemsEqual( is, trigger ) ) - { - return entry.getValue(); - } - } + if (ItemStack.areItemsEqual(is, trigger)) { + return entry.getValue(); + } + } - // Next, check if the Item you're holding supports any registered capability - for( EnumFacing face : EnumFacing.VALUES ) - { - for( Entry, TunnelType> entry : this.capTunnels.entrySet() ) - { - if( trigger.hasCapability( entry.getKey(), face ) ) - { - return entry.getValue(); - } - } - } + // Next, check if the Item you're holding supports any registered capability + for (EnumFacing face : EnumFacing.VALUES) { + for (Entry, TunnelType> entry : this.capTunnels.entrySet()) { + if (trigger.hasCapability(entry.getKey(), face)) { + return entry.getValue(); + } + } + } - // Use the mod id as last option. - for( final Entry entry : this.modIdTunnels.entrySet() ) - { - if( trigger.getItem().getRegistryName() != null && trigger.getItem().getRegistryName().getResourceDomain().equals( entry.getKey() ) ) - { - return entry.getValue(); - } - } - } + // Use the mod id as last option. + for (final Entry entry : this.modIdTunnels.entrySet()) { + if (trigger.getItem().getRegistryName() != null && trigger.getItem().getRegistryName().getResourceDomain().equals(entry.getKey())) { + return entry.getValue(); + } + } + } - return null; - } + return null; + } - @Nonnull - private ItemStack getModItem( final String modID, final String name, final int meta ) - { + @Nonnull + private ItemStack getModItem(final String modID, final String name, final int meta) { - final Item item = Item.getByNameOrId( modID + ":" + name ); + final Item item = Item.getByNameOrId(modID + ":" + name); - if( item == null ) - { - return ItemStack.EMPTY; - } + if (item == null) { + return ItemStack.EMPTY; + } - final ItemStack myItemStack = new ItemStack( item, 1, meta ); - return myItemStack; - } + final ItemStack myItemStack = new ItemStack(item, 1, meta); + return myItemStack; + } - private void addNewAttunement( final IItemDefinition definition, final TunnelType type ) - { - definition.maybeStack( 1 ).ifPresent( definitionStack -> this.addNewAttunement( definitionStack, type ) ); - } + private void addNewAttunement(final IItemDefinition definition, final TunnelType type) { + definition.maybeStack(1).ifPresent(definitionStack -> this.addNewAttunement(definitionStack, type)); + } } diff --git a/src/main/java/appeng/core/features/registries/PartModels.java b/src/main/java/appeng/core/features/registries/PartModels.java index e90fae3e3..9e96d14db 100644 --- a/src/main/java/appeng/core/features/registries/PartModels.java +++ b/src/main/java/appeng/core/features/registries/PartModels.java @@ -19,40 +19,34 @@ package appeng.core.features.registries; +import appeng.api.parts.IPartModels; +import net.minecraft.util.ResourceLocation; + import java.util.Collection; import java.util.HashSet; import java.util.Set; -import net.minecraft.util.ResourceLocation; -import appeng.api.parts.IPartModels; +public class PartModels implements IPartModels { + private final Set models = new HashSet<>(); -public class PartModels implements IPartModels -{ + private boolean initialized = false; - private final Set models = new HashSet<>(); + @Override + public void registerModels(Collection partModels) { + if (this.initialized) { + throw new IllegalStateException("Cannot register models after the pre-initialization phase!"); + } - private boolean initialized = false; + this.models.addAll(partModels); + } - @Override - public void registerModels( Collection partModels ) - { - if( this.initialized ) - { - throw new IllegalStateException( "Cannot register models after the pre-initialization phase!" ); - } + public Set getModels() { + return this.models; + } - this.models.addAll( partModels ); - } - - public Set getModels() - { - return this.models; - } - - public void setInitialized( boolean initialized ) - { - this.initialized = initialized; - } + public void setInitialized(boolean initialized) { + this.initialized = initialized; + } } diff --git a/src/main/java/appeng/core/features/registries/PlayerRegistry.java b/src/main/java/appeng/core/features/registries/PlayerRegistry.java index c4f663e64..840086410 100644 --- a/src/main/java/appeng/core/features/registries/PlayerRegistry.java +++ b/src/main/java/appeng/core/features/registries/PlayerRegistry.java @@ -19,40 +19,33 @@ package appeng.core.features.registries; -import javax.annotation.Nullable; - -import com.mojang.authlib.GameProfile; - -import net.minecraft.entity.player.EntityPlayer; - import appeng.api.features.IPlayerRegistry; import appeng.core.worlddata.WorldData; +import com.mojang.authlib.GameProfile; +import net.minecraft.entity.player.EntityPlayer; + +import javax.annotation.Nullable; -public class PlayerRegistry implements IPlayerRegistry -{ +public class PlayerRegistry implements IPlayerRegistry { - @Override - public int getID( final GameProfile username ) - { - if( username == null || !username.isComplete() ) - { - return -1; - } + @Override + public int getID(final GameProfile username) { + if (username == null || !username.isComplete()) { + return -1; + } - return WorldData.instance().playerData().getPlayerID( username ); - } + return WorldData.instance().playerData().getPlayerID(username); + } - @Override - public int getID( final EntityPlayer player ) - { - return this.getID( player.getGameProfile() ); - } + @Override + public int getID(final EntityPlayer player) { + return this.getID(player.getGameProfile()); + } - @Nullable - @Override - public EntityPlayer findPlayer( final int playerID ) - { - return WorldData.instance().playerData().getPlayerFromID( playerID ); - } + @Nullable + @Override + public EntityPlayer findPlayer(final int playerID) { + return WorldData.instance().playerData().getPlayerFromID(playerID); + } } diff --git a/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java b/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java index 5f89f14c5..2f8b93347 100644 --- a/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java +++ b/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java @@ -19,14 +19,6 @@ package appeng.core.features.registries; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import javax.annotation.Nullable; - import appeng.api.features.IRecipeHandlerRegistry; import appeng.api.recipes.ICraftHandler; import appeng.api.recipes.IRecipeHandler; @@ -34,6 +26,9 @@ import appeng.api.recipes.ISubItemResolver; import appeng.core.AELog; import appeng.recipes.RecipeHandler; +import javax.annotation.Nullable; +import java.util.*; + /** * @author AlgorithmX2 @@ -41,76 +36,61 @@ import appeng.recipes.RecipeHandler; * @version rv3 - 10.08.2015 * @since rv0 */ -public class RecipeHandlerRegistry implements IRecipeHandlerRegistry -{ - private final Map> handlers = new HashMap<>( 20 ); - private final Collection resolvers = new ArrayList<>(); +public class RecipeHandlerRegistry implements IRecipeHandlerRegistry { + private final Map> handlers = new HashMap<>(20); + private final Collection resolvers = new ArrayList<>(); - @Override - public void addNewCraftHandler( final String name, final Class handler ) - { - this.handlers.put( name.toLowerCase( Locale.ENGLISH ), handler ); - } + @Override + public void addNewCraftHandler(final String name, final Class handler) { + this.handlers.put(name.toLowerCase(Locale.ENGLISH), handler); + } - @Override - public void addNewSubItemResolver( final ISubItemResolver sir ) - { - this.resolvers.add( sir ); - } + @Override + public void addNewSubItemResolver(final ISubItemResolver sir) { + this.resolvers.add(sir); + } - @Nullable - @Override - public ICraftHandler getCraftHandlerFor( final String name ) - { - final Class clz = this.handlers.get( name ); - if( clz == null ) - { - return null; - } - try - { - return clz.newInstance(); - } - catch( final Throwable e ) - { - AELog.error( "Error Caused when trying to construct " + clz.getName() ); - AELog.debug( e ); + @Nullable + @Override + public ICraftHandler getCraftHandlerFor(final String name) { + final Class clz = this.handlers.get(name); + if (clz == null) { + return null; + } + try { + return clz.newInstance(); + } catch (final Throwable e) { + AELog.error("Error Caused when trying to construct " + clz.getName()); + AELog.debug(e); - this.handlers.put( name, null ); // clear it.. + this.handlers.put(name, null); // clear it.. - return null; - } - } + return null; + } + } - @Override - public IRecipeHandler createNewRecipehandler() - { - return new RecipeHandler(); - } + @Override + public IRecipeHandler createNewRecipehandler() { + return new RecipeHandler(); + } - @Nullable - @Override - public Object resolveItem( final String nameSpace, final String itemName ) - { - for( final ISubItemResolver sir : this.resolvers ) - { - Object rr = null; + @Nullable + @Override + public Object resolveItem(final String nameSpace, final String itemName) { + for (final ISubItemResolver sir : this.resolvers) { + Object rr = null; - try - { - rr = sir.resolveItemByName( nameSpace, itemName ); - } - catch( final Throwable t ) - { - AELog.debug( t ); - } + try { + rr = sir.resolveItemByName(nameSpace, itemName); + } catch (final Throwable t) { + AELog.debug(t); + } - if( rr != null ) - { - return rr; - } - } + if (rr != null) { + return rr; + } + } - return null; - } + return null; + } } diff --git a/src/main/java/appeng/core/features/registries/RegistryContainer.java b/src/main/java/appeng/core/features/registries/RegistryContainer.java index 14678d0ec..c26813c54 100644 --- a/src/main/java/appeng/core/features/registries/RegistryContainer.java +++ b/src/main/java/appeng/core/features/registries/RegistryContainer.java @@ -19,18 +19,7 @@ package appeng.core.features.registries; -import appeng.api.features.IChargerRegistry; -import appeng.api.features.IGrinderRegistry; -import appeng.api.features.IInscriberRegistry; -import appeng.api.features.ILocatableRegistry; -import appeng.api.features.IMatterCannonAmmoRegistry; -import appeng.api.features.IP2PTunnelRegistry; -import appeng.api.features.IPlayerRegistry; -import appeng.api.features.IRecipeHandlerRegistry; -import appeng.api.features.IRegistryContainer; -import appeng.api.features.ISpecialComparisonRegistry; -import appeng.api.features.IWirelessTermRegistry; -import appeng.api.features.IWorldGen; +import appeng.api.features.*; import appeng.api.movable.IMovableRegistry; import appeng.api.networking.IGridCacheRegistry; import appeng.api.parts.IPartModels; @@ -50,111 +39,95 @@ import appeng.core.features.registries.inscriber.InscriberRegistry; * @version rv5 * @since rv0 */ -public class RegistryContainer implements IRegistryContainer -{ - private final IGrinderRegistry grinder = new GrinderRecipeManager(); - private final IInscriberRegistry inscriber = new InscriberRegistry(); - private final IChargerRegistry charger = new ChargerRegistry(); - private final ICellRegistry cell = new CellRegistry(); - private final ILocatableRegistry locatable = new LocatableRegistry(); - private final ISpecialComparisonRegistry comparison = new SpecialComparisonRegistry(); - private final IWirelessTermRegistry wireless = new WirelessRegistry(); - private final IGridCacheRegistry gridCache = new GridCacheRegistry(); - private final IP2PTunnelRegistry p2pTunnel = new P2PTunnelRegistry(); - private final IMovableRegistry movable = new MovableTileRegistry(); - private final IMatterCannonAmmoRegistry matterCannonReg = new MatterCannonAmmoRegistry(); - private final IPlayerRegistry playerRegistry = new PlayerRegistry(); - private final IRecipeHandlerRegistry recipeReg = new RecipeHandlerRegistry(); - private final IPartModels partModels = new PartModels(); +public class RegistryContainer implements IRegistryContainer { + private final IGrinderRegistry grinder = new GrinderRecipeManager(); + private final IInscriberRegistry inscriber = new InscriberRegistry(); + private final IChargerRegistry charger = new ChargerRegistry(); + private final ICellRegistry cell = new CellRegistry(); + private final ILocatableRegistry locatable = new LocatableRegistry(); + private final ISpecialComparisonRegistry comparison = new SpecialComparisonRegistry(); + private final IWirelessTermRegistry wireless = new WirelessRegistry(); + private final IGridCacheRegistry gridCache = new GridCacheRegistry(); + private final IP2PTunnelRegistry p2pTunnel = new P2PTunnelRegistry(); + private final IMovableRegistry movable = new MovableTileRegistry(); + private final IMatterCannonAmmoRegistry matterCannonReg = new MatterCannonAmmoRegistry(); + private final IPlayerRegistry playerRegistry = new PlayerRegistry(); + private final IRecipeHandlerRegistry recipeReg = new RecipeHandlerRegistry(); + private final IPartModels partModels = new PartModels(); - @Override - public IMovableRegistry movable() - { - return this.movable; - } + @Override + public IMovableRegistry movable() { + return this.movable; + } - @Override - public IGridCacheRegistry gridCache() - { - return this.gridCache; - } + @Override + public IGridCacheRegistry gridCache() { + return this.gridCache; + } - @Override - public ISpecialComparisonRegistry specialComparison() - { - return this.comparison; - } + @Override + public ISpecialComparisonRegistry specialComparison() { + return this.comparison; + } - @Override - public IWirelessTermRegistry wireless() - { - return this.wireless; - } + @Override + public IWirelessTermRegistry wireless() { + return this.wireless; + } - @Override - public ICellRegistry cell() - { - return this.cell; - } + @Override + public ICellRegistry cell() { + return this.cell; + } - @Override - public IGrinderRegistry grinder() - { - return this.grinder; - } + @Override + public IGrinderRegistry grinder() { + return this.grinder; + } - @Override - public IInscriberRegistry inscriber() - { - return this.inscriber; - } + @Override + public IInscriberRegistry inscriber() { + return this.inscriber; + } - @Override - public IChargerRegistry charger() - { - return this.charger; - } + @Override + public IChargerRegistry charger() { + return this.charger; + } - @Override - public ILocatableRegistry locatable() - { - return this.locatable; - } + @Override + public ILocatableRegistry locatable() { + return this.locatable; + } - @Override - public IP2PTunnelRegistry p2pTunnel() - { - return this.p2pTunnel; - } + @Override + public IP2PTunnelRegistry p2pTunnel() { + return this.p2pTunnel; + } - @Override - public IMatterCannonAmmoRegistry matterCannon() - { - return this.matterCannonReg; - } + @Override + public IMatterCannonAmmoRegistry matterCannon() { + return this.matterCannonReg; + } - @Override - public IPlayerRegistry players() - { - return this.playerRegistry; - } + @Override + public IPlayerRegistry players() { + return this.playerRegistry; + } - @Override - public IRecipeHandlerRegistry recipes() - { - return this.recipeReg; - } + @Override + public IRecipeHandlerRegistry recipes() { + return this.recipeReg; + } - @Override - public IWorldGen worldgen() - { - return WorldGenRegistry.INSTANCE; - } + @Override + public IWorldGen worldgen() { + return WorldGenRegistry.INSTANCE; + } - @Override - public IPartModels partModels() - { - return this.partModels; - } + @Override + public IPartModels partModels() { + return this.partModels; + } } diff --git a/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java b/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java index d62fa3871..909f97788 100644 --- a/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java +++ b/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java @@ -19,44 +19,37 @@ package appeng.core.features.registries; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.item.ItemStack; - import appeng.api.features.IItemComparison; import appeng.api.features.IItemComparisonProvider; import appeng.api.features.ISpecialComparisonRegistry; +import net.minecraft.item.ItemStack; + +import java.util.ArrayList; +import java.util.List; -public class SpecialComparisonRegistry implements ISpecialComparisonRegistry -{ +public class SpecialComparisonRegistry implements ISpecialComparisonRegistry { - private final List CompRegistry; + private final List CompRegistry; - public SpecialComparisonRegistry() - { - this.CompRegistry = new ArrayList<>(); - } + public SpecialComparisonRegistry() { + this.CompRegistry = new ArrayList<>(); + } - @Override - public IItemComparison getSpecialComparison( final ItemStack stack ) - { - for( final IItemComparisonProvider i : this.CompRegistry ) - { - final IItemComparison comp = i.getComparison( stack ); - if( comp != null ) - { - return comp; - } - } + @Override + public IItemComparison getSpecialComparison(final ItemStack stack) { + for (final IItemComparisonProvider i : this.CompRegistry) { + final IItemComparison comp = i.getComparison(stack); + if (comp != null) { + return comp; + } + } - return null; - } + return null; + } - @Override - public void addComparisonProvider( final IItemComparisonProvider prov ) - { - this.CompRegistry.add( prov ); - } + @Override + public void addComparisonProvider(final IItemComparisonProvider prov) { + this.CompRegistry.add(prov); + } } diff --git a/src/main/java/appeng/core/features/registries/WirelessRegistry.java b/src/main/java/appeng/core/features/registries/WirelessRegistry.java index 3a32ea3a9..35690001d 100644 --- a/src/main/java/appeng/core/features/registries/WirelessRegistry.java +++ b/src/main/java/appeng/core/features/registries/WirelessRegistry.java @@ -19,13 +19,6 @@ package appeng.core.features.registries; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import appeng.api.AEApi; import appeng.api.features.ILocatable; import appeng.api.features.IWirelessTermHandler; @@ -33,89 +26,77 @@ import appeng.api.features.IWirelessTermRegistry; import appeng.core.localization.PlayerMessages; import appeng.core.sync.GuiBridge; import appeng.util.Platform; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; + +import java.util.ArrayList; +import java.util.List; -public final class WirelessRegistry implements IWirelessTermRegistry -{ - private final List handlers; +public final class WirelessRegistry implements IWirelessTermRegistry { + private final List handlers; - public WirelessRegistry() - { - this.handlers = new ArrayList<>(); - } + public WirelessRegistry() { + this.handlers = new ArrayList<>(); + } - @Override - public void registerWirelessHandler( final IWirelessTermHandler handler ) - { - if( handler != null ) - { - this.handlers.add( handler ); - } - } + @Override + public void registerWirelessHandler(final IWirelessTermHandler handler) { + if (handler != null) { + this.handlers.add(handler); + } + } - @Override - public boolean isWirelessTerminal( final ItemStack is ) - { - for( final IWirelessTermHandler h : this.handlers ) - { - if( h.canHandle( is ) ) - { - return true; - } - } - return false; - } + @Override + public boolean isWirelessTerminal(final ItemStack is) { + for (final IWirelessTermHandler h : this.handlers) { + if (h.canHandle(is)) { + return true; + } + } + return false; + } - @Override - public IWirelessTermHandler getWirelessTerminalHandler( final ItemStack is ) - { - for( final IWirelessTermHandler h : this.handlers ) - { - if( h.canHandle( is ) ) - { - return h; - } - } - return null; - } + @Override + public IWirelessTermHandler getWirelessTerminalHandler(final ItemStack is) { + for (final IWirelessTermHandler h : this.handlers) { + if (h.canHandle(is)) { + return h; + } + } + return null; + } - @Override - public void openWirelessTerminalGui( final ItemStack item, final World w, final EntityPlayer player ) - { - if( Platform.isClient() ) - { - return; - } + @Override + public void openWirelessTerminalGui(final ItemStack item, final World w, final EntityPlayer player) { + if (Platform.isClient()) { + return; + } - if( !this.isWirelessTerminal( item ) ) - { - player.sendMessage( PlayerMessages.DeviceNotWirelessTerminal.get() ); - return; - } + if (!this.isWirelessTerminal(item)) { + player.sendMessage(PlayerMessages.DeviceNotWirelessTerminal.get()); + return; + } - final IWirelessTermHandler handler = this.getWirelessTerminalHandler( item ); - final String unparsedKey = handler.getEncryptionKey( item ); - if( unparsedKey.isEmpty() ) - { - player.sendMessage( PlayerMessages.DeviceNotLinked.get() ); - return; - } + final IWirelessTermHandler handler = this.getWirelessTerminalHandler(item); + final String unparsedKey = handler.getEncryptionKey(item); + if (unparsedKey.isEmpty()) { + player.sendMessage(PlayerMessages.DeviceNotLinked.get()); + return; + } - final long parsedKey = Long.parseLong( unparsedKey ); - final ILocatable securityStation = AEApi.instance().registries().locatable().getLocatableBy( parsedKey ); - if( securityStation == null ) - { - player.sendMessage( PlayerMessages.StationCanNotBeLocated.get() ); - return; - } + final long parsedKey = Long.parseLong(unparsedKey); + final ILocatable securityStation = AEApi.instance().registries().locatable().getLocatableBy(parsedKey); + if (securityStation == null) { + player.sendMessage(PlayerMessages.StationCanNotBeLocated.get()); + return; + } - if( handler.hasPower( player, 0.5, item ) ) - { - Platform.openGUI( player, null, null, GuiBridge.GUI_WIRELESS_TERM ); - } - else - { - player.sendMessage( PlayerMessages.DeviceNotPowered.get() ); - } - } + if (handler.hasPower(player, 0.5, item)) { + Platform.openGUI(player, null, null, GuiBridge.GUI_WIRELESS_TERM); + } else { + player.sendMessage(PlayerMessages.DeviceNotPowered.get()); + } + } } diff --git a/src/main/java/appeng/core/features/registries/WorldGenRegistry.java b/src/main/java/appeng/core/features/registries/WorldGenRegistry.java index 3425cd442..231b96323 100644 --- a/src/main/java/appeng/core/features/registries/WorldGenRegistry.java +++ b/src/main/java/appeng/core/features/registries/WorldGenRegistry.java @@ -19,104 +19,83 @@ package appeng.core.features.registries; -import java.util.HashSet; - +import appeng.api.features.IWorldGen; import net.minecraft.world.World; import net.minecraft.world.WorldProvider; -import appeng.api.features.IWorldGen; +import java.util.HashSet; -public final class WorldGenRegistry implements IWorldGen -{ +public final class WorldGenRegistry implements IWorldGen { - public static final WorldGenRegistry INSTANCE = new WorldGenRegistry(); - private final TypeSet[] types; + public static final WorldGenRegistry INSTANCE = new WorldGenRegistry(); + private final TypeSet[] types; - private WorldGenRegistry() - { + private WorldGenRegistry() { - this.types = new TypeSet[WorldGenType.values().length]; + this.types = new TypeSet[WorldGenType.values().length]; - for( final WorldGenType type : WorldGenType.values() ) - { - this.types[type.ordinal()] = new TypeSet(); - } - } + for (final WorldGenType type : WorldGenType.values()) { + this.types[type.ordinal()] = new TypeSet(); + } + } - @Override - public void disableWorldGenForProviderID( final WorldGenType type, final Class provider ) - { - if( type == null ) - { - throw new IllegalArgumentException( "Bad Type Passed" ); - } + @Override + public void disableWorldGenForProviderID(final WorldGenType type, final Class provider) { + if (type == null) { + throw new IllegalArgumentException("Bad Type Passed"); + } - if( provider == null ) - { - throw new IllegalArgumentException( "Bad Provider Passed" ); - } + if (provider == null) { + throw new IllegalArgumentException("Bad Provider Passed"); + } - this.types[type.ordinal()].badProviders.add( provider ); - } + this.types[type.ordinal()].badProviders.add(provider); + } - @Override - public void enableWorldGenForDimension( final WorldGenType type, final int dimensionID ) - { - if( type == null ) - { - throw new IllegalArgumentException( "Bad Type Passed" ); - } + @Override + public void enableWorldGenForDimension(final WorldGenType type, final int dimensionID) { + if (type == null) { + throw new IllegalArgumentException("Bad Type Passed"); + } - this.types[type.ordinal()].enabledDimensions.add( dimensionID ); - } + this.types[type.ordinal()].enabledDimensions.add(dimensionID); + } - @Override - public void disableWorldGenForDimension( final WorldGenType type, final int dimensionID ) - { - if( type == null ) - { - throw new IllegalArgumentException( "Bad Type Passed" ); - } + @Override + public void disableWorldGenForDimension(final WorldGenType type, final int dimensionID) { + if (type == null) { + throw new IllegalArgumentException("Bad Type Passed"); + } - this.types[type.ordinal()].badDimensions.add( dimensionID ); - } + this.types[type.ordinal()].badDimensions.add(dimensionID); + } - @Override - public boolean isWorldGenEnabled( final WorldGenType type, final World w ) - { - if( type == null ) - { - throw new IllegalArgumentException( "Bad Type Passed" ); - } + @Override + public boolean isWorldGenEnabled(final WorldGenType type, final World w) { + if (type == null) { + throw new IllegalArgumentException("Bad Type Passed"); + } - if( w == null ) - { - throw new IllegalArgumentException( "Bad Provider Passed" ); - } + if (w == null) { + throw new IllegalArgumentException("Bad Provider Passed"); + } - final boolean isBadProvider = this.types[type.ordinal()].badProviders.contains( w.provider.getClass() ); - final boolean isBadDimension = this.types[type.ordinal()].badDimensions.contains( w.provider.getDimension() ); - final boolean isGoodDimension = this.types[type.ordinal()].enabledDimensions.contains( w.provider.getDimension() ); + final boolean isBadProvider = this.types[type.ordinal()].badProviders.contains(w.provider.getClass()); + final boolean isBadDimension = this.types[type.ordinal()].badDimensions.contains(w.provider.getDimension()); + final boolean isGoodDimension = this.types[type.ordinal()].enabledDimensions.contains(w.provider.getDimension()); - if( isBadProvider || isBadDimension ) - { - return false; - } + if (isBadProvider || isBadDimension) { + return false; + } - if( !isGoodDimension && type == WorldGenType.METEORITES ) - { - return false; - } + return isGoodDimension || type != WorldGenType.METEORITES; + } - return true; - } + private static class TypeSet { - private static class TypeSet - { - - final HashSet> badProviders = new HashSet<>(); - final HashSet badDimensions = new HashSet<>(); - final HashSet enabledDimensions = new HashSet<>(); - } + final HashSet> badProviders = new HashSet<>(); + final HashSet badDimensions = new HashSet<>(); + final HashSet enabledDimensions = new HashSet<>(); + } } diff --git a/src/main/java/appeng/core/features/registries/cell/BasicCellHandler.java b/src/main/java/appeng/core/features/registries/cell/BasicCellHandler.java index c4fba4323..60cbbaf23 100644 --- a/src/main/java/appeng/core/features/registries/cell/BasicCellHandler.java +++ b/src/main/java/appeng/core/features/registries/cell/BasicCellHandler.java @@ -19,36 +19,27 @@ package appeng.core.features.registries.cell; -import net.minecraft.item.ItemStack; - -import appeng.api.storage.ICellHandler; -import appeng.api.storage.ICellInventory; -import appeng.api.storage.ICellInventoryHandler; -import appeng.api.storage.ISaveProvider; -import appeng.api.storage.IStorageChannel; +import appeng.api.storage.*; import appeng.api.storage.data.IAEStack; import appeng.me.storage.BasicCellInventory; import appeng.me.storage.BasicCellInventoryHandler; +import net.minecraft.item.ItemStack; -public class BasicCellHandler implements ICellHandler -{ +public class BasicCellHandler implements ICellHandler { - @Override - public boolean isCell( final ItemStack is ) - { - return BasicCellInventory.isCell( is ); - } + @Override + public boolean isCell(final ItemStack is) { + return BasicCellInventory.isCell(is); + } - @Override - public > ICellInventoryHandler getCellInventory( final ItemStack is, final ISaveProvider container, final IStorageChannel channel ) - { - final ICellInventory inv = BasicCellInventory.createInventory( is, container ); - if( inv == null || inv.getChannel() != channel ) - { - return null; - } - return new BasicCellInventoryHandler<>( inv, channel ); - } + @Override + public > ICellInventoryHandler getCellInventory(final ItemStack is, final ISaveProvider container, final IStorageChannel channel) { + final ICellInventory inv = BasicCellInventory.createInventory(is, container); + if (inv == null || inv.getChannel() != channel) { + return null; + } + return new BasicCellInventoryHandler<>(inv, channel); + } } diff --git a/src/main/java/appeng/core/features/registries/cell/BasicItemCellGuiHandler.java b/src/main/java/appeng/core/features/registries/cell/BasicItemCellGuiHandler.java index bdb7e595c..b4a0e3599 100644 --- a/src/main/java/appeng/core/features/registries/cell/BasicItemCellGuiHandler.java +++ b/src/main/java/appeng/core/features/registries/cell/BasicItemCellGuiHandler.java @@ -1,11 +1,6 @@ - package appeng.core.features.registries.cell; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - import appeng.api.AEApi; import appeng.api.implementations.tiles.IChestOrDrive; import appeng.api.storage.ICellGuiHandler; @@ -17,19 +12,19 @@ import appeng.api.storage.data.IAEStack; import appeng.api.util.AEPartLocation; import appeng.core.sync.GuiBridge; import appeng.util.Platform; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; -public class BasicItemCellGuiHandler implements ICellGuiHandler -{ - @Override - public > boolean isHandlerFor( final IStorageChannel channel ) - { - return channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } +public class BasicItemCellGuiHandler implements ICellGuiHandler { + @Override + public > boolean isHandlerFor(final IStorageChannel channel) { + return channel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } - @Override - public void openChestGui( final EntityPlayer player, final IChestOrDrive chest, final ICellHandler cellHandler, final IMEInventoryHandler inv, final ItemStack is, final IStorageChannel chan ) - { - Platform.openGUI( player, (TileEntity) chest, AEPartLocation.fromFacing( chest.getUp() ), GuiBridge.GUI_ME ); - } + @Override + public void openChestGui(final EntityPlayer player, final IChestOrDrive chest, final ICellHandler cellHandler, final IMEInventoryHandler inv, final ItemStack is, final IStorageChannel chan) { + Platform.openGUI(player, (TileEntity) chest, AEPartLocation.fromFacing(chest.getUp()), GuiBridge.GUI_ME); + } } diff --git a/src/main/java/appeng/core/features/registries/cell/CellRegistry.java b/src/main/java/appeng/core/features/registries/cell/CellRegistry.java index 11619891e..1aaba666c 100644 --- a/src/main/java/appeng/core/features/registries/cell/CellRegistry.java +++ b/src/main/java/appeng/core/features/registries/cell/CellRegistry.java @@ -19,124 +19,96 @@ package appeng.core.features.registries.cell; +import appeng.api.storage.*; +import appeng.api.storage.data.IAEStack; +import com.google.common.base.Preconditions; +import com.google.common.base.Verify; +import net.minecraft.item.ItemStack; + import java.util.ArrayList; import java.util.List; -import com.google.common.base.Preconditions; -import com.google.common.base.Verify; -import net.minecraft.item.ItemStack; +public class CellRegistry implements ICellRegistry { -import appeng.api.storage.ICellGuiHandler; -import appeng.api.storage.ICellHandler; -import appeng.api.storage.ICellInventoryHandler; -import appeng.api.storage.ICellRegistry; -import appeng.api.storage.ISaveProvider; -import appeng.api.storage.IStorageChannel; -import appeng.api.storage.data.IAEStack; + private final List handlers; + private final List guiHandlers; + public CellRegistry() { + this.handlers = new ArrayList<>(); + this.guiHandlers = new ArrayList<>(); + } -public class CellRegistry implements ICellRegistry -{ + @Override + public void addCellHandler(final ICellHandler handler) { + Preconditions.checkNotNull(handler, "Called before FMLInitializationEvent."); + Preconditions.checkArgument(!this.handlers.contains(handler), "Tried to register the same handler instance twice."); - private final List handlers; - private final List guiHandlers; + this.handlers.add(handler); - public CellRegistry() - { - this.handlers = new ArrayList<>(); - this.guiHandlers = new ArrayList<>(); - } + // Verify that the first entry is always our own handler. + Verify.verify(this.handlers.get(0) instanceof BasicCellHandler); + } - @Override - public void addCellHandler( final ICellHandler handler ) - { - Preconditions.checkNotNull( handler, "Called before FMLInitializationEvent." ); - Preconditions.checkArgument( !this.handlers.contains( handler ), "Tried to register the same handler instance twice." ); + @Override + public boolean isCellHandled(final ItemStack is) { + if (is.isEmpty()) { + return false; + } + for (final ICellHandler ch : this.handlers) { + if (ch.isCell(is)) { + return true; + } + } + return false; + } - this.handlers.add( handler ); + @Override + public ICellHandler getHandler(final ItemStack is) { + if (is.isEmpty()) { + return null; + } + for (final ICellHandler ch : this.handlers) { + if (ch.isCell(is)) { + return ch; + } + } + return null; + } - // Verify that the first entry is always our own handler. - Verify.verify( this.handlers.get( 0 ) instanceof BasicCellHandler ); - } + @Override + public > ICellInventoryHandler getCellInventory(final ItemStack is, final ISaveProvider container, final IStorageChannel chan) { + if (is.isEmpty()) { + return null; + } + for (final ICellHandler ch : this.handlers) { + if (ch.isCell(is)) { + return ch.getCellInventory(is, container, chan); + } + } + return null; + } - @Override - public boolean isCellHandled( final ItemStack is ) - { - if( is.isEmpty() ) - { - return false; - } - for( final ICellHandler ch : this.handlers ) - { - if( ch.isCell( is ) ) - { - return true; - } - } - return false; - } + @Override + public void addCellGuiHandler(ICellGuiHandler handler) { + this.guiHandlers.add(handler); + } - @Override - public ICellHandler getHandler( final ItemStack is ) - { - if( is.isEmpty() ) - { - return null; - } - for( final ICellHandler ch : this.handlers ) - { - if( ch.isCell( is ) ) - { - return ch; - } - } - return null; - } + @Override + public > ICellGuiHandler getGuiHandler(final IStorageChannel channel, final ItemStack is) { + ICellGuiHandler fallBack = null; - @Override - public > ICellInventoryHandler getCellInventory( final ItemStack is, final ISaveProvider container, final IStorageChannel chan ) - { - if( is.isEmpty() ) - { - return null; - } - for( final ICellHandler ch : this.handlers ) - { - if( ch.isCell( is ) ) - { - return ch.getCellInventory( is, container, chan ); - } - } - return null; - } + for (final ICellGuiHandler ch : this.guiHandlers) { + if (ch.isHandlerFor(channel)) { + if (ch.isSpecializedFor(is)) { + return ch; + } - @Override - public void addCellGuiHandler( ICellGuiHandler handler ) - { - this.guiHandlers.add( handler ); - } - - @Override - public > ICellGuiHandler getGuiHandler( final IStorageChannel channel, final ItemStack is ) - { - ICellGuiHandler fallBack = null; - - for( final ICellGuiHandler ch : this.guiHandlers ) - { - if( ch.isHandlerFor( channel ) ) - { - if( ch.isSpecializedFor( is ) ) - { - return ch; - } - - if( fallBack == null ) - { - fallBack = ch; - } - } - } - return fallBack; - } + if (fallBack == null) { + fallBack = ch; + } + } + } + return fallBack; + } } diff --git a/src/main/java/appeng/core/features/registries/cell/CreativeCellHandler.java b/src/main/java/appeng/core/features/registries/cell/CreativeCellHandler.java index 4a9f3e81c..f91f7a778 100644 --- a/src/main/java/appeng/core/features/registries/cell/CreativeCellHandler.java +++ b/src/main/java/appeng/core/features/registries/cell/CreativeCellHandler.java @@ -19,8 +19,6 @@ package appeng.core.features.registries.cell; -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.api.storage.ICellHandler; import appeng.api.storage.ICellInventoryHandler; @@ -29,37 +27,32 @@ import appeng.api.storage.IStorageChannel; import appeng.api.storage.channels.IItemStorageChannel; import appeng.items.storage.ItemCreativeStorageCell; import appeng.me.storage.CreativeCellInventory; +import net.minecraft.item.ItemStack; -public final class CreativeCellHandler implements ICellHandler -{ +public final class CreativeCellHandler implements ICellHandler { - @Override - public boolean isCell( final ItemStack is ) - { - return !is.isEmpty() && is.getItem() instanceof ItemCreativeStorageCell; - } + @Override + public boolean isCell(final ItemStack is) { + return !is.isEmpty() && is.getItem() instanceof ItemCreativeStorageCell; + } - @Override - public ICellInventoryHandler getCellInventory( final ItemStack is, final ISaveProvider container, final IStorageChannel channel ) - { - if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) && !is.isEmpty() && is - .getItem() instanceof ItemCreativeStorageCell ) - { - return CreativeCellInventory.getCell( is ); - } - return null; - } + @Override + public ICellInventoryHandler getCellInventory(final ItemStack is, final ISaveProvider container, final IStorageChannel channel) { + if (channel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class) && !is.isEmpty() && is + .getItem() instanceof ItemCreativeStorageCell) { + return CreativeCellInventory.getCell(is); + } + return null; + } - @Override - public int getStatusForCell( final ItemStack is, final ICellInventoryHandler handler ) - { - return 2; - } + @Override + public int getStatusForCell(final ItemStack is, final ICellInventoryHandler handler) { + return 2; + } - @Override - public double cellIdleDrain( final ItemStack is, final ICellInventoryHandler handler ) - { - return 0; - } + @Override + public double cellIdleDrain(final ItemStack is, final ICellInventoryHandler handler) { + return 0; + } } diff --git a/src/main/java/appeng/core/features/registries/charger/ChargerRegistry.java b/src/main/java/appeng/core/features/registries/charger/ChargerRegistry.java index 743252db4..7cd8ddc3b 100644 --- a/src/main/java/appeng/core/features/registries/charger/ChargerRegistry.java +++ b/src/main/java/appeng/core/features/registries/charger/ChargerRegistry.java @@ -19,57 +19,49 @@ package appeng.core.features.registries.charger; -import java.util.IdentityHashMap; -import java.util.Map; +import appeng.api.features.IChargerRegistry; +import com.google.common.base.Preconditions; +import net.minecraft.item.Item; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; - -import com.google.common.base.Preconditions; - -import net.minecraft.item.Item; - -import appeng.api.features.IChargerRegistry; +import java.util.IdentityHashMap; +import java.util.Map; -public class ChargerRegistry implements IChargerRegistry -{ - private static final double DEFAULT_CHARGE_RATE = 160d; - private static final double CAPPED_CHARGE_RATE = 16000d; +public class ChargerRegistry implements IChargerRegistry { + private static final double DEFAULT_CHARGE_RATE = 160d; + private static final double CAPPED_CHARGE_RATE = 16000d; - private final Map chargeRates; + private final Map chargeRates; - public ChargerRegistry() - { - this.chargeRates = new IdentityHashMap<>(); - } + public ChargerRegistry() { + this.chargeRates = new IdentityHashMap<>(); + } - @Override - @Nonnegative - public double getChargeRate( @Nonnull Item item ) - { - Preconditions.checkNotNull( item ); + @Override + @Nonnegative + public double getChargeRate(@Nonnull Item item) { + Preconditions.checkNotNull(item); - return this.chargeRates.getOrDefault( item, DEFAULT_CHARGE_RATE ); - } + return this.chargeRates.getOrDefault(item, DEFAULT_CHARGE_RATE); + } - @Override - public void addChargeRate( @Nonnull Item item, @Nonnegative double value ) - { - Preconditions.checkNotNull( item ); - Preconditions.checkArgument( value > 0d ); + @Override + public void addChargeRate(@Nonnull Item item, @Nonnegative double value) { + Preconditions.checkNotNull(item); + Preconditions.checkArgument(value > 0d); - final double cappedValue = Math.min( value, CAPPED_CHARGE_RATE ); + final double cappedValue = Math.min(value, CAPPED_CHARGE_RATE); - this.chargeRates.put( item, cappedValue ); - } + this.chargeRates.put(item, cappedValue); + } - @Override - public void removeChargeRate( @Nonnull Item item ) - { - Preconditions.checkNotNull( item ); + @Override + public void removeChargeRate(@Nonnull Item item) { + Preconditions.checkNotNull(item); - this.chargeRates.remove( item ); - } + this.chargeRates.remove(item); + } } diff --git a/src/main/java/appeng/core/features/registries/grinder/AppEngGrinderRecipe.java b/src/main/java/appeng/core/features/registries/grinder/AppEngGrinderRecipe.java index 5aeed1336..d3f210e48 100644 --- a/src/main/java/appeng/core/features/registries/grinder/AppEngGrinderRecipe.java +++ b/src/main/java/appeng/core/features/registries/grinder/AppEngGrinderRecipe.java @@ -19,90 +19,78 @@ package appeng.core.features.registries.grinder; -import java.util.Optional; - +import appeng.api.features.IGrinderRecipe; import net.minecraft.item.ItemStack; -import appeng.api.features.IGrinderRecipe; +import java.util.Optional; -public class AppEngGrinderRecipe implements IGrinderRecipe -{ +public class AppEngGrinderRecipe implements IGrinderRecipe { - private final ItemStack in; - private final ItemStack out; + private final ItemStack in; + private final ItemStack out; - private final float optionalChance; - private final Optional optionalOutput; + private final float optionalChance; + private final Optional optionalOutput; - private final float optionalChance2; - private final Optional optionalOutput2; + private final float optionalChance2; + private final Optional optionalOutput2; - private final int turns; + private final int turns; - AppEngGrinderRecipe( final ItemStack input, final ItemStack output, final int cost ) - { - this( input, output, null, null, 0, 0, cost ); - } + AppEngGrinderRecipe(final ItemStack input, final ItemStack output, final int cost) { + this(input, output, null, null, 0, 0, cost); + } - AppEngGrinderRecipe( final ItemStack input, final ItemStack output, final ItemStack optional, final float chance, final int cost ) - { - this( input, output, optional, null, chance, 0, cost ); - } + AppEngGrinderRecipe(final ItemStack input, final ItemStack output, final ItemStack optional, final float chance, final int cost) { + this(input, output, optional, null, chance, 0, cost); + } - AppEngGrinderRecipe( final ItemStack input, final ItemStack output, final ItemStack optional1, final ItemStack optional2, final float chance1, final float chance2, final int cost ) - { - this.in = input; - this.out = output; + AppEngGrinderRecipe(final ItemStack input, final ItemStack output, final ItemStack optional1, final ItemStack optional2, final float chance1, final float chance2, final int cost) { + this.in = input; + this.out = output; - this.optionalOutput = Optional.ofNullable( optional1 ); - this.optionalChance = chance1; + this.optionalOutput = Optional.ofNullable(optional1); + this.optionalChance = chance1; - this.optionalOutput2 = Optional.ofNullable( optional2 ); - this.optionalChance2 = chance2; + this.optionalOutput2 = Optional.ofNullable(optional2); + this.optionalChance2 = chance2; - this.turns = cost; - } + this.turns = cost; + } - @Override - public ItemStack getInput() - { - return this.in; - } + @Override + public ItemStack getInput() { + return this.in; + } - @Override - public ItemStack getOutput() - { - return this.out; - } + @Override + public ItemStack getOutput() { + return this.out; + } - @Override - public Optional getOptionalOutput() - { - return this.optionalOutput; - } + @Override + public Optional getOptionalOutput() { + return this.optionalOutput; + } - @Override - public Optional getSecondOptionalOutput() - { - return this.optionalOutput2; - } + @Override + public Optional getSecondOptionalOutput() { + return this.optionalOutput2; + } - @Override - public float getOptionalChance() - { - return this.optionalChance; - } + @Override + public float getOptionalChance() { + return this.optionalChance; + } - @Override - public float getSecondOptionalChance() - { - return this.optionalChance2; - } + @Override + public float getSecondOptionalChance() { + return this.optionalChance2; + } - @Override - public int getRequiredTurns() - { - return this.turns; - } + @Override + public int getRequiredTurns() { + return this.turns; + } } diff --git a/src/main/java/appeng/core/features/registries/grinder/GrinderRecipeManager.java b/src/main/java/appeng/core/features/registries/grinder/GrinderRecipeManager.java index 9977f6c73..91f834025 100644 --- a/src/main/java/appeng/core/features/registries/grinder/GrinderRecipeManager.java +++ b/src/main/java/appeng/core/features/registries/grinder/GrinderRecipeManager.java @@ -19,481 +19,406 @@ package appeng.core.features.registries.grinder; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Map.Entry; - -import javax.annotation.Nonnull; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Maps; - -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import appeng.api.features.IGrinderRecipe; -import appeng.api.features.IGrinderRecipeBuilder; -import appeng.api.features.IGrinderRegistry; -import appeng.api.features.IInscriberRecipe; -import appeng.api.features.IInscriberRecipeBuilder; +import appeng.api.features.*; import appeng.core.AEConfig; import appeng.core.AELog; import appeng.recipes.ores.IOreListener; import appeng.recipes.ores.OreDictionaryHandler; import appeng.util.Platform; +import com.google.common.base.Preconditions; +import com.google.common.collect.Maps; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import javax.annotation.Nonnull; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; -public final class GrinderRecipeManager implements IGrinderRegistry, IOreListener -{ - private final Map recipes; - private final Map ores; - private final Map ingots; - private final Map dusts; - private final Map dustToOreRatio; - public GrinderRecipeManager() - { - this.recipes = Maps.newHashMap(); - this.ores = Maps.newHashMap(); - this.ingots = Maps.newHashMap(); - this.dusts = Maps.newHashMap(); - this.dustToOreRatio = Maps.newHashMap(); +public final class GrinderRecipeManager implements IGrinderRegistry, IOreListener { + private final Map recipes; + private final Map ores; + private final Map ingots; + private final Map dusts; + private final Map dustToOreRatio; - this.addDustRatio( "Obsidian", 1 ); - this.addDustRatio( "Charcoal", 1 ); - this.addDustRatio( "Coal", 1 ); + public GrinderRecipeManager() { + this.recipes = Maps.newHashMap(); + this.ores = Maps.newHashMap(); + this.ingots = Maps.newHashMap(); + this.dusts = Maps.newHashMap(); + this.dustToOreRatio = Maps.newHashMap(); - this.addOre( "Coal", new ItemStack( Items.COAL ) ); - this.addOre( "Charcoal", new ItemStack( Items.COAL, 1, 1 ) ); + this.addDustRatio("Obsidian", 1); + this.addDustRatio("Charcoal", 1); + this.addDustRatio("Coal", 1); - this.addOre( "NetherQuartz", new ItemStack( Blocks.QUARTZ_ORE ) ); - this.addIngot( "NetherQuartz", new ItemStack( Items.QUARTZ ) ); + this.addOre("Coal", new ItemStack(Items.COAL)); + this.addOre("Charcoal", new ItemStack(Items.COAL, 1, 1)); - this.addOre( "Gold", new ItemStack( Blocks.GOLD_ORE ) ); - this.addIngot( "Gold", new ItemStack( Items.GOLD_INGOT ) ); + this.addOre("NetherQuartz", new ItemStack(Blocks.QUARTZ_ORE)); + this.addIngot("NetherQuartz", new ItemStack(Items.QUARTZ)); - this.addOre( "Iron", new ItemStack( Blocks.IRON_ORE ) ); - this.addIngot( "Iron", new ItemStack( Items.IRON_INGOT ) ); - - this.addOre( "Obsidian", new ItemStack( Blocks.OBSIDIAN ) ); - - this.addIngot( "Ender", new ItemStack( Items.ENDER_PEARL ) ); - this.addIngot( "EnderPearl", new ItemStack( Items.ENDER_PEARL ) ); - - this.addIngot( "Wheat", new ItemStack( Items.WHEAT ) ); - - OreDictionaryHandler.INSTANCE.observe( this ); - } - - @Override - public IGrinderRecipeBuilder builder() - { - return new Builder(); - } - - @Override - public boolean addRecipe( IGrinderRecipe recipe ) - { - Preconditions.checkNotNull( recipe, "Cannot add null as recipe." ); - - return this.injectRecipe( recipe ); - } - - @Override - public Collection getRecipes() - { - return Collections.unmodifiableCollection( this.recipes.values() ); - } - - @Override - public boolean removeRecipe( IGrinderRecipe recipe ) - { - Preconditions.checkNotNull( recipe, "Cannot remove null as recipe." ); - - final CacheKey key = new CacheKey( recipe.getInput() ); - final IGrinderRecipe removedRecipe = this.recipes.remove( key ); - - this.log( "Removed Grinding of '%1%s'", Platform.getItemDisplayName( recipe.getInput() ) ); - - return removedRecipe != null; - } - - @Override - public IGrinderRecipe getRecipeForInput( final ItemStack input ) - { - this.log( "Looking up recipe for '%1$s'", Platform.getItemDisplayName( input ) ); - - if( input == null ) - { - return null; - } - - final IGrinderRecipe recipe = this.recipes.get( new CacheKey( input ) ); - - if( recipe == null ) - { - return null; - } - - this.log( "Recipe for '%1$s' found '%2$s'", input.getUnlocalizedName(), Platform.getItemDisplayName( recipe.getOutput() ) ); - return recipe; - } - - @Override - public void addDustRatio( String oredictName, int ratio ) - { - Preconditions.checkNotNull( oredictName ); - Preconditions.checkArgument( ratio > 0 ); - - this.log( "Added ratio for '%1$s' of %2$d", oredictName, ratio ); - - this.dustToOreRatio.put( oredictName, ratio ); - } - - @Override - public boolean removeDustRatio( String oredictName ) - { - Preconditions.checkNotNull( oredictName ); - - this.log( "Removed ratio for '%1$s'", oredictName ); - - return this.dustToOreRatio.remove( oredictName ) != null; - } - - @Override - public void oreRegistered( final String name, final ItemStack item ) - { - if( !AEConfig.instance().getGrinderBlackList().contains( name ) && ( name.startsWith( "ore" ) || name.startsWith( "crystal" ) || name - .startsWith( "gem" ) || name.startsWith( "ingot" ) || name.startsWith( "dust" ) ) ) - { - for( final String ore : AEConfig.instance().getGrinderOres() ) - { - if( name.equals( "ore" + ore ) ) - { - this.addOre( ore, item ); - } - else if( name.equals( "crystal" + ore ) || name.equals( "ingot" + ore ) || name.equals( "gem" + ore ) ) - { - this.addIngot( ore, item ); - } - else if( name.equals( "dust" + ore ) ) - { - this.addDust( ore, item ); - } - } - } - } - - private boolean injectRecipe( final IGrinderRecipe grinderRecipe ) - { - final CacheKey cacheKey = new CacheKey( grinderRecipe.getInput() ); - - if( this.recipes.containsKey( cacheKey ) ) - { - this.log( "Tried to add duplicate recipe for '%1$s'", Platform.getItemDisplayName( grinderRecipe.getInput() ) ); - return false; - } - - this.recipes.put( cacheKey, grinderRecipe ); - - return true; - } - - private int getDustToOreRatio( final String name ) - { - return this.dustToOreRatio.getOrDefault( name, 2 ); - } - - private void addOre( final String name, final ItemStack item ) - { - if( item == null ) - { - return; - } - this.log( "Adding Ore: '%1$s'", Platform.getItemDisplayName( item ) ); - - this.ores.put( item, name ); - - if( this.dusts.containsKey( name ) ) - { - final ItemStack is = this.dusts.get( name ).copy(); - final int ratio = this.getDustToOreRatio( name ); - if( ratio > 1 ) - { - final ItemStack extra = is.copy(); - extra.setCount( ratio - 1 ); - - final IGrinderRecipeBuilder builder = this.builder(); - IGrinderRecipe grinderRecipe = builder.withInput( item ) - .withOutput( is ) - .withFirstOptional( extra, (float) ( AEConfig.instance().getOreDoublePercentage() / 100.0 ) ) - .withTurns( 8 ) - .build(); - - this.addRecipe( grinderRecipe ); - } - else - { - final IGrinderRecipeBuilder builder = this.builder(); - IGrinderRecipe grinderRecipe = builder.withInput( item ) - .withOutput( is ) - .withTurns( 8 ) - .build(); - - this.addRecipe( grinderRecipe ); - } - } - } - - private void addIngot( final String name, final ItemStack item ) - { - if( item == null ) - { - return; - } - this.log( "Adding Ingot: '%1$s'", Platform.getItemDisplayName( item ) ); - - this.ingots.put( item, name ); - - if( this.dusts.containsKey( name ) ) - { - final IGrinderRecipeBuilder builder = this.builder(); - IGrinderRecipe grinderRecipe = builder.withInput( item ) - .withOutput( this.dusts.get( name ) ) - .withTurns( 4 ) - .build(); - - this.addRecipe( grinderRecipe ); - } - } - - private void addDust( final String name, final ItemStack item ) - { - if( item == null ) - { - return; - } - - if( this.dusts.containsKey( name ) ) - { - this.log( "Rejecting Dust: '%1$s'", Platform.getItemDisplayName( item ) ); - return; - } - - this.log( "Adding Dust: '%1$s'", Platform.getItemDisplayName( item ) ); - - this.dusts.put( name, item ); - - for( final Entry d : this.ores.entrySet() ) - { - if( name.equals( d.getValue() ) ) - { - final ItemStack is = item.copy(); - is.setCount( 1 ); - final int ratio = this.getDustToOreRatio( name ); - if( ratio > 1 ) - { - final ItemStack extra = is.copy(); - extra.setCount( ratio - 1 ); - - final IGrinderRecipeBuilder builder = this.builder(); - final IGrinderRecipe grinderRecipe = builder.withInput( d.getKey() ) - .withOutput( is ) - .withFirstOptional( extra, (float) ( AEConfig.instance().getOreDoublePercentage() / 100.0 ) ) - .withTurns( 8 ) - .build(); - - this.addRecipe( grinderRecipe ); - } - else - { - final IGrinderRecipeBuilder builder = this.builder(); - final IGrinderRecipe grinderRecipe = builder.withInput( d.getKey() ) - .withOutput( is ) - .withTurns( 8 ) - .build(); - - this.addRecipe( grinderRecipe ); - } - } - } - - for( final Entry d : this.ingots.entrySet() ) - { - if( name.equals( d.getValue() ) ) - { - final IGrinderRecipeBuilder builder = this.builder(); - final IGrinderRecipe grinderRecipe = builder.withInput( d.getKey() ) - .withOutput( item ) - .withTurns( 4 ) - .build(); - - this.addRecipe( grinderRecipe ); - } - } - } - - private void log( final String o, Object... params ) - { - AELog.grinder( o, params ); - } - - private static class CacheKey - { - private final Item item; - private final int damage; - - CacheKey( ItemStack input ) - { - Preconditions.checkNotNull( input ); - Preconditions.checkNotNull( input.getItem() ); - - this.item = input.getItem(); - this.damage = input.getItemDamage(); - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + this.damage; - result = prime * result + ( ( this.item == null ) ? 0 : this.item.hashCode() ); - return result; - } - - @Override - public boolean equals( Object obj ) - { - if( this == obj ) - { - return true; - } - if( obj == null || this.getClass() != obj.getClass() ) - { - return false; - } - - CacheKey other = (CacheKey) obj; - - if( this.damage != other.damage ) - { - return false; - } - - if( this.item == null ) - { - if( other.item != null ) - { - return false; - } - } - else if( this.item != other.item ) - { - return false; - } - - return true; - } - - } - - /** - * Internal {@link IInscriberRecipeBuilder} implementation. - * Needs to be adapted to represent a correct {@link IInscriberRecipe} - */ - private static final class Builder implements IGrinderRecipeBuilder - { - - private ItemStack in; - private ItemStack out; - - private float optionalChance; - private ItemStack optionalOutput; - - private float optionalChance2; - private ItemStack optionalOutput2; - - private int turns = 8; - - @Override - public IGrinderRecipeBuilder withInput( ItemStack input ) - { - Preconditions.checkNotNull( input ); - Preconditions.checkArgument( !input.isEmpty(), "Input cannot be empty." ); - - this.in = this.copy( input ); - - return this; - } - - @Override - public IGrinderRecipeBuilder withOutput( ItemStack output ) - { - Preconditions.checkNotNull( output ); - Preconditions.checkArgument( !output.isEmpty(), "Output cannot be empty." ); - - this.out = this.copy( output ); - - return this; - } - - @Override - public IGrinderRecipeBuilder withFirstOptional( ItemStack optional, float chance ) - { - Preconditions.checkNotNull( optional ); - Preconditions.checkArgument( !optional.isEmpty(), "Optional cannot be empty." ); - Preconditions.checkArgument( chance >= 0 && chance <= 1.0 ); - - this.optionalOutput = this.copy( optional ); - this.optionalChance = chance; - - return this; - } - - @Override - public IGrinderRecipeBuilder withSecondOptional( ItemStack optional, float chance ) - { - Preconditions.checkNotNull( optional ); - Preconditions.checkArgument( !optional.isEmpty(), "Optional cannot be empty." ); - Preconditions.checkArgument( chance >= 0 && chance <= 1.0 ); - - this.optionalOutput2 = this.copy( optional ); - this.optionalChance2 = chance; - - return this; - } - - @Override - public IGrinderRecipeBuilder withTurns( int turns ) - { - Preconditions.checkArgument( turns > 0 ); - - this.turns = turns; - - return this; - } - - @Nonnull - @Override - public IGrinderRecipe build() - { - Preconditions.checkState( this.in != null, "Input itemstack must be defined." ); - Preconditions.checkState( this.out != null, "Output itemstack must be defined." ); - - return new AppEngGrinderRecipe( this.in, this.out, this.optionalOutput, this.optionalOutput2, this.optionalChance, this.optionalChance2, this.turns ); - } - - private ItemStack copy( final ItemStack is ) - { - if( is != null ) - { - return is.copy(); - } - return null; - } - } + this.addOre("Gold", new ItemStack(Blocks.GOLD_ORE)); + this.addIngot("Gold", new ItemStack(Items.GOLD_INGOT)); + + this.addOre("Iron", new ItemStack(Blocks.IRON_ORE)); + this.addIngot("Iron", new ItemStack(Items.IRON_INGOT)); + + this.addOre("Obsidian", new ItemStack(Blocks.OBSIDIAN)); + + this.addIngot("Ender", new ItemStack(Items.ENDER_PEARL)); + this.addIngot("EnderPearl", new ItemStack(Items.ENDER_PEARL)); + + this.addIngot("Wheat", new ItemStack(Items.WHEAT)); + + OreDictionaryHandler.INSTANCE.observe(this); + } + + @Override + public IGrinderRecipeBuilder builder() { + return new Builder(); + } + + @Override + public boolean addRecipe(IGrinderRecipe recipe) { + Preconditions.checkNotNull(recipe, "Cannot add null as recipe."); + + return this.injectRecipe(recipe); + } + + @Override + public Collection getRecipes() { + return Collections.unmodifiableCollection(this.recipes.values()); + } + + @Override + public boolean removeRecipe(IGrinderRecipe recipe) { + Preconditions.checkNotNull(recipe, "Cannot remove null as recipe."); + + final CacheKey key = new CacheKey(recipe.getInput()); + final IGrinderRecipe removedRecipe = this.recipes.remove(key); + + this.log("Removed Grinding of '%1%s'", Platform.getItemDisplayName(recipe.getInput())); + + return removedRecipe != null; + } + + @Override + public IGrinderRecipe getRecipeForInput(final ItemStack input) { + this.log("Looking up recipe for '%1$s'", Platform.getItemDisplayName(input)); + + if (input == null) { + return null; + } + + final IGrinderRecipe recipe = this.recipes.get(new CacheKey(input)); + + if (recipe == null) { + return null; + } + + this.log("Recipe for '%1$s' found '%2$s'", input.getUnlocalizedName(), Platform.getItemDisplayName(recipe.getOutput())); + return recipe; + } + + @Override + public void addDustRatio(String oredictName, int ratio) { + Preconditions.checkNotNull(oredictName); + Preconditions.checkArgument(ratio > 0); + + this.log("Added ratio for '%1$s' of %2$d", oredictName, ratio); + + this.dustToOreRatio.put(oredictName, ratio); + } + + @Override + public boolean removeDustRatio(String oredictName) { + Preconditions.checkNotNull(oredictName); + + this.log("Removed ratio for '%1$s'", oredictName); + + return this.dustToOreRatio.remove(oredictName) != null; + } + + @Override + public void oreRegistered(final String name, final ItemStack item) { + if (!AEConfig.instance().getGrinderBlackList().contains(name) && (name.startsWith("ore") || name.startsWith("crystal") || name + .startsWith("gem") || name.startsWith("ingot") || name.startsWith("dust"))) { + for (final String ore : AEConfig.instance().getGrinderOres()) { + if (name.equals("ore" + ore)) { + this.addOre(ore, item); + } else if (name.equals("crystal" + ore) || name.equals("ingot" + ore) || name.equals("gem" + ore)) { + this.addIngot(ore, item); + } else if (name.equals("dust" + ore)) { + this.addDust(ore, item); + } + } + } + } + + private boolean injectRecipe(final IGrinderRecipe grinderRecipe) { + final CacheKey cacheKey = new CacheKey(grinderRecipe.getInput()); + + if (this.recipes.containsKey(cacheKey)) { + this.log("Tried to add duplicate recipe for '%1$s'", Platform.getItemDisplayName(grinderRecipe.getInput())); + return false; + } + + this.recipes.put(cacheKey, grinderRecipe); + + return true; + } + + private int getDustToOreRatio(final String name) { + return this.dustToOreRatio.getOrDefault(name, 2); + } + + private void addOre(final String name, final ItemStack item) { + if (item == null) { + return; + } + this.log("Adding Ore: '%1$s'", Platform.getItemDisplayName(item)); + + this.ores.put(item, name); + + if (this.dusts.containsKey(name)) { + final ItemStack is = this.dusts.get(name).copy(); + final int ratio = this.getDustToOreRatio(name); + if (ratio > 1) { + final ItemStack extra = is.copy(); + extra.setCount(ratio - 1); + + final IGrinderRecipeBuilder builder = this.builder(); + IGrinderRecipe grinderRecipe = builder.withInput(item) + .withOutput(is) + .withFirstOptional(extra, (float) (AEConfig.instance().getOreDoublePercentage() / 100.0)) + .withTurns(8) + .build(); + + this.addRecipe(grinderRecipe); + } else { + final IGrinderRecipeBuilder builder = this.builder(); + IGrinderRecipe grinderRecipe = builder.withInput(item) + .withOutput(is) + .withTurns(8) + .build(); + + this.addRecipe(grinderRecipe); + } + } + } + + private void addIngot(final String name, final ItemStack item) { + if (item == null) { + return; + } + this.log("Adding Ingot: '%1$s'", Platform.getItemDisplayName(item)); + + this.ingots.put(item, name); + + if (this.dusts.containsKey(name)) { + final IGrinderRecipeBuilder builder = this.builder(); + IGrinderRecipe grinderRecipe = builder.withInput(item) + .withOutput(this.dusts.get(name)) + .withTurns(4) + .build(); + + this.addRecipe(grinderRecipe); + } + } + + private void addDust(final String name, final ItemStack item) { + if (item == null) { + return; + } + + if (this.dusts.containsKey(name)) { + this.log("Rejecting Dust: '%1$s'", Platform.getItemDisplayName(item)); + return; + } + + this.log("Adding Dust: '%1$s'", Platform.getItemDisplayName(item)); + + this.dusts.put(name, item); + + for (final Entry d : this.ores.entrySet()) { + if (name.equals(d.getValue())) { + final ItemStack is = item.copy(); + is.setCount(1); + final int ratio = this.getDustToOreRatio(name); + if (ratio > 1) { + final ItemStack extra = is.copy(); + extra.setCount(ratio - 1); + + final IGrinderRecipeBuilder builder = this.builder(); + final IGrinderRecipe grinderRecipe = builder.withInput(d.getKey()) + .withOutput(is) + .withFirstOptional(extra, (float) (AEConfig.instance().getOreDoublePercentage() / 100.0)) + .withTurns(8) + .build(); + + this.addRecipe(grinderRecipe); + } else { + final IGrinderRecipeBuilder builder = this.builder(); + final IGrinderRecipe grinderRecipe = builder.withInput(d.getKey()) + .withOutput(is) + .withTurns(8) + .build(); + + this.addRecipe(grinderRecipe); + } + } + } + + for (final Entry d : this.ingots.entrySet()) { + if (name.equals(d.getValue())) { + final IGrinderRecipeBuilder builder = this.builder(); + final IGrinderRecipe grinderRecipe = builder.withInput(d.getKey()) + .withOutput(item) + .withTurns(4) + .build(); + + this.addRecipe(grinderRecipe); + } + } + } + + private void log(final String o, Object... params) { + AELog.grinder(o, params); + } + + private static class CacheKey { + private final Item item; + private final int damage; + + CacheKey(ItemStack input) { + Preconditions.checkNotNull(input); + Preconditions.checkNotNull(input.getItem()); + + this.item = input.getItem(); + this.damage = input.getItemDamage(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + this.damage; + result = prime * result + ((this.item == null) ? 0 : this.item.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || this.getClass() != obj.getClass()) { + return false; + } + + CacheKey other = (CacheKey) obj; + + if (this.damage != other.damage) { + return false; + } + + if (this.item == null) { + return other.item == null; + } else return this.item == other.item; + } + + } + + /** + * Internal {@link IInscriberRecipeBuilder} implementation. + * Needs to be adapted to represent a correct {@link IInscriberRecipe} + */ + private static final class Builder implements IGrinderRecipeBuilder { + + private ItemStack in; + private ItemStack out; + + private float optionalChance; + private ItemStack optionalOutput; + + private float optionalChance2; + private ItemStack optionalOutput2; + + private int turns = 8; + + @Override + public IGrinderRecipeBuilder withInput(ItemStack input) { + Preconditions.checkNotNull(input); + Preconditions.checkArgument(!input.isEmpty(), "Input cannot be empty."); + + this.in = this.copy(input); + + return this; + } + + @Override + public IGrinderRecipeBuilder withOutput(ItemStack output) { + Preconditions.checkNotNull(output); + Preconditions.checkArgument(!output.isEmpty(), "Output cannot be empty."); + + this.out = this.copy(output); + + return this; + } + + @Override + public IGrinderRecipeBuilder withFirstOptional(ItemStack optional, float chance) { + Preconditions.checkNotNull(optional); + Preconditions.checkArgument(!optional.isEmpty(), "Optional cannot be empty."); + Preconditions.checkArgument(chance >= 0 && chance <= 1.0); + + this.optionalOutput = this.copy(optional); + this.optionalChance = chance; + + return this; + } + + @Override + public IGrinderRecipeBuilder withSecondOptional(ItemStack optional, float chance) { + Preconditions.checkNotNull(optional); + Preconditions.checkArgument(!optional.isEmpty(), "Optional cannot be empty."); + Preconditions.checkArgument(chance >= 0 && chance <= 1.0); + + this.optionalOutput2 = this.copy(optional); + this.optionalChance2 = chance; + + return this; + } + + @Override + public IGrinderRecipeBuilder withTurns(int turns) { + Preconditions.checkArgument(turns > 0); + + this.turns = turns; + + return this; + } + + @Nonnull + @Override + public IGrinderRecipe build() { + Preconditions.checkState(this.in != null, "Input itemstack must be defined."); + Preconditions.checkState(this.out != null, "Output itemstack must be defined."); + + return new AppEngGrinderRecipe(this.in, this.out, this.optionalOutput, this.optionalOutput2, this.optionalChance, this.optionalChance2, this.turns); + } + + private ItemStack copy(final ItemStack is) { + if (is != null) { + return is.copy(); + } + return null; + } + } } diff --git a/src/main/java/appeng/core/features/registries/inscriber/InscriberInscribeRecipe.java b/src/main/java/appeng/core/features/registries/inscriber/InscriberInscribeRecipe.java index 0b367f1c8..d70792aa5 100644 --- a/src/main/java/appeng/core/features/registries/inscriber/InscriberInscribeRecipe.java +++ b/src/main/java/appeng/core/features/registries/inscriber/InscriberInscribeRecipe.java @@ -19,14 +19,12 @@ package appeng.core.features.registries.inscriber; -import java.util.Collection; +import appeng.api.features.InscriberProcessType; +import net.minecraft.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; - -import net.minecraft.item.ItemStack; - -import appeng.api.features.InscriberProcessType; +import java.util.Collection; /** @@ -36,10 +34,8 @@ import appeng.api.features.InscriberProcessType; * @version rv2 * @since rv2 */ -public class InscriberInscribeRecipe extends InscriberRecipe -{ - InscriberInscribeRecipe( @Nonnull final Collection inputs, @Nonnull final ItemStack output, @Nullable final ItemStack top, @Nullable final ItemStack bot ) - { - super( inputs, output, top, bot, InscriberProcessType.INSCRIBE ); - } +public class InscriberInscribeRecipe extends InscriberRecipe { + InscriberInscribeRecipe(@Nonnull final Collection inputs, @Nonnull final ItemStack output, @Nullable final ItemStack top, @Nullable final ItemStack bot) { + super(inputs, output, top, bot, InscriberProcessType.INSCRIBE); + } } diff --git a/src/main/java/appeng/core/features/registries/inscriber/InscriberRecipe.java b/src/main/java/appeng/core/features/registries/inscriber/InscriberRecipe.java index 820ae8a55..2c63dd8c1 100644 --- a/src/main/java/appeng/core/features/registries/inscriber/InscriberRecipe.java +++ b/src/main/java/appeng/core/features/registries/inscriber/InscriberRecipe.java @@ -19,19 +19,17 @@ package appeng.core.features.registries.inscriber; +import appeng.api.features.IInscriberRecipe; +import appeng.api.features.InscriberProcessType; +import net.minecraft.item.ItemStack; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import net.minecraft.item.ItemStack; - -import appeng.api.features.IInscriberRecipe; -import appeng.api.features.InscriberProcessType; - /** * Basic inscriber recipe @@ -40,111 +38,96 @@ import appeng.api.features.InscriberProcessType; * @version rv2 * @since rv2 */ -public class InscriberRecipe implements IInscriberRecipe -{ - @Nonnull - private final List inputs; +public class InscriberRecipe implements IInscriberRecipe { + @Nonnull + private final List inputs; - @Nonnull - private final ItemStack output; + @Nonnull + private final ItemStack output; - @Nonnull - private final Optional maybeTop; + @Nonnull + private final Optional maybeTop; - @Nonnull - private final Optional maybeBot; + @Nonnull + private final Optional maybeBot; - @Nonnull - private final InscriberProcessType type; + @Nonnull + private final InscriberProcessType type; - InscriberRecipe( @Nonnull final Collection inputs, @Nonnull final ItemStack output, @Nullable final ItemStack top, @Nullable final ItemStack bot, @Nonnull final InscriberProcessType type ) - { - this.inputs = new ArrayList<>( inputs.size() ); - this.inputs.addAll( inputs ); + InscriberRecipe(@Nonnull final Collection inputs, @Nonnull final ItemStack output, @Nullable final ItemStack top, @Nullable final ItemStack bot, @Nonnull final InscriberProcessType type) { + this.inputs = new ArrayList<>(inputs.size()); + this.inputs.addAll(inputs); - this.output = output; - this.maybeTop = Optional.ofNullable( top ); - this.maybeBot = Optional.ofNullable( bot ); + this.output = output; + this.maybeTop = Optional.ofNullable(top); + this.maybeBot = Optional.ofNullable(bot); - this.type = type; - } + this.type = type; + } - @Nonnull - @Override - public final List getInputs() - { - return this.inputs; - } + @Nonnull + @Override + public final List getInputs() { + return this.inputs; + } - @Nonnull - @Override - public final ItemStack getOutput() - { - return this.output; - } + @Nonnull + @Override + public final ItemStack getOutput() { + return this.output; + } - @Nonnull - @Override - public final Optional getTopOptional() - { - return this.maybeTop; - } + @Nonnull + @Override + public final Optional getTopOptional() { + return this.maybeTop; + } - @Nonnull - @Override - public final Optional getBottomOptional() - { - return this.maybeBot; - } + @Nonnull + @Override + public final Optional getBottomOptional() { + return this.maybeBot; + } - @Nonnull - @Override - public final InscriberProcessType getProcessType() - { - return this.type; - } + @Nonnull + @Override + public final InscriberProcessType getProcessType() { + return this.type; + } - @Override - public boolean equals( final Object o ) - { - if( this == o ) - { - return true; - } - if( !( o instanceof IInscriberRecipe ) ) - { - return false; - } + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (!(o instanceof IInscriberRecipe)) { + return false; + } - final IInscriberRecipe that = (IInscriberRecipe) o; + final IInscriberRecipe that = (IInscriberRecipe) o; - if( !this.inputs.equals( that.getInputs() ) ) - { - return false; - } - if( !this.output.equals( that.getOutput() ) ) - { - return false; - } - if( !this.maybeTop.equals( that.getTopOptional() ) ) - { - return false; - } - if( !this.maybeBot.equals( that.getBottomOptional() ) ) - { - return false; - } - return this.type == that.getProcessType(); - } + if (!this.inputs.equals(that.getInputs())) { + return false; + } + if (!this.output.equals(that.getOutput())) { + return false; + } + if (!this.maybeTop.equals(that.getTopOptional())) { + return false; + } + if (!this.maybeBot.equals(that.getBottomOptional())) { + return false; + } + return this.type == that.getProcessType(); + } - @Override - public int hashCode() - { - int result = this.inputs.hashCode(); - result = 31 * result + this.output.hashCode(); - result = 31 * result + this.maybeTop.hashCode(); - result = 31 * result + this.maybeBot.hashCode(); - result = 31 * result + this.type.hashCode(); - return result; - } + @Override + public int hashCode() { + int result = this.inputs.hashCode(); + result = 31 * result + this.output.hashCode(); + result = 31 * result + this.maybeTop.hashCode(); + result = 31 * result + this.maybeBot.hashCode(); + result = 31 * result + this.type.hashCode(); + return result; + } } diff --git a/src/main/java/appeng/core/features/registries/inscriber/InscriberRegistry.java b/src/main/java/appeng/core/features/registries/inscriber/InscriberRegistry.java index 7bd3e33b2..a3c583e04 100644 --- a/src/main/java/appeng/core/features/registries/inscriber/InscriberRegistry.java +++ b/src/main/java/appeng/core/features/registries/inscriber/InscriberRegistry.java @@ -19,24 +19,15 @@ package appeng.core.features.registries.inscriber; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import javax.annotation.Nonnull; - -import com.google.common.base.Preconditions; - -import net.minecraft.item.ItemStack; - import appeng.api.features.IInscriberRecipe; import appeng.api.features.IInscriberRecipeBuilder; import appeng.api.features.IInscriberRegistry; import appeng.api.features.InscriberProcessType; +import com.google.common.base.Preconditions; +import net.minecraft.item.ItemStack; + +import javax.annotation.Nonnull; +import java.util.*; /** @@ -44,168 +35,150 @@ import appeng.api.features.InscriberProcessType; * @version rv3 * @since rv2 */ -public final class InscriberRegistry implements IInscriberRegistry -{ - private final Set recipes; - private final Set optionals; - private final Set inputs; +public final class InscriberRegistry implements IInscriberRegistry { + private final Set recipes; + private final Set optionals; + private final Set inputs; - public InscriberRegistry() - { - this.inputs = new HashSet<>(); - this.optionals = new HashSet<>(); - this.recipes = new HashSet<>(); - } + public InscriberRegistry() { + this.inputs = new HashSet<>(); + this.optionals = new HashSet<>(); + this.recipes = new HashSet<>(); + } - @Nonnull - @Override - public Collection getRecipes() - { - return Collections.unmodifiableCollection( this.recipes ); - } + @Nonnull + @Override + public Collection getRecipes() { + return Collections.unmodifiableCollection(this.recipes); + } - @Nonnull - @Override - public Set getOptionals() - { - return this.optionals; - } + @Nonnull + @Override + public Set getOptionals() { + return this.optionals; + } - @Nonnull - @Override - public Set getInputs() - { - return this.inputs; - } + @Nonnull + @Override + public Set getInputs() { + return this.inputs; + } - @Nonnull - @Override - public IInscriberRecipeBuilder builder() - { - return new Builder(); - } + @Nonnull + @Override + public IInscriberRecipeBuilder builder() { + return new Builder(); + } - @Override - public boolean addRecipe( final IInscriberRecipe recipe ) - { - Preconditions.checkNotNull( recipe, "Tried to add (null) as inscriber recipe to the registry." ); + @Override + public boolean addRecipe(final IInscriberRecipe recipe) { + Preconditions.checkNotNull(recipe, "Tried to add (null) as inscriber recipe to the registry."); - if( this.recipes.add( recipe ) ) - { - recipe.getTopOptional().ifPresent( this.optionals::add ); - recipe.getBottomOptional().ifPresent( this.optionals::add ); + if (this.recipes.add(recipe)) { + recipe.getTopOptional().ifPresent(this.optionals::add); + recipe.getBottomOptional().ifPresent(this.optionals::add); - this.inputs.addAll( recipe.getInputs() ); + this.inputs.addAll(recipe.getInputs()); - return true; - } + return true; + } - return false; - } + return false; + } - @Override - public boolean removeRecipe( final IInscriberRecipe toBeRemovedRecipe ) - { - Preconditions.checkNotNull( toBeRemovedRecipe, "Tried to remove (null) from the registry." ); + @Override + public boolean removeRecipe(final IInscriberRecipe toBeRemovedRecipe) { + Preconditions.checkNotNull(toBeRemovedRecipe, "Tried to remove (null) from the registry."); - boolean changed = false; + boolean changed = false; - for( final Iterator iterator = this.recipes.iterator(); iterator.hasNext(); ) - { - final IInscriberRecipe recipe = iterator.next(); - if( recipe.equals( toBeRemovedRecipe ) ) - { - changed = true; - iterator.remove(); - } - } + for (final Iterator iterator = this.recipes.iterator(); iterator.hasNext(); ) { + final IInscriberRecipe recipe = iterator.next(); + if (recipe.equals(toBeRemovedRecipe)) { + changed = true; + iterator.remove(); + } + } - return changed; - } + return changed; + } - /** - * Internal {@link IInscriberRecipeBuilder} implementation. - * Needs to be adapted to represent a correct {@link IInscriberRecipe} - */ - private static final class Builder implements IInscriberRecipeBuilder - { - private List inputs; - private ItemStack output; - private ItemStack topOptional; - private ItemStack bottomOptional; - private InscriberProcessType type; + /** + * Internal {@link IInscriberRecipeBuilder} implementation. + * Needs to be adapted to represent a correct {@link IInscriberRecipe} + */ + private static final class Builder implements IInscriberRecipeBuilder { + private List inputs; + private ItemStack output; + private ItemStack topOptional; + private ItemStack bottomOptional; + private InscriberProcessType type; - @Nonnull - @Override - public Builder withInputs( @Nonnull final Collection inputs ) - { - Preconditions.checkNotNull( inputs ); - Preconditions.checkArgument( !inputs.isEmpty() ); + @Nonnull + @Override + public Builder withInputs(@Nonnull final Collection inputs) { + Preconditions.checkNotNull(inputs); + Preconditions.checkArgument(!inputs.isEmpty()); - this.inputs = new ArrayList<>( inputs.size() ); - this.inputs.addAll( inputs ); + this.inputs = new ArrayList<>(inputs.size()); + this.inputs.addAll(inputs); - return this; - } + return this; + } - @Nonnull - @Override - public Builder withOutput( @Nonnull final ItemStack output ) - { - Preconditions.checkNotNull( output ); - Preconditions.checkArgument( !output.isEmpty() ); + @Nonnull + @Override + public Builder withOutput(@Nonnull final ItemStack output) { + Preconditions.checkNotNull(output); + Preconditions.checkArgument(!output.isEmpty()); - this.output = output; + this.output = output; - return this; - } + return this; + } - @Nonnull - @Override - public Builder withTopOptional( @Nonnull final ItemStack topOptional ) - { - Preconditions.checkNotNull( topOptional ); - Preconditions.checkArgument( !topOptional.isEmpty() ); + @Nonnull + @Override + public Builder withTopOptional(@Nonnull final ItemStack topOptional) { + Preconditions.checkNotNull(topOptional); + Preconditions.checkArgument(!topOptional.isEmpty()); - this.topOptional = topOptional; + this.topOptional = topOptional; - return this; - } + return this; + } - @Nonnull - @Override - public Builder withBottomOptional( @Nonnull final ItemStack bottomOptional ) - { - Preconditions.checkNotNull( bottomOptional ); - Preconditions.checkArgument( !bottomOptional.isEmpty() ); + @Nonnull + @Override + public Builder withBottomOptional(@Nonnull final ItemStack bottomOptional) { + Preconditions.checkNotNull(bottomOptional); + Preconditions.checkArgument(!bottomOptional.isEmpty()); - this.bottomOptional = bottomOptional; + this.bottomOptional = bottomOptional; - return this; - } + return this; + } - @Nonnull - @Override - public Builder withProcessType( @Nonnull final InscriberProcessType type ) - { - Preconditions.checkNotNull( type ); + @Nonnull + @Override + public Builder withProcessType(@Nonnull final InscriberProcessType type) { + Preconditions.checkNotNull(type); - this.type = type; + this.type = type; - return this; - } + return this; + } - @Nonnull - @Override - public IInscriberRecipe build() - { - Preconditions.checkState( this.inputs != null, "Input must be defined." ); - Preconditions.checkState( !this.inputs.isEmpty(), "Input must have a size." ); - Preconditions.checkState( !this.output.isEmpty(), "Output cannot be empty." ); - Preconditions.checkState( !this.topOptional.isEmpty() || !this.bottomOptional.isEmpty(), "One optional must be defined." ); - Preconditions.checkState( this.type != null, "Process type must be defined." ); + @Nonnull + @Override + public IInscriberRecipe build() { + Preconditions.checkState(this.inputs != null, "Input must be defined."); + Preconditions.checkState(!this.inputs.isEmpty(), "Input must have a size."); + Preconditions.checkState(!this.output.isEmpty(), "Output cannot be empty."); + Preconditions.checkState(!this.topOptional.isEmpty() || !this.bottomOptional.isEmpty(), "One optional must be defined."); + Preconditions.checkState(this.type != null, "Process type must be defined."); - return new InscriberRecipe( this.inputs, this.output, this.topOptional, this.bottomOptional, this.type ); - } - } + return new InscriberRecipe(this.inputs, this.output, this.topOptional, this.bottomOptional, this.type); + } + } } diff --git a/src/main/java/appeng/core/localization/ButtonToolTips.java b/src/main/java/appeng/core/localization/ButtonToolTips.java index 03afa271a..ecbe17a65 100644 --- a/src/main/java/appeng/core/localization/ButtonToolTips.java +++ b/src/main/java/appeng/core/localization/ButtonToolTips.java @@ -19,180 +19,174 @@ package appeng.core.localization; -import appeng.api.config.SchedulingMode; import net.minecraft.util.text.translation.I18n; -public enum ButtonToolTips -{ - PowerUnits, - IOMode, - CondenserOutput, - RedstoneMode, - MatchingFuzzy, +public enum ButtonToolTips { + PowerUnits, + IOMode, + CondenserOutput, + RedstoneMode, + MatchingFuzzy, - MatchingMode, - TransferDirection, - SortOrder, - SortBy, - View, + MatchingMode, + TransferDirection, + SortOrder, + SortBy, + View, - PartitionStorage, - Clear, - FuzzyMode, - OperationMode, - TrashController, + PartitionStorage, + Clear, + FuzzyMode, + OperationMode, + TrashController, - InterfaceBlockingMode, - InterfaceCraftingMode, - Trash, - MatterBalls, + InterfaceBlockingMode, + InterfaceCraftingMode, + Trash, + MatterBalls, - Singularity, - Read, - Write, - ReadWrite, - AlwaysActive, + Singularity, + Read, + Write, + ReadWrite, + AlwaysActive, - ActiveWithoutSignal, - ActiveWithSignal, - ActiveOnPulse, + ActiveWithoutSignal, + ActiveWithSignal, + ActiveOnPulse, - EmitLevelsBelow, - EmitLevelAbove, - MatchingExact, - TransferToNetwork, + EmitLevelsBelow, + EmitLevelAbove, + MatchingExact, + TransferToNetwork, - TransferToStorageCell, - ToggleSortDirection, + TransferToStorageCell, + ToggleSortDirection, - SearchMode_Auto, - SearchMode_Standard, - SearchMode_JEIAuto, - SearchMode_JEIStandard, - SearchMode_AutoKeep, - SearchMode_StandardKeep, - SearchMode_JEIAutoKeep, - SearchMode_JEIStandardKeep, + SearchMode_Auto, + SearchMode_Standard, + SearchMode_JEIAuto, + SearchMode_JEIStandard, + SearchMode_AutoKeep, + SearchMode_StandardKeep, + SearchMode_JEIAutoKeep, + SearchMode_JEIStandardKeep, - SearchMode, - ItemName, - NumberOfItems, - PartitionStorageHint, + SearchMode, + ItemName, + NumberOfItems, + PartitionStorageHint, - ClearSettings, - StoredItems, - StoredCraftable, - Craftable, + ClearSettings, + StoredItems, + StoredCraftable, + Craftable, - FZPercent_25, - FZPercent_50, - FZPercent_75, - FZPercent_99, - FZIgnoreAll, + FZPercent_25, + FZPercent_50, + FZPercent_75, + FZPercent_99, + FZIgnoreAll, - MoveWhenEmpty, - MoveWhenWorkIsDone, - MoveWhenFull, - Disabled, - Enable, + MoveWhenEmpty, + MoveWhenWorkIsDone, + MoveWhenFull, + Disabled, + Enable, - Blocking, - NonBlocking, + Blocking, + NonBlocking, - LevelType, - LevelType_Energy, - LevelType_Item, - InventoryTweaks, - TerminalStyle, - TerminalStyle_Full, - TerminalStyle_Tall, - TerminalStyle_Small, + LevelType, + LevelType_Energy, + LevelType_Item, + InventoryTweaks, + TerminalStyle, + TerminalStyle_Full, + TerminalStyle_Tall, + TerminalStyle_Small, - Stash, - StashDesc, - Encode, - EncodeDescription, - Substitutions, - SubstitutionsOn, - SubstitutionsOff, - SubstitutionsDescEnabled, - SubstitutionsDescDisabled, - CraftOnly, - CraftEither, + Stash, + StashDesc, + Encode, + EncodeDescription, + Substitutions, + SubstitutionsOn, + SubstitutionsOff, + SubstitutionsDescEnabled, + SubstitutionsDescDisabled, + CraftOnly, + CraftEither, - Craft, - Mod, - DoesntDespawn, - EmitterMode, - CraftViaRedstone, - EmitWhenCrafting, - ReportInaccessibleItems, - ReportInaccessibleItemsYes, - ReportInaccessibleItemsNo, - ReportInaccessibleFluids, - ReportInaccessibleFluidsYes, - ReportInaccessibleFluidsNo, + Craft, + Mod, + DoesntDespawn, + EmitterMode, + CraftViaRedstone, + EmitWhenCrafting, + ReportInaccessibleItems, + ReportInaccessibleItemsYes, + ReportInaccessibleItemsNo, + ReportInaccessibleFluids, + ReportInaccessibleFluidsYes, + ReportInaccessibleFluidsNo, - BlockPlacement, - BlockPlacementYes, - BlockPlacementNo, + BlockPlacement, + BlockPlacementYes, + BlockPlacementNo, - MultiplyByTwo, - MultiplyByTwoDesc, - MultiplyByThree, - MultiplyByThreeDesc, - IncreaseByOne, - IncreaseByOneDesc, - DivideByTwo, - DivideByTwoDesc, - DivideByThree, - DivideByThreeDesc, - DecreaseByOne, - DecreaseByOneDesc, - MaxCount, - MaxCountDesc, - FreeMolecularSlotShortcut, - FreeMolecularSlotShortcutDesc, - ToggleShowFullInterfaces, - ToggleShowFullInterfacesOnDesc, - ToggleShowFullInterfacesOffDesc, - HighlightInterface, - HighlightInterfaceDesc, + MultiplyByTwo, + MultiplyByTwoDesc, + MultiplyByThree, + MultiplyByThreeDesc, + IncreaseByOne, + IncreaseByOneDesc, + DivideByTwo, + DivideByTwoDesc, + DivideByThree, + DivideByThreeDesc, + DecreaseByOne, + DecreaseByOneDesc, + MaxCount, + MaxCountDesc, + FreeMolecularSlotShortcut, + FreeMolecularSlotShortcutDesc, + ToggleShowFullInterfaces, + ToggleShowFullInterfacesOnDesc, + ToggleShowFullInterfacesOffDesc, + HighlightInterface, + HighlightInterfaceDesc, - // Used in the tooltips of the items in the terminal, when moused over - ItemsStored, - ItemsRequestable, + // Used in the tooltips of the items in the terminal, when moused over + ItemsStored, + ItemsRequestable, - SchedulingMode, - SchedulingModeDefault, - SchedulingModeRoundRobin, - SchedulingModeRandom, + SchedulingMode, + SchedulingModeDefault, + SchedulingModeRoundRobin, + SchedulingModeRandom, - FilterMode, - FilterModeKeep, - FilterModeClear; + FilterMode, + FilterModeKeep, + FilterModeClear; - private final String root; + private final String root; - ButtonToolTips() - { - this.root = "gui.tooltips.appliedenergistics2"; - } + ButtonToolTips() { + this.root = "gui.tooltips.appliedenergistics2"; + } - ButtonToolTips( final String r ) - { - this.root = r; - } + ButtonToolTips(final String r) { + this.root = r; + } - public String getLocal() - { - return I18n.translateToLocal( this.getUnlocalized() ); - } + public String getLocal() { + return I18n.translateToLocal(this.getUnlocalized()); + } - public String getUnlocalized() - { - return this.root + '.' + this.toString(); - } + public String getUnlocalized() { + return this.root + '.' + this; + } } diff --git a/src/main/java/appeng/core/localization/GuiText.java b/src/main/java/appeng/core/localization/GuiText.java index 07268813a..6b0f5e78a 100644 --- a/src/main/java/appeng/core/localization/GuiText.java +++ b/src/main/java/appeng/core/localization/GuiText.java @@ -22,207 +22,202 @@ package appeng.core.localization; import net.minecraft.util.text.translation.I18n; -public enum GuiText -{ - inventory( "container" ), // mc's default Inventory localization. +public enum GuiText { + inventory("container"), // mc's default Inventory localization. - Chest, - StoredEnergy, - Of, - Condenser, - Drive, - GrindStone, - SkyChest, + Chest, + StoredEnergy, + Of, + Condenser, + Drive, + GrindStone, + SkyChest, - VibrationChamber, - SpatialIOPort, - LevelEmitter, - FluidLevelEmitter, - Terminal, + VibrationChamber, + SpatialIOPort, + LevelEmitter, + FluidLevelEmitter, + Terminal, - Interface, - FluidInterface, - Config, - StoredItems, - StoredFluids, - Patterns, - ImportBus, - ImportBusFluids, - ExportBus, - ExportBusFluids, + Interface, + FluidInterface, + Config, + StoredItems, + StoredFluids, + Patterns, + ImportBus, + ImportBusFluids, + ExportBus, + ExportBusFluids, - CellWorkbench, - NetworkDetails, - StorageCells, - IOBuses, - IOBusesFluids, + CellWorkbench, + NetworkDetails, + StorageCells, + IOBuses, + IOBusesFluids, - IOPort, - BytesUsed, - Types, - QuantumLinkChamber, - PortableCell, + IOPort, + BytesUsed, + Types, + QuantumLinkChamber, + PortableCell, - NetworkTool, - PowerUsageRate, - PowerInputRate, - Installed, - EnergyDrain, + NetworkTool, + PowerUsageRate, + PowerInputRate, + Installed, + EnergyDrain, - StorageBus, - OreDictStorageBus, - StorageBusFluids, - Priority, - Security, - Encoded, - Blank, - Unlinked, - Linked, + StorageBus, + OreDictStorageBus, + StorageBusFluids, + Priority, + Security, + Encoded, + Blank, + Unlinked, + Linked, - SecurityCardEditor, - NoPermissions, - WirelessTerminal, - Wireless, + SecurityCardEditor, + NoPermissions, + WirelessTerminal, + Wireless, - CraftingTerminal, - FormationPlane, - FluidFormationPlane, - Inscriber, - QuartzCuttingKnife, + CraftingTerminal, + FormationPlane, + FluidFormationPlane, + Inscriber, + QuartzCuttingKnife, - Renamer, + Renamer, - // tunnel names - METunnel, - ItemTunnel, - RedstoneTunnel, - EUTunnel, - FluidTunnel, - OCTunnel, - LightTunnel, - FETunnel, - GTEUTunnel, - PressureTunnel, + // tunnel names + METunnel, + ItemTunnel, + RedstoneTunnel, + EUTunnel, + FluidTunnel, + OCTunnel, + LightTunnel, + FETunnel, + GTEUTunnel, + PressureTunnel, - // spatial - StoredSize, - CellId, + // spatial + StoredSize, + CellId, - CopyMode, - CopyModeDesc, - PatternTerminal, + CopyMode, + CopyModeDesc, + PatternTerminal, - // Pattern tooltips - CraftingPattern, - ProcessingPattern, - Crafts, - Creates, - And, - With, - Substitute, - Yes, - No, + // Pattern tooltips + CraftingPattern, + ProcessingPattern, + Crafts, + Creates, + And, + With, + Substitute, + Yes, + No, - MolecularAssembler, + MolecularAssembler, - StoredPower, - MaxPower, - RequiredPower, - Efficiency, - SCSSize, - SCSInvalid, - InWorldCrafting, + StoredPower, + MaxPower, + RequiredPower, + Efficiency, + SCSSize, + SCSInvalid, + InWorldCrafting, - inWorldFluix, - inWorldPurificationCertus, - inWorldPurificationNether, + inWorldFluix, + inWorldPurificationCertus, + inWorldPurificationNether, - inWorldPurificationFluix, - inWorldSingularity, - ChargedQuartz, + inWorldPurificationFluix, + inWorldSingularity, + ChargedQuartz, - NoSecondOutput, - OfSecondOutput, - MultipleOutputs, + NoSecondOutput, + OfSecondOutput, + MultipleOutputs, - Stores, - Next, - SelectAmount, - Lumen, - Empty, + Stores, + Next, + SelectAmount, + Lumen, + Empty, - ConfirmCrafting, - Stored, - Crafting, - Scheduled, - CraftingStatus, - Cancel, - ETA, - ETAFormat, + ConfirmCrafting, + Stored, + Crafting, + Scheduled, + CraftingStatus, + Cancel, + ETA, + ETAFormat, - FromStorage, - ToCraft, - CraftingPlan, - CalculatingWait, - Start, - Bytes, + FromStorage, + ToCraft, + CraftingPlan, + CalculatingWait, + Start, + Bytes, - CraftingCPU, - Automatic, - CoProcessors, - Simulation, - Missing, + CraftingCPU, + Automatic, + CoProcessors, + Simulation, + Missing, - InterfaceTerminal, - InterfaceConfigurationTerminal, - NoCraftingCPUs, - Clean, - InvalidPattern, + InterfaceTerminal, + InterfaceConfigurationTerminal, + NoCraftingCPUs, + Clean, + InvalidPattern, - InterfaceTerminalHint, - Range, - TransparentFacades, - TransparentFacadesHint, + InterfaceTerminalHint, + Range, + TransparentFacades, + TransparentFacadesHint, - NoCraftingJobs, - CPUs, - FacadeCrafting, - inWorldCraftingPresses, - ChargedQuartzFind, + NoCraftingJobs, + CPUs, + FacadeCrafting, + inWorldCraftingPresses, + ChargedQuartzFind, - Included, - Excluded, - Partitioned, - Precise, - Fuzzy, + Included, + Excluded, + Partitioned, + Precise, + Fuzzy, - // Used in a terminal to indicate that an item is craftable - SmallFontCraft, - LargeFontCraft, + // Used in a terminal to indicate that an item is craftable + SmallFontCraft, + LargeFontCraft, - // Used in a ME Interface when no appropriate TileEntity was detected near it - Nothing; + // Used in a ME Interface when no appropriate TileEntity was detected near it + Nothing; - private final String root; + private final String root; - GuiText() - { - this.root = "gui.appliedenergistics2"; - } + GuiText() { + this.root = "gui.appliedenergistics2"; + } - GuiText( final String r ) - { - this.root = r; - } + GuiText(final String r) { + this.root = r; + } - public String getLocal() - { - return I18n.translateToLocal( this.getUnlocalized() ); - } + public String getLocal() { + return I18n.translateToLocal(this.getUnlocalized()); + } - public String getUnlocalized() - { - return this.root + '.' + this.toString(); - } + public String getUnlocalized() { + return this.root + '.' + this; + } } diff --git a/src/main/java/appeng/core/localization/PlayerMessages.java b/src/main/java/appeng/core/localization/PlayerMessages.java index 6a177d658..1ec5db52f 100644 --- a/src/main/java/appeng/core/localization/PlayerMessages.java +++ b/src/main/java/appeng/core/localization/PlayerMessages.java @@ -23,34 +23,32 @@ import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentTranslation; -public enum PlayerMessages -{ - ChestCannotReadStorageCell, - InvalidMachine, - LoadedSettings, - SavedSettings, - ResetSettings, - MachineNotPowered, +public enum PlayerMessages { + ChestCannotReadStorageCell, + InvalidMachine, + LoadedSettings, + SavedSettings, + ResetSettings, + MachineNotPowered, - isNowLocked, - isNowUnlocked, - AmmoDepleted, - CommunicationError, - OutOfRange, - DeviceNotPowered, - DeviceNotWirelessTerminal, - DeviceNotLinked, - StationCanNotBeLocated, - SettingCleared,; + isNowLocked, + isNowUnlocked, + AmmoDepleted, + CommunicationError, + OutOfRange, + DeviceNotPowered, + DeviceNotWirelessTerminal, + DeviceNotLinked, + StationCanNotBeLocated, + SettingCleared, + ; - public ITextComponent get() - { - return new TextComponentTranslation( this.getName() ); - } + public ITextComponent get() { + return new TextComponentTranslation(this.getName()); + } - String getName() - { - return "chat.appliedenergistics2." + this.toString(); - } + String getName() { + return "chat.appliedenergistics2." + this; + } } diff --git a/src/main/java/appeng/core/localization/WailaText.java b/src/main/java/appeng/core/localization/WailaText.java index 98ac1442e..89109d88c 100644 --- a/src/main/java/appeng/core/localization/WailaText.java +++ b/src/main/java/appeng/core/localization/WailaText.java @@ -22,48 +22,43 @@ package appeng.core.localization; import net.minecraft.util.text.translation.I18n; -public enum WailaText -{ - Crafting, +public enum WailaText { + Crafting, - DeviceOnline, - DeviceOffline, - DeviceMissingChannel, + DeviceOnline, + DeviceOffline, + DeviceMissingChannel, - P2PUnlinked, - P2P_INPUT_ONE_OUTPUT, - P2P_INPUT_MANY_OUTPUTS, - P2P_OUTPUT_ONE_INPUT, - P2P_OUTPUT_MANY_INPUTS, - P2POutput, + P2PUnlinked, + P2P_INPUT_ONE_OUTPUT, + P2P_INPUT_MANY_OUTPUTS, + P2P_OUTPUT_ONE_INPUT, + P2P_OUTPUT_MANY_INPUTS, + P2POutput, - Locked, - Unlocked, - Showing, + Locked, + Unlocked, + Showing, - Contains, - Channels; + Contains, + Channels; - private final String root; + private final String root; - WailaText() - { - this.root = "waila.appliedenergistics2"; - } + WailaText() { + this.root = "waila.appliedenergistics2"; + } - WailaText( final String r ) - { - this.root = r; - } + WailaText(final String r) { + this.root = r; + } - public String getLocal() - { - return I18n.translateToLocal( this.getUnlocalized() ); - } + public String getLocal() { + return I18n.translateToLocal(this.getUnlocalized()); + } - public String getUnlocalized() - { - return this.root + '.' + this.toString(); - } + public String getUnlocalized() { + return this.root + '.' + this; + } } diff --git a/src/main/java/appeng/core/settings/TickRates.java b/src/main/java/appeng/core/settings/TickRates.java index e69edeae3..4d450d343 100644 --- a/src/main/java/appeng/core/settings/TickRates.java +++ b/src/main/java/appeng/core/settings/TickRates.java @@ -22,78 +22,71 @@ package appeng.core.settings; import appeng.core.AEConfig; -public enum TickRates -{ +public enum TickRates { - Interface( 5, 120 ), + Interface(5, 120), - ImportBus( 5, 40 ), + ImportBus(5, 40), - FluidImportBus( 5, 40 ), + FluidImportBus(5, 40), - ExportBus( 5, 60 ), + ExportBus(5, 60), - FluidExportBus( 5, 60 ), + FluidExportBus(5, 60), - AnnihilationPlane( 2, 120 ), + AnnihilationPlane(2, 120), - METunnel( 5, 20 ), + METunnel(5, 20), - Inscriber( 1, 1 ), + Inscriber(1, 1), - Charger( 10, 120 ), + Charger(10, 120), - IOPort( 1, 5 ), + IOPort(1, 5), - VibrationChamber( 10, 40 ), + VibrationChamber(10, 40), - StorageBus( 5, 60 ), + StorageBus(5, 60), - FluidStorageBus( 5, 60 ), + FluidStorageBus(5, 60), - ItemTunnel( 5, 60 ), + ItemTunnel(5, 60), - LightTunnel( 5, 60 ), + LightTunnel(5, 60), - OpenComputersTunnel( 1, 5 ), + OpenComputersTunnel(1, 5), - PressureTunnel( 1, 120 ); + PressureTunnel(1, 120); - private int min; - private int max; + private int min; + private int max; - TickRates( final int min, final int max ) - { - this.setMin( min ); - this.setMax( max ); - } + TickRates(final int min, final int max) { + this.setMin(min); + this.setMax(max); + } - public void Load( final AEConfig config ) - { - config.addCustomCategoryComment( "TickRates", - " Min / Max Tickrates for dynamic ticking, most of these components also use sleeping, to prevent constant ticking, adjust with care, non standard rates are not supported or tested." ); - this.setMin( config.get( "TickRates", this.name() + ".min", this.getMin() ).getInt( this.getMin() ) ); - this.setMax( config.get( "TickRates", this.name() + ".max", this.getMax() ).getInt( this.getMax() ) ); - } + public void Load(final AEConfig config) { + config.addCustomCategoryComment("TickRates", + " Min / Max Tickrates for dynamic ticking, most of these components also use sleeping, to prevent constant ticking, adjust with care, non standard rates are not supported or tested."); + this.setMin(config.get("TickRates", this.name() + ".min", this.getMin()).getInt(this.getMin())); + this.setMax(config.get("TickRates", this.name() + ".max", this.getMax()).getInt(this.getMax())); + } - public int getMax() - { - return this.max; - } + public int getMax() { + return this.max; + } - public void setMax( final int max ) - { - this.max = max; - } + public void setMax(final int max) { + this.max = max; + } - public int getMin() - { - return this.min; - } + public int getMin() { + return this.min; + } - public void setMin( final int min ) - { - this.min = min; - } + public void setMin(final int min) { + this.min = min; + } } diff --git a/src/main/java/appeng/core/stats/AdvancementTriggers.java b/src/main/java/appeng/core/stats/AdvancementTriggers.java index ded683317..c3edb8693 100644 --- a/src/main/java/appeng/core/stats/AdvancementTriggers.java +++ b/src/main/java/appeng/core/stats/AdvancementTriggers.java @@ -22,38 +22,32 @@ package appeng.core.stats; import appeng.bootstrap.ICriterionTriggerRegistry; -public class AdvancementTriggers -{ - private AppEngAdvancementTrigger networkApprentice = new AppEngAdvancementTrigger( "network_apprentice" ); - private AppEngAdvancementTrigger networkEngineer = new AppEngAdvancementTrigger( "network_engineer" ); - private AppEngAdvancementTrigger networkAdmin = new AppEngAdvancementTrigger( "network_admin" ); - private AppEngAdvancementTrigger spatialExplorer = new AppEngAdvancementTrigger( "spatial_explorer" ); +public class AdvancementTriggers { + private final AppEngAdvancementTrigger networkApprentice = new AppEngAdvancementTrigger("network_apprentice"); + private final AppEngAdvancementTrigger networkEngineer = new AppEngAdvancementTrigger("network_engineer"); + private final AppEngAdvancementTrigger networkAdmin = new AppEngAdvancementTrigger("network_admin"); + private final AppEngAdvancementTrigger spatialExplorer = new AppEngAdvancementTrigger("spatial_explorer"); - public AdvancementTriggers( ICriterionTriggerRegistry registry ) - { - registry.register( this.networkApprentice ); - registry.register( this.networkEngineer ); - registry.register( this.networkAdmin ); - registry.register( this.spatialExplorer ); - } + public AdvancementTriggers(ICriterionTriggerRegistry registry) { + registry.register(this.networkApprentice); + registry.register(this.networkEngineer); + registry.register(this.networkAdmin); + registry.register(this.spatialExplorer); + } - public IAdvancementTrigger getNetworkApprentice() - { - return this.networkApprentice; - } + public IAdvancementTrigger getNetworkApprentice() { + return this.networkApprentice; + } - public IAdvancementTrigger getNetworkEngineer() - { - return this.networkEngineer; - } + public IAdvancementTrigger getNetworkEngineer() { + return this.networkEngineer; + } - public IAdvancementTrigger getNetworkAdmin() - { - return this.networkAdmin; - } + public IAdvancementTrigger getNetworkAdmin() { + return this.networkAdmin; + } - public IAdvancementTrigger getSpatialExplorer() - { - return this.spatialExplorer; - } + public IAdvancementTrigger getSpatialExplorer() { + return this.spatialExplorer; + } } diff --git a/src/main/java/appeng/core/stats/AppEngAdvancementTrigger.java b/src/main/java/appeng/core/stats/AppEngAdvancementTrigger.java index 73c212891..a1d58528f 100644 --- a/src/main/java/appeng/core/stats/AppEngAdvancementTrigger.java +++ b/src/main/java/appeng/core/stats/AppEngAdvancementTrigger.java @@ -19,157 +19,124 @@ package appeng.core.stats; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - +import appeng.core.AppEng; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; - import net.minecraft.advancements.ICriterionTrigger; import net.minecraft.advancements.PlayerAdvancements; import net.minecraft.advancements.critereon.AbstractCriterionInstance; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ResourceLocation; -import appeng.core.AppEng; +import java.util.*; -public class AppEngAdvancementTrigger implements ICriterionTrigger, IAdvancementTrigger -{ - private final ResourceLocation ID; - private final Map listeners = new HashMap<>(); +public class AppEngAdvancementTrigger implements ICriterionTrigger, IAdvancementTrigger { + private final ResourceLocation ID; + private final Map listeners = new HashMap<>(); - public AppEngAdvancementTrigger( String parString ) - { - super(); - this.ID = new ResourceLocation( AppEng.MOD_ID, parString ); - } + public AppEngAdvancementTrigger(String parString) { + super(); + this.ID = new ResourceLocation(AppEng.MOD_ID, parString); + } - @Override - public ResourceLocation getId() - { - return this.ID; - } + @Override + public ResourceLocation getId() { + return this.ID; + } - @Override - public void addListener( PlayerAdvancements playerAdvancementsIn, ICriterionTrigger.Listener listener ) - { - AppEngAdvancementTrigger.Listeners l = this.listeners.get( playerAdvancementsIn ); + @Override + public void addListener(PlayerAdvancements playerAdvancementsIn, ICriterionTrigger.Listener listener) { + AppEngAdvancementTrigger.Listeners l = this.listeners.get(playerAdvancementsIn); - if( l == null ) - { - l = new AppEngAdvancementTrigger.Listeners( playerAdvancementsIn ); - this.listeners.put( playerAdvancementsIn, l ); - } + if (l == null) { + l = new AppEngAdvancementTrigger.Listeners(playerAdvancementsIn); + this.listeners.put(playerAdvancementsIn, l); + } - l.add( listener ); - } + l.add(listener); + } - @Override - public void removeListener( PlayerAdvancements playerAdvancementsIn, ICriterionTrigger.Listener listener ) - { - AppEngAdvancementTrigger.Listeners l = this.listeners.get( playerAdvancementsIn ); + @Override + public void removeListener(PlayerAdvancements playerAdvancementsIn, ICriterionTrigger.Listener listener) { + AppEngAdvancementTrigger.Listeners l = this.listeners.get(playerAdvancementsIn); - if( l != null ) - { - l.remove( listener ); + if (l != null) { + l.remove(listener); - if( l.isEmpty() ) - { - this.listeners.remove( playerAdvancementsIn ); - } - } - } + if (l.isEmpty()) { + this.listeners.remove(playerAdvancementsIn); + } + } + } - @Override - public void removeAllListeners( PlayerAdvancements playerAdvancementsIn ) - { - this.listeners.remove( playerAdvancementsIn ); - } + @Override + public void removeAllListeners(PlayerAdvancements playerAdvancementsIn) { + this.listeners.remove(playerAdvancementsIn); + } - @Override - public AppEngAdvancementTrigger.Instance deserializeInstance( JsonObject json, JsonDeserializationContext context ) - { - return new AppEngAdvancementTrigger.Instance( this.getId() ); - } + @Override + public AppEngAdvancementTrigger.Instance deserializeInstance(JsonObject json, JsonDeserializationContext context) { + return new AppEngAdvancementTrigger.Instance(this.getId()); + } - @Override - public void trigger( EntityPlayerMP parPlayer ) - { - AppEngAdvancementTrigger.Listeners l = this.listeners.get( parPlayer.getAdvancements() ); + @Override + public void trigger(EntityPlayerMP parPlayer) { + AppEngAdvancementTrigger.Listeners l = this.listeners.get(parPlayer.getAdvancements()); - if( l != null ) - { - l.trigger( parPlayer ); - } - } + if (l != null) { + l.trigger(parPlayer); + } + } - public static class Instance extends AbstractCriterionInstance - { - public Instance( ResourceLocation parID ) - { - super( parID ); - } + public static class Instance extends AbstractCriterionInstance { + public Instance(ResourceLocation parID) { + super(parID); + } - public boolean test() - { - return true; - } - } + public boolean test() { + return true; + } + } - static class Listeners - { - private final PlayerAdvancements playerAdvancements; - private final Set> listeners = new HashSet<>(); + static class Listeners { + private final PlayerAdvancements playerAdvancements; + private final Set> listeners = new HashSet<>(); - Listeners( PlayerAdvancements playerAdvancementsIn ) - { - this.playerAdvancements = playerAdvancementsIn; - } + Listeners(PlayerAdvancements playerAdvancementsIn) { + this.playerAdvancements = playerAdvancementsIn; + } - public boolean isEmpty() - { - return this.listeners.isEmpty(); - } + public boolean isEmpty() { + return this.listeners.isEmpty(); + } - public void add( ICriterionTrigger.Listener listener ) - { - this.listeners.add( listener ); - } + public void add(ICriterionTrigger.Listener listener) { + this.listeners.add(listener); + } - public void remove( ICriterionTrigger.Listener listener ) - { - this.listeners.remove( listener ); - } + public void remove(ICriterionTrigger.Listener listener) { + this.listeners.remove(listener); + } - public void trigger( EntityPlayerMP player ) - { - List> list = null; + public void trigger(EntityPlayerMP player) { + List> list = null; - for( ICriterionTrigger.Listener listener : this.listeners ) - { - if( listener.getCriterionInstance().test() ) - { - if( list == null ) - { - list = new ArrayList<>(); - } + for (ICriterionTrigger.Listener listener : this.listeners) { + if (listener.getCriterionInstance().test()) { + if (list == null) { + list = new ArrayList<>(); + } - list.add( listener ); - } - } + list.add(listener); + } + } - if( list != null ) - { - for( ICriterionTrigger.Listener l : list ) - { - l.grantCriterion( this.playerAdvancements ); - } - } - } - } + if (list != null) { + for (ICriterionTrigger.Listener l : list) { + l.grantCriterion(this.playerAdvancements); + } + } + } + } } diff --git a/src/main/java/appeng/core/stats/IAdvancementTrigger.java b/src/main/java/appeng/core/stats/IAdvancementTrigger.java index e5563f3ec..e98ec972f 100644 --- a/src/main/java/appeng/core/stats/IAdvancementTrigger.java +++ b/src/main/java/appeng/core/stats/IAdvancementTrigger.java @@ -23,7 +23,6 @@ import net.minecraft.entity.player.EntityPlayerMP; @FunctionalInterface -public interface IAdvancementTrigger -{ - void trigger( EntityPlayerMP parPlayer ); +public interface IAdvancementTrigger { + void trigger(EntityPlayerMP parPlayer); } diff --git a/src/main/java/appeng/core/stats/PartItemPredicate.java b/src/main/java/appeng/core/stats/PartItemPredicate.java index 018b9963c..1c6b72ab3 100644 --- a/src/main/java/appeng/core/stats/PartItemPredicate.java +++ b/src/main/java/appeng/core/stats/PartItemPredicate.java @@ -19,52 +19,41 @@ package appeng.core.stats; +import appeng.core.AppEng; +import appeng.items.parts.ItemPart; +import appeng.items.parts.PartType; import com.google.gson.JsonObject; - import net.minecraft.advancements.critereon.ItemPredicate; import net.minecraft.item.ItemStack; import net.minecraft.util.JsonUtils; import net.minecraft.util.ResourceLocation; import net.minecraftforge.advancements.critereon.ItemPredicates; -import appeng.core.AppEng; -import appeng.items.parts.ItemPart; -import appeng.items.parts.PartType; +public class PartItemPredicate extends ItemPredicate { + private final PartType partType; -public class PartItemPredicate extends ItemPredicate -{ - private final PartType partType; + public PartItemPredicate(String partName) { + this.partType = PartType.valueOf(partName.toUpperCase()); + } - public PartItemPredicate( String partName ) - { - this.partType = PartType.valueOf( partName.toUpperCase() ); - } + @Override + public boolean test(ItemStack item) { + if (ItemPart.instance != null && item.getItem() == ItemPart.instance) { + return ItemPart.instance.getTypeByStack(item) == this.partType; + } + return false; + } - @Override - public boolean test( ItemStack item ) - { - if( ItemPart.instance != null && item.getItem() == ItemPart.instance ) - { - return ItemPart.instance.getTypeByStack( item ) == this.partType; - } - return false; - } + public static ItemPredicate deserialize(JsonObject jsonobject) { + if (jsonobject.has("part")) { + return new PartItemPredicate(JsonUtils.getString(jsonobject, "part")); + } else { + return ItemPredicate.ANY; + } + } - public static ItemPredicate deserialize( JsonObject jsonobject ) - { - if( jsonobject.has( "part" ) ) - { - return new PartItemPredicate( JsonUtils.getString( jsonobject, "part" ) ); - } - else - { - return ItemPredicate.ANY; - } - } - - public static void register() - { - ItemPredicates.register( new ResourceLocation( AppEng.MOD_ID, "part" ), PartItemPredicate::deserialize ); - } + public static void register() { + ItemPredicates.register(new ResourceLocation(AppEng.MOD_ID, "part"), PartItemPredicate::deserialize); + } } diff --git a/src/main/java/appeng/core/stats/Stats.java b/src/main/java/appeng/core/stats/Stats.java index 12b0193b8..8f1d0ab05 100644 --- a/src/main/java/appeng/core/stats/Stats.java +++ b/src/main/java/appeng/core/stats/Stats.java @@ -24,38 +24,32 @@ import net.minecraft.stats.StatBasic; import net.minecraft.util.text.TextComponentTranslation; -public enum Stats -{ +public enum Stats { - // done - ItemsInserted, + // done + ItemsInserted, - // done - ItemsExtracted, + // done + ItemsExtracted, - // done - TurnedCranks; + // done + TurnedCranks; - private StatBasic stat; + private StatBasic stat; - Stats() - { - } + Stats() { + } - public void addToPlayer( final EntityPlayer player, final int howMany ) - { - player.addStat( this.stat, howMany ); - } + public void addToPlayer(final EntityPlayer player, final int howMany) { + player.addStat(this.stat, howMany); + } - public static void register() - { - for( final Stats s : Stats.values() ) - { - if( s.stat == null ) - { - s.stat = new StatBasic( "stat.ae2." + s.name(), new TextComponentTranslation( "stat.ae2." + s.name() ) ); - s.stat.registerStat(); - } - } - } + public static void register() { + for (final Stats s : Stats.values()) { + if (s.stat == null) { + s.stat = new StatBasic("stat.ae2." + s.name(), new TextComponentTranslation("stat.ae2." + s.name())); + s.stat.registerStat(); + } + } + } } diff --git a/src/main/java/appeng/core/sync/AppEngPacket.java b/src/main/java/appeng/core/sync/AppEngPacket.java index 6bbb52e16..9663f62a4 100644 --- a/src/main/java/appeng/core/sync/AppEngPacket.java +++ b/src/main/java/appeng/core/sync/AppEngPacket.java @@ -19,111 +19,93 @@ package appeng.core.sync; -import java.io.ByteArrayInputStream; -import java.io.IOException; - +import appeng.core.AEConfig; +import appeng.core.AELog; +import appeng.core.features.AEFeature; +import appeng.core.sync.network.INetworkInfo; +import appeng.core.sync.network.NetworkHandler; import io.netty.buffer.ByteBuf; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.INetHandler; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; -import appeng.core.AEConfig; -import appeng.core.AELog; -import appeng.core.features.AEFeature; -import appeng.core.sync.network.INetworkInfo; -import appeng.core.sync.network.NetworkHandler; +import java.io.ByteArrayInputStream; +import java.io.IOException; -public abstract class AppEngPacket implements Packet -{ - private PacketBuffer p; - private PacketCallState caller; +public abstract class AppEngPacket implements Packet { + private PacketBuffer p; + private PacketCallState caller; - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - throw new UnsupportedOperationException( "This packet ( " + this.getPacketID() + " does not implement a server side handler." ); - } + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + throw new UnsupportedOperationException("This packet ( " + this.getPacketID() + " does not implement a server side handler."); + } - public final int getPacketID() - { - return AppEngPacketHandlerBase.PacketTypes.getID( this.getClass() ).ordinal(); - } + public final int getPacketID() { + return AppEngPacketHandlerBase.PacketTypes.getID(this.getClass()).ordinal(); + } - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - throw new UnsupportedOperationException( "This packet ( " + this.getPacketID() + " does not implement a client side handler." ); - } + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + throw new UnsupportedOperationException("This packet ( " + this.getPacketID() + " does not implement a client side handler."); + } - protected void configureWrite( final ByteBuf data ) - { - data.capacity( data.readableBytes() ); - this.p = new PacketBuffer( data ); - } + protected void configureWrite(final ByteBuf data) { + data.capacity(data.readableBytes()); + this.p = new PacketBuffer(data); + } - public FMLProxyPacket getProxy() - { - if( this.p.array().length > 2 * 1024 * 1024 ) // 2k walking room :) - { - throw new IllegalArgumentException( "Sorry AE2 made a " + this.p.array().length + " byte packet by accident!" ); - } + public FMLProxyPacket getProxy() { + if (this.p.array().length > 2 * 1024 * 1024) // 2k walking room :) + { + throw new IllegalArgumentException("Sorry AE2 made a " + this.p.array().length + " byte packet by accident!"); + } - final FMLProxyPacket pp = new FMLProxyPacket( this.p, NetworkHandler.instance().getChannel() ); + final FMLProxyPacket pp = new FMLProxyPacket(this.p, NetworkHandler.instance().getChannel()); - if( AEConfig.instance().isFeatureEnabled( AEFeature.PACKET_LOGGING ) ) - { - AELog.info( this.getClass().getName() + " : " + pp.payload().readableBytes() ); - } + if (AEConfig.instance().isFeatureEnabled(AEFeature.PACKET_LOGGING)) { + AELog.info(this.getClass().getName() + " : " + pp.payload().readableBytes()); + } - return pp; - } + return pp; + } - @Override - public void readPacketData( final PacketBuffer buf ) throws IOException - { - throw new RuntimeException( "Not Implemented" ); - } + @Override + public void readPacketData(final PacketBuffer buf) throws IOException { + throw new RuntimeException("Not Implemented"); + } - @Override - public void writePacketData( final PacketBuffer buf ) throws IOException - { - throw new RuntimeException( "Not Implemented" ); - } + @Override + public void writePacketData(final PacketBuffer buf) throws IOException { + throw new RuntimeException("Not Implemented"); + } - // TODO: Figure out why Forge/Minecraft on the server sets the stream data buffer to PooledUnsafeDirectByteBuf + // TODO: Figure out why Forge/Minecraft on the server sets the stream data buffer to PooledUnsafeDirectByteBuf - public ByteArrayInputStream getPacketByteArray( ByteBuf stream, int readerIndex, int readableBytes ) - { - final ByteArrayInputStream bytes; - if( stream.hasArray() ) - { - bytes = new ByteArrayInputStream( stream.array(), readerIndex, readableBytes ); - } - else - { - byte[] data = new byte[stream.capacity()]; - stream.getBytes( readerIndex, data, 0, readableBytes ); - bytes = new ByteArrayInputStream( data ); - } - return bytes; - } + public ByteArrayInputStream getPacketByteArray(ByteBuf stream, int readerIndex, int readableBytes) { + final ByteArrayInputStream bytes; + if (stream.hasArray()) { + bytes = new ByteArrayInputStream(stream.array(), readerIndex, readableBytes); + } else { + byte[] data = new byte[stream.capacity()]; + stream.getBytes(readerIndex, data, 0, readableBytes); + bytes = new ByteArrayInputStream(data); + } + return bytes; + } - public ByteArrayInputStream getPacketByteArray( ByteBuf stream ) - { - return this.getPacketByteArray( stream, 0, stream.readableBytes() ); - } + public ByteArrayInputStream getPacketByteArray(ByteBuf stream) { + return this.getPacketByteArray(stream, 0, stream.readableBytes()); + } - public void setCallParam( final PacketCallState call ) - { - this.caller = call; - } + public void setCallParam(final PacketCallState call) { + this.caller = call; + } - @Override - public void processPacket( final INetHandler handler ) - { - this.caller.call( this ); - } + @Override + public void processPacket(final INetHandler handler) { + this.caller.call(this); + } } diff --git a/src/main/java/appeng/core/sync/AppEngPacketHandlerBase.java b/src/main/java/appeng/core/sync/AppEngPacketHandlerBase.java index 1aefa289f..5738fb18c 100644 --- a/src/main/java/appeng/core/sync/AppEngPacketHandlerBase.java +++ b/src/main/java/appeng/core/sync/AppEngPacketHandlerBase.java @@ -19,117 +19,105 @@ package appeng.core.sync; +import appeng.core.sync.packets.*; +import io.netty.buffer.ByteBuf; + import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; -import appeng.core.sync.packets.*; -import io.netty.buffer.ByteBuf; + +public class AppEngPacketHandlerBase { + private static final Map, PacketTypes> REVERSE_LOOKUP = new HashMap<>(); + + public enum PacketTypes { + PACKET_COMPASS_REQUEST(PacketCompassRequest.class), + + PACKET_COMPASS_RESPONSE(PacketCompassResponse.class), + + PACKET_INVENTORY_ACTION(PacketInventoryAction.class), + + PACKET_ME_INVENTORY_UPDATE(PacketMEInventoryUpdate.class), + + PACKET_ME_FLUID_INVENTORY_UPDATE(PacketMEFluidInventoryUpdate.class), + + PACKET_CONFIG_BUTTON(PacketConfigButton.class), + + PACKET_PART_PLACEMENT(PacketPartPlacement.class), + + PACKET_LIGHTNING(PacketLightning.class), + + PACKET_MATTER_CANNON(PacketMatterCannon.class), + + PACKET_MOCK_EXPLOSION(PacketMockExplosion.class), + + PACKET_VALUE_CONFIG(PacketValueConfig.class), + + PACKET_TRANSITION_EFFECT(PacketTransitionEffect.class), + + PACKET_PROGRESS_VALUE(PacketProgressBar.class), + + PACKET_CLICK(PacketClick.class), + + PACKET_SWITCH_GUIS(PacketSwitchGuis.class), + + PACKET_SWAP_SLOTS(PacketSwapSlots.class), + + PACKET_PATTERN_SLOT(PacketPatternSlot.class), + + PACKET_RECIPE_JEI(PacketJEIRecipe.class), + + PACKET_TARGET_ITEM(PacketTargetItemStack.class), + + PACKET_TARGET_FLUID(PacketTargetFluidStack.class), + + PACKET_CRAFTING_REQUEST(PacketCraftRequest.class), + + PACKET_ASSEMBLER_ANIMATION(PacketAssemblerAnimation.class), + + PACKET_COMPRESSED_NBT(PacketCompressedNBT.class), + + PACKET_PAINTED_ENTITY(PacketPaintedEntity.class), + + PACKET_FLUID_TANK(PacketFluidSlot.class), + + PACKET_INFORM_PLAYER(PacketInformPlayer.class), + + PACKET_CRAFTING_CPUS_UPDATE(PacketCraftingCPUsUpdate.class); -public class AppEngPacketHandlerBase -{ - private static final Map, PacketTypes> REVERSE_LOOKUP = new HashMap<>(); + private final Class packetClass; + private final Constructor packetConstructor; - public enum PacketTypes - { - PACKET_COMPASS_REQUEST( PacketCompassRequest.class ), + PacketTypes(final Class c) { + this.packetClass = c; - PACKET_COMPASS_RESPONSE( PacketCompassResponse.class ), + Constructor x = null; + try { + x = this.packetClass.getConstructor(ByteBuf.class); + } catch (final NoSuchMethodException ignored) { + } catch (final SecurityException ignored) { + } - PACKET_INVENTORY_ACTION( PacketInventoryAction.class ), + this.packetConstructor = x; + REVERSE_LOOKUP.put(this.packetClass, this); - PACKET_ME_INVENTORY_UPDATE( PacketMEInventoryUpdate.class ), + if (this.packetConstructor == null) { + throw new IllegalStateException("Invalid Packet Class " + c + ", must be constructable on DataInputStream"); + } + } - PACKET_ME_FLUID_INVENTORY_UPDATE( PacketMEFluidInventoryUpdate.class ), + public static PacketTypes getPacket(final int id) { + return (values())[id]; + } - PACKET_CONFIG_BUTTON( PacketConfigButton.class ), + static PacketTypes getID(final Class c) { + return REVERSE_LOOKUP.get(c); + } - PACKET_PART_PLACEMENT( PacketPartPlacement.class ), - - PACKET_LIGHTNING( PacketLightning.class ), - - PACKET_MATTER_CANNON( PacketMatterCannon.class ), - - PACKET_MOCK_EXPLOSION( PacketMockExplosion.class ), - - PACKET_VALUE_CONFIG( PacketValueConfig.class ), - - PACKET_TRANSITION_EFFECT( PacketTransitionEffect.class ), - - PACKET_PROGRESS_VALUE( PacketProgressBar.class ), - - PACKET_CLICK( PacketClick.class ), - - PACKET_SWITCH_GUIS( PacketSwitchGuis.class ), - - PACKET_SWAP_SLOTS( PacketSwapSlots.class ), - - PACKET_PATTERN_SLOT( PacketPatternSlot.class ), - - PACKET_RECIPE_JEI( PacketJEIRecipe.class ), - - PACKET_TARGET_ITEM( PacketTargetItemStack.class ), - - PACKET_TARGET_FLUID( PacketTargetFluidStack.class ), - - PACKET_CRAFTING_REQUEST( PacketCraftRequest.class ), - - PACKET_ASSEMBLER_ANIMATION( PacketAssemblerAnimation.class ), - - PACKET_COMPRESSED_NBT( PacketCompressedNBT.class ), - - PACKET_PAINTED_ENTITY( PacketPaintedEntity.class ), - - PACKET_FLUID_TANK( PacketFluidSlot.class ), - - PACKET_INFORM_PLAYER( PacketInformPlayer.class ), - - PACKET_CRAFTING_CPUS_UPDATE( PacketCraftingCPUsUpdate.class); - - - private final Class packetClass; - private final Constructor packetConstructor; - - PacketTypes( final Class c ) - { - this.packetClass = c; - - Constructor x = null; - try - { - x = this.packetClass.getConstructor( ByteBuf.class ); - } - catch( final NoSuchMethodException ignored ) - { - } - catch( final SecurityException ignored ) - { - } - - this.packetConstructor = x; - REVERSE_LOOKUP.put( this.packetClass, this ); - - if( this.packetConstructor == null ) - { - throw new IllegalStateException( "Invalid Packet Class " + c + ", must be constructable on DataInputStream" ); - } - } - - public static PacketTypes getPacket( final int id ) - { - return ( values() )[id]; - } - - static PacketTypes getID( final Class c ) - { - return REVERSE_LOOKUP.get( c ); - } - - public AppEngPacket parsePacket( final ByteBuf in ) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException - { - return this.packetConstructor.newInstance( in ); - } - } + public AppEngPacket parsePacket(final ByteBuf in) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + return this.packetConstructor.newInstance(in); + } + } } diff --git a/src/main/java/appeng/core/sync/GuiBridge.java b/src/main/java/appeng/core/sync/GuiBridge.java index c6bb4d245..64fcb6c26 100644 --- a/src/main/java/appeng/core/sync/GuiBridge.java +++ b/src/main/java/appeng/core/sync/GuiBridge.java @@ -19,22 +19,6 @@ package appeng.core.sync; -import java.lang.reflect.Constructor; - -import appeng.container.implementations.*; -import appeng.helpers.ICustomNameObject; -import appeng.items.contents.QuartzKnifeObj; -import appeng.parts.misc.PartOreDicStorageBus; -import appeng.parts.reporting.*; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.fml.common.network.IGuiHandler; -import net.minecraftforge.fml.relauncher.ReflectionHelper; - import appeng.api.AEApi; import appeng.api.config.SecurityPermissions; import appeng.api.exceptions.AppEngException; @@ -58,31 +42,27 @@ import appeng.client.gui.GuiNull; import appeng.container.AEBaseContainer; import appeng.container.ContainerNull; import appeng.container.ContainerOpenContext; -import appeng.fluids.container.ContainerFluidFormationPlane; -import appeng.fluids.container.ContainerFluidIO; -import appeng.fluids.container.ContainerFluidInterface; -import appeng.fluids.container.ContainerFluidLevelEmitter; -import appeng.fluids.container.ContainerFluidStorageBus; -import appeng.fluids.container.ContainerFluidTerminal; +import appeng.container.implementations.*; +import appeng.fluids.container.*; import appeng.fluids.helper.IFluidInterfaceHost; import appeng.fluids.parts.PartFluidFormationPlane; import appeng.fluids.parts.PartFluidLevelEmitter; import appeng.fluids.parts.PartFluidStorageBus; import appeng.fluids.parts.PartSharedFluidBus; +import appeng.helpers.ICustomNameObject; import appeng.helpers.IInterfaceHost; import appeng.helpers.IPriorityHost; import appeng.helpers.WirelessTerminalGuiObject; +import appeng.items.contents.QuartzKnifeObj; import appeng.parts.automation.PartFormationPlane; import appeng.parts.automation.PartLevelEmitter; +import appeng.parts.misc.PartOreDicStorageBus; import appeng.parts.misc.PartStorageBus; +import appeng.parts.reporting.*; import appeng.tile.crafting.TileCraftingTile; import appeng.tile.crafting.TileMolecularAssembler; import appeng.tile.grindstone.TileGrinder; -import appeng.tile.misc.TileCellWorkbench; -import appeng.tile.misc.TileCondenser; -import appeng.tile.misc.TileInscriber; -import appeng.tile.misc.TileSecurityStation; -import appeng.tile.misc.TileVibrationChamber; +import appeng.tile.misc.*; import appeng.tile.networking.TileWireless; import appeng.tile.qnb.TileQuantumBridge; import appeng.tile.spatial.TileSpatialIOPort; @@ -91,450 +71,381 @@ import appeng.tile.storage.TileDrive; import appeng.tile.storage.TileIOPort; import appeng.tile.storage.TileSkyChest; import appeng.util.Platform; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fml.common.network.IGuiHandler; +import net.minecraftforge.fml.relauncher.ReflectionHelper; +import java.lang.reflect.Constructor; -public enum GuiBridge implements IGuiHandler -{ - GUI_Handler(), - GUI_GRINDER( ContainerGrinder.class, TileGrinder.class, GuiHostType.WORLD, null ), +public enum GuiBridge implements IGuiHandler { + GUI_Handler(), - GUI_QNB( ContainerQNB.class, TileQuantumBridge.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_GRINDER(ContainerGrinder.class, TileGrinder.class, GuiHostType.WORLD, null), - GUI_SKYCHEST( ContainerSkyChest.class, TileSkyChest.class, GuiHostType.WORLD, null ), + GUI_QNB(ContainerQNB.class, TileQuantumBridge.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_CHEST( ContainerChest.class, TileChest.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_SKYCHEST(ContainerSkyChest.class, TileSkyChest.class, GuiHostType.WORLD, null), - GUI_WIRELESS( ContainerWireless.class, TileWireless.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_CHEST(ContainerChest.class, TileChest.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_ME( ContainerMEMonitorable.class, ITerminalHost.class, GuiHostType.WORLD, null ), + GUI_WIRELESS(ContainerWireless.class, TileWireless.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_PORTABLE_CELL( ContainerMEPortableCell.class, IPortableCell.class, GuiHostType.ITEM, null ), + GUI_ME(ContainerMEMonitorable.class, ITerminalHost.class, GuiHostType.WORLD, null), - GUI_WIRELESS_TERM( ContainerWirelessTerm.class, WirelessTerminalGuiObject.class, GuiHostType.ITEM, null ), + GUI_PORTABLE_CELL(ContainerMEPortableCell.class, IPortableCell.class, GuiHostType.ITEM, null), - GUI_NETWORK_STATUS( ContainerNetworkStatus.class, INetworkTool.class, GuiHostType.ITEM, null ), + GUI_WIRELESS_TERM(ContainerWirelessTerm.class, WirelessTerminalGuiObject.class, GuiHostType.ITEM, null), - GUI_CRAFTING_CPU( ContainerCraftingCPU.class, TileCraftingTile.class, GuiHostType.WORLD, SecurityPermissions.CRAFT ), + GUI_NETWORK_STATUS(ContainerNetworkStatus.class, INetworkTool.class, GuiHostType.ITEM, null), - GUI_NETWORK_TOOL( ContainerNetworkTool.class, INetworkTool.class, GuiHostType.ITEM, null ), + GUI_CRAFTING_CPU(ContainerCraftingCPU.class, TileCraftingTile.class, GuiHostType.WORLD, SecurityPermissions.CRAFT), - GUI_QUARTZ_KNIFE( ContainerQuartzKnife.class, QuartzKnifeObj.class, GuiHostType.ITEM, null ), + GUI_NETWORK_TOOL(ContainerNetworkTool.class, INetworkTool.class, GuiHostType.ITEM, null), - GUI_DRIVE( ContainerDrive.class, TileDrive.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_QUARTZ_KNIFE(ContainerQuartzKnife.class, QuartzKnifeObj.class, GuiHostType.ITEM, null), - GUI_VIBRATION_CHAMBER( ContainerVibrationChamber.class, TileVibrationChamber.class, GuiHostType.WORLD, null ), + GUI_DRIVE(ContainerDrive.class, TileDrive.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_CONDENSER( ContainerCondenser.class, TileCondenser.class, GuiHostType.WORLD, null ), + GUI_VIBRATION_CHAMBER(ContainerVibrationChamber.class, TileVibrationChamber.class, GuiHostType.WORLD, null), - GUI_INTERFACE( ContainerInterface.class, IInterfaceHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_CONDENSER(ContainerCondenser.class, TileCondenser.class, GuiHostType.WORLD, null), - GUI_FLUID_INTERFACE( ContainerFluidInterface.class, IFluidInterfaceHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_INTERFACE(ContainerInterface.class, IInterfaceHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_BUS( ContainerUpgradeable.class, IUpgradeableHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_FLUID_INTERFACE(ContainerFluidInterface.class, IFluidInterfaceHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_BUS_FLUID( ContainerFluidIO.class, PartSharedFluidBus.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_BUS(ContainerUpgradeable.class, IUpgradeableHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_IOPORT( ContainerIOPort.class, TileIOPort.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_BUS_FLUID(ContainerFluidIO.class, PartSharedFluidBus.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_STORAGEBUS( ContainerStorageBus.class, PartStorageBus.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_IOPORT(ContainerIOPort.class, TileIOPort.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_OREDICTSTORAGEBUS( ContainerOreDictStorageBus.class, PartOreDicStorageBus.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_STORAGEBUS(ContainerStorageBus.class, PartStorageBus.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_STORAGEBUS_FLUID( ContainerFluidStorageBus.class, PartFluidStorageBus.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_OREDICTSTORAGEBUS(ContainerOreDictStorageBus.class, PartOreDicStorageBus.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_FORMATION_PLANE( ContainerFormationPlane.class, PartFormationPlane.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_STORAGEBUS_FLUID(ContainerFluidStorageBus.class, PartFluidStorageBus.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_FLUID_FORMATION_PLANE( ContainerFluidFormationPlane.class, PartFluidFormationPlane.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_FORMATION_PLANE(ContainerFormationPlane.class, PartFormationPlane.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_PRIORITY( ContainerPriority.class, IPriorityHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_FLUID_FORMATION_PLANE(ContainerFluidFormationPlane.class, PartFluidFormationPlane.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_SECURITY( ContainerSecurityStation.class, TileSecurityStation.class, GuiHostType.WORLD, SecurityPermissions.SECURITY ), + GUI_PRIORITY(ContainerPriority.class, IPriorityHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_CRAFTING_TERMINAL( ContainerCraftingTerm.class, PartCraftingTerminal.class, GuiHostType.WORLD, SecurityPermissions.CRAFT ), + GUI_SECURITY(ContainerSecurityStation.class, TileSecurityStation.class, GuiHostType.WORLD, SecurityPermissions.SECURITY), - GUI_PATTERN_TERMINAL( ContainerPatternTerm.class, PartPatternTerminal.class, GuiHostType.WORLD, SecurityPermissions.CRAFT ), + GUI_CRAFTING_TERMINAL(ContainerCraftingTerm.class, PartCraftingTerminal.class, GuiHostType.WORLD, SecurityPermissions.CRAFT), - GUI_EXPANDED_PROCESSING_PATTERN_TERMINAL( ContainerExpandedProcessingPatternTerm.class, PartExpandedProcessingPatternTerminal.class, GuiHostType.WORLD, SecurityPermissions.CRAFT ), + GUI_PATTERN_TERMINAL(ContainerPatternTerm.class, PartPatternTerminal.class, GuiHostType.WORLD, SecurityPermissions.CRAFT), - GUI_FLUID_TERMINAL( ContainerFluidTerminal.class, ITerminalHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_EXPANDED_PROCESSING_PATTERN_TERMINAL(ContainerExpandedProcessingPatternTerm.class, PartExpandedProcessingPatternTerminal.class, GuiHostType.WORLD, SecurityPermissions.CRAFT), - // extends (Container/Gui) + Bus - GUI_LEVEL_EMITTER( ContainerLevelEmitter.class, PartLevelEmitter.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_FLUID_TERMINAL(ContainerFluidTerminal.class, ITerminalHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_FLUID_LEVEL_EMITTER( ContainerFluidLevelEmitter.class, PartFluidLevelEmitter.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + // extends (Container/Gui) + Bus + GUI_LEVEL_EMITTER(ContainerLevelEmitter.class, PartLevelEmitter.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_SPATIAL_IO_PORT( ContainerSpatialIOPort.class, TileSpatialIOPort.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_FLUID_LEVEL_EMITTER(ContainerFluidLevelEmitter.class, PartFluidLevelEmitter.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_INSCRIBER( ContainerInscriber.class, TileInscriber.class, GuiHostType.WORLD, null ), + GUI_SPATIAL_IO_PORT(ContainerSpatialIOPort.class, TileSpatialIOPort.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_CELL_WORKBENCH( ContainerCellWorkbench.class, TileCellWorkbench.class, GuiHostType.WORLD, null ), + GUI_INSCRIBER(ContainerInscriber.class, TileInscriber.class, GuiHostType.WORLD, null), - GUI_MAC( ContainerMAC.class, TileMolecularAssembler.class, GuiHostType.WORLD, null ), + GUI_CELL_WORKBENCH(ContainerCellWorkbench.class, TileCellWorkbench.class, GuiHostType.WORLD, null), - GUI_CRAFTING_AMOUNT( ContainerCraftAmount.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT ), + GUI_MAC(ContainerMAC.class, TileMolecularAssembler.class, GuiHostType.WORLD, null), - GUI_CRAFTING_CONFIRM( ContainerCraftConfirm.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT ), + GUI_CRAFTING_AMOUNT(ContainerCraftAmount.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT), - GUI_INTERFACE_TERMINAL( ContainerInterfaceTerminal.class, PartInterfaceTerminal.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_CRAFTING_CONFIRM(ContainerCraftConfirm.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT), - GUI_CRAFTING_STATUS( ContainerCraftingStatus.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT ), + GUI_INTERFACE_TERMINAL(ContainerInterfaceTerminal.class, PartInterfaceTerminal.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_INTERFACE_CONFIGURATION_TERMINAL( ContainerInterfaceConfigurationTerminal.class, PartInterfaceConfigurationTerminal.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_CRAFTING_STATUS(ContainerCraftingStatus.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT), - GUI_RENAMER( ContainerRenamer.class, ICustomNameObject.class, GuiHostType.WORLD, SecurityPermissions.BUILD ); + GUI_INTERFACE_CONFIGURATION_TERMINAL(ContainerInterfaceConfigurationTerminal.class, PartInterfaceConfigurationTerminal.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - private final Class tileClass; - private final Class containerClass; - private Class guiClass; - private GuiHostType type; - private SecurityPermissions requiredPermission; + GUI_RENAMER(ContainerRenamer.class, ICustomNameObject.class, GuiHostType.WORLD, SecurityPermissions.BUILD); - GuiBridge() - { - this.tileClass = null; - this.guiClass = null; - this.containerClass = null; - } + private final Class tileClass; + private final Class containerClass; + private Class guiClass; + private GuiHostType type; + private SecurityPermissions requiredPermission; - GuiBridge( final Class containerClass, final SecurityPermissions requiredPermission ) - { - this.requiredPermission = requiredPermission; - this.containerClass = containerClass; - this.tileClass = null; - this.getGui(); - } + GuiBridge() { + this.tileClass = null; + this.guiClass = null; + this.containerClass = null; + } - /** - * I honestly wish I could just use the GuiClass Names myself, but I can't access them without MC's Server - * Exploding. - */ - private void getGui() - { - if( Platform.isClient() ) - { - AEBaseGui.class.getName(); - - final String start = this.containerClass.getName(); - final String guiClass = start.replaceFirst( "container.", "client.gui." ).replace( ".Container", ".Gui" ); - - if( start.equals( guiClass ) ) - { - throw new IllegalStateException( "Unable to find gui class" ); - } - this.guiClass = ReflectionHelper.getClass( this.getClass().getClassLoader(), guiClass ); - if( this.guiClass == null ) - { - throw new IllegalStateException( "Cannot Load class: " + guiClass ); - } - } - } - - GuiBridge( final Class containerClass, final Class tileClass, final GuiHostType type, final SecurityPermissions requiredPermission ) - { - this.requiredPermission = requiredPermission; - this.containerClass = containerClass; - this.type = type; - this.tileClass = tileClass; - this.getGui(); - } - - @Override - public Object getServerGuiElement( final int ordinal, final EntityPlayer player, final World w, final int x, final int y, final int z ) - { - final AEPartLocation side = AEPartLocation.fromOrdinal( ordinal & 0x07 ); - final GuiBridge ID = values()[ordinal >> 4]; - final boolean stem = ( ( ordinal >> 3 ) & 1 ) == 1; - if( ID.type.isItem() ) - { - ItemStack it = ItemStack.EMPTY; - if( stem ) - { - it = player.inventory.getCurrentItem(); - } - else if( x >= 0 && x < player.inventory.mainInventory.size() ) - { - it = player.inventory.getStackInSlot( x ); - } - final Object myItem = this.getGuiObject( it, player, w, x, y, z ); - if( myItem != null && ID.CorrectTileOrPart( myItem ) ) - { - return this.updateGui( ID.ConstructContainer( player.inventory, side, myItem ), w, x, y, z, side, myItem ); - } - } - if( ID.type.isTile() ) - { - final TileEntity TE = w.getTileEntity( new BlockPos( x, y, z ) ); - if( TE instanceof IPartHost ) - { - ( (IPartHost) TE ).getPart( side ); - final IPart part = ( (IPartHost) TE ).getPart( side ); - if( ID.CorrectTileOrPart( part ) ) - { - return this.updateGui( ID.ConstructContainer( player.inventory, side, part ), w, x, y, z, side, part ); - } - } - else - { - if( ID.CorrectTileOrPart( TE ) ) - { - return this.updateGui( ID.ConstructContainer( player.inventory, side, TE ), w, x, y, z, side, TE ); - } - } - } - return new ContainerNull(); - } - - private Object getGuiObject( final ItemStack it, final EntityPlayer player, final World w, final int x, final int y, final int z ) - { - if( !it.isEmpty() ) - { - if( it.getItem() instanceof IGuiItem ) - { - return ( (IGuiItem) it.getItem() ).getGuiObject( it, w, new BlockPos( x, y, z ) ); - } - - final IWirelessTermHandler wh = AEApi.instance().registries().wireless().getWirelessTerminalHandler( it ); - if( wh != null ) - { - return new WirelessTerminalGuiObject( wh, it, player, w, x, y, z ); - } - } - - return null; - } - - public boolean CorrectTileOrPart( final Object tE ) - { - if( this.tileClass == null ) - { - throw new IllegalArgumentException( "This Gui Cannot use the standard Handler." ); - } - - return this.tileClass.isInstance( tE ); - } - - private Object updateGui( final Object newContainer, final World w, final int x, final int y, final int z, final AEPartLocation side, final Object myItem ) - { - if( newContainer instanceof AEBaseContainer ) - { - final AEBaseContainer bc = (AEBaseContainer) newContainer; - bc.setOpenContext( new ContainerOpenContext( myItem ) ); - bc.getOpenContext().setWorld( w ); - bc.getOpenContext().setX( x ); - bc.getOpenContext().setY( y ); - bc.getOpenContext().setZ( z ); - bc.getOpenContext().setSide( side ); - } - - return newContainer; - } - - public Object ConstructContainer( final InventoryPlayer inventory, final AEPartLocation side, final Object tE ) - { - try - { - final Constructor[] c = this.containerClass.getConstructors(); - if( c.length == 0 ) - { - throw new AppEngException( "Invalid Gui Class" ); - } - - final Constructor target = this.findConstructor( c, inventory, tE ); - - if( target == null ) - { - throw new IllegalStateException( "Cannot find " + this.containerClass.getName() + "( " + this.typeName( inventory ) + ", " + this - .typeName( tE ) + " )" ); - } - - return target.newInstance( inventory, tE ); - } - catch( final Throwable t ) - { - throw new IllegalStateException( t ); - } - } - - private Constructor findConstructor( final Constructor[] c, final InventoryPlayer inventory, final Object tE ) - { - for( final Constructor con : c ) - { - final Class[] types = con.getParameterTypes(); - if( types.length == 2 ) - { - if( types[0].isAssignableFrom( inventory.getClass() ) && types[1].isAssignableFrom( tE.getClass() ) ) - { - return con; - } - } - } - return null; - } - - private String typeName( final Object inventory ) - { - if( inventory == null ) - { - return "NULL"; - } - - return inventory.getClass().getName(); - } - - @Override - public Object getClientGuiElement( final int ordinal, final EntityPlayer player, final World w, final int x, final int y, final int z ) - { - final AEPartLocation side = AEPartLocation.fromOrdinal( ordinal & 0x07 ); - final GuiBridge ID = values()[ordinal >> 4]; - final boolean stem = ( ( ordinal >> 3 ) & 1 ) == 1; - if( ID.type.isItem() ) - { - ItemStack it = ItemStack.EMPTY; - if( stem ) - { - it = player.inventory.getCurrentItem(); - } - else if( x >= 0 && x < player.inventory.mainInventory.size() ) - { - it = player.inventory.getStackInSlot( x ); - } - final Object myItem = this.getGuiObject( it, player, w, x, y, z ); - if( myItem != null && ID.CorrectTileOrPart( myItem ) ) - { - return ID.ConstructGui( player.inventory, side, myItem ); - } - } - if( ID.type.isTile() ) - { - final TileEntity TE = w.getTileEntity( new BlockPos( x, y, z ) ); - if( TE instanceof IPartHost ) - { - ( (IPartHost) TE ).getPart( side ); - final IPart part = ( (IPartHost) TE ).getPart( side ); - if( ID.CorrectTileOrPart( part ) ) - { - return ID.ConstructGui( player.inventory, side, part ); - } - } - else - { - if( ID.CorrectTileOrPart( TE ) ) - { - return ID.ConstructGui( player.inventory, side, TE ); - } - } - } - return new GuiNull( new ContainerNull() ); - } - - public Object ConstructGui( final InventoryPlayer inventory, final AEPartLocation side, final Object tE ) - { - try - { - final Constructor[] c = this.guiClass.getConstructors(); - if( c.length == 0 ) - { - throw new AppEngException( "Invalid Gui Class" ); - } - - final Constructor target = this.findConstructor( c, inventory, tE ); - - if( target == null ) - { - throw new IllegalStateException( "Cannot find " + this.containerClass.getName() + "( " + this.typeName( inventory ) + ", " + this - .typeName( tE ) + " )" ); - } - - return target.newInstance( inventory, tE ); - } - catch( final Throwable t ) - { - throw new IllegalStateException( t ); - } - } - - public boolean hasPermissions( final TileEntity te, final int x, final int y, final int z, final AEPartLocation side, final EntityPlayer player ) - { - final World w = player.getEntityWorld(); - final BlockPos pos = new BlockPos( x, y, z ); - - if( Platform.hasPermissions( te != null ? new DimensionalCoord( te ) : new DimensionalCoord( player.world, pos ), player ) ) - { - if( this.type.isItem() ) - { - final ItemStack it = player.inventory.getCurrentItem(); - if( !it.isEmpty() && it.getItem() instanceof IGuiItem ) - { - final Object myItem = ( (IGuiItem) it.getItem() ).getGuiObject( it, w, pos ); - if( this.CorrectTileOrPart( myItem ) ) - { - return true; - } - } - } - - if( this.type.isTile() ) - { - final TileEntity TE = w.getTileEntity( pos ); - if( TE instanceof IPartHost ) - { - ( (IPartHost) TE ).getPart( side ); - final IPart part = ( (IPartHost) TE ).getPart( side ); - if( this.CorrectTileOrPart( part ) ) - { - return this.securityCheck( part, player ); - } - } - else - { - if( this.CorrectTileOrPart( TE ) ) - { - return this.securityCheck( TE, player ); - } - } - } - } - return false; - } - - private boolean securityCheck( final Object te, final EntityPlayer player ) - { - if( te instanceof IActionHost && this.requiredPermission != null ) - { - - final IGridNode gn = ( (IActionHost) te ).getActionableNode(); - if( gn != null ) - { - final IGrid g = gn.getGrid(); - if( g != null ) - { - final boolean requirePower = false; - if( requirePower ) - { - final IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - if( !eg.isNetworkPowered() ) - { - return false; - } - } - - final ISecurityGrid sg = g.getCache( ISecurityGrid.class ); - if( sg.hasPermission( player, this.requiredPermission ) ) - { - return true; - } - } - } - - return false; - } - return true; - } - - public GuiHostType getType() - { - return this.type; - } + GuiBridge(final Class containerClass, final SecurityPermissions requiredPermission) { + this.requiredPermission = requiredPermission; + this.containerClass = containerClass; + this.tileClass = null; + this.getGui(); + } + + /** + * I honestly wish I could just use the GuiClass Names myself, but I can't access them without MC's Server + * Exploding. + */ + private void getGui() { + if (Platform.isClient()) { + AEBaseGui.class.getName(); + + final String start = this.containerClass.getName(); + final String guiClass = start.replaceFirst("container.", "client.gui.").replace(".Container", ".Gui"); + + if (start.equals(guiClass)) { + throw new IllegalStateException("Unable to find gui class"); + } + this.guiClass = ReflectionHelper.getClass(this.getClass().getClassLoader(), guiClass); + if (this.guiClass == null) { + throw new IllegalStateException("Cannot Load class: " + guiClass); + } + } + } + + GuiBridge(final Class containerClass, final Class tileClass, final GuiHostType type, final SecurityPermissions requiredPermission) { + this.requiredPermission = requiredPermission; + this.containerClass = containerClass; + this.type = type; + this.tileClass = tileClass; + this.getGui(); + } + + @Override + public Object getServerGuiElement(final int ordinal, final EntityPlayer player, final World w, final int x, final int y, final int z) { + final AEPartLocation side = AEPartLocation.fromOrdinal(ordinal & 0x07); + final GuiBridge ID = values()[ordinal >> 4]; + final boolean stem = ((ordinal >> 3) & 1) == 1; + if (ID.type.isItem()) { + ItemStack it = ItemStack.EMPTY; + if (stem) { + it = player.inventory.getCurrentItem(); + } else if (x >= 0 && x < player.inventory.mainInventory.size()) { + it = player.inventory.getStackInSlot(x); + } + final Object myItem = this.getGuiObject(it, player, w, x, y, z); + if (myItem != null && ID.CorrectTileOrPart(myItem)) { + return this.updateGui(ID.ConstructContainer(player.inventory, side, myItem), w, x, y, z, side, myItem); + } + } + if (ID.type.isTile()) { + final TileEntity TE = w.getTileEntity(new BlockPos(x, y, z)); + if (TE instanceof IPartHost) { + ((IPartHost) TE).getPart(side); + final IPart part = ((IPartHost) TE).getPart(side); + if (ID.CorrectTileOrPart(part)) { + return this.updateGui(ID.ConstructContainer(player.inventory, side, part), w, x, y, z, side, part); + } + } else { + if (ID.CorrectTileOrPart(TE)) { + return this.updateGui(ID.ConstructContainer(player.inventory, side, TE), w, x, y, z, side, TE); + } + } + } + return new ContainerNull(); + } + + private Object getGuiObject(final ItemStack it, final EntityPlayer player, final World w, final int x, final int y, final int z) { + if (!it.isEmpty()) { + if (it.getItem() instanceof IGuiItem) { + return ((IGuiItem) it.getItem()).getGuiObject(it, w, new BlockPos(x, y, z)); + } + + final IWirelessTermHandler wh = AEApi.instance().registries().wireless().getWirelessTerminalHandler(it); + if (wh != null) { + return new WirelessTerminalGuiObject(wh, it, player, w, x, y, z); + } + } + + return null; + } + + public boolean CorrectTileOrPart(final Object tE) { + if (this.tileClass == null) { + throw new IllegalArgumentException("This Gui Cannot use the standard Handler."); + } + + return this.tileClass.isInstance(tE); + } + + private Object updateGui(final Object newContainer, final World w, final int x, final int y, final int z, final AEPartLocation side, final Object myItem) { + if (newContainer instanceof AEBaseContainer) { + final AEBaseContainer bc = (AEBaseContainer) newContainer; + bc.setOpenContext(new ContainerOpenContext(myItem)); + bc.getOpenContext().setWorld(w); + bc.getOpenContext().setX(x); + bc.getOpenContext().setY(y); + bc.getOpenContext().setZ(z); + bc.getOpenContext().setSide(side); + } + + return newContainer; + } + + public Object ConstructContainer(final InventoryPlayer inventory, final AEPartLocation side, final Object tE) { + try { + final Constructor[] c = this.containerClass.getConstructors(); + if (c.length == 0) { + throw new AppEngException("Invalid Gui Class"); + } + + final Constructor target = this.findConstructor(c, inventory, tE); + + if (target == null) { + throw new IllegalStateException("Cannot find " + this.containerClass.getName() + "( " + this.typeName(inventory) + ", " + this + .typeName(tE) + " )"); + } + + return target.newInstance(inventory, tE); + } catch (final Throwable t) { + throw new IllegalStateException(t); + } + } + + private Constructor findConstructor(final Constructor[] c, final InventoryPlayer inventory, final Object tE) { + for (final Constructor con : c) { + final Class[] types = con.getParameterTypes(); + if (types.length == 2) { + if (types[0].isAssignableFrom(inventory.getClass()) && types[1].isAssignableFrom(tE.getClass())) { + return con; + } + } + } + return null; + } + + private String typeName(final Object inventory) { + if (inventory == null) { + return "NULL"; + } + + return inventory.getClass().getName(); + } + + @Override + public Object getClientGuiElement(final int ordinal, final EntityPlayer player, final World w, final int x, final int y, final int z) { + final AEPartLocation side = AEPartLocation.fromOrdinal(ordinal & 0x07); + final GuiBridge ID = values()[ordinal >> 4]; + final boolean stem = ((ordinal >> 3) & 1) == 1; + if (ID.type.isItem()) { + ItemStack it = ItemStack.EMPTY; + if (stem) { + it = player.inventory.getCurrentItem(); + } else if (x >= 0 && x < player.inventory.mainInventory.size()) { + it = player.inventory.getStackInSlot(x); + } + final Object myItem = this.getGuiObject(it, player, w, x, y, z); + if (myItem != null && ID.CorrectTileOrPart(myItem)) { + return ID.ConstructGui(player.inventory, side, myItem); + } + } + if (ID.type.isTile()) { + final TileEntity TE = w.getTileEntity(new BlockPos(x, y, z)); + if (TE instanceof IPartHost) { + ((IPartHost) TE).getPart(side); + final IPart part = ((IPartHost) TE).getPart(side); + if (ID.CorrectTileOrPart(part)) { + return ID.ConstructGui(player.inventory, side, part); + } + } else { + if (ID.CorrectTileOrPart(TE)) { + return ID.ConstructGui(player.inventory, side, TE); + } + } + } + return new GuiNull(new ContainerNull()); + } + + public Object ConstructGui(final InventoryPlayer inventory, final AEPartLocation side, final Object tE) { + try { + final Constructor[] c = this.guiClass.getConstructors(); + if (c.length == 0) { + throw new AppEngException("Invalid Gui Class"); + } + + final Constructor target = this.findConstructor(c, inventory, tE); + + if (target == null) { + throw new IllegalStateException("Cannot find " + this.containerClass.getName() + "( " + this.typeName(inventory) + ", " + this + .typeName(tE) + " )"); + } + + return target.newInstance(inventory, tE); + } catch (final Throwable t) { + throw new IllegalStateException(t); + } + } + + public boolean hasPermissions(final TileEntity te, final int x, final int y, final int z, final AEPartLocation side, final EntityPlayer player) { + final World w = player.getEntityWorld(); + final BlockPos pos = new BlockPos(x, y, z); + + if (Platform.hasPermissions(te != null ? new DimensionalCoord(te) : new DimensionalCoord(player.world, pos), player)) { + if (this.type.isItem()) { + final ItemStack it = player.inventory.getCurrentItem(); + if (!it.isEmpty() && it.getItem() instanceof IGuiItem) { + final Object myItem = ((IGuiItem) it.getItem()).getGuiObject(it, w, pos); + if (this.CorrectTileOrPart(myItem)) { + return true; + } + } + } + + if (this.type.isTile()) { + final TileEntity TE = w.getTileEntity(pos); + if (TE instanceof IPartHost) { + ((IPartHost) TE).getPart(side); + final IPart part = ((IPartHost) TE).getPart(side); + if (this.CorrectTileOrPart(part)) { + return this.securityCheck(part, player); + } + } else { + if (this.CorrectTileOrPart(TE)) { + return this.securityCheck(TE, player); + } + } + } + } + return false; + } + + private boolean securityCheck(final Object te, final EntityPlayer player) { + if (te instanceof IActionHost && this.requiredPermission != null) { + + final IGridNode gn = ((IActionHost) te).getActionableNode(); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + final boolean requirePower = false; + if (requirePower) { + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + if (!eg.isNetworkPowered()) { + return false; + } + } + + final ISecurityGrid sg = g.getCache(ISecurityGrid.class); + return sg.hasPermission(player, this.requiredPermission); + } + } + + return false; + } + return true; + } + + public GuiHostType getType() { + return this.type; + } } diff --git a/src/main/java/appeng/core/sync/GuiHostType.java b/src/main/java/appeng/core/sync/GuiHostType.java index ac7800285..ea503e758 100644 --- a/src/main/java/appeng/core/sync/GuiHostType.java +++ b/src/main/java/appeng/core/sync/GuiHostType.java @@ -19,17 +19,14 @@ package appeng.core.sync; -public enum GuiHostType -{ - ITEM_OR_WORLD, ITEM, WORLD; +public enum GuiHostType { + ITEM_OR_WORLD, ITEM, WORLD; - public boolean isItem() - { - return this != WORLD; - } + public boolean isItem() { + return this != WORLD; + } - boolean isTile() - { - return this != ITEM; - } + boolean isTile() { + return this != ITEM; + } } diff --git a/src/main/java/appeng/core/sync/PacketCallState.java b/src/main/java/appeng/core/sync/PacketCallState.java index 71c316b20..82c9ddbb1 100644 --- a/src/main/java/appeng/core/sync/PacketCallState.java +++ b/src/main/java/appeng/core/sync/PacketCallState.java @@ -19,9 +19,8 @@ package appeng.core.sync; -public abstract class PacketCallState -{ +public abstract class PacketCallState { - public abstract void call( AppEngPacket appEngPacket ); + public abstract void call(AppEngPacket appEngPacket); } diff --git a/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java b/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java index 193440e46..2ae747e2d 100644 --- a/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java +++ b/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java @@ -19,64 +19,49 @@ package appeng.core.sync.network; -import java.lang.reflect.InvocationTargetException; - +import appeng.core.AELog; +import appeng.core.sync.AppEngPacket; +import appeng.core.sync.AppEngPacketHandlerBase; +import appeng.core.sync.PacketCallState; import io.netty.buffer.ByteBuf; - import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.INetHandler; import net.minecraft.network.PacketThreadUtil; import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; -import appeng.core.AELog; -import appeng.core.sync.AppEngPacket; -import appeng.core.sync.AppEngPacketHandlerBase; -import appeng.core.sync.PacketCallState; +import java.lang.reflect.InvocationTargetException; -public class AppEngClientPacketHandler extends AppEngPacketHandlerBase implements IPacketHandler -{ +public class AppEngClientPacketHandler extends AppEngPacketHandlerBase implements IPacketHandler { - @Override - public void onPacketData( final INetworkInfo manager, final INetHandler handler, final FMLProxyPacket packet, final EntityPlayer player ) - { - final ByteBuf stream = packet.payload(); + @Override + public void onPacketData(final INetworkInfo manager, final INetHandler handler, final FMLProxyPacket packet, final EntityPlayer player) { + final ByteBuf stream = packet.payload(); - try - { - final int packetType = stream.readInt(); - final AppEngPacket pack = PacketTypes.getPacket( packetType ).parsePacket( stream ); + try { + final int packetType = stream.readInt(); + final AppEngPacket pack = PacketTypes.getPacket(packetType).parsePacket(stream); - final PacketCallState callState = new PacketCallState() - { + final PacketCallState callState = new PacketCallState() { - @Override - public void call( final AppEngPacket appEngPacket ) - { - appEngPacket.clientPacketData( manager, appEngPacket, Minecraft.getMinecraft().player ); - } - }; + @Override + public void call(final AppEngPacket appEngPacket) { + appEngPacket.clientPacketData(manager, appEngPacket, Minecraft.getMinecraft().player); + } + }; - pack.setCallParam( callState ); - PacketThreadUtil.checkThreadAndEnqueue( pack, handler, Minecraft.getMinecraft() ); - callState.call( pack ); - } - catch( final InstantiationException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final InvocationTargetException e ) - { - AELog.debug( e ); - } - } + pack.setCallParam(callState); + PacketThreadUtil.checkThreadAndEnqueue(pack, handler, Minecraft.getMinecraft()); + callState.call(pack); + } catch (final InstantiationException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final InvocationTargetException e) { + AELog.debug(e); + } + } } diff --git a/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java b/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java index a7546bd6f..1d96e70e7 100644 --- a/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java +++ b/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java @@ -19,64 +19,49 @@ package appeng.core.sync.network; -import java.lang.reflect.InvocationTargetException; - +import appeng.core.AELog; +import appeng.core.sync.AppEngPacket; +import appeng.core.sync.AppEngPacketHandlerBase; +import appeng.core.sync.PacketCallState; import io.netty.buffer.ByteBuf; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.INetHandler; import net.minecraft.network.PacketThreadUtil; import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; -import appeng.core.AELog; -import appeng.core.sync.AppEngPacket; -import appeng.core.sync.AppEngPacketHandlerBase; -import appeng.core.sync.PacketCallState; +import java.lang.reflect.InvocationTargetException; -public final class AppEngServerPacketHandler extends AppEngPacketHandlerBase implements IPacketHandler -{ +public final class AppEngServerPacketHandler extends AppEngPacketHandlerBase implements IPacketHandler { - @Override - public void onPacketData( final INetworkInfo manager, final INetHandler handler, final FMLProxyPacket packet, final EntityPlayer player ) - { - final ByteBuf stream = packet.payload(); + @Override + public void onPacketData(final INetworkInfo manager, final INetHandler handler, final FMLProxyPacket packet, final EntityPlayer player) { + final ByteBuf stream = packet.payload(); - try - { - final int packetType = stream.readInt(); - final AppEngPacket pack = PacketTypes.getPacket( packetType ).parsePacket( stream ); + try { + final int packetType = stream.readInt(); + final AppEngPacket pack = PacketTypes.getPacket(packetType).parsePacket(stream); - final PacketCallState callState = new PacketCallState() - { + final PacketCallState callState = new PacketCallState() { - @Override - public void call( final AppEngPacket appEngPacket ) - { - appEngPacket.serverPacketData( manager, appEngPacket, player ); - } - }; + @Override + public void call(final AppEngPacket appEngPacket) { + appEngPacket.serverPacketData(manager, appEngPacket, player); + } + }; - pack.setCallParam( callState ); - PacketThreadUtil.checkThreadAndEnqueue( pack, handler, ( (EntityPlayerMP) player ).getServer() ); - callState.call( pack ); - } - catch( final InstantiationException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final InvocationTargetException e ) - { - AELog.debug( e ); - } - } + pack.setCallParam(callState); + PacketThreadUtil.checkThreadAndEnqueue(pack, handler, player.getServer()); + callState.call(pack); + } catch (final InstantiationException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final InvocationTargetException e) { + AELog.debug(e); + } + } } diff --git a/src/main/java/appeng/core/sync/network/INetworkInfo.java b/src/main/java/appeng/core/sync/network/INetworkInfo.java index 51766b76c..5fb7e60c8 100644 --- a/src/main/java/appeng/core/sync/network/INetworkInfo.java +++ b/src/main/java/appeng/core/sync/network/INetworkInfo.java @@ -19,7 +19,6 @@ package appeng.core.sync.network; -public interface INetworkInfo -{ +public interface INetworkInfo { } diff --git a/src/main/java/appeng/core/sync/network/IPacketHandler.java b/src/main/java/appeng/core/sync/network/IPacketHandler.java index be5cf3972..a7e921de7 100644 --- a/src/main/java/appeng/core/sync/network/IPacketHandler.java +++ b/src/main/java/appeng/core/sync/network/IPacketHandler.java @@ -24,9 +24,8 @@ import net.minecraft.network.INetHandler; import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; -public interface IPacketHandler -{ +public interface IPacketHandler { - void onPacketData( INetworkInfo manager, INetHandler handler, FMLProxyPacket packet, EntityPlayer player ); + void onPacketData(INetworkInfo manager, INetHandler handler, FMLProxyPacket packet, EntityPlayer player); } diff --git a/src/main/java/appeng/core/sync/network/NetworkHandler.java b/src/main/java/appeng/core/sync/network/NetworkHandler.java index 384329a15..06a452fb4 100644 --- a/src/main/java/appeng/core/sync/network/NetworkHandler.java +++ b/src/main/java/appeng/core/sync/network/NetworkHandler.java @@ -19,6 +19,7 @@ package appeng.core.sync.network; +import appeng.core.sync.AppEngPacket; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.ThreadQuickExitException; @@ -29,123 +30,93 @@ import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientCustomPacketE import net.minecraftforge.fml.common.network.FMLNetworkEvent.ServerCustomPacketEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; -import appeng.core.sync.AppEngPacket; +public class NetworkHandler { + public static NetworkHandler instance; -public class NetworkHandler -{ - public static NetworkHandler instance; + private final FMLEventChannel ec; + private final String myChannelName; - private final FMLEventChannel ec; - private final String myChannelName; + private final IPacketHandler clientHandler; + private final IPacketHandler serveHandler; - private final IPacketHandler clientHandler; - private final IPacketHandler serveHandler; + public NetworkHandler(final String channelName) { + FMLCommonHandler.instance().bus().register(this); + this.ec = NetworkRegistry.INSTANCE.newEventDrivenChannel(this.myChannelName = channelName); + this.ec.register(this); - public NetworkHandler( final String channelName ) - { - FMLCommonHandler.instance().bus().register( this ); - this.ec = NetworkRegistry.INSTANCE.newEventDrivenChannel( this.myChannelName = channelName ); - this.ec.register( this ); + this.clientHandler = this.createClientSide(); + this.serveHandler = this.createServerSide(); + } - this.clientHandler = this.createClientSide(); - this.serveHandler = this.createServerSide(); - } + public static void init(final String channelName) { + instance = new NetworkHandler(channelName); + } - public static void init( final String channelName ) - { - instance = new NetworkHandler( channelName ); - } + public static NetworkHandler instance() { + return instance; + } - public static NetworkHandler instance() - { - return instance; - } + private IPacketHandler createClientSide() { + try { + return new AppEngClientPacketHandler(); + } catch (final Throwable t) { + return null; + } + } - private IPacketHandler createClientSide() - { - try - { - return new AppEngClientPacketHandler(); - } - catch( final Throwable t ) - { - return null; - } - } + private IPacketHandler createServerSide() { + try { + return new AppEngServerPacketHandler(); + } catch (final Throwable t) { + return null; + } + } - private IPacketHandler createServerSide() - { - try - { - return new AppEngServerPacketHandler(); - } - catch( final Throwable t ) - { - return null; - } - } + @SubscribeEvent + public void serverPacket(final ServerCustomPacketEvent ev) { + final NetHandlerPlayServer srv = (NetHandlerPlayServer) ev.getPacket().handler(); + if (this.serveHandler != null) { + try { + this.serveHandler.onPacketData(null, ev.getHandler(), ev.getPacket(), srv.player); + } catch (final ThreadQuickExitException ignored) { - @SubscribeEvent - public void serverPacket( final ServerCustomPacketEvent ev ) - { - final NetHandlerPlayServer srv = (NetHandlerPlayServer) ev.getPacket().handler(); - if( this.serveHandler != null ) - { - try - { - this.serveHandler.onPacketData( null, ev.getHandler(), ev.getPacket(), srv.player ); - } - catch( final ThreadQuickExitException ignored ) - { + } + } + } - } - } - } + @SubscribeEvent + public void clientPacket(final ClientCustomPacketEvent ev) { + if (this.clientHandler != null) { + try { + this.clientHandler.onPacketData(null, ev.getHandler(), ev.getPacket(), null); + } catch (final ThreadQuickExitException ignored) { - @SubscribeEvent - public void clientPacket( final ClientCustomPacketEvent ev ) - { - if( this.clientHandler != null ) - { - try - { - this.clientHandler.onPacketData( null, ev.getHandler(), ev.getPacket(), null ); - } - catch( final ThreadQuickExitException ignored ) - { + } + } + } - } - } - } + public String getChannel() { + return this.myChannelName; + } - public String getChannel() - { - return this.myChannelName; - } + public void sendToAll(final AppEngPacket message) { + this.ec.sendToAll(message.getProxy()); + } - public void sendToAll( final AppEngPacket message ) - { - this.ec.sendToAll( message.getProxy() ); - } + public void sendTo(final AppEngPacket message, final EntityPlayerMP player) { + this.ec.sendTo(message.getProxy(), player); + } - public void sendTo( final AppEngPacket message, final EntityPlayerMP player ) - { - this.ec.sendTo( message.getProxy(), player ); - } + public void sendToAllAround(final AppEngPacket message, final NetworkRegistry.TargetPoint point) { + this.ec.sendToAllAround(message.getProxy(), point); + } - public void sendToAllAround( final AppEngPacket message, final NetworkRegistry.TargetPoint point ) - { - this.ec.sendToAllAround( message.getProxy(), point ); - } + public void sendToDimension(final AppEngPacket message, final int dimensionId) { + this.ec.sendToDimension(message.getProxy(), dimensionId); + } - public void sendToDimension( final AppEngPacket message, final int dimensionId ) - { - this.ec.sendToDimension( message.getProxy(), dimensionId ); - } - - public void sendToServer( final AppEngPacket message ) - { - this.ec.sendToServer( message.getProxy() ); - } + public void sendToServer(final AppEngPacket message) { + this.ec.sendToServer(message.getProxy()); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketAssemblerAnimation.java b/src/main/java/appeng/core/sync/packets/PacketAssemblerAnimation.java index c4993e557..f72d6e543 100644 --- a/src/main/java/appeng/core/sync/packets/PacketAssemblerAnimation.java +++ b/src/main/java/appeng/core/sync/packets/PacketAssemblerAnimation.java @@ -19,68 +19,62 @@ package appeng.core.sync.packets; -import java.io.IOException; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.math.BlockPos; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.storage.data.IAEItemStack; import appeng.client.EffectType; import appeng.core.AppEng; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.util.item.AEItemStack; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import java.io.IOException; -public class PacketAssemblerAnimation extends AppEngPacket -{ +public class PacketAssemblerAnimation extends AppEngPacket { - private final int x; - private final int y; - private final int z; - public final byte rate; - public final IAEItemStack is; + private final int x; + private final int y; + private final int z; + public final byte rate; + public final IAEItemStack is; - // automatic. - public PacketAssemblerAnimation( final ByteBuf stream ) throws IOException - { - this.x = stream.readInt(); - this.y = stream.readInt(); - this.z = stream.readInt(); - this.rate = stream.readByte(); - this.is = AEItemStack.fromPacket( stream ); - } + // automatic. + public PacketAssemblerAnimation(final ByteBuf stream) throws IOException { + this.x = stream.readInt(); + this.y = stream.readInt(); + this.z = stream.readInt(); + this.rate = stream.readByte(); + this.is = AEItemStack.fromPacket(stream); + } - // api - public PacketAssemblerAnimation( final BlockPos pos, final byte rate, final IAEItemStack is ) throws IOException - { + // api + public PacketAssemblerAnimation(final BlockPos pos, final byte rate, final IAEItemStack is) throws IOException { - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( this.x = pos.getX() ); - data.writeInt( this.y = pos.getY() ); - data.writeInt( this.z = pos.getZ() ); - data.writeByte( this.rate = rate ); - is.writeToPacket( data ); - this.is = is; + data.writeInt(this.getPacketID()); + data.writeInt(this.x = pos.getX()); + data.writeInt(this.y = pos.getY()); + data.writeInt(this.z = pos.getZ()); + data.writeByte(this.rate = rate); + is.writeToPacket(data); + this.is = is; - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final double d0 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); - final double d1 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); - final double d2 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final double d0 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); + final double d1 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); + final double d2 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); - AppEng.proxy.spawnEffect( EffectType.Assembler, player.getEntityWorld(), this.x + d0, this.y + d1, this.z + d2, this ); - } + AppEng.proxy.spawnEffect(EffectType.Assembler, player.getEntityWorld(), this.x + d0, this.y + d1, this.z + d2, this); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketClick.java b/src/main/java/appeng/core/sync/packets/PacketClick.java index 286f5cac8..893cb39e7 100644 --- a/src/main/java/appeng/core/sync/packets/PacketClick.java +++ b/src/main/java/appeng/core/sync/packets/PacketClick.java @@ -19,17 +19,6 @@ package appeng.core.sync.packets; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; - import appeng.api.AEApi; import appeng.api.definitions.IComparableDefinition; import appeng.api.definitions.IItems; @@ -40,115 +29,101 @@ import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.items.tools.ToolNetworkTool; import appeng.items.tools.powered.ToolColorApplicator; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; -public class PacketClick extends AppEngPacket -{ +public class PacketClick extends AppEngPacket { - private final int x; - private final int y; - private final int z; - private EnumFacing side; - private final float hitX; - private final float hitY; - private final float hitZ; - private EnumHand hand; - private final boolean leftClick; + private final int x; + private final int y; + private final int z; + private EnumFacing side; + private final float hitX; + private final float hitY; + private final float hitZ; + private EnumHand hand; + private final boolean leftClick; - // automatic. - public PacketClick( final ByteBuf stream ) - { - this.x = stream.readInt(); - this.y = stream.readInt(); - this.z = stream.readInt(); - byte side = stream.readByte(); - if( side != -1 ) - { - this.side = EnumFacing.values()[side]; - } - else - { - this.side = null; - } - this.hitX = stream.readFloat(); - this.hitY = stream.readFloat(); - this.hitZ = stream.readFloat(); - this.hand = EnumHand.values()[stream.readByte()]; - this.leftClick = stream.readBoolean(); - } + // automatic. + public PacketClick(final ByteBuf stream) { + this.x = stream.readInt(); + this.y = stream.readInt(); + this.z = stream.readInt(); + byte side = stream.readByte(); + if (side != -1) { + this.side = EnumFacing.values()[side]; + } else { + this.side = null; + } + this.hitX = stream.readFloat(); + this.hitY = stream.readFloat(); + this.hitZ = stream.readFloat(); + this.hand = EnumHand.values()[stream.readByte()]; + this.leftClick = stream.readBoolean(); + } - // api - public PacketClick( final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand ) - { - this( pos, side, hitX, hitY, hitZ, hand, false ); - } + // api + public PacketClick(final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand) { + this(pos, side, hitX, hitY, hitZ, hand, false); + } - public PacketClick( final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand, boolean leftClick ) - { + public PacketClick(final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand, boolean leftClick) { - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( this.x = pos.getX() ); - data.writeInt( this.y = pos.getY() ); - data.writeInt( this.z = pos.getZ() ); - if( side == null ) - { - data.writeByte( -1 ); - } - else - { - data.writeByte( side.ordinal() ); - } - data.writeFloat( this.hitX = hitX ); - data.writeFloat( this.hitY = hitY ); - data.writeFloat( this.hitZ = hitZ ); - data.writeByte( hand.ordinal() ); - data.writeBoolean( this.leftClick = leftClick ); + data.writeInt(this.getPacketID()); + data.writeInt(this.x = pos.getX()); + data.writeInt(this.y = pos.getY()); + data.writeInt(this.z = pos.getZ()); + if (side == null) { + data.writeByte(-1); + } else { + data.writeByte(side.ordinal()); + } + data.writeFloat(this.hitX = hitX); + data.writeFloat(this.hitY = hitY); + data.writeFloat(this.hitZ = hitZ); + data.writeByte(hand.ordinal()); + data.writeBoolean(this.leftClick = leftClick); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final ItemStack is = player.inventory.getCurrentItem(); - final IItems items = AEApi.instance().definitions().items(); - final IComparableDefinition maybeMemoryCard = items.memoryCard(); - final IComparableDefinition maybeColorApplicator = items.colorApplicator(); - final BlockPos pos = new BlockPos( this.x, this.y, this.z ); - if( this.leftClick ) - { - final Block block = player.world.getBlockState( pos ).getBlock(); - if( block instanceof BlockCableBus ) - { - ( (BlockCableBus) block ).onBlockClickPacket( player.world, pos, player, this.hand, new Vec3d( this.hitX, this.hitY, this.hitZ ) ); - } - } - else - { - if( !is.isEmpty() ) - { - if( is.getItem() instanceof ToolNetworkTool ) - { - final ToolNetworkTool tnt = (ToolNetworkTool) is.getItem(); - tnt.serverSideToolLogic( is, player, this.hand, player.world, pos, this.side, this.hitX, this.hitY, - this.hitZ ); - } - - else if( maybeMemoryCard.isSameAs( is ) ) - { - final IMemoryCard mem = (IMemoryCard) is.getItem(); - mem.notifyUser( player, MemoryCardMessages.SETTINGS_CLEARED ); - is.setTagCompound( null ); - } - - else if( maybeColorApplicator.isSameAs( is ) ) - { - final ToolColorApplicator mem = (ToolColorApplicator) is.getItem(); - mem.cycleColors( is, mem.getColor( is ), 1 ); - } - } - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final ItemStack is = player.inventory.getCurrentItem(); + final IItems items = AEApi.instance().definitions().items(); + final IComparableDefinition maybeMemoryCard = items.memoryCard(); + final IComparableDefinition maybeColorApplicator = items.colorApplicator(); + final BlockPos pos = new BlockPos(this.x, this.y, this.z); + if (this.leftClick) { + final Block block = player.world.getBlockState(pos).getBlock(); + if (block instanceof BlockCableBus) { + ((BlockCableBus) block).onBlockClickPacket(player.world, pos, player, this.hand, new Vec3d(this.hitX, this.hitY, this.hitZ)); + } + } else { + if (!is.isEmpty()) { + if (is.getItem() instanceof ToolNetworkTool) { + final ToolNetworkTool tnt = (ToolNetworkTool) is.getItem(); + tnt.serverSideToolLogic(is, player, this.hand, player.world, pos, this.side, this.hitX, this.hitY, + this.hitZ); + } else if (maybeMemoryCard.isSameAs(is)) { + final IMemoryCard mem = (IMemoryCard) is.getItem(); + mem.notifyUser(player, MemoryCardMessages.SETTINGS_CLEARED); + is.setTagCompound(null); + } else if (maybeColorApplicator.isSameAs(is)) { + final ToolColorApplicator mem = (ToolColorApplicator) is.getItem(); + mem.cycleColors(is, mem.getColor(is), 1); + } + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java b/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java index 1e913e44b..a6c91b66e 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java +++ b/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java @@ -19,66 +19,59 @@ package appeng.core.sync.packets; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; - import appeng.api.util.DimensionalCoord; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.core.sync.network.NetworkHandler; import appeng.core.worlddata.WorldData; import appeng.services.compass.ICompassCallback; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; -public class PacketCompassRequest extends AppEngPacket implements ICompassCallback -{ +public class PacketCompassRequest extends AppEngPacket implements ICompassCallback { - final long attunement; - final int cx; - final int cz; - final int cdy; + final long attunement; + final int cx; + final int cz; + final int cdy; - private EntityPlayer talkBackTo; + private EntityPlayer talkBackTo; - // automatic. - public PacketCompassRequest( final ByteBuf stream ) - { - this.attunement = stream.readLong(); - this.cx = stream.readInt(); - this.cz = stream.readInt(); - this.cdy = stream.readInt(); - } + // automatic. + public PacketCompassRequest(final ByteBuf stream) { + this.attunement = stream.readLong(); + this.cx = stream.readInt(); + this.cz = stream.readInt(); + this.cdy = stream.readInt(); + } - // api - public PacketCompassRequest( final long attunement, final int cx, final int cz, final int cdy ) - { + // api + public PacketCompassRequest(final long attunement, final int cx, final int cz, final int cdy) { - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeLong( this.attunement = attunement ); - data.writeInt( this.cx = cx ); - data.writeInt( this.cz = cz ); - data.writeInt( this.cdy = cdy ); + data.writeInt(this.getPacketID()); + data.writeLong(this.attunement = attunement); + data.writeInt(this.cx = cx); + data.writeInt(this.cz = cz); + data.writeInt(this.cdy = cdy); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void calculatedDirection( final boolean hasResult, final boolean spin, final double radians, final double dist ) - { - NetworkHandler.instance().sendTo( new PacketCompassResponse( this, hasResult, spin, radians ), (EntityPlayerMP) this.talkBackTo ); - } + @Override + public void calculatedDirection(final boolean hasResult, final boolean spin, final double radians, final double dist) { + NetworkHandler.instance().sendTo(new PacketCompassResponse(this, hasResult, spin, radians), (EntityPlayerMP) this.talkBackTo); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - this.talkBackTo = player; + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + this.talkBackTo = player; - final DimensionalCoord loc = new DimensionalCoord( player.world, this.cx << 4, this.cdy << 5, this.cz << 4 ); - WorldData.instance().compassData().service().getCompassDirection( loc, 174, this ); - } + final DimensionalCoord loc = new DimensionalCoord(player.world, this.cx << 4, this.cdy << 5, this.cz << 4); + WorldData.instance().compassData().service().getCompassDirection(loc, 174, this); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java b/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java index 4f90ae417..da4f6cbaf 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java +++ b/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java @@ -19,60 +19,54 @@ package appeng.core.sync.packets; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; - import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.hooks.CompassManager; import appeng.hooks.CompassResult; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; -public class PacketCompassResponse extends AppEngPacket -{ +public class PacketCompassResponse extends AppEngPacket { - private final long attunement; - private final int cx; - private final int cz; - private final int cdy; + private final long attunement; + private final int cx; + private final int cz; + private final int cdy; - private CompassResult cr; + private CompassResult cr; - // automatic. - public PacketCompassResponse( final ByteBuf stream ) - { - this.attunement = stream.readLong(); - this.cx = stream.readInt(); - this.cz = stream.readInt(); - this.cdy = stream.readInt(); + // automatic. + public PacketCompassResponse(final ByteBuf stream) { + this.attunement = stream.readLong(); + this.cx = stream.readInt(); + this.cz = stream.readInt(); + this.cdy = stream.readInt(); - this.cr = new CompassResult( stream.readBoolean(), stream.readBoolean(), stream.readDouble() ); - } + this.cr = new CompassResult(stream.readBoolean(), stream.readBoolean(), stream.readDouble()); + } - // api - public PacketCompassResponse( final PacketCompassRequest req, final boolean hasResult, final boolean spin, final double radians ) - { + // api + public PacketCompassResponse(final PacketCompassRequest req, final boolean hasResult, final boolean spin, final double radians) { - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeLong( this.attunement = req.attunement ); - data.writeInt( this.cx = req.cx ); - data.writeInt( this.cz = req.cz ); - data.writeInt( this.cdy = req.cdy ); + data.writeInt(this.getPacketID()); + data.writeLong(this.attunement = req.attunement); + data.writeInt(this.cx = req.cx); + data.writeInt(this.cz = req.cz); + data.writeInt(this.cdy = req.cdy); - data.writeBoolean( hasResult ); - data.writeBoolean( spin ); - data.writeDouble( radians ); + data.writeBoolean(hasResult); + data.writeBoolean(spin); + data.writeDouble(radians); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - CompassManager.INSTANCE.postResult( this.attunement, this.cx << 4, this.cdy << 5, this.cz << 4, this.cr ); - } + @Override + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + CompassManager.INSTANCE.postResult(this.attunement, this.cx << 4, this.cdy << 5, this.cz << 4, this.cr); + } } \ No newline at end of file diff --git a/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java b/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java index c661f5b1c..9bdec09ad 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java +++ b/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java @@ -19,18 +19,12 @@ package appeng.core.sync.packets; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - import appeng.client.gui.implementations.GuiInterfaceConfigurationTerminal; +import appeng.client.gui.implementations.GuiInterfaceTerminal; +import appeng.core.sync.AppEngPacket; +import appeng.core.sync.network.INetworkInfo; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; - import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; @@ -39,84 +33,72 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.client.gui.implementations.GuiInterfaceTerminal; -import appeng.core.sync.AppEngPacket; -import appeng.core.sync.network.INetworkInfo; +import java.io.*; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; -public class PacketCompressedNBT extends AppEngPacket -{ +public class PacketCompressedNBT extends AppEngPacket { - // input. - private final NBTTagCompound in; - // output... - private final ByteBuf data; - private final GZIPOutputStream compressFrame; + // input. + private final NBTTagCompound in; + // output... + private final ByteBuf data; + private final GZIPOutputStream compressFrame; - // automatic. - public PacketCompressedNBT( final ByteBuf stream ) throws IOException - { - this.data = null; - this.compressFrame = null; + // automatic. + public PacketCompressedNBT(final ByteBuf stream) throws IOException { + this.data = null; + this.compressFrame = null; - final GZIPInputStream gzReader = new GZIPInputStream( new InputStream() - { + final GZIPInputStream gzReader = new GZIPInputStream(new InputStream() { - @Override - public int read() throws IOException - { - if( stream.readableBytes() <= 0 ) - { - return -1; - } + @Override + public int read() throws IOException { + if (stream.readableBytes() <= 0) { + return -1; + } - return stream.readByte() & 0xff; - } - } ); + return stream.readByte() & 0xff; + } + }); - final DataInputStream inStream = new DataInputStream( gzReader ); - this.in = CompressedStreamTools.read( inStream ); - inStream.close(); - } + final DataInputStream inStream = new DataInputStream(gzReader); + this.in = CompressedStreamTools.read(inStream); + inStream.close(); + } - // api - public PacketCompressedNBT( final NBTTagCompound din ) throws IOException - { + // api + public PacketCompressedNBT(final NBTTagCompound din) throws IOException { - this.data = Unpooled.buffer( 2048 ); - this.data.writeInt( this.getPacketID() ); + this.data = Unpooled.buffer(2048); + this.data.writeInt(this.getPacketID()); - this.in = din; + this.in = din; - this.compressFrame = new GZIPOutputStream( new OutputStream() - { + this.compressFrame = new GZIPOutputStream(new OutputStream() { - @Override - public void write( final int value ) throws IOException - { - PacketCompressedNBT.this.data.writeByte( value ); - } - } ); + @Override + public void write(final int value) throws IOException { + PacketCompressedNBT.this.data.writeByte(value); + } + }); - CompressedStreamTools.write( din, new DataOutputStream( this.compressFrame ) ); - this.compressFrame.close(); + CompressedStreamTools.write(din, new DataOutputStream(this.compressFrame)); + this.compressFrame.close(); - this.configureWrite( this.data ); - } + this.configureWrite(this.data); + } - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final GuiScreen gs = Minecraft.getMinecraft().currentScreen; + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - if( gs instanceof GuiInterfaceTerminal ) - { - ( (GuiInterfaceTerminal) gs ).postUpdate( this.in ); - } - else if( gs instanceof GuiInterfaceConfigurationTerminal ) - { - ( (GuiInterfaceConfigurationTerminal) gs ).postUpdate( this.in ); - } - } + if (gs instanceof GuiInterfaceTerminal) { + ((GuiInterfaceTerminal) gs).postUpdate(this.in); + } else if (gs instanceof GuiInterfaceConfigurationTerminal) { + ((GuiInterfaceConfigurationTerminal) gs).postUpdate(this.in); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketConfigButton.java b/src/main/java/appeng/core/sync/packets/PacketConfigButton.java index 421107535..ced48bc3d 100644 --- a/src/main/java/appeng/core/sync/packets/PacketConfigButton.java +++ b/src/main/java/appeng/core/sync/packets/PacketConfigButton.java @@ -19,12 +19,6 @@ package appeng.core.sync.packets; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; - import appeng.api.config.Settings; import appeng.api.util.IConfigManager; import appeng.api.util.IConfigurableObject; @@ -33,49 +27,47 @@ import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.helpers.Reflected; import appeng.util.Platform; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; -public final class PacketConfigButton extends AppEngPacket -{ - private final Settings option; - private final boolean rotationDirection; +public final class PacketConfigButton extends AppEngPacket { + private final Settings option; + private final boolean rotationDirection; - // automatic. - @Reflected - public PacketConfigButton( final ByteBuf stream ) - { - this.option = Settings.values()[stream.readInt()]; - this.rotationDirection = stream.readBoolean(); - } + // automatic. + @Reflected + public PacketConfigButton(final ByteBuf stream) { + this.option = Settings.values()[stream.readInt()]; + this.rotationDirection = stream.readBoolean(); + } - // api - public PacketConfigButton( final Settings option, final boolean rotationDirection ) - { - this.option = option; - this.rotationDirection = rotationDirection; + // api + public PacketConfigButton(final Settings option, final boolean rotationDirection) { + this.option = option; + this.rotationDirection = rotationDirection; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( option.ordinal() ); - data.writeBoolean( rotationDirection ); + data.writeInt(this.getPacketID()); + data.writeInt(option.ordinal()); + data.writeBoolean(rotationDirection); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - if( sender.openContainer instanceof AEBaseContainer ) - { - final AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; - if( baseContainer.getTarget() instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) baseContainer.getTarget() ).getConfigManager(); - final Enum newState = Platform.rotateEnum( cm.getSetting( this.option ), this.rotationDirection, this.option.getPossibleValues() ); - cm.putSetting( this.option, newState ); - } - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final EntityPlayerMP sender = (EntityPlayerMP) player; + if (sender.openContainer instanceof AEBaseContainer) { + final AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; + if (baseContainer.getTarget() instanceof IConfigurableObject) { + final IConfigManager cm = ((IConfigurableObject) baseContainer.getTarget()).getConfigManager(); + final Enum newState = Platform.rotateEnum(cm.getSetting(this.option), this.rotationDirection, this.option.getPossibleValues()); + cm.putSetting(this.option, newState); + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketCraftRequest.java b/src/main/java/appeng/core/sync/packets/PacketCraftRequest.java index 5f867a442..6c20d09b4 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCraftRequest.java +++ b/src/main/java/appeng/core/sync/packets/PacketCraftRequest.java @@ -19,14 +19,6 @@ package appeng.core.sync.packets; -import java.util.concurrent.Future; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridNode; import appeng.api.networking.crafting.ICraftingGrid; @@ -40,89 +32,81 @@ import appeng.core.sync.AppEngPacket; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.INetworkInfo; import appeng.util.Platform; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; + +import java.util.concurrent.Future; -public class PacketCraftRequest extends AppEngPacket -{ +public class PacketCraftRequest extends AppEngPacket { - private final long amount; - private final boolean heldShift; + private final long amount; + private final boolean heldShift; - // automatic. - public PacketCraftRequest( final ByteBuf stream ) - { - this.heldShift = stream.readBoolean(); - this.amount = stream.readLong(); - } + // automatic. + public PacketCraftRequest(final ByteBuf stream) { + this.heldShift = stream.readBoolean(); + this.amount = stream.readLong(); + } - public PacketCraftRequest( final int craftAmt, final boolean shift ) - { - this.amount = craftAmt; - this.heldShift = shift; + public PacketCraftRequest(final int craftAmt, final boolean shift) { + this.amount = craftAmt; + this.heldShift = shift; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeBoolean( shift ); - data.writeLong( this.amount ); + data.writeInt(this.getPacketID()); + data.writeBoolean(shift); + data.writeLong(this.amount); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - if( player.openContainer instanceof ContainerCraftAmount ) - { - final ContainerCraftAmount cca = (ContainerCraftAmount) player.openContainer; - final Object target = cca.getTarget(); - if( target instanceof IActionHost ) - { - final IActionHost ah = (IActionHost) target; - final IGridNode gn = ah.getActionableNode(); - if( gn == null ) - { - return; - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + if (player.openContainer instanceof ContainerCraftAmount) { + final ContainerCraftAmount cca = (ContainerCraftAmount) player.openContainer; + final Object target = cca.getTarget(); + if (target instanceof IActionHost) { + final IActionHost ah = (IActionHost) target; + final IGridNode gn = ah.getActionableNode(); + if (gn == null) { + return; + } - final IGrid g = gn.getGrid(); - if( g == null || cca.getItemToCraft() == null ) - { - return; - } + final IGrid g = gn.getGrid(); + if (g == null || cca.getItemToCraft() == null) { + return; + } - cca.getItemToCraft().setStackSize( this.amount ); + cca.getItemToCraft().setStackSize(this.amount); - Future futureJob = null; - try - { - final ICraftingGrid cg = g.getCache( ICraftingGrid.class ); - futureJob = cg.beginCraftingJob( cca.getWorld(), cca.getGrid(), cca.getActionSrc(), cca.getItemToCraft(), null ); + Future futureJob = null; + try { + final ICraftingGrid cg = g.getCache(ICraftingGrid.class); + futureJob = cg.beginCraftingJob(cca.getWorld(), cca.getGrid(), cca.getActionSrc(), cca.getItemToCraft(), null); - final ContainerOpenContext context = cca.getOpenContext(); - if( context != null ) - { - final TileEntity te = context.getTile(); - Platform.openGUI( player, te, cca.getOpenContext().getSide(), GuiBridge.GUI_CRAFTING_CONFIRM ); + final ContainerOpenContext context = cca.getOpenContext(); + if (context != null) { + final TileEntity te = context.getTile(); + Platform.openGUI(player, te, cca.getOpenContext().getSide(), GuiBridge.GUI_CRAFTING_CONFIRM); - if( player.openContainer instanceof ContainerCraftConfirm ) - { - final ContainerCraftConfirm ccc = (ContainerCraftConfirm) player.openContainer; - ccc.setAutoStart( this.heldShift ); - ccc.setJob( futureJob ); - cca.detectAndSendChanges(); - } - } - } - catch( final Throwable e ) - { - if( futureJob != null ) - { - futureJob.cancel( true ); - } - AELog.debug( e ); - } - } - } - } + if (player.openContainer instanceof ContainerCraftConfirm) { + final ContainerCraftConfirm ccc = (ContainerCraftConfirm) player.openContainer; + ccc.setAutoStart(this.heldShift); + ccc.setJob(futureJob); + cca.detectAndSendChanges(); + } + } + } catch (final Throwable e) { + if (futureJob != null) { + futureJob.cancel(true); + } + AELog.debug(e); + } + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketCraftingCPUsUpdate.java b/src/main/java/appeng/core/sync/packets/PacketCraftingCPUsUpdate.java index 0a795d771..ac3c3c282 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCraftingCPUsUpdate.java +++ b/src/main/java/appeng/core/sync/packets/PacketCraftingCPUsUpdate.java @@ -17,46 +17,37 @@ public class PacketCraftingCPUsUpdate extends AppEngPacket { private final CraftingCPUStatus[] cpus; - public PacketCraftingCPUsUpdate( final ByteBuf stream ) - { + public PacketCraftingCPUsUpdate(final ByteBuf stream) { int count = stream.readInt(); cpus = new CraftingCPUStatus[count]; - for( int i = 0; i < count; i++ ) - { - try - { - cpus[i] = new CraftingCPUStatus( stream ); - } - catch( IOException e ) - { - cpus[i] = new CraftingCPUStatus( ); + for (int i = 0; i < count; i++) { + try { + cpus[i] = new CraftingCPUStatus(stream); + } catch (IOException e) { + cpus[i] = new CraftingCPUStatus(); } } } - public PacketCraftingCPUsUpdate( final Collection cpus ) throws IOException - { - this.cpus = cpus.toArray( new CraftingCPUStatus[0] ); + public PacketCraftingCPUsUpdate(final Collection cpus) throws IOException { + this.cpus = cpus.toArray(new CraftingCPUStatus[0]); final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( this.cpus.length ); - for( CraftingCPUStatus cpu : this.cpus ) - { - cpu.writeToPacket( data ); + data.writeInt(this.getPacketID()); + data.writeInt(this.cpus.length); + for (CraftingCPUStatus cpu : this.cpus) { + cpu.writeToPacket(data); } - this.configureWrite( data ); + this.configureWrite(data); } @Override - public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - if( gs instanceof GuiCraftingStatus) - { + if (gs instanceof GuiCraftingStatus) { GuiCraftingStatus gui = (GuiCraftingStatus) gs; - gui.postCPUUpdate( this.cpus ); + gui.postCPUUpdate(this.cpus); } } diff --git a/src/main/java/appeng/core/sync/packets/PacketFluidSlot.java b/src/main/java/appeng/core/sync/packets/PacketFluidSlot.java index 3816fa702..ef06b6f96 100644 --- a/src/main/java/appeng/core/sync/packets/PacketFluidSlot.java +++ b/src/main/java/appeng/core/sync/packets/PacketFluidSlot.java @@ -19,77 +19,65 @@ package appeng.core.sync.packets; -import java.util.HashMap; -import java.util.Map; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fml.common.network.ByteBufUtils; - import appeng.api.storage.data.IAEFluidStack; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.fluids.container.IFluidSyncContainer; import appeng.fluids.util.AEFluidStack; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fml.common.network.ByteBufUtils; + +import java.util.HashMap; +import java.util.Map; -public class PacketFluidSlot extends AppEngPacket -{ - private final Map list; +public class PacketFluidSlot extends AppEngPacket { + private final Map list; - public PacketFluidSlot( final ByteBuf stream ) - { - this.list = new HashMap<>(); - NBTTagCompound tag = ByteBufUtils.readTag( stream ); + public PacketFluidSlot(final ByteBuf stream) { + this.list = new HashMap<>(); + NBTTagCompound tag = ByteBufUtils.readTag(stream); - for( final String key : tag.getKeySet() ) - { - this.list.put( Integer.parseInt( key ), AEFluidStack.fromNBT( tag.getCompoundTag( key ) ) ); - } - } + for (final String key : tag.getKeySet()) { + this.list.put(Integer.parseInt(key), AEFluidStack.fromNBT(tag.getCompoundTag(key))); + } + } - // api - public PacketFluidSlot( final Map list ) - { - this.list = list; - final NBTTagCompound sendTag = new NBTTagCompound(); - for( Map.Entry fs : list.entrySet() ) - { - final NBTTagCompound tag = new NBTTagCompound(); - if( fs.getValue() != null ) - { - fs.getValue().writeToNBT( tag ); - } - sendTag.setTag( fs.getKey().toString(), tag ); - } + // api + public PacketFluidSlot(final Map list) { + this.list = list; + final NBTTagCompound sendTag = new NBTTagCompound(); + for (Map.Entry fs : list.entrySet()) { + final NBTTagCompound tag = new NBTTagCompound(); + if (fs.getValue() != null) { + fs.getValue().writeToNBT(tag); + } + sendTag.setTag(fs.getKey().toString(), tag); + } - final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - ByteBufUtils.writeTag( data, sendTag ); - this.configureWrite( data ); - } + final ByteBuf data = Unpooled.buffer(); + data.writeInt(this.getPacketID()); + ByteBufUtils.writeTag(data, sendTag); + this.configureWrite(data); + } - @Override - public void clientPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; - if( c instanceof IFluidSyncContainer ) - { - ( (IFluidSyncContainer) c ).receiveFluidSlots( this.list ); - } - } + @Override + public void clientPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final Container c = player.openContainer; + if (c instanceof IFluidSyncContainer) { + ((IFluidSyncContainer) c).receiveFluidSlots(this.list); + } + } - @Override - public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) - { - final Container c = player.openContainer; - if( c instanceof IFluidSyncContainer ) - { - ( (IFluidSyncContainer) c ).receiveFluidSlots( this.list ); - } - } + @Override + public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) { + final Container c = player.openContainer; + if (c instanceof IFluidSyncContainer) { + ((IFluidSyncContainer) c).receiveFluidSlots(this.list); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketInformPlayer.java b/src/main/java/appeng/core/sync/packets/PacketInformPlayer.java index 3cdd553a4..781635272 100644 --- a/src/main/java/appeng/core/sync/packets/PacketInformPlayer.java +++ b/src/main/java/appeng/core/sync/packets/PacketInformPlayer.java @@ -12,65 +12,55 @@ import net.minecraft.util.text.TextComponentString; import java.io.IOException; -public class PacketInformPlayer extends AppEngPacket -{ - private IAEItemStack actualItem = null; - private IAEItemStack reportedItem = null; - private final InfoType type; +public class PacketInformPlayer extends AppEngPacket { + private IAEItemStack actualItem = null; + private IAEItemStack reportedItem = null; + private final InfoType type; - public PacketInformPlayer( ByteBuf stream ) throws IOException - { - this.type = InfoType.values()[stream.readInt()]; - switch ( type ) - { - case PARTIAL_ITEM_EXTRACTION: - this.reportedItem = AEItemStack.fromPacket( stream ); - this.actualItem = AEItemStack.fromPacket( stream ); - break; - case NO_ITEMS_EXTRACTED: - this.reportedItem = AEItemStack.fromPacket( stream ); - break; - } - } + public PacketInformPlayer(ByteBuf stream) throws IOException { + this.type = InfoType.values()[stream.readInt()]; + switch (type) { + case PARTIAL_ITEM_EXTRACTION: + this.reportedItem = AEItemStack.fromPacket(stream); + this.actualItem = AEItemStack.fromPacket(stream); + break; + case NO_ITEMS_EXTRACTED: + this.reportedItem = AEItemStack.fromPacket(stream); + break; + } + } - public PacketInformPlayer( IAEItemStack expected, IAEItemStack actual, InfoType type ) throws IOException - { - this.reportedItem = expected; - this.actualItem = actual; - this.type = type; + public PacketInformPlayer(IAEItemStack expected, IAEItemStack actual, InfoType type) throws IOException { + this.reportedItem = expected; + this.actualItem = actual; + this.type = type; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); + data.writeInt(this.getPacketID()); - data.writeInt( type.ordinal() ); + data.writeInt(type.ordinal()); - reportedItem.writeToPacket( data ); - if( actualItem != null ) - { - actualItem.writeToPacket( data ); - } + reportedItem.writeToPacket(data); + if (actualItem != null) { + actualItem.writeToPacket(data); + } - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - TextComponentString msg = null; + @Override + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + TextComponentString msg = null; - if( this.type == InfoType.PARTIAL_ITEM_EXTRACTION ) - { - AppEng.proxy.getPlayers().get( 0 ).sendStatusMessage( new TextComponentString( "System reported " + reportedItem.getStackSize() + " " + reportedItem.getItem().getItemStackDisplayName( reportedItem.getDefinition() ) + " available but could only extract " + actualItem.getStackSize() ), false ); - } - else if( this.type == InfoType.NO_ITEMS_EXTRACTED ) - { - AppEng.proxy.getPlayers().get( 0 ).sendStatusMessage( new TextComponentString( "System reported " + reportedItem.getStackSize() + " " + reportedItem.getItem().getItemStackDisplayName( reportedItem.getDefinition() ) + " available but could not extract anything" ), false ); - } - } + if (this.type == InfoType.PARTIAL_ITEM_EXTRACTION) { + AppEng.proxy.getPlayers().get(0).sendStatusMessage(new TextComponentString("System reported " + reportedItem.getStackSize() + " " + reportedItem.getItem().getItemStackDisplayName(reportedItem.getDefinition()) + " available but could only extract " + actualItem.getStackSize()), false); + } else if (this.type == InfoType.NO_ITEMS_EXTRACTED) { + AppEng.proxy.getPlayers().get(0).sendStatusMessage(new TextComponentString("System reported " + reportedItem.getStackSize() + " " + reportedItem.getItem().getItemStackDisplayName(reportedItem.getDefinition()) + " available but could not extract anything"), false); + } + } - public enum InfoType - { - PARTIAL_ITEM_EXTRACTION, NO_ITEMS_EXTRACTED - } + public enum InfoType { + PARTIAL_ITEM_EXTRACTION, NO_ITEMS_EXTRACTED + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java b/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java index e273df7c4..ccedf61bb 100644 --- a/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java +++ b/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java @@ -19,271 +19,218 @@ package appeng.core.sync.packets; -import java.io.IOException; -import java.util.Collections; - import appeng.api.storage.data.IAEFluidStack; +import appeng.api.storage.data.IAEItemStack; import appeng.client.me.SlotDisconnected; +import appeng.container.AEBaseContainer; +import appeng.container.ContainerOpenContext; +import appeng.container.implementations.ContainerCraftAmount; import appeng.container.implementations.ContainerInterfaceConfigurationTerminal; import appeng.container.implementations.ContainerInterfaceConfigurationTerminal.ConfigTracker; import appeng.container.slot.IJEITargetSlot; import appeng.container.slot.SlotFake; import appeng.core.AELog; +import appeng.core.AppEng; +import appeng.core.sync.AppEngPacket; +import appeng.core.sync.GuiBridge; +import appeng.core.sync.network.INetworkInfo; import appeng.core.sync.network.NetworkHandler; import appeng.fluids.client.gui.widgets.GuiFluidSlot; import appeng.fluids.container.ContainerFluidConfigurable; import appeng.fluids.util.AEFluidStack; +import appeng.helpers.InventoryAction; +import appeng.util.Platform; import appeng.util.helpers.ItemHandlerUtil; import appeng.util.inv.WrapperRangeItemHandler; +import appeng.util.item.AEItemStack; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; - -import appeng.api.storage.data.IAEItemStack; -import appeng.container.AEBaseContainer; -import appeng.container.ContainerOpenContext; -import appeng.container.implementations.ContainerCraftAmount; -import appeng.core.AppEng; -import appeng.core.sync.AppEngPacket; -import appeng.core.sync.GuiBridge; -import appeng.core.sync.network.INetworkInfo; -import appeng.helpers.InventoryAction; -import appeng.util.Platform; -import appeng.util.item.AEItemStack; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.items.IItemHandler; +import java.io.IOException; +import java.util.Collections; -public class PacketInventoryAction extends AppEngPacket -{ - private final InventoryAction action; - private final int slot; - private final long id; - private final IAEItemStack slotItem; +public class PacketInventoryAction extends AppEngPacket { - // automatic. - public PacketInventoryAction( final ByteBuf stream ) throws IOException - { - this.action = InventoryAction.values()[stream.readInt()]; - this.slot = stream.readInt(); - this.id = stream.readLong(); - final boolean hasItem = stream.readBoolean(); + private final InventoryAction action; + private final int slot; + private final long id; + private final IAEItemStack slotItem; - if( hasItem ) - { - this.slotItem = AEItemStack.fromPacket( stream ); - } - else - { - this.slotItem = null; - } - } + // automatic. + public PacketInventoryAction(final ByteBuf stream) throws IOException { + this.action = InventoryAction.values()[stream.readInt()]; + this.slot = stream.readInt(); + this.id = stream.readLong(); + final boolean hasItem = stream.readBoolean(); - // api - public PacketInventoryAction( final InventoryAction action, final int slot, final IAEItemStack slotItem ) throws IOException - { - if( Platform.isClient() ) - { - throw new IllegalStateException( "invalid packet, client cannot post inv actions with stacks." ); - } + if (hasItem) { + this.slotItem = AEItemStack.fromPacket(stream); + } else { + this.slotItem = null; + } + } - this.action = action; - this.slot = slot; - this.id = 0; - this.slotItem = slotItem; + // api + public PacketInventoryAction(final InventoryAction action, final int slot, final IAEItemStack slotItem) throws IOException { + if (Platform.isClient()) { + throw new IllegalStateException("invalid packet, client cannot post inv actions with stacks."); + } - final ByteBuf data = Unpooled.buffer(); + this.action = action; + this.slot = slot; + this.id = 0; + this.slotItem = slotItem; - data.writeInt( this.getPacketID() ); - data.writeInt( action.ordinal() ); - data.writeInt( slot ); - data.writeLong( this.id ); + final ByteBuf data = Unpooled.buffer(); - if( slotItem == null ) - { - data.writeBoolean( false ); - } - else - { - data.writeBoolean( true ); - slotItem.writeToPacket( data ); - } + data.writeInt(this.getPacketID()); + data.writeInt(action.ordinal()); + data.writeInt(slot); + data.writeLong(this.id); - this.configureWrite( data ); - } + if (slotItem == null) { + data.writeBoolean(false); + } else { + data.writeBoolean(true); + slotItem.writeToPacket(data); + } - public PacketInventoryAction( final InventoryAction action, final IJEITargetSlot slot, final IAEItemStack slotItem ) throws IOException - { + this.configureWrite(data); + } - this.action = action; - if( slot instanceof SlotFake ) - { - this.slot = ( (SlotFake) slot ).slotNumber; - this.id = 0; - } - else if( slot instanceof SlotDisconnected ) - { - this.slot = ( (SlotDisconnected) slot ).getSlotIndex(); - this.id = ( (SlotDisconnected) slot ).getSlot().getId(); - } - else - { - this.slot = ( (GuiFluidSlot) slot ).getId(); - this.id = 0; - } - this.slotItem = slotItem; + public PacketInventoryAction(final InventoryAction action, final IJEITargetSlot slot, final IAEItemStack slotItem) throws IOException { - final ByteBuf data = Unpooled.buffer(); + this.action = action; + if (slot instanceof SlotFake) { + this.slot = ((SlotFake) slot).slotNumber; + this.id = 0; + } else if (slot instanceof SlotDisconnected) { + this.slot = ((SlotDisconnected) slot).getSlotIndex(); + this.id = ((SlotDisconnected) slot).getSlot().getId(); + } else { + this.slot = ((GuiFluidSlot) slot).getId(); + this.id = 0; + } + this.slotItem = slotItem; - data.writeInt( this.getPacketID() ); - data.writeInt( action.ordinal() ); - data.writeInt( this.slot ); - data.writeLong( this.id ); + final ByteBuf data = Unpooled.buffer(); - if( slotItem == null ) - { - data.writeBoolean( false ); - } - else - { - data.writeBoolean( true ); - slotItem.writeToPacket( data ); - } + data.writeInt(this.getPacketID()); + data.writeInt(action.ordinal()); + data.writeInt(this.slot); + data.writeLong(this.id); - this.configureWrite( data ); - } + if (slotItem == null) { + data.writeBoolean(false); + } else { + data.writeBoolean(true); + slotItem.writeToPacket(data); + } - // api - public PacketInventoryAction( final InventoryAction action, final int slot, final long id ) - { - this.action = action; - this.slot = slot; - this.id = id; - this.slotItem = null; + this.configureWrite(data); + } - final ByteBuf data = Unpooled.buffer(); + // api + public PacketInventoryAction(final InventoryAction action, final int slot, final long id) { + this.action = action; + this.slot = slot; + this.id = id; + this.slotItem = null; - data.writeInt( this.getPacketID() ); - data.writeInt( action.ordinal() ); - data.writeInt( slot ); - data.writeLong( id ); - data.writeBoolean( false ); + final ByteBuf data = Unpooled.buffer(); - this.configureWrite( data ); - } + data.writeInt(this.getPacketID()); + data.writeInt(action.ordinal()); + data.writeInt(slot); + data.writeLong(id); + data.writeBoolean(false); - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - if( sender.openContainer instanceof AEBaseContainer ) - { - final AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; - if( this.action == InventoryAction.AUTO_CRAFT ) - { - final ContainerOpenContext context = baseContainer.getOpenContext(); - if( context != null ) - { - final TileEntity te = context.getTile(); - Platform.openGUI( sender, te, baseContainer.getOpenContext().getSide(), GuiBridge.GUI_CRAFTING_AMOUNT ); + this.configureWrite(data); + } - if( sender.openContainer instanceof ContainerCraftAmount ) - { - final ContainerCraftAmount cca = (ContainerCraftAmount) sender.openContainer; + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final EntityPlayerMP sender = (EntityPlayerMP) player; + if (sender.openContainer instanceof AEBaseContainer) { + final AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; + if (this.action == InventoryAction.AUTO_CRAFT) { + final ContainerOpenContext context = baseContainer.getOpenContext(); + if (context != null) { + final TileEntity te = context.getTile(); + Platform.openGUI(sender, te, baseContainer.getOpenContext().getSide(), GuiBridge.GUI_CRAFTING_AMOUNT); - if( baseContainer.getTargetStack() != null ) - { - cca.getCraftingItem().putStack( baseContainer.getTargetStack().asItemStackRepresentation() ); - // This is the *actual* item that matters, not the display item above - cca.setItemToCraft( baseContainer.getTargetStack() ); - } + if (sender.openContainer instanceof ContainerCraftAmount) { + final ContainerCraftAmount cca = (ContainerCraftAmount) sender.openContainer; - cca.detectAndSendChanges(); - } - } - } - else if( this.action == InventoryAction.PLACE_JEI_GHOST_ITEM ) - { - if( sender.openContainer instanceof ContainerFluidConfigurable ) - { - if( this.slotItem != null ) - { - IAEFluidStack aefs = AEFluidStack.fromNBT( this.slotItem.getDefinition().getTagCompound() ); - if( aefs != null ) - { - aefs.setStackSize( 1000 ); - ( (ContainerFluidConfigurable) sender.openContainer ).getFluidConfigInventory().setFluidInSlot( this.slot, aefs ); - NetworkHandler.instance().sendToServer( new PacketFluidSlot( Collections.singletonMap( this.slot, aefs ) ) ); - } - } - } - else if( sender.openContainer instanceof ContainerInterfaceConfigurationTerminal ) - { - ConfigTracker inv = ( (ContainerInterfaceConfigurationTerminal) sender.openContainer ).getSlotByID( this.id ); - final IItemHandler theSlot = new WrapperRangeItemHandler( inv.getServer(), 0, slot + 1 ); + if (baseContainer.getTargetStack() != null) { + cca.getCraftingItem().putStack(baseContainer.getTargetStack().asItemStackRepresentation()); + // This is the *actual* item that matters, not the display item above + cca.setItemToCraft(baseContainer.getTargetStack()); + } - ItemHandlerUtil.setStackInSlot( theSlot, this.slot, this.slotItem.createItemStack() ); + cca.detectAndSendChanges(); + } + } + } else if (this.action == InventoryAction.PLACE_JEI_GHOST_ITEM) { + if (sender.openContainer instanceof ContainerFluidConfigurable) { + if (this.slotItem != null) { + IAEFluidStack aefs = AEFluidStack.fromNBT(this.slotItem.getDefinition().getTagCompound()); + if (aefs != null) { + aefs.setStackSize(1000); + ((ContainerFluidConfigurable) sender.openContainer).getFluidConfigInventory().setFluidInSlot(this.slot, aefs); + NetworkHandler.instance().sendToServer(new PacketFluidSlot(Collections.singletonMap(this.slot, aefs))); + } + } + } else if (sender.openContainer instanceof ContainerInterfaceConfigurationTerminal) { + ConfigTracker inv = ((ContainerInterfaceConfigurationTerminal) sender.openContainer).getSlotByID(this.id); + final IItemHandler theSlot = new WrapperRangeItemHandler(inv.getServer(), 0, slot + 1); - } - else if( this.slot < sender.openContainer.inventorySlots.size() ) - { - Slot senderSlot = sender.openContainer.inventorySlots.get( this.slot ); - if( senderSlot instanceof SlotFake ) - { - if( this.slotItem != null ) - { - senderSlot.putStack( this.slotItem.createItemStack() ); - if( senderSlot.getStack().isEmpty() ) - { - IAEFluidStack aefs = AEFluidStack.fromNBT( this.slotItem.getDefinition().getTagCompound() ); - if( aefs != null ) - { - FluidStack fluid = aefs.getFluidStack(); - senderSlot.putStack( AEFluidStack.fromFluidStack( fluid ).asItemStackRepresentation() ); - } - } - } - else - { - senderSlot.putStack( ItemStack.EMPTY ); - } - try - { - NetworkHandler.instance().sendTo( new PacketInventoryAction( InventoryAction.UPDATE_HAND, 0, AEItemStack.fromItemStack( ItemStack.EMPTY ) ), sender ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } - else - { - baseContainer.doAction( sender, this.action, this.slot, this.id ); - } - } - } + ItemHandlerUtil.setStackInSlot(theSlot, this.slot, this.slotItem.createItemStack()); - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - if( this.action == InventoryAction.UPDATE_HAND ) - { - if( this.slotItem == null ) - { - AppEng.proxy.getPlayers().get( 0 ).inventory.setItemStack( ItemStack.EMPTY ); - } - else - { - AppEng.proxy.getPlayers().get( 0 ).inventory.setItemStack( this.slotItem.createItemStack() ); - } - } - } + } else if (this.slot < sender.openContainer.inventorySlots.size()) { + Slot senderSlot = sender.openContainer.inventorySlots.get(this.slot); + if (senderSlot instanceof SlotFake) { + if (this.slotItem != null) { + senderSlot.putStack(this.slotItem.createItemStack()); + if (senderSlot.getStack().isEmpty()) { + IAEFluidStack aefs = AEFluidStack.fromNBT(this.slotItem.getDefinition().getTagCompound()); + if (aefs != null) { + FluidStack fluid = aefs.getFluidStack(); + senderSlot.putStack(AEFluidStack.fromFluidStack(fluid).asItemStackRepresentation()); + } + } + } else { + senderSlot.putStack(ItemStack.EMPTY); + } + try { + NetworkHandler.instance().sendTo(new PacketInventoryAction(InventoryAction.UPDATE_HAND, 0, AEItemStack.fromItemStack(ItemStack.EMPTY)), sender); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } else { + baseContainer.doAction(sender, this.action, this.slot, this.id); + } + } + } + + @Override + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + if (this.action == InventoryAction.UPDATE_HAND) { + if (this.slotItem == null) { + AppEng.proxy.getPlayers().get(0).inventory.setItemStack(ItemStack.EMPTY); + } else { + AppEng.proxy.getPlayers().get(0).inventory.setItemStack(this.slotItem.createItemStack()); + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketJEIRecipe.java b/src/main/java/appeng/core/sync/packets/PacketJEIRecipe.java index a9156e433..a1a5ca9dd 100644 --- a/src/main/java/appeng/core/sync/packets/PacketJEIRecipe.java +++ b/src/main/java/appeng/core/sync/packets/PacketJEIRecipe.java @@ -19,32 +19,9 @@ package appeng.core.sync.packets; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import appeng.api.config.FuzzyMode; -import appeng.container.implementations.ContainerExpandedProcessingPatternTerm; -import appeng.container.implementations.ContainerPatternTerm; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.inventory.Container; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraftforge.fml.common.Optional; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.Actionable; +import appeng.api.config.FuzzyMode; import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; import appeng.api.networking.IGridNode; @@ -55,6 +32,8 @@ import appeng.api.networking.storage.IStorageGrid; import appeng.api.storage.IMEMonitor; import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEItemStack; +import appeng.container.implementations.ContainerExpandedProcessingPatternTerm; +import appeng.container.implementations.ContainerPatternTerm; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.helpers.IContainerCraftingPacket; @@ -65,277 +44,238 @@ import appeng.util.inv.AdaptorItemHandler; import appeng.util.inv.WrapperInvItemHandler; import appeng.util.item.AEItemStack; import appeng.util.prioritylist.IPartitionList; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.Container; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.items.IItemHandler; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; -public class PacketJEIRecipe extends AppEngPacket -{ +public class PacketJEIRecipe extends AppEngPacket { - private List recipe; - private List output; - static ItemStack[] emptyArray = {ItemStack.EMPTY}; + private List recipe; + private List output; + static ItemStack[] emptyArray = {ItemStack.EMPTY}; - // automatic. - public PacketJEIRecipe( final ByteBuf stream ) throws IOException - { - final ByteArrayInputStream bytes = this.getPacketByteArray( stream ); - bytes.skip( stream.readerIndex() ); - final NBTTagCompound comp = CompressedStreamTools.readCompressed( bytes ); - if( comp != null ) - { - this.recipe = new ArrayList<>(); + // automatic. + public PacketJEIRecipe(final ByteBuf stream) throws IOException { + final ByteArrayInputStream bytes = this.getPacketByteArray(stream); + bytes.skip(stream.readerIndex()); + final NBTTagCompound comp = CompressedStreamTools.readCompressed(bytes); + if (comp != null) { + this.recipe = new ArrayList<>(); - for( int x = 0; x < comp.getKeySet().size(); x++ ) - { - if( comp.hasKey( "#" + x ) ) - { - final NBTTagList list = comp.getTagList( "#" + x, 10 ); - if( list.tagCount() > 0 ) - { - this.recipe.add( new ItemStack[list.tagCount()] ); - for( int y = 0; y < list.tagCount(); y++ ) - { - this.recipe.get( x )[y] = new ItemStack( list.getCompoundTagAt( y ) ); - } - } - else - { - this.recipe.add( emptyArray ); - } - } - } + for (int x = 0; x < comp.getKeySet().size(); x++) { + if (comp.hasKey("#" + x)) { + final NBTTagList list = comp.getTagList("#" + x, 10); + if (list.tagCount() > 0) { + this.recipe.add(new ItemStack[list.tagCount()]); + for (int y = 0; y < list.tagCount(); y++) { + this.recipe.get(x)[y] = new ItemStack(list.getCompoundTagAt(y)); + } + } else { + this.recipe.add(emptyArray); + } + } + } - if( comp.hasKey( "outputs" ) ) - { - final NBTTagList outputList = comp.getTagList( "outputs", 10 ); - this.output = new ArrayList<>(); - for( int z = 0; z < outputList.tagCount(); z++ ) - { - this.output.add( new ItemStack( outputList.getCompoundTagAt( z ) ) ); - } - } - } + if (comp.hasKey("outputs")) { + final NBTTagList outputList = comp.getTagList("outputs", 10); + this.output = new ArrayList<>(); + for (int z = 0; z < outputList.tagCount(); z++) { + this.output.add(new ItemStack(outputList.getCompoundTagAt(z))); + } + } + } - } + } - // api - public PacketJEIRecipe( final NBTTagCompound recipe ) throws IOException - { - final ByteBuf data = Unpooled.buffer(); + // api + public PacketJEIRecipe(final NBTTagCompound recipe) throws IOException { + final ByteBuf data = Unpooled.buffer(); - final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final DataOutputStream outputStream = new DataOutputStream( bytes ); + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + final DataOutputStream outputStream = new DataOutputStream(bytes); - data.writeInt( this.getPacketID() ); + data.writeInt(this.getPacketID()); - CompressedStreamTools.writeCompressed( recipe, outputStream ); - data.writeBytes( bytes.toByteArray() ); + CompressedStreamTools.writeCompressed(recipe, outputStream); + data.writeBytes(bytes.toByteArray()); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP pmp = (EntityPlayerMP) player; - final Container con = pmp.openContainer; + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final EntityPlayerMP pmp = (EntityPlayerMP) player; + final Container con = pmp.openContainer; - if( !( con instanceof IContainerCraftingPacket ) ) - { - return; - } + if (!(con instanceof IContainerCraftingPacket)) { + return; + } - final IContainerCraftingPacket cct = (IContainerCraftingPacket) con; - final IGridNode node = cct.getNetworkNode(); + final IContainerCraftingPacket cct = (IContainerCraftingPacket) con; + final IGridNode node = cct.getNetworkNode(); - if( node == null ) - { - return; - } + if (node == null) { + return; + } - final IGrid grid = node.getGrid(); - if( grid == null ) - { - return; - } + final IGrid grid = node.getGrid(); + if (grid == null) { + return; + } - final IStorageGrid inv = grid.getCache( IStorageGrid.class ); - final IEnergyGrid energy = grid.getCache( IEnergyGrid.class ); - final ISecurityGrid security = grid.getCache( ISecurityGrid.class ); - final ICraftingGrid crafting = grid.getCache( ICraftingGrid.class ); - final IItemHandler craftMatrix = cct.getInventoryByName( "crafting" ); - final IItemHandler playerInventory = cct.getInventoryByName( "player" ); + final IStorageGrid inv = grid.getCache(IStorageGrid.class); + final IEnergyGrid energy = grid.getCache(IEnergyGrid.class); + final ISecurityGrid security = grid.getCache(ISecurityGrid.class); + final ICraftingGrid crafting = grid.getCache(ICraftingGrid.class); + final IItemHandler craftMatrix = cct.getInventoryByName("crafting"); + final IItemHandler playerInventory = cct.getInventoryByName("player"); - if( inv != null && this.recipe != null && security != null ) - { - final IMEMonitor storage = inv.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - final IPartitionList filter = ItemViewCell.createFilter( cct.getViewCells() ); + if (inv != null && this.recipe != null && security != null) { + final IMEMonitor storage = inv.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + final IPartitionList filter = ItemViewCell.createFilter(cct.getViewCells()); - for( int x = 0; x < craftMatrix.getSlots(); x++ ) - { - ItemStack currentItem = craftMatrix.getStackInSlot( x ); + for (int x = 0; x < craftMatrix.getSlots(); x++) { + ItemStack currentItem = craftMatrix.getStackInSlot(x); - if( x >= this.recipe.size() ) - { - currentItem = ItemStack.EMPTY; - } + if (x >= this.recipe.size()) { + currentItem = ItemStack.EMPTY; + } - // prepare slots - if( !currentItem.isEmpty() ) - { - // already the correct item? - ItemStack newItem = this.canUseInSlot( x, currentItem ); + // prepare slots + if (!currentItem.isEmpty()) { + // already the correct item? + ItemStack newItem = this.canUseInSlot(x, currentItem); - if( !cct.useRealItems() && this.recipe.get( x ) != null ) - { - if( this.recipe.get( x ).length > 0 ) - { - currentItem.setCount( recipe.get( x )[0].getCount() ); - } - } + if (!cct.useRealItems() && this.recipe.get(x) != null) { + if (this.recipe.get(x).length > 0) { + currentItem.setCount(recipe.get(x)[0].getCount()); + } + } - // put away old item - if( newItem != currentItem && security.hasPermission( player, SecurityPermissions.INJECT ) ) - { - final IAEItemStack in = AEItemStack.fromItemStack( currentItem ); - final IAEItemStack out = cct.useRealItems() ? Platform.poweredInsert( energy, storage, in, cct.getActionSource() ) : null; - if( out != null ) - { - currentItem = out.createItemStack(); - } - else - { - currentItem = ItemStack.EMPTY; - } - } - } + // put away old item + if (newItem != currentItem && security.hasPermission(player, SecurityPermissions.INJECT)) { + final IAEItemStack in = AEItemStack.fromItemStack(currentItem); + final IAEItemStack out = cct.useRealItems() ? Platform.poweredInsert(energy, storage, in, cct.getActionSource()) : null; + if (out != null) { + currentItem = out.createItemStack(); + } else { + currentItem = ItemStack.EMPTY; + } + } + } - if( currentItem.isEmpty() && recipe.size() > x && recipe.get( x ) != null ) - { - // for each variant - for( int y = 0; y < this.recipe.get( x ).length && currentItem.isEmpty(); y++ ) - { - final IAEItemStack request = AEItemStack.fromItemStack( this.recipe.get( x )[y] ); - if( request != null ) - { - // try ae - if( ( filter == null || filter.isListed( request ) ) && security.hasPermission( player, SecurityPermissions.EXTRACT ) ) - { - request.setStackSize( 1 ); - IAEItemStack out; + if (currentItem.isEmpty() && recipe.size() > x && recipe.get(x) != null) { + // for each variant + for (int y = 0; y < this.recipe.get(x).length && currentItem.isEmpty(); y++) { + final IAEItemStack request = AEItemStack.fromItemStack(this.recipe.get(x)[y]); + if (request != null) { + // try ae + if ((filter == null || filter.isListed(request)) && security.hasPermission(player, SecurityPermissions.EXTRACT)) { + request.setStackSize(1); + IAEItemStack out; - if( cct.useRealItems() ) - { - out = Platform.poweredExtraction( energy, storage, request, cct.getActionSource() ); - if( out == null ) - { - if( request.getItem().isDamageable() || Platform.isGTDamageableItem( request.getItem() ) ) - { - Collection outList = inv.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).getStorageList().findFuzzy( request, FuzzyMode.IGNORE_ALL ); - for( IAEItemStack is : outList ) - { - if( is.getDefinition().getMetadata() == request.getDefinition().getMetadata() ) - { - out = Platform.poweredExtraction( energy, storage, is.copy().setStackSize( 1 ), cct.getActionSource() ); - } - if( out != null ) - { - break; - } - } - } - } - } - else - { - // Query the crafting grid if there is a pattern providing the item - if( !crafting.getCraftingFor( request, null, 0, null ).isEmpty() ) - { - out = request; - } - else - { - // Fall back using an existing item - out = storage.extractItems( request, Actionable.SIMULATE, cct.getActionSource() ); - } - } + if (cct.useRealItems()) { + out = Platform.poweredExtraction(energy, storage, request, cct.getActionSource()); + if (out == null) { + if (request.getItem().isDamageable() || Platform.isGTDamageableItem(request.getItem())) { + Collection outList = inv.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)).getStorageList().findFuzzy(request, FuzzyMode.IGNORE_ALL); + for (IAEItemStack is : outList) { + if (is.getDefinition().getMetadata() == request.getDefinition().getMetadata()) { + out = Platform.poweredExtraction(energy, storage, is.copy().setStackSize(1), cct.getActionSource()); + } + if (out != null) { + break; + } + } + } + } + } else { + // Query the crafting grid if there is a pattern providing the item + if (!crafting.getCraftingFor(request, null, 0, null).isEmpty()) { + out = request; + } else { + // Fall back using an existing item + out = storage.extractItems(request, Actionable.SIMULATE, cct.getActionSource()); + } + } - if( out != null ) - { - if( !cct.useRealItems() ) - { - out.setStackSize( recipe.get( x )[y].getCount() ); - } - currentItem = out.createItemStack(); - } - } + if (out != null) { + if (!cct.useRealItems()) { + out.setStackSize(recipe.get(x)[y].getCount()); + } + currentItem = out.createItemStack(); + } + } - // try inventory - if( currentItem.isEmpty() ) - { - AdaptorItemHandler ad = new AdaptorItemHandler( playerInventory ); + // try inventory + if (currentItem.isEmpty()) { + AdaptorItemHandler ad = new AdaptorItemHandler(playerInventory); - if( cct.useRealItems() ) - { - currentItem = ad.removeSimilarItems( 1, this.recipe.get( x )[y], FuzzyMode.IGNORE_ALL, null ); - } - else - { - currentItem = ad.simulateSimilarRemove( recipe.get( x )[y].getCount(), this.recipe.get( x )[y], FuzzyMode.IGNORE_ALL, null ); - } - } - } - } - if( !cct.useRealItems() ) - { - if( currentItem.isEmpty() && recipe.size() > x && this.recipe.get( x ) != null ) - { - currentItem = this.recipe.get( x )[0].copy(); - } - } - } - ItemHandlerUtil.setStackInSlot( craftMatrix, x, currentItem ); - } + if (cct.useRealItems()) { + currentItem = ad.removeSimilarItems(1, this.recipe.get(x)[y], FuzzyMode.IGNORE_ALL, null); + } else { + currentItem = ad.simulateSimilarRemove(recipe.get(x)[y].getCount(), this.recipe.get(x)[y], FuzzyMode.IGNORE_ALL, null); + } + } + } + } + if (!cct.useRealItems()) { + if (currentItem.isEmpty() && recipe.size() > x && this.recipe.get(x) != null) { + currentItem = this.recipe.get(x)[0].copy(); + } + } + } + ItemHandlerUtil.setStackInSlot(craftMatrix, x, currentItem); + } - con.onCraftMatrixChanged( new WrapperInvItemHandler( craftMatrix ) ); + con.onCraftMatrixChanged(new WrapperInvItemHandler(craftMatrix)); - if( this.output != null && ( ( con instanceof ContainerPatternTerm && !( (ContainerPatternTerm) con ).isCraftingMode() ) || con instanceof ContainerExpandedProcessingPatternTerm ) ) - { - IItemHandler outputSlots = cct.getInventoryByName( "output" ); - for( int i = 0; i < outputSlots.getSlots(); ++i ) - { - ItemHandlerUtil.setStackInSlot( outputSlots, i, ItemStack.EMPTY ); - } - for( int i = 0; i < this.output.size() && i < outputSlots.getSlots(); ++i ) - { - if( this.output.get( i ) == null || this.output.get( i ) == ItemStack.EMPTY ) - { - continue; - } - ItemHandlerUtil.setStackInSlot( outputSlots, i, this.output.get( i ) ); - } - } - } - } + if (this.output != null && ((con instanceof ContainerPatternTerm && !((ContainerPatternTerm) con).isCraftingMode()) || con instanceof ContainerExpandedProcessingPatternTerm)) { + IItemHandler outputSlots = cct.getInventoryByName("output"); + for (int i = 0; i < outputSlots.getSlots(); ++i) { + ItemHandlerUtil.setStackInSlot(outputSlots, i, ItemStack.EMPTY); + } + for (int i = 0; i < this.output.size() && i < outputSlots.getSlots(); ++i) { + if (this.output.get(i) == null || this.output.get(i) == ItemStack.EMPTY) { + continue; + } + ItemHandlerUtil.setStackInSlot(outputSlots, i, this.output.get(i)); + } + } + } + } - /** - * @param slot - * @param is itemstack - * @return is if it can be used, else EMPTY - */ - private ItemStack canUseInSlot( int slot, ItemStack is ) - { - if( this.recipe.get( slot ) != null ) - { - for( ItemStack option : this.recipe.get( slot ) ) - { - if( ItemStack.areItemStacksEqual( is, option ) ) - { - return is; - } - } - } - return ItemStack.EMPTY; - } + /** + * @param slot + * @param is itemstack + * @return is if it can be used, else EMPTY + */ + private ItemStack canUseInSlot(int slot, ItemStack is) { + if (this.recipe.get(slot) != null) { + for (ItemStack option : this.recipe.get(slot)) { + if (ItemStack.areItemStacksEqual(is, option)) { + return is; + } + } + } + return ItemStack.EMPTY; + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketLightning.java b/src/main/java/appeng/core/sync/packets/PacketLightning.java index 40a46c102..459e8835d 100644 --- a/src/main/java/appeng/core/sync/packets/PacketLightning.java +++ b/src/main/java/appeng/core/sync/packets/PacketLightning.java @@ -19,68 +19,58 @@ package appeng.core.sync.packets; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.client.render.effects.LightningFX; import appeng.core.AEConfig; import appeng.core.AppEng; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.util.Platform; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class PacketLightning extends AppEngPacket -{ +public class PacketLightning extends AppEngPacket { - private final double x; - private final double y; - private final double z; + private final double x; + private final double y; + private final double z; - // automatic. - public PacketLightning( final ByteBuf stream ) - { - this.x = stream.readFloat(); - this.y = stream.readFloat(); - this.z = stream.readFloat(); - } + // automatic. + public PacketLightning(final ByteBuf stream) { + this.x = stream.readFloat(); + this.y = stream.readFloat(); + this.z = stream.readFloat(); + } - // api - public PacketLightning( final double x, final double y, final double z ) - { - this.x = x; - this.y = y; - this.z = z; + // api + public PacketLightning(final double x, final double y, final double z) { + this.x = x; + this.y = y; + this.z = z; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeFloat( (float) x ); - data.writeFloat( (float) y ); - data.writeFloat( (float) z ); + data.writeInt(this.getPacketID()); + data.writeFloat((float) x); + data.writeFloat((float) y); + data.writeFloat((float) z); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - try - { - if( Platform.isClient() && AEConfig.instance().isEnableEffects() ) - { - final LightningFX fx = new LightningFX( AppEng.proxy.getWorld(), this.x, this.y, this.z, 0.0f, 0.0f, 0.0f ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - catch( final Exception ignored ) - { - } - } + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + try { + if (Platform.isClient() && AEConfig.instance().isEnableEffects()) { + final LightningFX fx = new LightningFX(AppEng.proxy.getWorld(), this.x, this.y, this.z, 0.0f, 0.0f, 0.0f); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } catch (final Exception ignored) { + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketMEFluidInventoryUpdate.java b/src/main/java/appeng/core/sync/packets/PacketMEFluidInventoryUpdate.java index 3e1638631..8b2110fff 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMEFluidInventoryUpdate.java +++ b/src/main/java/appeng/core/sync/packets/PacketMEFluidInventoryUpdate.java @@ -19,6 +19,22 @@ package appeng.core.sync.packets; +import appeng.api.storage.data.IAEFluidStack; +import appeng.core.AELog; +import appeng.core.sync.AppEngPacket; +import appeng.core.sync.network.INetworkInfo; +import appeng.fluids.client.gui.GuiFluidTerminal; +import appeng.fluids.util.AEFluidStack; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import javax.annotation.Nullable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -28,181 +44,137 @@ import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; -import javax.annotation.Nullable; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import appeng.api.storage.data.IAEFluidStack; -import appeng.core.AELog; -import appeng.core.sync.AppEngPacket; -import appeng.core.sync.network.INetworkInfo; -import appeng.fluids.client.gui.GuiFluidTerminal; -import appeng.fluids.util.AEFluidStack; - /** * @author BrockWS * @version rv6 - 22/05/2018 * @since rv6 22/05/2018 */ -public class PacketMEFluidInventoryUpdate extends AppEngPacket -{ - private static final int UNCOMPRESSED_PACKET_BYTE_LIMIT = 16 * 1024 * 1024; - private static final int OPERATION_BYTE_LIMIT = 2 * 1024; - private static final int TEMP_BUFFER_SIZE = 1024; - private static final int STREAM_MASK = 0xff; +public class PacketMEFluidInventoryUpdate extends AppEngPacket { + private static final int UNCOMPRESSED_PACKET_BYTE_LIMIT = 16 * 1024 * 1024; + private static final int OPERATION_BYTE_LIMIT = 2 * 1024; + private static final int TEMP_BUFFER_SIZE = 1024; + private static final int STREAM_MASK = 0xff; - // input. - @Nullable - private final List list; - // output... - private final byte ref; + // input. + @Nullable + private final List list; + // output... + private final byte ref; - @Nullable - private final ByteBuf data; - @Nullable - private final GZIPOutputStream compressFrame; + @Nullable + private final ByteBuf data; + @Nullable + private final GZIPOutputStream compressFrame; - private int writtenBytes = 0; - private boolean empty = true; + private int writtenBytes = 0; + private boolean empty = true; - // automatic. - public PacketMEFluidInventoryUpdate( final ByteBuf stream ) throws IOException - { - this.data = null; - this.compressFrame = null; - this.list = new LinkedList<>(); - this.ref = stream.readByte(); + // automatic. + public PacketMEFluidInventoryUpdate(final ByteBuf stream) throws IOException { + this.data = null; + this.compressFrame = null; + this.list = new LinkedList<>(); + this.ref = stream.readByte(); - // int originalBytes = stream.readableBytes(); + // int originalBytes = stream.readableBytes(); - try( final GZIPInputStream gzReader = new GZIPInputStream( new InputStream() - { - @Override - public int read() throws IOException - { - if( stream.readableBytes() <= 0 ) - { - return -1; - } + try (final GZIPInputStream gzReader = new GZIPInputStream(new InputStream() { + @Override + public int read() throws IOException { + if (stream.readableBytes() <= 0) { + return -1; + } - return stream.readByte() & STREAM_MASK; - } - } ) ) - { + return stream.readByte() & STREAM_MASK; + } + })) { - final ByteBuf uncompressed = Unpooled.buffer( stream.readableBytes() ); - final byte[] tmp = new byte[TEMP_BUFFER_SIZE]; + final ByteBuf uncompressed = Unpooled.buffer(stream.readableBytes()); + final byte[] tmp = new byte[TEMP_BUFFER_SIZE]; - while( gzReader.available() != 0 ) - { - final int bytes = gzReader.read( tmp ); + while (gzReader.available() != 0) { + final int bytes = gzReader.read(tmp); - if( bytes > 0 ) - { - uncompressed.writeBytes( tmp, 0, bytes ); - } - } + if (bytes > 0) { + uncompressed.writeBytes(tmp, 0, bytes); + } + } - while( uncompressed.readableBytes() > 0 ) - { - this.list.add( AEFluidStack.fromPacket( uncompressed ) ); - } - } + while (uncompressed.readableBytes() > 0) { + this.list.add(AEFluidStack.fromPacket(uncompressed)); + } + } - this.empty = this.list.isEmpty(); - } + this.empty = this.list.isEmpty(); + } - // api - public PacketMEFluidInventoryUpdate() throws IOException - { - this( (byte) 0 ); - } + // api + public PacketMEFluidInventoryUpdate() throws IOException { + this((byte) 0); + } - // api - public PacketMEFluidInventoryUpdate( final byte ref ) throws IOException - { - this.ref = ref; - this.data = Unpooled.buffer( OPERATION_BYTE_LIMIT ); - this.data.writeInt( this.getPacketID() ); - this.data.writeByte( this.ref ); + // api + public PacketMEFluidInventoryUpdate(final byte ref) throws IOException { + this.ref = ref; + this.data = Unpooled.buffer(OPERATION_BYTE_LIMIT); + this.data.writeInt(this.getPacketID()); + this.data.writeByte(this.ref); - this.compressFrame = new GZIPOutputStream( new OutputStream() - { - @Override - public void write( final int value ) throws IOException - { - PacketMEFluidInventoryUpdate.this.data.writeByte( value ); - } - } ); + this.compressFrame = new GZIPOutputStream(new OutputStream() { + @Override + public void write(final int value) throws IOException { + PacketMEFluidInventoryUpdate.this.data.writeByte(value); + } + }); - this.list = null; - } + this.list = null; + } - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final GuiScreen gs = Minecraft.getMinecraft().currentScreen; + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - if( gs instanceof GuiFluidTerminal ) - { - ( (GuiFluidTerminal) gs ).postUpdate( this.list ); - } - } + if (gs instanceof GuiFluidTerminal) { + ((GuiFluidTerminal) gs).postUpdate(this.list); + } + } - @Nullable - @Override - public FMLProxyPacket getProxy() - { - try - { - this.compressFrame.close(); + @Nullable + @Override + public FMLProxyPacket getProxy() { + try { + this.compressFrame.close(); - this.configureWrite( this.data ); - return super.getProxy(); - } - catch( final IOException e ) - { - AELog.debug( e ); - } + this.configureWrite(this.data); + return super.getProxy(); + } catch (final IOException e) { + AELog.debug(e); + } - return null; - } + return null; + } - public void appendFluid( final IAEFluidStack fs ) throws IOException, BufferOverflowException - { - final ByteBuf tmp = Unpooled.buffer( OPERATION_BYTE_LIMIT ); - fs.writeToPacket( tmp ); + public void appendFluid(final IAEFluidStack fs) throws IOException, BufferOverflowException { + final ByteBuf tmp = Unpooled.buffer(OPERATION_BYTE_LIMIT); + fs.writeToPacket(tmp); - this.compressFrame.flush(); - if( this.writtenBytes + tmp.readableBytes() > UNCOMPRESSED_PACKET_BYTE_LIMIT ) - { - throw new BufferOverflowException(); - } - else - { - this.writtenBytes += tmp.readableBytes(); - this.compressFrame.write( tmp.array(), 0, tmp.readableBytes() ); - this.empty = false; - } - } + this.compressFrame.flush(); + if (this.writtenBytes + tmp.readableBytes() > UNCOMPRESSED_PACKET_BYTE_LIMIT) { + throw new BufferOverflowException(); + } else { + this.writtenBytes += tmp.readableBytes(); + this.compressFrame.write(tmp.array(), 0, tmp.readableBytes()); + this.empty = false; + } + } - public int getLength() - { - return this.data.readableBytes(); - } + public int getLength() { + return this.data.readableBytes(); + } - public boolean isEmpty() - { - return this.empty; - } + public boolean isEmpty() { + return this.empty; + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketMEInventoryUpdate.java b/src/main/java/appeng/core/sync/packets/PacketMEInventoryUpdate.java index 9ac3f9131..0bb6f49f2 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMEInventoryUpdate.java +++ b/src/main/java/appeng/core/sync/packets/PacketMEInventoryUpdate.java @@ -19,27 +19,6 @@ package appeng.core.sync.packets; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.BufferOverflowException; -import java.util.ArrayList; -import java.util.List; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -import javax.annotation.Nullable; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.storage.data.IAEItemStack; import appeng.client.gui.implementations.GuiCraftConfirm; import appeng.client.gui.implementations.GuiCraftingCPU; @@ -49,173 +28,163 @@ import appeng.core.AELog; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.util.item.AEItemStack; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.BufferOverflowException; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; -public class PacketMEInventoryUpdate extends AppEngPacket -{ - private static final int UNCOMPRESSED_PACKET_BYTE_LIMIT = 16 * 1024 * 1024; - private static final int OPERATION_BYTE_LIMIT = 2 * 1024; - private static final int TEMP_BUFFER_SIZE = 1024; - private static final int STREAM_MASK = 0xff; +public class PacketMEInventoryUpdate extends AppEngPacket { + private static final int UNCOMPRESSED_PACKET_BYTE_LIMIT = 16 * 1024 * 1024; + private static final int OPERATION_BYTE_LIMIT = 2 * 1024; + private static final int TEMP_BUFFER_SIZE = 1024; + private static final int STREAM_MASK = 0xff; - // input. - @Nullable - private final List list; - // output... - private final byte ref; + // input. + @Nullable + private final List list; + // output... + private final byte ref; - @Nullable - private final ByteBuf data; - @Nullable - private final GZIPOutputStream compressFrame; + @Nullable + private final ByteBuf data; + @Nullable + private final GZIPOutputStream compressFrame; - private int writtenBytes = 0; - private boolean empty = true; + private int writtenBytes = 0; + private boolean empty = true; - // automatic. - public PacketMEInventoryUpdate( final ByteBuf stream ) throws IOException - { - this.data = null; - this.compressFrame = null; - this.list = new ArrayList<>(); - this.ref = stream.readByte(); + // automatic. + public PacketMEInventoryUpdate(final ByteBuf stream) throws IOException { + this.data = null; + this.compressFrame = null; + this.list = new ArrayList<>(); + this.ref = stream.readByte(); - // int originalBytes = stream.readableBytes(); + // int originalBytes = stream.readableBytes(); - try( GZIPInputStream gzReader = new GZIPInputStream( new InputStream() - { - @Override - public int read() throws IOException - { - if( stream.readableBytes() <= 0 ) - { - return -1; - } + try (GZIPInputStream gzReader = new GZIPInputStream(new InputStream() { + @Override + public int read() throws IOException { + if (stream.readableBytes() <= 0) { + return -1; + } - return stream.readByte() & STREAM_MASK; - } - } ) ) - { - final ByteBuf uncompressed = Unpooled.buffer( stream.readableBytes() ); - final byte[] tmp = new byte[TEMP_BUFFER_SIZE]; + return stream.readByte() & STREAM_MASK; + } + })) { + final ByteBuf uncompressed = Unpooled.buffer(stream.readableBytes()); + final byte[] tmp = new byte[TEMP_BUFFER_SIZE]; - while( gzReader.available() != 0 ) - { - final int bytes = gzReader.read( tmp ); + while (gzReader.available() != 0) { + final int bytes = gzReader.read(tmp); - if( bytes > 0 ) - { - uncompressed.writeBytes( tmp, 0, bytes ); - } - } + if (bytes > 0) { + uncompressed.writeBytes(tmp, 0, bytes); + } + } - while( uncompressed.readableBytes() > 0 ) - { - this.list.add( AEItemStack.fromPacket( uncompressed ) ); - } - } + while (uncompressed.readableBytes() > 0) { + this.list.add(AEItemStack.fromPacket(uncompressed)); + } + } - this.empty = this.list.isEmpty(); + this.empty = this.list.isEmpty(); - } + } - // api - public PacketMEInventoryUpdate() throws IOException - { - this( (byte) 0 ); - } + // api + public PacketMEInventoryUpdate() throws IOException { + this((byte) 0); + } - // api - public PacketMEInventoryUpdate( final byte ref ) throws IOException - { - this.ref = ref; - this.data = Unpooled.buffer( OPERATION_BYTE_LIMIT ); - this.data.writeInt( this.getPacketID() ); - this.data.writeByte( this.ref ); + // api + public PacketMEInventoryUpdate(final byte ref) throws IOException { + this.ref = ref; + this.data = Unpooled.buffer(OPERATION_BYTE_LIMIT); + this.data.writeInt(this.getPacketID()); + this.data.writeByte(this.ref); - this.compressFrame = new GZIPOutputStream( new OutputStream() - { - @Override - public void write( final int value ) throws IOException - { - PacketMEInventoryUpdate.this.data.writeByte( value ); - } - } ); + this.compressFrame = new GZIPOutputStream(new OutputStream() { + @Override + public void write(final int value) throws IOException { + PacketMEInventoryUpdate.this.data.writeByte(value); + } + }); - this.list = null; - } + this.list = null; + } - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final GuiScreen gs = Minecraft.getMinecraft().currentScreen; + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - if( gs instanceof GuiCraftConfirm ) - { - ( (GuiCraftConfirm) gs ).postUpdate( this.list, this.ref ); - } + if (gs instanceof GuiCraftConfirm) { + ((GuiCraftConfirm) gs).postUpdate(this.list, this.ref); + } - if( gs instanceof GuiCraftingCPU ) - { - ( (GuiCraftingCPU) gs ).postUpdate( this.list, this.ref ); - } + if (gs instanceof GuiCraftingCPU) { + ((GuiCraftingCPU) gs).postUpdate(this.list, this.ref); + } - if( gs instanceof GuiMEMonitorable ) - { - ( (GuiMEMonitorable) gs ).postUpdate( this.list ); - } + if (gs instanceof GuiMEMonitorable) { + ((GuiMEMonitorable) gs).postUpdate(this.list); + } - if( gs instanceof GuiNetworkStatus ) - { - ( (GuiNetworkStatus) gs ).postUpdate( this.list ); - } - } + if (gs instanceof GuiNetworkStatus) { + ((GuiNetworkStatus) gs).postUpdate(this.list); + } + } - @Nullable - @Override - public FMLProxyPacket getProxy() - { - try - { - this.compressFrame.close(); + @Nullable + @Override + public FMLProxyPacket getProxy() { + try { + this.compressFrame.close(); - this.configureWrite( this.data ); - return super.getProxy(); - } - catch( final IOException e ) - { - AELog.debug( e ); - } + this.configureWrite(this.data); + return super.getProxy(); + } catch (final IOException e) { + AELog.debug(e); + } - return null; - } + return null; + } - public void appendItem( final IAEItemStack is ) throws IOException, BufferOverflowException - { - final ByteBuf tmp = Unpooled.buffer( OPERATION_BYTE_LIMIT ); - is.writeToPacket( tmp ); + public void appendItem(final IAEItemStack is) throws IOException, BufferOverflowException { + final ByteBuf tmp = Unpooled.buffer(OPERATION_BYTE_LIMIT); + is.writeToPacket(tmp); - this.compressFrame.flush(); - if( this.writtenBytes + tmp.readableBytes() > UNCOMPRESSED_PACKET_BYTE_LIMIT ) - { - throw new BufferOverflowException(); - } - else - { - this.writtenBytes += tmp.readableBytes(); - this.compressFrame.write( tmp.array(), 0, tmp.readableBytes() ); - this.empty = false; - } - } + this.compressFrame.flush(); + if (this.writtenBytes + tmp.readableBytes() > UNCOMPRESSED_PACKET_BYTE_LIMIT) { + throw new BufferOverflowException(); + } else { + this.writtenBytes += tmp.readableBytes(); + this.compressFrame.write(tmp.array(), 0, tmp.readableBytes()); + this.empty = false; + } + } - public int getLength() - { - return this.data.readableBytes(); - } + public int getLength() { + return this.data.readableBytes(); + } - public boolean isEmpty() - { - return this.empty; - } + public boolean isEmpty() { + return this.empty; + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java b/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java index f6c6169cd..f368eccb2 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java +++ b/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java @@ -19,9 +19,11 @@ package appeng.core.sync.packets; +import appeng.client.render.effects.MatterCannonFX; +import appeng.core.sync.AppEngPacket; +import appeng.core.sync.network.INetworkInfo; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; - import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; @@ -30,79 +32,67 @@ import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.client.render.effects.MatterCannonFX; -import appeng.core.sync.AppEngPacket; -import appeng.core.sync.network.INetworkInfo; +public class PacketMatterCannon extends AppEngPacket { -public class PacketMatterCannon extends AppEngPacket -{ + private final double x; + private final double y; + private final double z; + private final double dx; + private final double dy; + private final double dz; + private final byte len; - private final double x; - private final double y; - private final double z; - private final double dx; - private final double dy; - private final double dz; - private final byte len; + // automatic. + public PacketMatterCannon(final ByteBuf stream) { + this.x = stream.readFloat(); + this.y = stream.readFloat(); + this.z = stream.readFloat(); + this.dx = stream.readFloat(); + this.dy = stream.readFloat(); + this.dz = stream.readFloat(); + this.len = stream.readByte(); + } - // automatic. - public PacketMatterCannon( final ByteBuf stream ) - { - this.x = stream.readFloat(); - this.y = stream.readFloat(); - this.z = stream.readFloat(); - this.dx = stream.readFloat(); - this.dy = stream.readFloat(); - this.dz = stream.readFloat(); - this.len = stream.readByte(); - } + // api + public PacketMatterCannon(final double x, final double y, final double z, final float dx, final float dy, final float dz, final byte len) { + final float dl = dx * dx + dy * dy + dz * dz; + final float dlz = (float) Math.sqrt(dl); - // api - public PacketMatterCannon( final double x, final double y, final double z, final float dx, final float dy, final float dz, final byte len ) - { - final float dl = dx * dx + dy * dy + dz * dz; - final float dlz = (float) Math.sqrt( dl ); + this.x = x; + this.y = y; + this.z = z; + this.dx = dx / dlz; + this.dy = dy / dlz; + this.dz = dz / dlz; + this.len = len; - this.x = x; - this.y = y; - this.z = z; - this.dx = dx / dlz; - this.dy = dy / dlz; - this.dz = dz / dlz; - this.len = len; + final ByteBuf data = Unpooled.buffer(); - final ByteBuf data = Unpooled.buffer(); + data.writeInt(this.getPacketID()); + data.writeFloat((float) x); + data.writeFloat((float) y); + data.writeFloat((float) z); + data.writeFloat((float) this.dx); + data.writeFloat((float) this.dy); + data.writeFloat((float) this.dz); + data.writeByte(len); - data.writeInt( this.getPacketID() ); - data.writeFloat( (float) x ); - data.writeFloat( (float) y ); - data.writeFloat( (float) z ); - data.writeFloat( (float) this.dx ); - data.writeFloat( (float) this.dy ); - data.writeFloat( (float) this.dz ); - data.writeByte( len ); + this.configureWrite(data); + } - this.configureWrite( data ); - } + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + try { - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - try - { + final World world = FMLClientHandler.instance().getClient().world; + for (int a = 1; a < this.len; a++) { + final MatterCannonFX fx = new MatterCannonFX(world, this.x + this.dx * a, this.y + this.dy * a, this.z + this.dz * a, Items.DIAMOND); - final World world = FMLClientHandler.instance().getClient().world; - for( int a = 1; a < this.len; a++ ) - { - final MatterCannonFX fx = new MatterCannonFX( world, this.x + this.dx * a, this.y + this.dy * a, this.z + this.dz * a, Items.DIAMOND ); - - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - catch( final Exception ignored ) - { - } - } + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } catch (final Exception ignored) { + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java b/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java index 829a59e81..2f8b75515 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java +++ b/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java @@ -19,57 +19,51 @@ package appeng.core.sync.packets; +import appeng.core.AppEng; +import appeng.core.sync.AppEngPacket; +import appeng.core.sync.network.INetworkInfo; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.core.AppEng; -import appeng.core.sync.AppEngPacket; -import appeng.core.sync.network.INetworkInfo; +public class PacketMockExplosion extends AppEngPacket { -public class PacketMockExplosion extends AppEngPacket -{ + private final double x; + private final double y; + private final double z; - private final double x; - private final double y; - private final double z; + // automatic. + public PacketMockExplosion(final ByteBuf stream) { + this.x = stream.readDouble(); + this.y = stream.readDouble(); + this.z = stream.readDouble(); + } - // automatic. - public PacketMockExplosion( final ByteBuf stream ) - { - this.x = stream.readDouble(); - this.y = stream.readDouble(); - this.z = stream.readDouble(); - } + // api + public PacketMockExplosion(final double x, final double y, final double z) { + this.x = x; + this.y = y; + this.z = z; - // api - public PacketMockExplosion( final double x, final double y, final double z ) - { - this.x = x; - this.y = y; - this.z = z; + final ByteBuf data = Unpooled.buffer(); - final ByteBuf data = Unpooled.buffer(); + data.writeInt(this.getPacketID()); + data.writeDouble(x); + data.writeDouble(y); + data.writeDouble(z); - data.writeInt( this.getPacketID() ); - data.writeDouble( x ); - data.writeDouble( y ); - data.writeDouble( z ); + this.configureWrite(data); + } - this.configureWrite( data ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final World world = AppEng.proxy.getWorld(); - world.spawnParticle( EnumParticleTypes.EXPLOSION_LARGE, this.x, this.y, this.z, 1.0D, 0.0D, 0.0D, new int[0] ); - } + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final World world = AppEng.proxy.getWorld(); + world.spawnParticle(EnumParticleTypes.EXPLOSION_LARGE, this.x, this.y, this.z, 1.0D, 0.0D, 0.0D); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java b/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java index 15a32cf1b..fddbc2cce 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java +++ b/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java @@ -19,51 +19,45 @@ package appeng.core.sync.packets; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; - import appeng.api.util.AEColor; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.hooks.TickHandler; import appeng.hooks.TickHandler.PlayerColor; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; -public class PacketPaintedEntity extends AppEngPacket -{ +public class PacketPaintedEntity extends AppEngPacket { - private final AEColor myColor; - private final int entityId; - private int ticks; + private final AEColor myColor; + private final int entityId; + private int ticks; - // automatic. - public PacketPaintedEntity( final ByteBuf stream ) - { - this.entityId = stream.readInt(); - this.myColor = AEColor.values()[stream.readByte()]; - this.ticks = stream.readInt(); - } + // automatic. + public PacketPaintedEntity(final ByteBuf stream) { + this.entityId = stream.readInt(); + this.myColor = AEColor.values()[stream.readByte()]; + this.ticks = stream.readInt(); + } - // api - public PacketPaintedEntity( final int myEntity, final AEColor myColor, final int ticksLeft ) - { + // api + public PacketPaintedEntity(final int myEntity, final AEColor myColor, final int ticksLeft) { - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( this.entityId = myEntity ); - data.writeByte( ( this.myColor = myColor ).ordinal() ); - data.writeInt( ticksLeft ); + data.writeInt(this.getPacketID()); + data.writeInt(this.entityId = myEntity); + data.writeByte((this.myColor = myColor).ordinal()); + data.writeInt(ticksLeft); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final PlayerColor pc = new PlayerColor( this.entityId, this.myColor, this.ticks ); - TickHandler.INSTANCE.getPlayerColors().put( this.entityId, pc ); - } + @Override + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final PlayerColor pc = new PlayerColor(this.entityId, this.myColor, this.ticks); + TickHandler.INSTANCE.getPlayerColors().put(this.entityId, pc); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java b/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java index 98c27bd67..ccd46df12 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java +++ b/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java @@ -19,67 +19,61 @@ package appeng.core.sync.packets; +import appeng.core.AppEng; +import appeng.core.sync.AppEngPacket; +import appeng.core.sync.network.INetworkInfo; +import appeng.parts.PartPlacement; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; -import appeng.core.AppEng; -import appeng.core.sync.AppEngPacket; -import appeng.core.sync.network.INetworkInfo; -import appeng.parts.PartPlacement; +public class PacketPartPlacement extends AppEngPacket { -public class PacketPartPlacement extends AppEngPacket -{ + private int x; + private int y; + private int z; + private int face; + private float eyeHeight; + private EnumHand hand; - private int x; - private int y; - private int z; - private int face; - private float eyeHeight; - private EnumHand hand; + // automatic. + public PacketPartPlacement(final ByteBuf stream) { + this.x = stream.readInt(); + this.y = stream.readInt(); + this.z = stream.readInt(); + this.face = stream.readByte(); + this.eyeHeight = stream.readFloat(); + this.hand = EnumHand.values()[stream.readByte()]; + } - // automatic. - public PacketPartPlacement( final ByteBuf stream ) - { - this.x = stream.readInt(); - this.y = stream.readInt(); - this.z = stream.readInt(); - this.face = stream.readByte(); - this.eyeHeight = stream.readFloat(); - this.hand = EnumHand.values()[stream.readByte()]; - } + // api + public PacketPartPlacement(final BlockPos pos, final EnumFacing face, final float eyeHeight, final EnumHand hand) { + final ByteBuf data = Unpooled.buffer(); - // api - public PacketPartPlacement( final BlockPos pos, final EnumFacing face, final float eyeHeight, final EnumHand hand ) - { - final ByteBuf data = Unpooled.buffer(); + data.writeInt(this.getPacketID()); + data.writeInt(pos.getX()); + data.writeInt(pos.getY()); + data.writeInt(pos.getZ()); + data.writeByte(face.ordinal()); + data.writeFloat(eyeHeight); + data.writeByte(hand.ordinal()); - data.writeInt( this.getPacketID() ); - data.writeInt( pos.getX() ); - data.writeInt( pos.getY() ); - data.writeInt( pos.getZ() ); - data.writeByte( face.ordinal() ); - data.writeFloat( eyeHeight ); - data.writeByte( hand.ordinal() ); + this.configureWrite(data); + } - this.configureWrite( data ); - } - - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - AppEng.proxy.updateRenderMode( sender ); - PartPlacement.setEyeHeight( this.eyeHeight ); - PartPlacement.place( sender.getHeldItem( this.hand ), new BlockPos( this.x, this.y, this.z ), EnumFacing.VALUES[this.face], sender, this.hand, - sender.world, - PartPlacement.PlaceType.INTERACT_FIRST_PASS, 0 ); - AppEng.proxy.updateRenderMode( null ); - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final EntityPlayerMP sender = (EntityPlayerMP) player; + AppEng.proxy.updateRenderMode(sender); + PartPlacement.setEyeHeight(this.eyeHeight); + PartPlacement.place(sender.getHeldItem(this.hand), new BlockPos(this.x, this.y, this.z), EnumFacing.VALUES[this.face], sender, this.hand, + sender.world, + PartPlacement.PlaceType.INTERACT_FIRST_PASS, 0); + AppEng.proxy.updateRenderMode(null); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketPatternSlot.java b/src/main/java/appeng/core/sync/packets/PacketPatternSlot.java index 483def08b..4a22380e1 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPatternSlot.java +++ b/src/main/java/appeng/core/sync/packets/PacketPatternSlot.java @@ -19,15 +19,6 @@ package appeng.core.sync.packets; -import java.io.IOException; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEItemStack; @@ -35,87 +26,81 @@ import appeng.container.implementations.ContainerPatternTerm; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.util.item.AEItemStack; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraftforge.items.IItemHandler; + +import java.io.IOException; -public class PacketPatternSlot extends AppEngPacket -{ +public class PacketPatternSlot extends AppEngPacket { - public final IAEItemStack slotItem; + public final IAEItemStack slotItem; - public final IAEItemStack[] pattern = new IAEItemStack[9]; + public final IAEItemStack[] pattern = new IAEItemStack[9]; - public final boolean shift; + public final boolean shift; - // automatic. - public PacketPatternSlot( final ByteBuf stream ) throws IOException - { + // automatic. + public PacketPatternSlot(final ByteBuf stream) throws IOException { - this.shift = stream.readBoolean(); + this.shift = stream.readBoolean(); - this.slotItem = this.readItem( stream ); + this.slotItem = this.readItem(stream); - for( int x = 0; x < 9; x++ ) - { - this.pattern[x] = this.readItem( stream ); - } - } + for (int x = 0; x < 9; x++) { + this.pattern[x] = this.readItem(stream); + } + } - private IAEItemStack readItem( final ByteBuf stream ) throws IOException - { - final boolean hasItem = stream.readBoolean(); + private IAEItemStack readItem(final ByteBuf stream) throws IOException { + final boolean hasItem = stream.readBoolean(); - if( hasItem ) - { - return AEItemStack.fromPacket( stream ); - } + if (hasItem) { + return AEItemStack.fromPacket(stream); + } - return null; - } + return null; + } - // api - public PacketPatternSlot( final IItemHandler pat, final IAEItemStack slotItem, final boolean shift ) throws IOException - { + // api + public PacketPatternSlot(final IItemHandler pat, final IAEItemStack slotItem, final boolean shift) throws IOException { - this.slotItem = slotItem; - this.shift = shift; + this.slotItem = slotItem; + this.shift = shift; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); + data.writeInt(this.getPacketID()); - data.writeBoolean( shift ); + data.writeBoolean(shift); - this.writeItem( slotItem, data ); - for( int x = 0; x < 9; x++ ) - { - this.pattern[x] = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( pat.getStackInSlot( x ) ); - this.writeItem( this.pattern[x], data ); - } + this.writeItem(slotItem, data); + for (int x = 0; x < 9; x++) { + this.pattern[x] = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(pat.getStackInSlot(x)); + this.writeItem(this.pattern[x], data); + } - this.configureWrite( data ); - } + this.configureWrite(data); + } - private void writeItem( final IAEItemStack slotItem, final ByteBuf data ) throws IOException - { - if( slotItem == null ) - { - data.writeBoolean( false ); - } - else - { - data.writeBoolean( true ); - slotItem.writeToPacket( data ); - } - } + private void writeItem(final IAEItemStack slotItem, final ByteBuf data) throws IOException { + if (slotItem == null) { + data.writeBoolean(false); + } else { + data.writeBoolean(true); + slotItem.writeToPacket(data); + } + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - if( sender.openContainer instanceof ContainerPatternTerm ) - { - final ContainerPatternTerm patternTerminal = (ContainerPatternTerm) sender.openContainer; - patternTerminal.craftOrGetItem( this ); - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final EntityPlayerMP sender = (EntityPlayerMP) player; + if (sender.openContainer instanceof ContainerPatternTerm) { + final ContainerPatternTerm patternTerminal = (ContainerPatternTerm) sender.openContainer; + patternTerminal.craftOrGetItem(this); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketProgressBar.java b/src/main/java/appeng/core/sync/packets/PacketProgressBar.java index 11f85a2ba..951edbded 100644 --- a/src/main/java/appeng/core/sync/packets/PacketProgressBar.java +++ b/src/main/java/appeng/core/sync/packets/PacketProgressBar.java @@ -19,62 +19,53 @@ package appeng.core.sync.packets; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; - import appeng.container.AEBaseContainer; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; -public class PacketProgressBar extends AppEngPacket -{ +public class PacketProgressBar extends AppEngPacket { - private final short id; - private final long value; + private final short id; + private final long value; - // automatic. - public PacketProgressBar( final ByteBuf stream ) - { - this.id = stream.readShort(); - this.value = stream.readLong(); - } + // automatic. + public PacketProgressBar(final ByteBuf stream) { + this.id = stream.readShort(); + this.value = stream.readLong(); + } - // api - public PacketProgressBar( final int shortID, final long value ) - { - this.id = (short) shortID; - this.value = value; + // api + public PacketProgressBar(final int shortID, final long value) { + this.id = (short) shortID; + this.value = value; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeShort( shortID ); - data.writeLong( value ); + data.writeInt(this.getPacketID()); + data.writeShort(shortID); + data.writeLong(value); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; - if( c instanceof AEBaseContainer ) - { - ( (AEBaseContainer) c ).updateFullProgressBar( this.id, this.value ); - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final Container c = player.openContainer; + if (c instanceof AEBaseContainer) { + ((AEBaseContainer) c).updateFullProgressBar(this.id, this.value); + } + } - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; - if( c instanceof AEBaseContainer ) - { - ( (AEBaseContainer) c ).updateFullProgressBar( this.id, this.value ); - } - } + @Override + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final Container c = player.openContainer; + if (c instanceof AEBaseContainer) { + ((AEBaseContainer) c).updateFullProgressBar(this.id, this.value); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java b/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java index f84f3e56d..4673f064b 100644 --- a/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java +++ b/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java @@ -19,47 +19,40 @@ package appeng.core.sync.packets; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; - import appeng.container.AEBaseContainer; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; -public class PacketSwapSlots extends AppEngPacket -{ +public class PacketSwapSlots extends AppEngPacket { - private final int slotA; - private final int slotB; + private final int slotA; + private final int slotB; - // automatic. - public PacketSwapSlots( final ByteBuf stream ) - { - this.slotA = stream.readInt(); - this.slotB = stream.readInt(); - } + // automatic. + public PacketSwapSlots(final ByteBuf stream) { + this.slotA = stream.readInt(); + this.slotB = stream.readInt(); + } - // api - public PacketSwapSlots( final int slotA, final int slotB ) - { - final ByteBuf data = Unpooled.buffer(); + // api + public PacketSwapSlots(final int slotA, final int slotB) { + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( this.slotA = slotA ); - data.writeInt( this.slotB = slotB ); + data.writeInt(this.getPacketID()); + data.writeInt(this.slotA = slotA); + data.writeInt(this.slotB = slotB); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - if( player != null && player.openContainer instanceof AEBaseContainer ) - { - ( (AEBaseContainer) player.openContainer ).swapSlotContents( this.slotA, this.slotB ); - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + if (player != null && player.openContainer instanceof AEBaseContainer) { + ((AEBaseContainer) player.openContainer).swapSlotContents(this.slotA, this.slotB); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java b/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java index 1910df48e..e6f4fd5d0 100644 --- a/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java +++ b/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java @@ -19,58 +19,50 @@ package appeng.core.sync.packets; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.tileentity.TileEntity; - import appeng.container.AEBaseContainer; import appeng.container.ContainerOpenContext; import appeng.core.sync.AppEngPacket; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.INetworkInfo; import appeng.util.Platform; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.tileentity.TileEntity; -public class PacketSwitchGuis extends AppEngPacket -{ +public class PacketSwitchGuis extends AppEngPacket { - private final GuiBridge newGui; + private final GuiBridge newGui; - // automatic. - public PacketSwitchGuis( final ByteBuf stream ) - { - this.newGui = GuiBridge.values()[stream.readInt()]; - } + // automatic. + public PacketSwitchGuis(final ByteBuf stream) { + this.newGui = GuiBridge.values()[stream.readInt()]; + } - // api - public PacketSwitchGuis( final GuiBridge newGui ) - { - this.newGui = newGui; + // api + public PacketSwitchGuis(final GuiBridge newGui) { + this.newGui = newGui; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( newGui.ordinal() ); + data.writeInt(this.getPacketID()); + data.writeInt(newGui.ordinal()); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; - if( c instanceof AEBaseContainer ) - { - final AEBaseContainer bc = (AEBaseContainer) c; - final ContainerOpenContext context = bc.getOpenContext(); - if( context != null ) - { - final TileEntity te = context.getTile(); - Platform.openGUI( player, te, context.getSide(), this.newGui ); - } - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final Container c = player.openContainer; + if (c instanceof AEBaseContainer) { + final AEBaseContainer bc = (AEBaseContainer) c; + final ContainerOpenContext context = bc.getOpenContext(); + if (context != null) { + final TileEntity te = context.getTile(); + Platform.openGUI(player, te, context.getSide(), this.newGui); + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketTargetFluidStack.java b/src/main/java/appeng/core/sync/packets/PacketTargetFluidStack.java index a2477a1fc..d978b4c52 100644 --- a/src/main/java/appeng/core/sync/packets/PacketTargetFluidStack.java +++ b/src/main/java/appeng/core/sync/packets/PacketTargetFluidStack.java @@ -19,17 +19,15 @@ package appeng.core.sync.packets; -import appeng.fluids.container.ContainerFluidInterface; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; - import appeng.core.AELog; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; +import appeng.fluids.container.ContainerFluidInterface; import appeng.fluids.container.ContainerFluidTerminal; import appeng.fluids.util.AEFluidStack; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; /** @@ -37,63 +35,46 @@ import appeng.fluids.util.AEFluidStack; * @version rv6 - 23/05/2018 * @since rv6 23/05/2018 */ -public class PacketTargetFluidStack extends AppEngPacket -{ - private AEFluidStack stack; +public class PacketTargetFluidStack extends AppEngPacket { + private AEFluidStack stack; - // automatic. - public PacketTargetFluidStack( final ByteBuf stream ) - { - try - { - if( stream.readableBytes() > 0 ) - { - this.stack = (AEFluidStack) AEFluidStack.fromPacket( stream ); - } - else - { - this.stack = null; - } - } - catch( Exception ex ) - { - AELog.debug( ex ); - this.stack = null; - } - } + // automatic. + public PacketTargetFluidStack(final ByteBuf stream) { + try { + if (stream.readableBytes() > 0) { + this.stack = (AEFluidStack) AEFluidStack.fromPacket(stream); + } else { + this.stack = null; + } + } catch (Exception ex) { + AELog.debug(ex); + this.stack = null; + } + } - // api - public PacketTargetFluidStack( AEFluidStack stack ) - { + // api + public PacketTargetFluidStack(AEFluidStack stack) { - this.stack = stack; + this.stack = stack; - final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - if( stack != null ) - { - try - { - stack.writeToPacket( data ); - } - catch( Exception ex ) - { - AELog.debug( ex ); - } - } - this.configureWrite( data ); - } + final ByteBuf data = Unpooled.buffer(); + data.writeInt(this.getPacketID()); + if (stack != null) { + try { + stack.writeToPacket(data); + } catch (Exception ex) { + AELog.debug(ex); + } + } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - if( player.openContainer instanceof ContainerFluidTerminal ) - { - ( (ContainerFluidTerminal) player.openContainer ).setTargetStack( this.stack ); - } - else if( player.openContainer instanceof ContainerFluidInterface ) - { - ( (ContainerFluidInterface) player.openContainer ).setTargetStack( this.stack ); - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + if (player.openContainer instanceof ContainerFluidTerminal) { + ((ContainerFluidTerminal) player.openContainer).setTargetStack(this.stack); + } else if (player.openContainer instanceof ContainerFluidInterface) { + ((ContainerFluidInterface) player.openContainer).setTargetStack(this.stack); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketTargetItemStack.java b/src/main/java/appeng/core/sync/packets/PacketTargetItemStack.java index c6834f244..2e7c6ecac 100644 --- a/src/main/java/appeng/core/sync/packets/PacketTargetItemStack.java +++ b/src/main/java/appeng/core/sync/packets/PacketTargetItemStack.java @@ -19,72 +19,55 @@ package appeng.core.sync.packets; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import net.minecraft.entity.player.EntityPlayer; - import appeng.container.AEBaseContainer; import appeng.core.AELog; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.util.item.AEItemStack; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; -public class PacketTargetItemStack extends AppEngPacket -{ - private AEItemStack stack; +public class PacketTargetItemStack extends AppEngPacket { + private AEItemStack stack; - // automatic. - public PacketTargetItemStack( final ByteBuf stream ) - { - try - { - if( stream.readableBytes() > 0 ) - { - this.stack = AEItemStack.fromPacket( stream ); - } - else - { - this.stack = null; - } - } - catch( Exception ex ) - { - AELog.debug( ex ); - this.stack = null; - } - } + // automatic. + public PacketTargetItemStack(final ByteBuf stream) { + try { + if (stream.readableBytes() > 0) { + this.stack = AEItemStack.fromPacket(stream); + } else { + this.stack = null; + } + } catch (Exception ex) { + AELog.debug(ex); + this.stack = null; + } + } - // api - public PacketTargetItemStack( AEItemStack stack ) - { + // api + public PacketTargetItemStack(AEItemStack stack) { - this.stack = stack; + this.stack = stack; - final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - if( stack != null ) - { - try - { - stack.writeToPacket( data ); - } - catch( Exception ex ) - { - AELog.debug( ex ); - } - } - this.configureWrite( data ); - } + final ByteBuf data = Unpooled.buffer(); + data.writeInt(this.getPacketID()); + if (stack != null) { + try { + stack.writeToPacket(data); + } catch (Exception ex) { + AELog.debug(ex); + } + } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - if( player.openContainer instanceof AEBaseContainer ) - { - ( (AEBaseContainer) player.openContainer ).setTargetStack( this.stack ); - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + if (player.openContainer instanceof AEBaseContainer) { + ((AEBaseContainer) player.openContainer).setTargetStack(this.stack); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java b/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java index 41ef1f13e..c6db06357 100644 --- a/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java +++ b/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java @@ -19,9 +19,14 @@ package appeng.core.sync.packets; +import appeng.api.util.AEPartLocation; +import appeng.client.render.effects.EnergyFx; +import appeng.core.AppEng; +import appeng.core.sync.AppEngPacket; +import appeng.core.sync.network.INetworkInfo; +import appeng.util.Platform; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; - import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; @@ -33,91 +38,76 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.util.AEPartLocation; -import appeng.client.render.effects.EnergyFx; -import appeng.core.AppEng; -import appeng.core.sync.AppEngPacket; -import appeng.core.sync.network.INetworkInfo; -import appeng.util.Platform; +public class PacketTransitionEffect extends AppEngPacket { -public class PacketTransitionEffect extends AppEngPacket -{ + private final boolean mode; + private final double x; + private final double y; + private final double z; + private final AEPartLocation d; - private final boolean mode; - private final double x; - private final double y; - private final double z; - private final AEPartLocation d; + // automatic. + public PacketTransitionEffect(final ByteBuf stream) { + this.x = stream.readFloat(); + this.y = stream.readFloat(); + this.z = stream.readFloat(); + this.d = AEPartLocation.fromOrdinal(stream.readByte()); + this.mode = stream.readBoolean(); + } - // automatic. - public PacketTransitionEffect( final ByteBuf stream ) - { - this.x = stream.readFloat(); - this.y = stream.readFloat(); - this.z = stream.readFloat(); - this.d = AEPartLocation.fromOrdinal( stream.readByte() ); - this.mode = stream.readBoolean(); - } + // api + public PacketTransitionEffect(final double x, final double y, final double z, final AEPartLocation dir, final boolean wasBlock) { + this.x = x; + this.y = y; + this.z = z; + this.d = dir; + this.mode = wasBlock; - // api - public PacketTransitionEffect( final double x, final double y, final double z, final AEPartLocation dir, final boolean wasBlock ) - { - this.x = x; - this.y = y; - this.z = z; - this.d = dir; - this.mode = wasBlock; + final ByteBuf data = Unpooled.buffer(); - final ByteBuf data = Unpooled.buffer(); + data.writeInt(this.getPacketID()); + data.writeFloat((float) x); + data.writeFloat((float) y); + data.writeFloat((float) z); + data.writeByte(this.d.ordinal()); + data.writeBoolean(wasBlock); - data.writeInt( this.getPacketID() ); - data.writeFloat( (float) x ); - data.writeFloat( (float) y ); - data.writeFloat( (float) z ); - data.writeByte( this.d.ordinal() ); - data.writeBoolean( wasBlock ); + this.configureWrite(data); + } - this.configureWrite( data ); - } + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final World world = AppEng.proxy.getWorld(); - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final World world = AppEng.proxy.getWorld(); + for (int zz = 0; zz < (this.mode ? 32 : 8); zz++) { + if (AppEng.proxy.shouldAddParticles(Platform.getRandom())) { + final EnergyFx fx = new EnergyFx(world, this.x + (this.mode ? (Platform + .getRandomInt() % 100) * 0.01 : (Platform.getRandomInt() % 100) * 0.005 - 0.25), this.y + (this.mode ? (Platform + .getRandomInt() % 100) * 0.01 : (Platform.getRandomInt() % 100) * 0.005 - 0.25), this.z + (this.mode ? (Platform + .getRandomInt() % 100) * 0.01 : (Platform.getRandomInt() % 100) * 0.005 - 0.25), Items.DIAMOND); - for( int zz = 0; zz < ( this.mode ? 32 : 8 ); zz++ ) - { - if( AppEng.proxy.shouldAddParticles( Platform.getRandom() ) ) - { - final EnergyFx fx = new EnergyFx( world, this.x + ( this.mode ? ( Platform - .getRandomInt() % 100 ) * 0.01 : ( Platform.getRandomInt() % 100 ) * 0.005 - 0.25 ), this.y + ( this.mode ? ( Platform - .getRandomInt() % 100 ) * 0.01 : ( Platform.getRandomInt() % 100 ) * 0.005 - 0.25 ), this.z + ( this.mode ? ( Platform - .getRandomInt() % 100 ) * 0.01 : ( Platform.getRandomInt() % 100 ) * 0.005 - 0.25 ), Items.DIAMOND ); + if (!this.mode) { + fx.fromItem(this.d); + } - if( !this.mode ) - { - fx.fromItem( this.d ); - } + fx.setMotionX(-0.1f * this.d.xOffset); + fx.setMotionY(-0.1f * this.d.yOffset); + fx.setMotionZ(-0.1f * this.d.zOffset); - fx.setMotionX( -0.1f * this.d.xOffset ); - fx.setMotionY( -0.1f * this.d.yOffset ); - fx.setMotionZ( -0.1f * this.d.zOffset ); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } + if (this.mode) { + final Block block = world.getBlockState(new BlockPos((int) this.x, (int) this.y, (int) this.z)).getBlock(); - if( this.mode ) - { - final Block block = world.getBlockState( new BlockPos( (int) this.x, (int) this.y, (int) this.z ) ).getBlock(); - - Minecraft.getMinecraft() - .getSoundHandler() - .playSound( new PositionedSoundRecord( block.getSoundType() - .getBreakSound(), SoundCategory.BLOCKS, ( block.getSoundType().getVolume() + 1.0F ) / 2.0F, block.getSoundType() - .getPitch() * 0.8F, (float) this.x + 0.5F, (float) this.y + 0.5F, (float) this.z + 0.5F ) ); - } - } + Minecraft.getMinecraft() + .getSoundHandler() + .playSound(new PositionedSoundRecord(block.getSoundType() + .getBreakSound(), SoundCategory.BLOCKS, (block.getSoundType().getVolume() + 1.0F) / 2.0F, block.getSoundType() + .getPitch() * 0.8F, (float) this.x + 0.5F, (float) this.y + 0.5F, (float) this.z + 0.5F)); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketValueConfig.java b/src/main/java/appeng/core/sync/packets/PacketValueConfig.java index 1f86f980c..c75d5e4df 100644 --- a/src/main/java/appeng/core/sync/packets/PacketValueConfig.java +++ b/src/main/java/appeng/core/sync/packets/PacketValueConfig.java @@ -19,16 +19,21 @@ package appeng.core.sync.packets; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - +import appeng.api.config.FuzzyMode; +import appeng.api.config.Settings; +import appeng.api.util.IConfigManager; +import appeng.api.util.IConfigurableObject; +import appeng.client.gui.implementations.GuiCraftingCPU; import appeng.client.gui.implementations.GuiOreDictStorageBus; +import appeng.container.AEBaseContainer; import appeng.container.implementations.*; +import appeng.core.sync.AppEngPacket; +import appeng.core.sync.network.INetworkInfo; +import appeng.fluids.container.ContainerFluidLevelEmitter; +import appeng.fluids.container.ContainerFluidStorageBus; +import appeng.helpers.IMouseWheelItem; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; - import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; @@ -36,390 +41,248 @@ import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumHand; -import appeng.api.config.FuzzyMode; -import appeng.api.config.Settings; -import appeng.api.util.IConfigManager; -import appeng.api.util.IConfigurableObject; -import appeng.client.gui.implementations.GuiCraftingCPU; -import appeng.container.AEBaseContainer; -import appeng.core.sync.AppEngPacket; -import appeng.core.sync.network.INetworkInfo; -import appeng.fluids.container.ContainerFluidLevelEmitter; -import appeng.fluids.container.ContainerFluidStorageBus; -import appeng.helpers.IMouseWheelItem; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; -public class PacketValueConfig extends AppEngPacket -{ +public class PacketValueConfig extends AppEngPacket { - private final String Name; - private final String Value; + private final String Name; + private final String Value; - // automatic. - public PacketValueConfig( final ByteBuf stream ) throws IOException - { - final DataInputStream dis = new DataInputStream( this.getPacketByteArray( stream, stream.readerIndex(), stream.readableBytes() ) ); - this.Name = dis.readUTF(); - this.Value = dis.readUTF(); - // dis.close(); - } + // automatic. + public PacketValueConfig(final ByteBuf stream) throws IOException { + final DataInputStream dis = new DataInputStream(this.getPacketByteArray(stream, stream.readerIndex(), stream.readableBytes())); + this.Name = dis.readUTF(); + this.Value = dis.readUTF(); + // dis.close(); + } - // api - public PacketValueConfig( final String name, final String value ) throws IOException - { - this.Name = name; - this.Value = value; + // api + public PacketValueConfig(final String name, final String value) throws IOException { + this.Name = name; + this.Value = value; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); + data.writeInt(this.getPacketID()); - final ByteArrayOutputStream bos = new ByteArrayOutputStream(); - final DataOutputStream dos = new DataOutputStream( bos ); - dos.writeUTF( name ); - dos.writeUTF( value ); - // dos.close(); + final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + final DataOutputStream dos = new DataOutputStream(bos); + dos.writeUTF(name); + dos.writeUTF(value); + // dos.close(); - data.writeBytes( bos.toByteArray() ); + data.writeBytes(bos.toByteArray()); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final Container c = player.openContainer; - if( this.Name.equals( "Item" ) && ( ( !player.getHeldItem( EnumHand.MAIN_HAND ).isEmpty() && player.getHeldItem( EnumHand.MAIN_HAND ) - .getItem() instanceof IMouseWheelItem ) || ( !player.getHeldItem( EnumHand.OFF_HAND ) - .isEmpty() && player.getHeldItem( EnumHand.OFF_HAND ).getItem() instanceof IMouseWheelItem ) ) ) - { - final EnumHand hand; - if( !player.getHeldItem( EnumHand.MAIN_HAND ).isEmpty() && player.getHeldItem( EnumHand.MAIN_HAND ).getItem() instanceof IMouseWheelItem ) - { - hand = EnumHand.MAIN_HAND; - } - else if( !player.getHeldItem( EnumHand.OFF_HAND ).isEmpty() && player.getHeldItem( EnumHand.OFF_HAND ).getItem() instanceof IMouseWheelItem ) - { - hand = EnumHand.OFF_HAND; - } - else - { - return; - } + if (this.Name.equals("Item") && ((!player.getHeldItem(EnumHand.MAIN_HAND).isEmpty() && player.getHeldItem(EnumHand.MAIN_HAND) + .getItem() instanceof IMouseWheelItem) || (!player.getHeldItem(EnumHand.OFF_HAND) + .isEmpty() && player.getHeldItem(EnumHand.OFF_HAND).getItem() instanceof IMouseWheelItem))) { + final EnumHand hand; + if (!player.getHeldItem(EnumHand.MAIN_HAND).isEmpty() && player.getHeldItem(EnumHand.MAIN_HAND).getItem() instanceof IMouseWheelItem) { + hand = EnumHand.MAIN_HAND; + } else if (!player.getHeldItem(EnumHand.OFF_HAND).isEmpty() && player.getHeldItem(EnumHand.OFF_HAND).getItem() instanceof IMouseWheelItem) { + hand = EnumHand.OFF_HAND; + } else { + return; + } - final ItemStack is = player.getHeldItem( hand ); - final IMouseWheelItem si = (IMouseWheelItem) is.getItem(); - si.onWheel( is, this.Value.equals( "WheelUp" ) ); - } - else if( this.Name.equals( "Terminal.Cpu.Set" ) && c instanceof ContainerCraftingStatus ) - { - final ContainerCraftingStatus qk = (ContainerCraftingStatus) c; - qk.selectCPU( Integer.parseInt( this.Value ) ); - } - else if( this.Name.equals( "Terminal.Cpu" ) && c instanceof ContainerCraftConfirm ) - { - final ContainerCraftConfirm qk = (ContainerCraftConfirm) c; - qk.cycleCpu( this.Value.equals( "Next" ) ); - } - else if( this.Name.equals( "Terminal.Start" ) && c instanceof ContainerCraftConfirm ) - { - final ContainerCraftConfirm qk = (ContainerCraftConfirm) c; - qk.startJob(); - } - else if( this.Name.equals( "TileCrafting.Cancel" ) && c instanceof ContainerCraftingCPU ) - { - final ContainerCraftingCPU qk = (ContainerCraftingCPU) c; - qk.cancelCrafting(); - } - else if( this.Name.equals( "QuartzKnife.Name" ) && c instanceof ContainerQuartzKnife ) - { - final ContainerQuartzKnife qk = (ContainerQuartzKnife) c; - qk.setName( this.Value ); - } - else if( this.Name.equals( "QuartzKnife.ReName" ) && c instanceof ContainerRenamer) - { - final ContainerRenamer qk = (ContainerRenamer) c; - qk.setNewName(this.Value); - } - else if( this.Name.equals( "TileSecurityStation.ToggleOption" ) && c instanceof ContainerSecurityStation ) - { - final ContainerSecurityStation sc = (ContainerSecurityStation) c; - sc.toggleSetting( this.Value, player ); - } - else if( this.Name.equals( "PriorityHost.Priority" ) && c instanceof ContainerPriority ) - { - final ContainerPriority pc = (ContainerPriority) c; - pc.setPriority( Integer.parseInt( this.Value ), player ); - } - else if( this.Name.equals( "LevelEmitter.Value" ) && c instanceof ContainerLevelEmitter ) - { - final ContainerLevelEmitter lvc = (ContainerLevelEmitter) c; - lvc.setLevel( Long.parseLong( this.Value ), player ); - } - else if( this.Name.equals( "FluidLevelEmitter.Value" ) && c instanceof ContainerFluidLevelEmitter ) - { - final ContainerFluidLevelEmitter lvc = (ContainerFluidLevelEmitter) c; - lvc.setLevel( Long.parseLong( this.Value ), player ); - } - else if( this.Name.startsWith( "PatternTerminal." ) ) - { - if( c instanceof ContainerPatternTerm ) - { - final ContainerPatternTerm cpt = (ContainerPatternTerm) c; - if( this.Name.equals( "PatternTerminal.CraftMode" ) ) - { - cpt.getPatternTerminal().setCraftingRecipe( this.Value.equals( "1" ) ); - } - else if( this.Name.equals( "PatternTerminal.Encode" ) ) - { - if( this.Value.equals( "2" ) ) - { - cpt.encodeAndMoveToInventory(); - } - else - { - cpt.encode(); - } - } - else if( this.Name.equals( "PatternTerminal.Clear" ) ) - { - cpt.clear(); - } - else if( this.Name.equals( "PatternTerminal.MultiplyByTwo" ) ) - { - cpt.multiply( 2 ); - } - else if( this.Name.equals( "PatternTerminal.MultiplyByThree" ) ) - { - cpt.multiply( 3 ); - } - else if( this.Name.equals( "PatternTerminal.DivideByTwo" ) ) - { - cpt.divide( 2 ); - } - else if( this.Name.equals( "PatternTerminal.DivideByThree" ) ) - { - cpt.divide( 3 ); - } - else if( this.Name.equals( "PatternTerminal.IncreaseByOne" ) ) - { - cpt.increase( 1 ); - } - else if( this.Name.equals( "PatternTerminal.DecreaseByOne" ) ) - { - cpt.decrease( 1 ); - } - else if( this.Name.equals( "PatternTerminal.MaximizeCount" ) ) - { - cpt.maximizeCount(); - } - else if( this.Name.equals( "PatternTerminal.Substitute" ) ) - { - cpt.getPatternTerminal().setSubstitution( this.Value.equals( "1" ) ); - } - } - else if( c instanceof ContainerExpandedProcessingPatternTerm ) - { - final ContainerExpandedProcessingPatternTerm cept = (ContainerExpandedProcessingPatternTerm) c; - if( this.Name.equals( "PatternTerminal.Encode" ) ) - { - if( this.Value.equals( "2" ) ) - { - cept.encodeAndMoveToInventory(); - } - else - { - cept.encode(); - } - } - else if( this.Name.equals( "PatternTerminal.Clear" ) ) - { - cept.clear(); - } - else if( this.Name.equals( "PatternTerminal.MultiplyByTwo" ) ) - { - cept.multiply( 2 ); - } - else if( this.Name.equals( "PatternTerminal.MultiplyByThree" ) ) - { - cept.multiply( 3 ); - } - else if( this.Name.equals( "PatternTerminal.DivideByTwo" ) ) - { - cept.divide( 2 ); - } - else if( this.Name.equals( "PatternTerminal.DivideByThree" ) ) - { - cept.divide( 3 ); - } - else if( this.Name.equals( "PatternTerminal.IncreaseByOne" ) ) - { - cept.increase( 1 ); - } - else if( this.Name.equals( "PatternTerminal.DecreaseByOne" ) ) - { - cept.decrease( 1 ); - } - else if( this.Name.equals( "PatternTerminal.MaximizeCount" ) ) - { - cept.maximizeCount(); - } - } - } - else if( this.Name.startsWith( "StorageBus." ) ) - { - if( this.Name.equals( "StorageBus.Action" ) ) - { - if( this.Value.equals( "Partition" ) ) - { - if( c instanceof ContainerStorageBus ) - { - ( (ContainerStorageBus) c ).partition(); - } - else if( c instanceof ContainerFluidStorageBus ) - { - ( (ContainerFluidStorageBus) c ).partition(); - } - else if( c instanceof ContainerOreDictStorageBus ) - { - ( (ContainerOreDictStorageBus) c ).partition(); - ( (ContainerOreDictStorageBus) c ).sendRegex(); - } - } - else if( this.Value.equals( "Clear" ) ) - { - if( c instanceof ContainerStorageBus ) - { - ( (ContainerStorageBus) c ).clear(); - } - else if( c instanceof ContainerFluidStorageBus ) - { - ( (ContainerFluidStorageBus) c ).clear(); - } - } - } - } - else if( this.Name.startsWith( "OreDictStorageBus" ) ) - { - if( c instanceof ContainerOreDictStorageBus ) - { - if( this.Name.equals( "OreDictStorageBus.save" ) ) - { - ( (ContainerOreDictStorageBus) c ).saveOreMatch( this.Value ); - } - if( this.Name.equals( "OreDictStorageBus.getRegex" ) ) - { - ( (ContainerOreDictStorageBus) c ).sendRegex(); - } - } - } - else if( this.Name.startsWith( "CellWorkbench." ) && c instanceof ContainerCellWorkbench ) - { - final ContainerCellWorkbench ccw = (ContainerCellWorkbench) c; - if( this.Name.equals( "CellWorkbench.Action" ) ) - { - if( this.Value.equals( "CopyMode" ) ) - { - ccw.nextWorkBenchCopyMode(); - } - else if( this.Value.equals( "Partition" ) ) - { - ccw.partition(); - } - else if( this.Value.equals( "Clear" ) ) - { - ccw.clear(); - } - } - else if( this.Name.equals( "CellWorkbench.Fuzzy" ) ) - { - ccw.setFuzzy( FuzzyMode.valueOf( this.Value ) ); - } - } - else if( c instanceof ContainerNetworkTool ) - { - if( this.Name.equals( "NetworkTool" ) && this.Value.equals( "Toggle" ) ) - { - ( (ContainerNetworkTool) c ).toggleFacadeMode(); - } - } - else if( c instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) c ).getConfigManager(); + final ItemStack is = player.getHeldItem(hand); + final IMouseWheelItem si = (IMouseWheelItem) is.getItem(); + si.onWheel(is, this.Value.equals("WheelUp")); + } else if (this.Name.equals("Terminal.Cpu.Set") && c instanceof ContainerCraftingStatus) { + final ContainerCraftingStatus qk = (ContainerCraftingStatus) c; + qk.selectCPU(Integer.parseInt(this.Value)); + } else if (this.Name.equals("Terminal.Cpu") && c instanceof ContainerCraftConfirm) { + final ContainerCraftConfirm qk = (ContainerCraftConfirm) c; + qk.cycleCpu(this.Value.equals("Next")); + } else if (this.Name.equals("Terminal.Start") && c instanceof ContainerCraftConfirm) { + final ContainerCraftConfirm qk = (ContainerCraftConfirm) c; + qk.startJob(); + } else if (this.Name.equals("TileCrafting.Cancel") && c instanceof ContainerCraftingCPU) { + final ContainerCraftingCPU qk = (ContainerCraftingCPU) c; + qk.cancelCrafting(); + } else if (this.Name.equals("QuartzKnife.Name") && c instanceof ContainerQuartzKnife) { + final ContainerQuartzKnife qk = (ContainerQuartzKnife) c; + qk.setName(this.Value); + } else if (this.Name.equals("QuartzKnife.ReName") && c instanceof ContainerRenamer) { + final ContainerRenamer qk = (ContainerRenamer) c; + qk.setNewName(this.Value); + } else if (this.Name.equals("TileSecurityStation.ToggleOption") && c instanceof ContainerSecurityStation) { + final ContainerSecurityStation sc = (ContainerSecurityStation) c; + sc.toggleSetting(this.Value, player); + } else if (this.Name.equals("PriorityHost.Priority") && c instanceof ContainerPriority) { + final ContainerPriority pc = (ContainerPriority) c; + pc.setPriority(Integer.parseInt(this.Value), player); + } else if (this.Name.equals("LevelEmitter.Value") && c instanceof ContainerLevelEmitter) { + final ContainerLevelEmitter lvc = (ContainerLevelEmitter) c; + lvc.setLevel(Long.parseLong(this.Value), player); + } else if (this.Name.equals("FluidLevelEmitter.Value") && c instanceof ContainerFluidLevelEmitter) { + final ContainerFluidLevelEmitter lvc = (ContainerFluidLevelEmitter) c; + lvc.setLevel(Long.parseLong(this.Value), player); + } else if (this.Name.startsWith("PatternTerminal.")) { + if (c instanceof ContainerPatternTerm) { + final ContainerPatternTerm cpt = (ContainerPatternTerm) c; + if (this.Name.equals("PatternTerminal.CraftMode")) { + cpt.getPatternTerminal().setCraftingRecipe(this.Value.equals("1")); + } else if (this.Name.equals("PatternTerminal.Encode")) { + if (this.Value.equals("2")) { + cpt.encodeAndMoveToInventory(); + } else { + cpt.encode(); + } + } else if (this.Name.equals("PatternTerminal.Clear")) { + cpt.clear(); + } else if (this.Name.equals("PatternTerminal.MultiplyByTwo")) { + cpt.multiply(2); + } else if (this.Name.equals("PatternTerminal.MultiplyByThree")) { + cpt.multiply(3); + } else if (this.Name.equals("PatternTerminal.DivideByTwo")) { + cpt.divide(2); + } else if (this.Name.equals("PatternTerminal.DivideByThree")) { + cpt.divide(3); + } else if (this.Name.equals("PatternTerminal.IncreaseByOne")) { + cpt.increase(1); + } else if (this.Name.equals("PatternTerminal.DecreaseByOne")) { + cpt.decrease(1); + } else if (this.Name.equals("PatternTerminal.MaximizeCount")) { + cpt.maximizeCount(); + } else if (this.Name.equals("PatternTerminal.Substitute")) { + cpt.getPatternTerminal().setSubstitution(this.Value.equals("1")); + } + } else if (c instanceof ContainerExpandedProcessingPatternTerm) { + final ContainerExpandedProcessingPatternTerm cept = (ContainerExpandedProcessingPatternTerm) c; + if (this.Name.equals("PatternTerminal.Encode")) { + if (this.Value.equals("2")) { + cept.encodeAndMoveToInventory(); + } else { + cept.encode(); + } + } else if (this.Name.equals("PatternTerminal.Clear")) { + cept.clear(); + } else if (this.Name.equals("PatternTerminal.MultiplyByTwo")) { + cept.multiply(2); + } else if (this.Name.equals("PatternTerminal.MultiplyByThree")) { + cept.multiply(3); + } else if (this.Name.equals("PatternTerminal.DivideByTwo")) { + cept.divide(2); + } else if (this.Name.equals("PatternTerminal.DivideByThree")) { + cept.divide(3); + } else if (this.Name.equals("PatternTerminal.IncreaseByOne")) { + cept.increase(1); + } else if (this.Name.equals("PatternTerminal.DecreaseByOne")) { + cept.decrease(1); + } else if (this.Name.equals("PatternTerminal.MaximizeCount")) { + cept.maximizeCount(); + } + } + } else if (this.Name.startsWith("StorageBus.")) { + if (this.Name.equals("StorageBus.Action")) { + if (this.Value.equals("Partition")) { + if (c instanceof ContainerStorageBus) { + ((ContainerStorageBus) c).partition(); + } else if (c instanceof ContainerFluidStorageBus) { + ((ContainerFluidStorageBus) c).partition(); + } else if (c instanceof ContainerOreDictStorageBus) { + ((ContainerOreDictStorageBus) c).partition(); + ((ContainerOreDictStorageBus) c).sendRegex(); + } + } else if (this.Value.equals("Clear")) { + if (c instanceof ContainerStorageBus) { + ((ContainerStorageBus) c).clear(); + } else if (c instanceof ContainerFluidStorageBus) { + ((ContainerFluidStorageBus) c).clear(); + } + } + } + } else if (this.Name.startsWith("OreDictStorageBus")) { + if (c instanceof ContainerOreDictStorageBus) { + if (this.Name.equals("OreDictStorageBus.save")) { + ((ContainerOreDictStorageBus) c).saveOreMatch(this.Value); + } + if (this.Name.equals("OreDictStorageBus.getRegex")) { + ((ContainerOreDictStorageBus) c).sendRegex(); + } + } + } else if (this.Name.startsWith("CellWorkbench.") && c instanceof ContainerCellWorkbench) { + final ContainerCellWorkbench ccw = (ContainerCellWorkbench) c; + if (this.Name.equals("CellWorkbench.Action")) { + if (this.Value.equals("CopyMode")) { + ccw.nextWorkBenchCopyMode(); + } else if (this.Value.equals("Partition")) { + ccw.partition(); + } else if (this.Value.equals("Clear")) { + ccw.clear(); + } + } else if (this.Name.equals("CellWorkbench.Fuzzy")) { + ccw.setFuzzy(FuzzyMode.valueOf(this.Value)); + } + } else if (c instanceof ContainerNetworkTool) { + if (this.Name.equals("NetworkTool") && this.Value.equals("Toggle")) { + ((ContainerNetworkTool) c).toggleFacadeMode(); + } + } else if (c instanceof IConfigurableObject) { + final IConfigManager cm = ((IConfigurableObject) c).getConfigManager(); - for( final Settings e : cm.getSettings() ) - { - if( e.name().equals( this.Name ) ) - { - final Enum def = cm.getSetting( e ); + for (final Settings e : cm.getSettings()) { + if (e.name().equals(this.Name)) { + final Enum def = cm.getSetting(e); - try - { - cm.putSetting( e, Enum.valueOf( def.getClass(), this.Value ) ); - } - catch( final IllegalArgumentException err ) - { - // :P - } + try { + cm.putSetting(e, Enum.valueOf(def.getClass(), this.Value)); + } catch (final IllegalArgumentException err) { + // :P + } - break; - } - } - } - } + break; + } + } + } + } - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; + @Override + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final Container c = player.openContainer; - if( this.Name.equals( "CustomName" ) && c instanceof AEBaseContainer ) - { - ( (AEBaseContainer) c ).setCustomName( this.Value ); - } - else if( this.Name.startsWith( "SyncDat." ) ) - { - ( (AEBaseContainer) c ).stringSync( Integer.parseInt( this.Name.substring( 8 ) ), this.Value ); - } - else if( this.Name.equals( "CraftingStatus" ) && this.Value.equals( "Clear" ) ) - { - final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - if( gs instanceof GuiCraftingCPU ) - { - ( (GuiCraftingCPU) gs ).clearItems(); - } - } - else if( this.Name.equals( "OreDictStorageBus.sendRegex" ) ) - { - final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - if( gs instanceof GuiOreDictStorageBus ) - { - ( (GuiOreDictStorageBus) gs ).fillRegex( this.Value ); - } - } - else if( c instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) c ).getConfigManager(); + if (this.Name.equals("CustomName") && c instanceof AEBaseContainer) { + ((AEBaseContainer) c).setCustomName(this.Value); + } else if (this.Name.startsWith("SyncDat.")) { + ((AEBaseContainer) c).stringSync(Integer.parseInt(this.Name.substring(8)), this.Value); + } else if (this.Name.equals("CraftingStatus") && this.Value.equals("Clear")) { + final GuiScreen gs = Minecraft.getMinecraft().currentScreen; + if (gs instanceof GuiCraftingCPU) { + ((GuiCraftingCPU) gs).clearItems(); + } + } else if (this.Name.equals("OreDictStorageBus.sendRegex")) { + final GuiScreen gs = Minecraft.getMinecraft().currentScreen; + if (gs instanceof GuiOreDictStorageBus) { + ((GuiOreDictStorageBus) gs).fillRegex(this.Value); + } + } else if (c instanceof IConfigurableObject) { + final IConfigManager cm = ((IConfigurableObject) c).getConfigManager(); - for( final Settings e : cm.getSettings() ) - { - if( e.name().equals( this.Name ) ) - { - final Enum def = cm.getSetting( e ); + for (final Settings e : cm.getSettings()) { + if (e.name().equals(this.Name)) { + final Enum def = cm.getSetting(e); - try - { - cm.putSetting( e, Enum.valueOf( def.getClass(), this.Value ) ); - } - catch( final IllegalArgumentException err ) - { - // :P - } + try { + cm.putSetting(e, Enum.valueOf(def.getClass(), this.Value)); + } catch (final IllegalArgumentException err) { + // :P + } - break; - } - } - } - } + break; + } + } + } + } } diff --git a/src/main/java/appeng/core/worlddata/CompassData.java b/src/main/java/appeng/core/worlddata/CompassData.java index 33a54225a..225f4fb58 100644 --- a/src/main/java/appeng/core/worlddata/CompassData.java +++ b/src/main/java/appeng/core/worlddata/CompassData.java @@ -19,13 +19,11 @@ package appeng.core.worlddata; -import java.io.File; - -import javax.annotation.Nonnull; - +import appeng.services.CompassService; import com.google.common.base.Preconditions; -import appeng.services.CompassService; +import javax.annotation.Nonnull; +import java.io.File; /** @@ -33,28 +31,24 @@ import appeng.services.CompassService; * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class CompassData implements IWorldCompassData, IOnWorldStoppable -{ - @Nonnull - private final CompassService service; +final class CompassData implements IWorldCompassData, IOnWorldStoppable { + @Nonnull + private final CompassService service; - public CompassData( @Nonnull final File compassDirectory, @Nonnull final CompassService service ) - { - Preconditions.checkNotNull( compassDirectory ); - Preconditions.checkNotNull( service ); + public CompassData(@Nonnull final File compassDirectory, @Nonnull final CompassService service) { + Preconditions.checkNotNull(compassDirectory); + Preconditions.checkNotNull(service); - this.service = service; - } + this.service = service; + } - @Override - public CompassService service() - { - return this.service; - } + @Override + public CompassService service() { + return this.service; + } - @Override - public void onWorldStop() - { - this.service.kill(); - } + @Override + public void onWorldStop() { + this.service.kill(); + } } diff --git a/src/main/java/appeng/core/worlddata/IOnWorldStartable.java b/src/main/java/appeng/core/worlddata/IOnWorldStartable.java index b6c5c325d..9bb03a088 100644 --- a/src/main/java/appeng/core/worlddata/IOnWorldStartable.java +++ b/src/main/java/appeng/core/worlddata/IOnWorldStartable.java @@ -24,7 +24,6 @@ package appeng.core.worlddata; * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IOnWorldStartable -{ - void onWorldStart(); +public interface IOnWorldStartable { + void onWorldStart(); } diff --git a/src/main/java/appeng/core/worlddata/IOnWorldStoppable.java b/src/main/java/appeng/core/worlddata/IOnWorldStoppable.java index 7a36e771f..8f205cafb 100644 --- a/src/main/java/appeng/core/worlddata/IOnWorldStoppable.java +++ b/src/main/java/appeng/core/worlddata/IOnWorldStoppable.java @@ -24,7 +24,6 @@ package appeng.core.worlddata; * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IOnWorldStoppable -{ - void onWorldStop(); +public interface IOnWorldStoppable { + void onWorldStop(); } diff --git a/src/main/java/appeng/core/worlddata/IWorldCompassData.java b/src/main/java/appeng/core/worlddata/IWorldCompassData.java index c4b74b85c..09b1becce 100644 --- a/src/main/java/appeng/core/worlddata/IWorldCompassData.java +++ b/src/main/java/appeng/core/worlddata/IWorldCompassData.java @@ -27,7 +27,6 @@ import appeng.services.CompassService; * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldCompassData -{ - CompassService service(); +public interface IWorldCompassData { + CompassService service(); } diff --git a/src/main/java/appeng/core/worlddata/IWorldData.java b/src/main/java/appeng/core/worlddata/IWorldData.java index e9c453ef7..ac892bb3c 100644 --- a/src/main/java/appeng/core/worlddata/IWorldData.java +++ b/src/main/java/appeng/core/worlddata/IWorldData.java @@ -27,21 +27,20 @@ import javax.annotation.Nonnull; * @version rv3 - 02.11.2015 * @since rv3 30.05.2015 */ -public interface IWorldData -{ - void onServerStopping(); +public interface IWorldData { + void onServerStopping(); - void onServerStoppped(); + void onServerStoppped(); - @Nonnull - IWorldGridStorageData storageData(); + @Nonnull + IWorldGridStorageData storageData(); - @Nonnull - IWorldPlayerData playerData(); + @Nonnull + IWorldPlayerData playerData(); - @Nonnull - IWorldCompassData compassData(); + @Nonnull + IWorldCompassData compassData(); - @Nonnull - IWorldSpawnData spawnData(); + @Nonnull + IWorldSpawnData spawnData(); } diff --git a/src/main/java/appeng/core/worlddata/IWorldDimensionData.java b/src/main/java/appeng/core/worlddata/IWorldDimensionData.java index cc2319b00..cf1d2b441 100644 --- a/src/main/java/appeng/core/worlddata/IWorldDimensionData.java +++ b/src/main/java/appeng/core/worlddata/IWorldDimensionData.java @@ -19,11 +19,10 @@ package appeng.core.worlddata; -import javax.annotation.Nullable; - +import appeng.api.util.WorldCoord; import net.minecraft.network.NetworkManager; -import appeng.api.util.WorldCoord; +import javax.annotation.Nullable; /** @@ -31,13 +30,12 @@ import appeng.api.util.WorldCoord; * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldDimensionData -{ - void addStorageCell( int newStorageCellID ); +public interface IWorldDimensionData { + void addStorageCell(int newStorageCellID); - WorldCoord getStoredSize( int dim ); + WorldCoord getStoredSize(int dim); - void setStoredSize( int dim, int targetX, int targetY, int targetZ ); + void setStoredSize(int dim, int targetX, int targetY, int targetZ); - void sendToPlayer( @Nullable NetworkManager manager ); + void sendToPlayer(@Nullable NetworkManager manager); } diff --git a/src/main/java/appeng/core/worlddata/IWorldGridStorageData.java b/src/main/java/appeng/core/worlddata/IWorldGridStorageData.java index c579a3249..739b525e1 100644 --- a/src/main/java/appeng/core/worlddata/IWorldGridStorageData.java +++ b/src/main/java/appeng/core/worlddata/IWorldGridStorageData.java @@ -19,28 +19,27 @@ package appeng.core.worlddata; +import appeng.me.GridStorage; + import javax.annotation.Nonnull; import javax.annotation.Nullable; -import appeng.me.GridStorage; - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldGridStorageData -{ - @Nullable - GridStorage getGridStorage( long storageID ); +public interface IWorldGridStorageData { + @Nullable + GridStorage getGridStorage(long storageID); - @Nonnull - GridStorage getNewGridStorage(); + @Nonnull + GridStorage getNewGridStorage(); - long nextGridStorage(); + long nextGridStorage(); - void destroyGridStorage( long id ); + void destroyGridStorage(long id); - int getNextOrderedValue( String name ); + int getNextOrderedValue(String name); } diff --git a/src/main/java/appeng/core/worlddata/IWorldPlayerData.java b/src/main/java/appeng/core/worlddata/IWorldPlayerData.java index 7d0f09bc1..184b5f12b 100644 --- a/src/main/java/appeng/core/worlddata/IWorldPlayerData.java +++ b/src/main/java/appeng/core/worlddata/IWorldPlayerData.java @@ -19,22 +19,20 @@ package appeng.core.worlddata; -import javax.annotation.Nullable; - import com.mojang.authlib.GameProfile; - import net.minecraft.entity.player.EntityPlayer; +import javax.annotation.Nullable; + /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldPlayerData -{ - @Nullable - EntityPlayer getPlayerFromID( int playerID ); +public interface IWorldPlayerData { + @Nullable + EntityPlayer getPlayerFromID(int playerID); - int getPlayerID( GameProfile profile ); + int getPlayerID(GameProfile profile); } diff --git a/src/main/java/appeng/core/worlddata/IWorldPlayerMapping.java b/src/main/java/appeng/core/worlddata/IWorldPlayerMapping.java index eca35002c..457108ef2 100644 --- a/src/main/java/appeng/core/worlddata/IWorldPlayerMapping.java +++ b/src/main/java/appeng/core/worlddata/IWorldPlayerMapping.java @@ -19,36 +19,33 @@ package appeng.core.worlddata; +import javax.annotation.Nonnull; import java.util.Optional; import java.util.UUID; -import javax.annotation.Nonnull; - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldPlayerMapping -{ - /** - * Tries to retrieve the UUID of a player. - * Might not be stored inside of the map. - * Should not happen though. - * - * @param id ID of the to be searched player - * - * @return maybe the UUID of the searched player - */ - @Nonnull - Optional get( int id ); +public interface IWorldPlayerMapping { + /** + * Tries to retrieve the UUID of a player. + * Might not be stored inside of the map. + * Should not happen though. + * + * @param id ID of the to be searched player + * @return maybe the UUID of the searched player + */ + @Nonnull + Optional get(int id); - /** - * Put in new players when they join the server - * - * @param id id of new player - * @param uuid UUID of new player - */ - void put( int id, @Nonnull UUID uuid ); + /** + * Put in new players when they join the server + * + * @param id id of new player + * @param uuid UUID of new player + */ + void put(int id, @Nonnull UUID uuid); } diff --git a/src/main/java/appeng/core/worlddata/IWorldSpawnData.java b/src/main/java/appeng/core/worlddata/IWorldSpawnData.java index adfd67245..8be93fa0f 100644 --- a/src/main/java/appeng/core/worlddata/IWorldSpawnData.java +++ b/src/main/java/appeng/core/worlddata/IWorldSpawnData.java @@ -19,23 +19,22 @@ package appeng.core.worlddata; -import java.util.Collection; - import net.minecraft.nbt.NBTTagCompound; +import java.util.Collection; + /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldSpawnData -{ - void setGenerated( int dim, int chunkX, int chunkZ ); +public interface IWorldSpawnData { + void setGenerated(int dim, int chunkX, int chunkZ); - boolean hasGenerated( int dim, int chunkX, int chunkZ ); + boolean hasGenerated(int dim, int chunkX, int chunkZ); - boolean addNearByMeteorites( int dim, int chunkX, int chunkZ, NBTTagCompound newData ); + boolean addNearByMeteorites(int dim, int chunkX, int chunkZ, NBTTagCompound newData); - Collection getNearByMeteorites( int dim, int chunkX, int chunkZ ); + Collection getNearByMeteorites(int dim, int chunkX, int chunkZ); } diff --git a/src/main/java/appeng/core/worlddata/MeteorDataNameEncoder.java b/src/main/java/appeng/core/worlddata/MeteorDataNameEncoder.java index 0ba649dca..c84fbc7a1 100644 --- a/src/main/java/appeng/core/worlddata/MeteorDataNameEncoder.java +++ b/src/main/java/appeng/core/worlddata/MeteorDataNameEncoder.java @@ -19,10 +19,10 @@ package appeng.core.worlddata; -import javax.annotation.Nonnull; - import com.google.common.base.Preconditions; +import javax.annotation.Nonnull; + /** * encodes data into a common name @@ -31,54 +31,48 @@ import com.google.common.base.Preconditions; * @version rv3 - 05.06.2015 * @since rv3 05.06.2015 */ -public class MeteorDataNameEncoder -{ - private static final char DATA_SEPARATOR = '_'; - private static final char BASE_EXTENSION_SEPARATOR = '.'; - private static final String FILE_EXTENSION = "dat"; +public class MeteorDataNameEncoder { + private static final char DATA_SEPARATOR = '_'; + private static final char BASE_EXTENSION_SEPARATOR = '.'; + private static final String FILE_EXTENSION = "dat"; - private final char dataSeparator; - @Nonnull - private final String fileExtension; - private final char baseExtSeparator; - private final int bitScale; + private final char dataSeparator; + @Nonnull + private final String fileExtension; + private final char baseExtSeparator; + private final int bitScale; - /** - * @param bitScale how often the coordinates will be shifted right (will scale coordinates down) - */ - public MeteorDataNameEncoder( final int bitScale ) - { - this( DATA_SEPARATOR, BASE_EXTENSION_SEPARATOR, FILE_EXTENSION, bitScale ); - } + /** + * @param bitScale how often the coordinates will be shifted right (will scale coordinates down) + */ + public MeteorDataNameEncoder(final int bitScale) { + this(DATA_SEPARATOR, BASE_EXTENSION_SEPARATOR, FILE_EXTENSION, bitScale); + } - private MeteorDataNameEncoder( final char dataSeparator, final char baseExtSeparator, @Nonnull final String fileExtension, final int bitScale ) - { - Preconditions.checkNotNull( fileExtension ); - Preconditions.checkArgument( !fileExtension.isEmpty() ); - Preconditions.checkArgument( bitScale >= 0 ); + private MeteorDataNameEncoder(final char dataSeparator, final char baseExtSeparator, @Nonnull final String fileExtension, final int bitScale) { + Preconditions.checkNotNull(fileExtension); + Preconditions.checkArgument(!fileExtension.isEmpty()); + Preconditions.checkArgument(bitScale >= 0); - this.dataSeparator = dataSeparator; - this.baseExtSeparator = baseExtSeparator; - this.fileExtension = fileExtension; - this.bitScale = bitScale; - } + this.dataSeparator = dataSeparator; + this.baseExtSeparator = baseExtSeparator; + this.fileExtension = fileExtension; + this.bitScale = bitScale; + } - /** - * @param dimension ID of the processed dimension. Can be any integer - * @param chunkX X coordinate of the chunk. Can be any integer - * @param chunkZ Z coordinate of the chunk. Can be any integer - * - * @return encoded file name suggestion in form of dim_x_y.dat where x and y will be - * shifted to stay conform with the vanilla chunk system - * - * @since rv3 05.06.2015 - */ - public String encode( final int dimension, final int chunkX, final int chunkZ ) - { - final int shiftedX = chunkX >> this.bitScale; - final int shiftedZ = chunkZ >> this.bitScale; + /** + * @param dimension ID of the processed dimension. Can be any integer + * @param chunkX X coordinate of the chunk. Can be any integer + * @param chunkZ Z coordinate of the chunk. Can be any integer + * @return encoded file name suggestion in form of dim_x_y.dat where x and y will be + * shifted to stay conform with the vanilla chunk system + * @since rv3 05.06.2015 + */ + public String encode(final int dimension, final int chunkX, final int chunkZ) { + final int shiftedX = chunkX >> this.bitScale; + final int shiftedZ = chunkZ >> this.bitScale; - return String.format( "%d%c%d%c%d%c%s", dimension, this.dataSeparator, shiftedX, this.dataSeparator, shiftedZ, this.baseExtSeparator, - this.fileExtension ); - } + return String.format("%d%c%d%c%d%c%s", dimension, this.dataSeparator, shiftedX, this.dataSeparator, shiftedZ, this.baseExtSeparator, + this.fileExtension); + } } diff --git a/src/main/java/appeng/core/worlddata/PlayerData.java b/src/main/java/appeng/core/worlddata/PlayerData.java index c576bd3e4..97c2b3a62 100644 --- a/src/main/java/appeng/core/worlddata/PlayerData.java +++ b/src/main/java/appeng/core/worlddata/PlayerData.java @@ -19,21 +19,18 @@ package appeng.core.worlddata; -import java.util.Optional; -import java.util.UUID; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - +import appeng.core.AppEng; import com.google.common.base.Preconditions; import com.mojang.authlib.GameProfile; - import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; -import appeng.core.AppEng; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Optional; +import java.util.UUID; /** @@ -45,96 +42,83 @@ import appeng.core.AppEng; * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class PlayerData implements IWorldPlayerData, IOnWorldStartable, IOnWorldStoppable -{ - private static final String LAST_PLAYER_CATEGORY = "Counters"; - private static final String LAST_PLAYER_KEY = "lastPlayer"; - private static final int LAST_PLAYER_DEFAULT = 0; +final class PlayerData implements IWorldPlayerData, IOnWorldStartable, IOnWorldStoppable { + private static final String LAST_PLAYER_CATEGORY = "Counters"; + private static final String LAST_PLAYER_KEY = "lastPlayer"; + private static final int LAST_PLAYER_DEFAULT = 0; - private final Configuration config; - private final IWorldPlayerMapping playerMapping; + private final Configuration config; + private final IWorldPlayerMapping playerMapping; - private int lastPlayerID; + private int lastPlayerID; - public PlayerData( @Nonnull final Configuration configFile ) - { - Preconditions.checkNotNull( configFile ); + public PlayerData(@Nonnull final Configuration configFile) { + Preconditions.checkNotNull(configFile); - this.config = configFile; + this.config = configFile; - final ConfigCategory playerList = this.config.getCategory( "players" ); - this.playerMapping = new PlayerMapping( playerList ); - } + final ConfigCategory playerList = this.config.getCategory("players"); + this.playerMapping = new PlayerMapping(playerList); + } - @Nullable - @Override - public EntityPlayer getPlayerFromID( final int playerID ) - { - final Optional maybe = this.playerMapping.get( playerID ); + @Nullable + @Override + public EntityPlayer getPlayerFromID(final int playerID) { + final Optional maybe = this.playerMapping.get(playerID); - if( maybe.isPresent() ) - { - final UUID uuid = maybe.get(); - for( final EntityPlayer player : AppEng.proxy.getPlayers() ) - { - if( player.getUniqueID().equals( uuid ) ) - { - return player; - } - } - } + if (maybe.isPresent()) { + final UUID uuid = maybe.get(); + for (final EntityPlayer player : AppEng.proxy.getPlayers()) { + if (player.getUniqueID().equals(uuid)) { + return player; + } + } + } - return null; - } + return null; + } - @Override - public int getPlayerID( @Nonnull final GameProfile profile ) - { - Preconditions.checkNotNull( profile ); - Preconditions.checkNotNull( this.config.getCategory( "players" ) ); - Preconditions.checkState( profile.isComplete() ); + @Override + public int getPlayerID(@Nonnull final GameProfile profile) { + Preconditions.checkNotNull(profile); + Preconditions.checkNotNull(this.config.getCategory("players")); + Preconditions.checkState(profile.isComplete()); - final ConfigCategory players = this.config.getCategory( "players" ); - final String uuid = profile.getId().toString(); - final Property maybePlayerID = players.get( uuid ); + final ConfigCategory players = this.config.getCategory("players"); + final String uuid = profile.getId().toString(); + final Property maybePlayerID = players.get(uuid); - if( maybePlayerID != null && maybePlayerID.isIntValue() ) - { - return maybePlayerID.getInt(); - } - else - { - final int newPlayerID = this.nextPlayer(); - final Property newPlayer = new Property( uuid, String.valueOf( newPlayerID ), Property.Type.INTEGER ); - players.put( uuid, newPlayer ); - this.playerMapping.put( newPlayerID, profile.getId() ); // add to reverse map - this.config.save(); + if (maybePlayerID != null && maybePlayerID.isIntValue()) { + return maybePlayerID.getInt(); + } else { + final int newPlayerID = this.nextPlayer(); + final Property newPlayer = new Property(uuid, String.valueOf(newPlayerID), Property.Type.INTEGER); + players.put(uuid, newPlayer); + this.playerMapping.put(newPlayerID, profile.getId()); // add to reverse map + this.config.save(); - return newPlayerID; - } - } + return newPlayerID; + } + } - private int nextPlayer() - { - final int r = this.lastPlayerID; - this.lastPlayerID++; - this.config.get( LAST_PLAYER_CATEGORY, LAST_PLAYER_KEY, this.lastPlayerID ).set( this.lastPlayerID ); - return r; - } + private int nextPlayer() { + final int r = this.lastPlayerID; + this.lastPlayerID++; + this.config.get(LAST_PLAYER_CATEGORY, LAST_PLAYER_KEY, this.lastPlayerID).set(this.lastPlayerID); + return r; + } - @Override - public void onWorldStart() - { - this.lastPlayerID = this.config.get( LAST_PLAYER_CATEGORY, LAST_PLAYER_KEY, LAST_PLAYER_DEFAULT ).getInt( LAST_PLAYER_DEFAULT ); + @Override + public void onWorldStart() { + this.lastPlayerID = this.config.get(LAST_PLAYER_CATEGORY, LAST_PLAYER_KEY, LAST_PLAYER_DEFAULT).getInt(LAST_PLAYER_DEFAULT); - this.config.save(); - } + this.config.save(); + } - @Override - public void onWorldStop() - { - this.config.save(); + @Override + public void onWorldStop() { + this.config.save(); - this.lastPlayerID = 0; - } + this.lastPlayerID = 0; + } } diff --git a/src/main/java/appeng/core/worlddata/PlayerMapping.java b/src/main/java/appeng/core/worlddata/PlayerMapping.java index f8ff3ccb6..3532942bd 100644 --- a/src/main/java/appeng/core/worlddata/PlayerMapping.java +++ b/src/main/java/appeng/core/worlddata/PlayerMapping.java @@ -19,52 +19,46 @@ package appeng.core.worlddata; +import com.google.common.base.Preconditions; +import net.minecraftforge.common.config.ConfigCategory; + +import javax.annotation.Nonnull; import java.util.Map; import java.util.Optional; import java.util.UUID; -import javax.annotation.Nonnull; - -import com.google.common.base.Preconditions; - -import net.minecraftforge.common.config.ConfigCategory; - /** * Wrapper class for the player mappings. * Will grant access to a pre initialized player map * based on the "players" category in the settings.cfg */ -final class PlayerMapping implements IWorldPlayerMapping -{ - /** - * View of player mappings, is not immutable, - * since it needs to be edited upon runtime, - * cause new players can join - */ - private final Map mappings; +final class PlayerMapping implements IWorldPlayerMapping { + /** + * View of player mappings, is not immutable, + * since it needs to be edited upon runtime, + * cause new players can join + */ + private final Map mappings; - public PlayerMapping( final ConfigCategory category ) - { - final PlayerMappingsInitializer init = new PlayerMappingsInitializer( category ); + public PlayerMapping(final ConfigCategory category) { + final PlayerMappingsInitializer init = new PlayerMappingsInitializer(category); - this.mappings = init.getPlayerMappings(); - } + this.mappings = init.getPlayerMappings(); + } - @Nonnull - @Override - public Optional get( final int id ) - { - final UUID maybe = this.mappings.get( id ); + @Nonnull + @Override + public Optional get(final int id) { + final UUID maybe = this.mappings.get(id); - return Optional.ofNullable( maybe ); - } + return Optional.ofNullable(maybe); + } - @Override - public void put( final int id, @Nonnull final UUID uuid ) - { - Preconditions.checkNotNull( uuid ); + @Override + public void put(final int id, @Nonnull final UUID uuid) { + Preconditions.checkNotNull(uuid); - this.mappings.put( id, uuid ); - } + this.mappings.put(id, uuid); + } } diff --git a/src/main/java/appeng/core/worlddata/PlayerMappingsInitializer.java b/src/main/java/appeng/core/worlddata/PlayerMappingsInitializer.java index 0abce24b2..aa7ce0e35 100644 --- a/src/main/java/appeng/core/worlddata/PlayerMappingsInitializer.java +++ b/src/main/java/appeng/core/worlddata/PlayerMappingsInitializer.java @@ -19,75 +19,67 @@ package appeng.core.worlddata; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - +import appeng.core.AELog; +import appeng.util.UUIDMatcher; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Property; -import appeng.core.AELog; -import appeng.util.UUIDMatcher; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; /** * Initializes a map of ID to UUID from the player list in the settings.cfg */ -class PlayerMappingsInitializer -{ - /** - * Internal immutable mapping - */ - private final Map playerMappings; +class PlayerMappingsInitializer { + /** + * Internal immutable mapping + */ + private final Map playerMappings; - /** - * Creates the initializer for the player mappings. - * The map will be filled upon construction - * and will only be filled with valid entries. - * If an invalid entry is found, an warning is printed, - * mostly due to migration problems from 1.7.2 to 1.7.10 - * where the UUIDs were introduced. - * - * @param playerList the category for the player list, generally extracted using the "players" tag - */ - PlayerMappingsInitializer( final ConfigCategory playerList ) - { - // Matcher for UUIDs - final UUIDMatcher matcher = new UUIDMatcher(); + /** + * Creates the initializer for the player mappings. + * The map will be filled upon construction + * and will only be filled with valid entries. + * If an invalid entry is found, an warning is printed, + * mostly due to migration problems from 1.7.2 to 1.7.10 + * where the UUIDs were introduced. + * + * @param playerList the category for the player list, generally extracted using the "players" tag + */ + PlayerMappingsInitializer(final ConfigCategory playerList) { + // Matcher for UUIDs + final UUIDMatcher matcher = new UUIDMatcher(); - // Initial capacity for mappings - final int capacity = playerList.size(); + // Initial capacity for mappings + final int capacity = playerList.size(); - // Mappings for the IDs is a regular HashMap - this.playerMappings = new HashMap<>( capacity ); + // Mappings for the IDs is a regular HashMap + this.playerMappings = new HashMap<>(capacity); - // Iterates through every pair of UUID to ID - for( final Map.Entry entry : playerList.getValues().entrySet() ) - { - final String maybeUUID = entry.getKey(); - final int id = entry.getValue().getInt(); + // Iterates through every pair of UUID to ID + for (final Map.Entry entry : playerList.getValues().entrySet()) { + final String maybeUUID = entry.getKey(); + final int id = entry.getValue().getInt(); - if( matcher.isUUID( maybeUUID ) ) - { - final UUID uuidString = UUID.fromString( maybeUUID ); + if (matcher.isUUID(maybeUUID)) { + final UUID uuidString = UUID.fromString(maybeUUID); - this.playerMappings.put( id, uuidString ); - } - else - { - AELog.warn( - "The configuration for players contained an outdated entry instead an expected UUID " + maybeUUID + " for the player " + id + ". Please clean this up." ); - } - } - } + this.playerMappings.put(id, uuidString); + } else { + AELog.warn( + "The configuration for players contained an outdated entry instead an expected UUID " + maybeUUID + " for the player " + id + ". Please clean this up."); + } + } + } - /** - * Getter - * - * @return Immutable map of the players mappings of their ID to their UUID - */ - public Map getPlayerMappings() - { - return this.playerMappings; - } + /** + * Getter + * + * @return Immutable map of the players mappings of their ID to their UUID + */ + public Map getPlayerMappings() { + return this.playerMappings; + } } diff --git a/src/main/java/appeng/core/worlddata/SpatialDimensionManager.java b/src/main/java/appeng/core/worlddata/SpatialDimensionManager.java index b55296036..eb3a61480 100644 --- a/src/main/java/appeng/core/worlddata/SpatialDimensionManager.java +++ b/src/main/java/appeng/core/worlddata/SpatialDimensionManager.java @@ -19,9 +19,8 @@ package appeng.core.worlddata; -import java.util.HashMap; -import java.util.Map; - +import appeng.api.storage.ISpatialDimension; +import appeng.capabilities.Capabilities; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.EnumFacing; @@ -31,215 +30,185 @@ import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.util.INBTSerializable; -import appeng.api.storage.ISpatialDimension; -import appeng.capabilities.Capabilities; +import java.util.HashMap; +import java.util.Map; -public class SpatialDimensionManager implements ISpatialDimension, ICapabilitySerializable -{ - private static final String NBT_SPATIAL_DATA_KEY = "spatial_data"; - private static final String NBT_SPATIAL_ID_KEY = "id"; +public class SpatialDimensionManager implements ISpatialDimension, ICapabilitySerializable { + private static final String NBT_SPATIAL_DATA_KEY = "spatial_data"; + private static final String NBT_SPATIAL_ID_KEY = "id"; - private World world; - private Map spatialData = new HashMap<>(); + private final World world; + private final Map spatialData = new HashMap<>(); - private static final int MAX_CELL_DIMENSION = 512; + private static final int MAX_CELL_DIMENSION = 512; - public SpatialDimensionManager( World world ) - { - this.world = world; - } + public SpatialDimensionManager(World world) { + this.world = world; + } - @Override - public World getWorld() - { - return this.world; - } + @Override + public World getWorld() { + return this.world; + } - @Override - public int createNewCellDimension( BlockPos contentSize, int owner ) - { - int newId = this.getNextId(); + @Override + public int createNewCellDimension(BlockPos contentSize, int owner) { + int newId = this.getNextId(); - StorageCellData data = new StorageCellData(); - data.contentDimension = contentSize; - data.owner = owner; + StorageCellData data = new StorageCellData(); + data.contentDimension = contentSize; + data.owner = owner; - this.spatialData.put( newId, data ); + this.spatialData.put(newId, data); - return newId; - } + return newId; + } - @Override - public void deleteCellDimension( int cellStorageId ) - { - StorageCellData removed = this.spatialData.remove( cellStorageId ); - if( removed != null ) - { - this.clearCellArea( cellStorageId, removed ); - } - } + @Override + public void deleteCellDimension(int cellStorageId) { + StorageCellData removed = this.spatialData.remove(cellStorageId); + if (removed != null) { + this.clearCellArea(cellStorageId, removed); + } + } - @Override - public boolean isCellDimension( int cellStorageId ) - { - return this.spatialData.containsKey( cellStorageId ); - } + @Override + public boolean isCellDimension(int cellStorageId) { + return this.spatialData.containsKey(cellStorageId); + } - @Override - public int getCellDimensionOwner( int cellStorageId ) - { - StorageCellData cell = this.spatialData.get( cellStorageId ); - if( cell != null ) - { - return cell.owner; - } - return -1; - } + @Override + public int getCellDimensionOwner(int cellStorageId) { + StorageCellData cell = this.spatialData.get(cellStorageId); + if (cell != null) { + return cell.owner; + } + return -1; + } - @Override - public BlockPos getCellDimensionOrigin( int cellStorageId ) - { - if( this.isCellDimension( cellStorageId ) ) - { - return this.getBlockPosFromId( cellStorageId ); - } - return null; - } + @Override + public BlockPos getCellDimensionOrigin(int cellStorageId) { + if (this.isCellDimension(cellStorageId)) { + return this.getBlockPosFromId(cellStorageId); + } + return null; + } - @Override - public BlockPos getCellContentSize( int cellStorageId ) - { - StorageCellData cell = this.spatialData.get( cellStorageId ); - if( cell != null ) - { - return cell.contentDimension; - } - return null; - } + @Override + public BlockPos getCellContentSize(int cellStorageId) { + StorageCellData cell = this.spatialData.get(cellStorageId); + if (cell != null) { + return cell.contentDimension; + } + return null; + } - @Override - public boolean hasCapability( Capability capability, EnumFacing facing ) - { - return capability == Capabilities.SPATIAL_DIMENSION; - } + @Override + public boolean hasCapability(Capability capability, EnumFacing facing) { + return capability == Capabilities.SPATIAL_DIMENSION; + } - @Override - public T getCapability( Capability capability, EnumFacing facing ) - { - if( capability == Capabilities.SPATIAL_DIMENSION ) - { - return (T) this; - } - return null; - } + @Override + public T getCapability(Capability capability, EnumFacing facing) { + if (capability == Capabilities.SPATIAL_DIMENSION) { + return (T) this; + } + return null; + } - @Override - public NBTTagCompound serializeNBT() - { - final NBTTagCompound ret = new NBTTagCompound(); - final NBTTagList list = new NBTTagList(); + @Override + public NBTTagCompound serializeNBT() { + final NBTTagCompound ret = new NBTTagCompound(); + final NBTTagList list = new NBTTagList(); - for( Map.Entry entry : this.spatialData.entrySet() ) - { - final NBTTagCompound nbt = entry.getValue().serializeNBT(); - nbt.setInteger( NBT_SPATIAL_ID_KEY, entry.getKey() ); - list.appendTag( nbt ); - } - ret.setTag( NBT_SPATIAL_DATA_KEY, list ); - return ret; - } + for (Map.Entry entry : this.spatialData.entrySet()) { + final NBTTagCompound nbt = entry.getValue().serializeNBT(); + nbt.setInteger(NBT_SPATIAL_ID_KEY, entry.getKey()); + list.appendTag(nbt); + } + ret.setTag(NBT_SPATIAL_DATA_KEY, list); + return ret; + } - @Override - public void deserializeNBT( NBTTagCompound nbt ) - { - if( nbt.hasKey( NBT_SPATIAL_DATA_KEY ) ) - { - final NBTTagList list = (NBTTagList) nbt.getTag( NBT_SPATIAL_DATA_KEY ); + @Override + public void deserializeNBT(NBTTagCompound nbt) { + if (nbt.hasKey(NBT_SPATIAL_DATA_KEY)) { + final NBTTagList list = (NBTTagList) nbt.getTag(NBT_SPATIAL_DATA_KEY); - this.spatialData.clear(); - for( int i = 0; i < list.tagCount(); ++i ) - { - final NBTTagCompound entry = list.getCompoundTagAt( i ); - final StorageCellData data = new StorageCellData(); - final int id = entry.getInteger( NBT_SPATIAL_ID_KEY ); - data.deserializeNBT( entry ); - this.spatialData.put( id, data ); - } - } - } + this.spatialData.clear(); + for (int i = 0; i < list.tagCount(); ++i) { + final NBTTagCompound entry = list.getCompoundTagAt(i); + final StorageCellData data = new StorageCellData(); + final int id = entry.getInteger(NBT_SPATIAL_ID_KEY); + data.deserializeNBT(entry); + this.spatialData.put(id, data); + } + } + } - private int getNextId() - { - return this.spatialData.keySet().stream().max( Integer::compare ).orElse( -1 ) + 1; - } + private int getNextId() { + return this.spatialData.keySet().stream().max(Integer::compare).orElse(-1) + 1; + } - private BlockPos getBlockPosFromId( int id ) - { - int signBits = id & 0b11; - int offsetBits = id >> 2; - int offsetScale = 1; - int posx = MAX_CELL_DIMENSION / 2; - int posz = MAX_CELL_DIMENSION / 2; + private BlockPos getBlockPosFromId(int id) { + int signBits = id & 0b11; + int offsetBits = id >> 2; + int offsetScale = 1; + int posx = MAX_CELL_DIMENSION / 2; + int posz = MAX_CELL_DIMENSION / 2; - // find quadrant - while( offsetBits != 0 ) - { - posx += MAX_CELL_DIMENSION * offsetScale * ( offsetBits & 0b01 ); - posz += MAX_CELL_DIMENSION * offsetScale * ( offsetBits >> 1 & 0b01 ); + // find quadrant + while (offsetBits != 0) { + posx += MAX_CELL_DIMENSION * offsetScale * (offsetBits & 0b01); + posz += MAX_CELL_DIMENSION * offsetScale * (offsetBits >> 1 & 0b01); - offsetBits >>= 2; - offsetScale <<= 1; - } + offsetBits >>= 2; + offsetScale <<= 1; + } - // mirror in one of 4 directions - if( ( signBits & 0b01 ) == 0 ) - { - posx *= -1; - } - if( ( signBits & 0b10 ) == 0 ) - { - posz *= -1; - } + // mirror in one of 4 directions + if ((signBits & 0b01) == 0) { + posx *= -1; + } + if ((signBits & 0b10) == 0) { + posz *= -1; + } - // offset from cell center - posx -= 64; - posz -= 64; + // offset from cell center + posx -= 64; + posz -= 64; - return new BlockPos( posx, 64, posz ); - } + return new BlockPos(posx, 64, posz); + } - private void clearCellArea( int cellId, StorageCellData cell ) - { - // TODO reset chunks? - } + private void clearCellArea(int cellId, StorageCellData cell) { + // TODO reset chunks? + } - private static class StorageCellData implements INBTSerializable - { - private static final String NBT_OWNER_KEY = "owner"; - private static final String NBT_DIM_X_KEY = "dim_x"; - private static final String NBT_DIM_Y_KEY = "dim_y"; - private static final String NBT_DIM_Z_KEY = "dim_z"; + private static class StorageCellData implements INBTSerializable { + private static final String NBT_OWNER_KEY = "owner"; + private static final String NBT_DIM_X_KEY = "dim_x"; + private static final String NBT_DIM_Y_KEY = "dim_y"; + private static final String NBT_DIM_Z_KEY = "dim_z"; - public BlockPos contentDimension; - public int owner; + public BlockPos contentDimension; + public int owner; - @Override - public NBTTagCompound serializeNBT() - { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setInteger( NBT_DIM_X_KEY, this.contentDimension.getX() ); - nbt.setInteger( NBT_DIM_Y_KEY, this.contentDimension.getY() ); - nbt.setInteger( NBT_DIM_Z_KEY, this.contentDimension.getZ() ); - nbt.setInteger( NBT_OWNER_KEY, this.owner ); - return nbt; - } + @Override + public NBTTagCompound serializeNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setInteger(NBT_DIM_X_KEY, this.contentDimension.getX()); + nbt.setInteger(NBT_DIM_Y_KEY, this.contentDimension.getY()); + nbt.setInteger(NBT_DIM_Z_KEY, this.contentDimension.getZ()); + nbt.setInteger(NBT_OWNER_KEY, this.owner); + return nbt; + } - @Override - public void deserializeNBT( NBTTagCompound nbt ) - { - this.contentDimension = new BlockPos( nbt.getInteger( NBT_DIM_X_KEY ), nbt.getInteger( NBT_DIM_Y_KEY ), nbt.getInteger( NBT_DIM_Z_KEY ) ); - this.owner = nbt.getInteger( NBT_OWNER_KEY ); - } - } + @Override + public void deserializeNBT(NBTTagCompound nbt) { + this.contentDimension = new BlockPos(nbt.getInteger(NBT_DIM_X_KEY), nbt.getInteger(NBT_DIM_Y_KEY), nbt.getInteger(NBT_DIM_Z_KEY)); + this.owner = nbt.getInteger(NBT_OWNER_KEY); + } + } } diff --git a/src/main/java/appeng/core/worlddata/SpawnData.java b/src/main/java/appeng/core/worlddata/SpawnData.java index f0f35bbe4..c1556d7e2 100644 --- a/src/main/java/appeng/core/worlddata/SpawnData.java +++ b/src/main/java/appeng/core/worlddata/SpawnData.java @@ -19,6 +19,12 @@ package appeng.core.worlddata; +import appeng.core.AELog; +import com.google.common.base.Preconditions; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; + +import javax.annotation.Nonnull; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -26,191 +32,143 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Collection; -import javax.annotation.Nonnull; - -import com.google.common.base.Preconditions; - -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; - -import appeng.core.AELog; - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class SpawnData implements IWorldSpawnData -{ - @Nonnull - private final File spawnDirectory; - @Nonnull - private final MeteorDataNameEncoder encoder; +final class SpawnData implements IWorldSpawnData { + @Nonnull + private final File spawnDirectory; + @Nonnull + private final MeteorDataNameEncoder encoder; - public SpawnData( @Nonnull final File spawnDirectory ) - { - Preconditions.checkNotNull( spawnDirectory ); + public SpawnData(@Nonnull final File spawnDirectory) { + Preconditions.checkNotNull(spawnDirectory); - this.spawnDirectory = spawnDirectory; - this.encoder = new MeteorDataNameEncoder( 4 ); - } + this.spawnDirectory = spawnDirectory; + this.encoder = new MeteorDataNameEncoder(4); + } - @Override - public void setGenerated( final int dim, final int chunkX, final int chunkZ ) - { - synchronized( SpawnData.class ) - { - final NBTTagCompound data = this.loadSpawnData( dim, chunkX, chunkZ ); + @Override + public void setGenerated(final int dim, final int chunkX, final int chunkZ) { + synchronized (SpawnData.class) { + final NBTTagCompound data = this.loadSpawnData(dim, chunkX, chunkZ); - // edit. - data.setBoolean( chunkX + "," + chunkZ, true ); + // edit. + data.setBoolean(chunkX + "," + chunkZ, true); - this.writeSpawnData( dim, chunkX, chunkZ, data ); - } - } + this.writeSpawnData(dim, chunkX, chunkZ, data); + } + } - @Override - public boolean hasGenerated( final int dim, final int chunkX, final int chunkZ ) - { - synchronized( SpawnData.class ) - { - final NBTTagCompound data = this.loadSpawnData( dim, chunkX, chunkZ ); - return data.getBoolean( chunkX + "," + chunkZ ); - } - } + @Override + public boolean hasGenerated(final int dim, final int chunkX, final int chunkZ) { + synchronized (SpawnData.class) { + final NBTTagCompound data = this.loadSpawnData(dim, chunkX, chunkZ); + return data.getBoolean(chunkX + "," + chunkZ); + } + } - @Override - public boolean addNearByMeteorites( final int dim, final int chunkX, final int chunkZ, final NBTTagCompound newData ) - { - synchronized( SpawnData.class ) - { - final NBTTagCompound data = this.loadSpawnData( dim, chunkX, chunkZ ); + @Override + public boolean addNearByMeteorites(final int dim, final int chunkX, final int chunkZ, final NBTTagCompound newData) { + synchronized (SpawnData.class) { + final NBTTagCompound data = this.loadSpawnData(dim, chunkX, chunkZ); - // edit. - final int size = data.getInteger( "num" ); - data.setTag( String.valueOf( size ), newData ); - data.setInteger( "num", size + 1 ); + // edit. + final int size = data.getInteger("num"); + data.setTag(String.valueOf(size), newData); + data.setInteger("num", size + 1); - this.writeSpawnData( dim, chunkX, chunkZ, data ); + this.writeSpawnData(dim, chunkX, chunkZ, data); - return true; - } - } + return true; + } + } - @Override - public Collection getNearByMeteorites( final int dim, final int chunkX, final int chunkZ ) - { - final Collection ll = new ArrayList<>(); + @Override + public Collection getNearByMeteorites(final int dim, final int chunkX, final int chunkZ) { + final Collection ll = new ArrayList<>(); - synchronized( SpawnData.class ) - { - for( int x = -1; x <= 1; x++ ) - { - for( int z = -1; z <= 1; z++ ) - { - final int cx = x + ( chunkX >> 4 ); - final int cz = z + ( chunkZ >> 4 ); + synchronized (SpawnData.class) { + for (int x = -1; x <= 1; x++) { + for (int z = -1; z <= 1; z++) { + final int cx = x + (chunkX >> 4); + final int cz = z + (chunkZ >> 4); - final NBTTagCompound data = this.loadSpawnData( dim, cx << 4, cz << 4 ); + final NBTTagCompound data = this.loadSpawnData(dim, cx << 4, cz << 4); - if( data != null ) - { - // edit. - final int size = data.getInteger( "num" ); - for( int s = 0; s < size; s++ ) - { - ll.add( data.getCompoundTag( String.valueOf( s ) ) ); - } - } - } - } - } + if (data != null) { + // edit. + final int size = data.getInteger("num"); + for (int s = 0; s < size; s++) { + ll.add(data.getCompoundTag(String.valueOf(s))); + } + } + } + } + } - return ll; - } + return ll; + } - private NBTTagCompound loadSpawnData( final int dim, final int chunkX, final int chunkZ ) - { - if( !Thread.holdsLock( SpawnData.class ) ) - { - throw new IllegalStateException( "Invalid Request" ); - } + private NBTTagCompound loadSpawnData(final int dim, final int chunkX, final int chunkZ) { + if (!Thread.holdsLock(SpawnData.class)) { + throw new IllegalStateException("Invalid Request"); + } - NBTTagCompound data = null; - final String fileName = this.encoder.encode( dim, chunkX, chunkZ ); - final File file = new File( this.spawnDirectory, fileName ); + NBTTagCompound data = null; + final String fileName = this.encoder.encode(dim, chunkX, chunkZ); + final File file = new File(this.spawnDirectory, fileName); - if( file.isFile() ) - { - FileInputStream fileInputStream = null; + if (file.isFile()) { + FileInputStream fileInputStream = null; - try - { - fileInputStream = new FileInputStream( file ); - data = CompressedStreamTools.readCompressed( fileInputStream ); - } - catch( final Throwable e ) - { - data = new NBTTagCompound(); - AELog.debug( e ); - } - finally - { - if( fileInputStream != null ) - { - try - { - fileInputStream.close(); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } - else - { - data = new NBTTagCompound(); - } + try { + fileInputStream = new FileInputStream(file); + data = CompressedStreamTools.readCompressed(fileInputStream); + } catch (final Throwable e) { + data = new NBTTagCompound(); + AELog.debug(e); + } finally { + if (fileInputStream != null) { + try { + fileInputStream.close(); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } else { + data = new NBTTagCompound(); + } - return data; - } + return data; + } - private void writeSpawnData( final int dim, final int chunkX, final int chunkZ, final NBTTagCompound data ) - { - if( !Thread.holdsLock( SpawnData.class ) ) - { - throw new IllegalStateException( "Invalid Request" ); - } + private void writeSpawnData(final int dim, final int chunkX, final int chunkZ, final NBTTagCompound data) { + if (!Thread.holdsLock(SpawnData.class)) { + throw new IllegalStateException("Invalid Request"); + } - final String fileName = this.encoder.encode( dim, chunkX, chunkZ ); - final File file = new File( this.spawnDirectory, fileName ); - FileOutputStream fileOutputStream = null; + final String fileName = this.encoder.encode(dim, chunkX, chunkZ); + final File file = new File(this.spawnDirectory, fileName); + FileOutputStream fileOutputStream = null; - try - { - fileOutputStream = new FileOutputStream( file ); - CompressedStreamTools.writeCompressed( data, fileOutputStream ); - } - catch( final Throwable e ) - { - AELog.debug( e ); - } - finally - { - if( fileOutputStream != null ) - { - try - { - fileOutputStream.close(); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } + try { + fileOutputStream = new FileOutputStream(file); + CompressedStreamTools.writeCompressed(data, fileOutputStream); + } catch (final Throwable e) { + AELog.debug(e); + } finally { + if (fileOutputStream != null) { + try { + fileOutputStream.close(); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } } diff --git a/src/main/java/appeng/core/worlddata/StorageData.java b/src/main/java/appeng/core/worlddata/StorageData.java index 59e2c99a8..f5eabfe5f 100644 --- a/src/main/java/appeng/core/worlddata/StorageData.java +++ b/src/main/java/appeng/core/worlddata/StorageData.java @@ -19,21 +19,18 @@ package appeng.core.worlddata; -import java.lang.ref.WeakReference; -import java.util.Map; -import java.util.WeakHashMap; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import com.google.common.base.Preconditions; - -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.common.config.Property; - import appeng.core.AELog; import appeng.me.GridStorage; import appeng.me.GridStorageSearch; +import com.google.common.base.Preconditions; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.ref.WeakReference; +import java.util.Map; +import java.util.WeakHashMap; /** @@ -41,125 +38,109 @@ import appeng.me.GridStorageSearch; * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class StorageData implements IWorldGridStorageData, IOnWorldStartable, IOnWorldStoppable -{ - private static final String LAST_GRID_STORAGE_CATEGORY = "Counters"; - private static final String LAST_GRID_STORAGE_KEY = "lastGridStorage"; - private static final int LAST_GRID_STORAGE_DEFAULT = 0; +final class StorageData implements IWorldGridStorageData, IOnWorldStartable, IOnWorldStoppable { + private static final String LAST_GRID_STORAGE_CATEGORY = "Counters"; + private static final String LAST_GRID_STORAGE_KEY = "lastGridStorage"; + private static final int LAST_GRID_STORAGE_DEFAULT = 0; - private static final String GRID_STORAGE_CATEGORY = "gridstorage"; + private static final String GRID_STORAGE_CATEGORY = "gridstorage"; - private final Map> loadedStorage = new WeakHashMap<>( 10 ); - private final Configuration config; + private final Map> loadedStorage = new WeakHashMap<>(10); + private final Configuration config; - private long lastGridStorage; + private long lastGridStorage; - public StorageData( @Nonnull final Configuration settingsFile ) - { - Preconditions.checkNotNull( settingsFile ); + public StorageData(@Nonnull final Configuration settingsFile) { + Preconditions.checkNotNull(settingsFile); - this.config = settingsFile; - } + this.config = settingsFile; + } - /** - * lazy loading, can load any id, even ones that don't exist anymore. - * - * @param storageID ID of grid storage - * - * @return corresponding grid storage - */ - @Nullable - @Override - public GridStorage getGridStorage( final long storageID ) - { - final GridStorageSearch gss = new GridStorageSearch( storageID ); - final WeakReference result = this.loadedStorage.get( gss ); + /** + * lazy loading, can load any id, even ones that don't exist anymore. + * + * @param storageID ID of grid storage + * @return corresponding grid storage + */ + @Nullable + @Override + public GridStorage getGridStorage(final long storageID) { + final GridStorageSearch gss = new GridStorageSearch(storageID); + final WeakReference result = this.loadedStorage.get(gss); - if( result == null || result.get() == null ) - { - final String id = String.valueOf( storageID ); - final String data = this.config.get( "gridstorage", id, "" ).getString(); - final GridStorage thisStorage = new GridStorage( data, storageID, gss ); - gss.setGridStorage( new WeakReference<>( thisStorage ) ); - this.loadedStorage.put( gss, new WeakReference<>( gss ) ); - return thisStorage; - } + if (result == null || result.get() == null) { + final String id = String.valueOf(storageID); + final String data = this.config.get("gridstorage", id, "").getString(); + final GridStorage thisStorage = new GridStorage(data, storageID, gss); + gss.setGridStorage(new WeakReference<>(thisStorage)); + this.loadedStorage.put(gss, new WeakReference<>(gss)); + return thisStorage; + } - return result.get().getGridStorage().get(); - } + return result.get().getGridStorage().get(); + } - /** - * create a new storage - */ - @Nonnull - @Override - public GridStorage getNewGridStorage() - { - final long storageID = this.nextGridStorage(); - final GridStorageSearch gss = new GridStorageSearch( storageID ); - final GridStorage newStorage = new GridStorage( storageID, gss ); - gss.setGridStorage( new WeakReference<>( newStorage ) ); - this.loadedStorage.put( gss, new WeakReference<>( gss ) ); + /** + * create a new storage + */ + @Nonnull + @Override + public GridStorage getNewGridStorage() { + final long storageID = this.nextGridStorage(); + final GridStorageSearch gss = new GridStorageSearch(storageID); + final GridStorage newStorage = new GridStorage(storageID, gss); + gss.setGridStorage(new WeakReference<>(newStorage)); + this.loadedStorage.put(gss, new WeakReference<>(gss)); - return newStorage; - } + return newStorage; + } - @Override - public long nextGridStorage() - { - final long r = this.lastGridStorage; - this.lastGridStorage++; - this.config.get( "Counters", "lastGridStorage", this.lastGridStorage ).set( Long.toString( this.lastGridStorage ) ); - return r; - } + @Override + public long nextGridStorage() { + final long r = this.lastGridStorage; + this.lastGridStorage++; + this.config.get("Counters", "lastGridStorage", this.lastGridStorage).set(Long.toString(this.lastGridStorage)); + return r; + } - @Override - public void destroyGridStorage( final long id ) - { - final String stringID = String.valueOf( id ); - this.config.getCategory( "gridstorage" ).remove( stringID ); - } + @Override + public void destroyGridStorage(final long id) { + final String stringID = String.valueOf(id); + this.config.getCategory("gridstorage").remove(stringID); + } - @Override - public int getNextOrderedValue( final String name ) - { - final Property p = this.config.get( "orderedValues", name, 0 ); - final int myValue = p.getInt(); - p.set( myValue + 1 ); - return myValue; - } + @Override + public int getNextOrderedValue(final String name) { + final Property p = this.config.get("orderedValues", name, 0); + final int myValue = p.getInt(); + p.set(myValue + 1); + return myValue; + } - @Override - public void onWorldStart() - { - final String lastString = this.config.get( LAST_GRID_STORAGE_CATEGORY, LAST_GRID_STORAGE_KEY, LAST_GRID_STORAGE_DEFAULT ).getString(); + @Override + public void onWorldStart() { + final String lastString = this.config.get(LAST_GRID_STORAGE_CATEGORY, LAST_GRID_STORAGE_KEY, LAST_GRID_STORAGE_DEFAULT).getString(); - try - { - this.lastGridStorage = Long.parseLong( lastString ); - } - catch( final NumberFormatException err ) - { - AELog.warn( "The config contained a value which was not represented as a Long: %s", lastString ); + try { + this.lastGridStorage = Long.parseLong(lastString); + } catch (final NumberFormatException err) { + AELog.warn("The config contained a value which was not represented as a Long: %s", lastString); - this.lastGridStorage = 0; - } - } + this.lastGridStorage = 0; + } + } - @Override - public void onWorldStop() - { - // populate new data - for( final GridStorageSearch gs : this.loadedStorage.keySet() ) - { - final GridStorage thisStorage = gs.getGridStorage().get(); - if( thisStorage != null && thisStorage.getGrid() != null && !thisStorage.getGrid().isEmpty() ) - { - final String value = thisStorage.getValue(); - this.config.get( GRID_STORAGE_CATEGORY, String.valueOf( thisStorage.getID() ), value ).set( value ); - } - } + @Override + public void onWorldStop() { + // populate new data + for (final GridStorageSearch gs : this.loadedStorage.keySet()) { + final GridStorage thisStorage = gs.getGridStorage().get(); + if (thisStorage != null && thisStorage.getGrid() != null && !thisStorage.getGrid().isEmpty()) { + final String value = thisStorage.getValue(); + this.config.get(GRID_STORAGE_CATEGORY, String.valueOf(thisStorage.getID()), value).set(value); + } + } - this.config.save(); - } + this.config.save(); + } } diff --git a/src/main/java/appeng/core/worlddata/WorldData.java b/src/main/java/appeng/core/worlddata/WorldData.java index 3ea29b8cf..e540206e2 100644 --- a/src/main/java/appeng/core/worlddata/WorldData.java +++ b/src/main/java/appeng/core/worlddata/WorldData.java @@ -19,28 +19,25 @@ package appeng.core.worlddata; -import java.io.File; -import java.util.List; -import java.util.concurrent.ThreadFactory; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - +import appeng.core.AEConfig; +import appeng.services.CompassService; +import appeng.services.compass.CompassThreadFactory; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; - import net.minecraft.server.MinecraftServer; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.config.Configuration; -import appeng.core.AEConfig; -import appeng.services.CompassService; -import appeng.services.compass.CompassThreadFactory; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.File; +import java.util.List; +import java.util.concurrent.ThreadFactory; /** * Singleton access to anything related to world-based data. - * + *

* Data will change depending which world is loaded. Will probably not affect SMP at all since only one world is loaded, * but SSP more, cause they play on * different worlds. @@ -49,163 +46,145 @@ import appeng.services.compass.CompassThreadFactory; * @version rv3 - 02.11.2015 * @since rv3 30.05.2015 */ -public final class WorldData implements IWorldData -{ - private static final String AE2_DIRECTORY_NAME = "AE2"; - private static final String SETTING_FILE_NAME = "settings.cfg"; - private static final String SPAWNDATA_DIR_NAME = "spawndata"; - private static final String COMPASS_DIR_NAME = "compass"; +public final class WorldData implements IWorldData { + private static final String AE2_DIRECTORY_NAME = "AE2"; + private static final String SETTING_FILE_NAME = "settings.cfg"; + private static final String SPAWNDATA_DIR_NAME = "spawndata"; + private static final String COMPASS_DIR_NAME = "compass"; - @Nullable - private static IWorldData instance; + @Nullable + private static IWorldData instance; - private final IWorldPlayerData playerData; - private final IWorldGridStorageData storageData; - private final IWorldCompassData compassData; - private final IWorldSpawnData spawnData; + private final IWorldPlayerData playerData; + private final IWorldGridStorageData storageData; + private final IWorldCompassData compassData; + private final IWorldSpawnData spawnData; - private final List startables; - private final List stoppables; + private final List startables; + private final List stoppables; - private final File ae2directory; - private final File spawnDirectory; - private final File compassDirectory; + private final File ae2directory; + private final File spawnDirectory; + private final File compassDirectory; - private final Configuration sharedConfig; + private final Configuration sharedConfig; - private WorldData( @Nonnull final File worldDirectory ) - { - Preconditions.checkNotNull( worldDirectory ); - Preconditions.checkArgument( worldDirectory.isDirectory() ); + private WorldData(@Nonnull final File worldDirectory) { + Preconditions.checkNotNull(worldDirectory); + Preconditions.checkArgument(worldDirectory.isDirectory()); - this.ae2directory = new File( worldDirectory, AE2_DIRECTORY_NAME ); - this.spawnDirectory = new File( this.ae2directory, SPAWNDATA_DIR_NAME ); - this.compassDirectory = new File( this.ae2directory, COMPASS_DIR_NAME ); + this.ae2directory = new File(worldDirectory, AE2_DIRECTORY_NAME); + this.spawnDirectory = new File(this.ae2directory, SPAWNDATA_DIR_NAME); + this.compassDirectory = new File(this.ae2directory, COMPASS_DIR_NAME); - final File settingsFile = new File( this.ae2directory, SETTING_FILE_NAME ); - this.sharedConfig = new Configuration( settingsFile, AEConfig.VERSION ); + final File settingsFile = new File(this.ae2directory, SETTING_FILE_NAME); + this.sharedConfig = new Configuration(settingsFile, AEConfig.VERSION); - final PlayerData playerData = new PlayerData( this.sharedConfig ); - final StorageData storageData = new StorageData( this.sharedConfig ); + final PlayerData playerData = new PlayerData(this.sharedConfig); + final StorageData storageData = new StorageData(this.sharedConfig); - final ThreadFactory compassThreadFactory = new CompassThreadFactory(); - final CompassService compassService = new CompassService( this.compassDirectory, compassThreadFactory ); - final CompassData compassData = new CompassData( this.compassDirectory, compassService ); + final ThreadFactory compassThreadFactory = new CompassThreadFactory(); + final CompassService compassService = new CompassService(this.compassDirectory, compassThreadFactory); + final CompassData compassData = new CompassData(this.compassDirectory, compassService); - final IWorldSpawnData spawnData = new SpawnData( this.spawnDirectory ); + final IWorldSpawnData spawnData = new SpawnData(this.spawnDirectory); - this.playerData = playerData; - this.storageData = storageData; - this.compassData = compassData; - this.spawnData = spawnData; + this.playerData = playerData; + this.storageData = storageData; + this.compassData = compassData; + this.spawnData = spawnData; - this.startables = Lists.newArrayList( playerData, storageData ); - this.stoppables = Lists.newArrayList( playerData, storageData, compassData ); - } + this.startables = Lists.newArrayList(playerData, storageData); + this.stoppables = Lists.newArrayList(playerData, storageData, compassData); + } - /** - * @return ae2 data related to a specific world - * - * @deprecated do not use singletons which are dependent on specific world state - */ - @Deprecated - @Nonnull - public static IWorldData instance() - { - return instance; - } + /** + * @return ae2 data related to a specific world + * @deprecated do not use singletons which are dependent on specific world state + */ + @Deprecated + @Nonnull + public static IWorldData instance() { + return instance; + } - /** - * Requires to start up from external from here - * - * drawback of the singleton build style - * - * @param server - */ - public static void onServerAboutToStart( MinecraftServer server ) - { - File worldDirectory = DimensionManager.getCurrentSaveRootDirectory(); - if( worldDirectory == null ) - { - worldDirectory = server.getActiveAnvilConverter().getSaveLoader( server.getFolderName(), false ).getWorldDirectory(); - } - final WorldData newInstance = new WorldData( worldDirectory ); + /** + * Requires to start up from external from here + *

+ * drawback of the singleton build style + * + * @param server + */ + public static void onServerAboutToStart(MinecraftServer server) { + File worldDirectory = DimensionManager.getCurrentSaveRootDirectory(); + if (worldDirectory == null) { + worldDirectory = server.getActiveAnvilConverter().getSaveLoader(server.getFolderName(), false).getWorldDirectory(); + } + final WorldData newInstance = new WorldData(worldDirectory); - instance = newInstance; - newInstance.onServerStarting(); - } + instance = newInstance; + newInstance.onServerStarting(); + } - private void onServerStarting() - { - // check if ae2 folder already exists, else create - if( !this.ae2directory.isDirectory() && !this.ae2directory.mkdir() ) - { - throw new IllegalStateException( "Failed to create " + this.ae2directory.getAbsolutePath() ); - } + private void onServerStarting() { + // check if ae2 folder already exists, else create + if (!this.ae2directory.isDirectory() && !this.ae2directory.mkdir()) { + throw new IllegalStateException("Failed to create " + this.ae2directory.getAbsolutePath()); + } - // check if compass folder already exists, else create - if( !this.compassDirectory.isDirectory() && !this.compassDirectory.mkdir() ) - { - throw new IllegalStateException( "Failed to create " + this.compassDirectory.getAbsolutePath() ); - } + // check if compass folder already exists, else create + if (!this.compassDirectory.isDirectory() && !this.compassDirectory.mkdir()) { + throw new IllegalStateException("Failed to create " + this.compassDirectory.getAbsolutePath()); + } - // check if spawn data dir already exists, else create - if( !this.spawnDirectory.isDirectory() && !this.spawnDirectory.mkdir() ) - { - throw new IllegalStateException( "Failed to create " + this.spawnDirectory.getAbsolutePath() ); - } + // check if spawn data dir already exists, else create + if (!this.spawnDirectory.isDirectory() && !this.spawnDirectory.mkdir()) { + throw new IllegalStateException("Failed to create " + this.spawnDirectory.getAbsolutePath()); + } - for( final IOnWorldStartable startable : this.startables ) - { - startable.onWorldStart(); - } + for (final IOnWorldStartable startable : this.startables) { + startable.onWorldStart(); + } - this.startables.clear(); - } + this.startables.clear(); + } - @Override - public void onServerStopping() - { - for( final IOnWorldStoppable stoppable : this.stoppables ) - { - stoppable.onWorldStop(); - } - } + @Override + public void onServerStopping() { + for (final IOnWorldStoppable stoppable : this.stoppables) { + stoppable.onWorldStop(); + } + } - @Override - public void onServerStoppped() - { - Preconditions.checkNotNull( instance ); + @Override + public void onServerStoppped() { + Preconditions.checkNotNull(instance); - this.stoppables.clear(); - instance = null; - } + this.stoppables.clear(); + instance = null; + } - @Nonnull - @Override - public IWorldGridStorageData storageData() - { - return this.storageData; - } + @Nonnull + @Override + public IWorldGridStorageData storageData() { + return this.storageData; + } - @Nonnull - @Override - public IWorldPlayerData playerData() - { - return this.playerData; - } + @Nonnull + @Override + public IWorldPlayerData playerData() { + return this.playerData; + } - @Nonnull - @Override - public IWorldCompassData compassData() - { - return this.compassData; - } + @Nonnull + @Override + public IWorldCompassData compassData() { + return this.compassData; + } - @Nonnull - @Override - public IWorldSpawnData spawnData() - { - return this.spawnData; - } + @Nonnull + @Override + public IWorldSpawnData spawnData() { + return this.spawnData; + } } diff --git a/src/main/java/appeng/crafting/CraftBranchFailure.java b/src/main/java/appeng/crafting/CraftBranchFailure.java index c04916783..724d778b7 100644 --- a/src/main/java/appeng/crafting/CraftBranchFailure.java +++ b/src/main/java/appeng/crafting/CraftBranchFailure.java @@ -22,17 +22,15 @@ package appeng.crafting; import appeng.api.storage.data.IAEItemStack; -public class CraftBranchFailure extends Exception -{ +public class CraftBranchFailure extends Exception { - private static final long serialVersionUID = 654603652836724823L; + private static final long serialVersionUID = 654603652836724823L; - private final IAEItemStack missing; + private final IAEItemStack missing; - public CraftBranchFailure( final IAEItemStack what, final long howMany ) - { - super( "Failed: " + what.getItem().getUnlocalizedName() + " x " + howMany ); - this.missing = what.copy(); - this.missing.setStackSize( howMany ); - } + public CraftBranchFailure(final IAEItemStack what, final long howMany) { + super("Failed: " + what.getItem().getUnlocalizedName() + " x " + howMany); + this.missing = what.copy(); + this.missing.setStackSize(howMany); + } } diff --git a/src/main/java/appeng/crafting/CraftingCalculationFailure.java b/src/main/java/appeng/crafting/CraftingCalculationFailure.java index bfaa7ece2..d7ebdc7cf 100644 --- a/src/main/java/appeng/crafting/CraftingCalculationFailure.java +++ b/src/main/java/appeng/crafting/CraftingCalculationFailure.java @@ -22,17 +22,15 @@ package appeng.crafting; import appeng.api.storage.data.IAEItemStack; -public class CraftingCalculationFailure extends RuntimeException -{ +public class CraftingCalculationFailure extends RuntimeException { - private static final long serialVersionUID = 654603652836724823L; + private static final long serialVersionUID = 654603652836724823L; - private final IAEItemStack missing; + private final IAEItemStack missing; - public CraftingCalculationFailure( final IAEItemStack what, final long howMany ) - { - super( "this should have been caught!" ); - this.missing = what.copy(); - this.missing.setStackSize( howMany ); - } + public CraftingCalculationFailure(final IAEItemStack what, final long howMany) { + super("this should have been caught!"); + this.missing = what.copy(); + this.missing.setStackSize(howMany); + } } diff --git a/src/main/java/appeng/crafting/CraftingJob.java b/src/main/java/appeng/crafting/CraftingJob.java index 3c0e81646..5583fe47c 100644 --- a/src/main/java/appeng/crafting/CraftingJob.java +++ b/src/main/java/appeng/crafting/CraftingJob.java @@ -46,358 +46,290 @@ import java.util.HashMap; import java.util.concurrent.TimeUnit; -public class CraftingJob implements Runnable, ICraftingJob -{ - private static final String LOG_CRAFTING_JOB = "CraftingJob (%s) issued by %s requesting [%s] using %s bytes took %s us"; - private static final String LOG_MACHINE_SOURCE_DETAILS = "Machine[object=%s, %s]"; +public class CraftingJob implements Runnable, ICraftingJob { + private static final String LOG_CRAFTING_JOB = "CraftingJob (%s) issued by %s requesting [%s] using %s bytes took %s us"; + private static final String LOG_MACHINE_SOURCE_DETAILS = "Machine[object=%s, %s]"; - private final MECraftingInventory original; - private final World world; - private final IItemList crafting = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - private final IItemList missing = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); + private final MECraftingInventory original; + private final World world; + private final IItemList crafting = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + private final IItemList missing = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); - private final HashMap opsAndMultiplier = new HashMap<>(); - private final Object monitor = new Object(); - private final Stopwatch tickSpreadingWatch = Stopwatch.createUnstarted(); - private final Stopwatch craftingTreeWatch = Stopwatch.createUnstarted(); - private final ICraftingGrid cc; - private CraftingTreeNode tree; - private final IAEItemStack output; - private boolean simulate = false; - private MECraftingInventory availableCheck; - private long bytes = 0; - private final IActionSource actionSrc; - private final ICraftingCallback callback; - private boolean running = false; - private boolean done = false; - private int time; - private int incTime; + private final HashMap opsAndMultiplier = new HashMap<>(); + private final Object monitor = new Object(); + private final Stopwatch tickSpreadingWatch = Stopwatch.createUnstarted(); + private final Stopwatch craftingTreeWatch = Stopwatch.createUnstarted(); + private final ICraftingGrid cc; + private CraftingTreeNode tree; + private final IAEItemStack output; + private boolean simulate = false; + private MECraftingInventory availableCheck; + private long bytes = 0; + private final IActionSource actionSrc; + private final ICraftingCallback callback; + private boolean running = false; + private boolean done = false; + private int time; + private int incTime; - private World wrapWorld( final World w ) - { - return w; - } + private World wrapWorld(final World w) { + return w; + } - public CraftingJob( final World w, final IGrid grid, final IActionSource actionSrc, final IAEItemStack what, final ICraftingCallback callback ) - { - this.world = this.wrapWorld( w ); - this.output = what.copy(); - this.actionSrc = actionSrc; + public CraftingJob(final World w, final IGrid grid, final IActionSource actionSrc, final IAEItemStack what, final ICraftingCallback callback) { + this.world = this.wrapWorld(w); + this.output = what.copy(); + this.actionSrc = actionSrc; - this.callback = callback; + this.callback = callback; - this.cc = grid.getCache( ICraftingGrid.class ); - final GridStorageCache sg = grid.getCache( IStorageGrid.class ); - this.original = new MECraftingInventory( sg.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).getStorageList() ); + this.cc = grid.getCache(ICraftingGrid.class); + final GridStorageCache sg = grid.getCache(IStorageGrid.class); + this.original = new MECraftingInventory(sg.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)).getStorageList()); - this.setTree( this.getCraftingTree( cc, what ) ); - this.availableCheck = null; - } + this.setTree(this.getCraftingTree(cc, what)); + this.availableCheck = null; + } - private CraftingTreeNode getCraftingTree( final ICraftingGrid cc, final IAEItemStack what ) - { - return new CraftingTreeNode( cc, this, what, null, -1, 0 ); - } + private CraftingTreeNode getCraftingTree(final ICraftingGrid cc, final IAEItemStack what) { + return new CraftingTreeNode(cc, this, what, null, -1, 0); + } - void refund( final IAEItemStack o ) - { - this.availableCheck.injectItems( o, Actionable.MODULATE, this.actionSrc ); - } + void refund(final IAEItemStack o) { + this.availableCheck.injectItems(o, Actionable.MODULATE, this.actionSrc); + } - IAEItemStack checkUse( final IAEItemStack available ) - { - return this.availableCheck.extractItems( available, Actionable.MODULATE, this.actionSrc ); - } + IAEItemStack checkUse(final IAEItemStack available) { + return this.availableCheck.extractItems(available, Actionable.MODULATE, this.actionSrc); + } - IAEItemStack checkAvailable( final IAEItemStack available ) - { - return this.availableCheck.extractItems( available, Actionable.SIMULATE, this.actionSrc ); - } + IAEItemStack checkAvailable(final IAEItemStack available) { + return this.availableCheck.extractItems(available, Actionable.SIMULATE, this.actionSrc); + } - void addTask( IAEItemStack what, final long crafts, final ICraftingPatternDetails details, final int depth ) - { - if( crafts > 0 ) - { - what = what.copy(); - what.setStackSize( what.getStackSize() * crafts ); - this.crafting.add( what ); - } - } + void addTask(IAEItemStack what, final long crafts, final ICraftingPatternDetails details, final int depth) { + if (crafts > 0) { + what = what.copy(); + what.setStackSize(what.getStackSize() * crafts); + this.crafting.add(what); + } + } - void addMissing( IAEItemStack what ) - { - what = what.copy(); - this.missing.add( what ); - } + void addMissing(IAEItemStack what) { + what = what.copy(); + this.missing.add(what); + } - @Override - public void run() - { - try - { - try - { - TickHandler.INSTANCE.registerCraftingSimulation( this.world, this ); - this.handlePausing(); + @Override + public void run() { + try { + try { + TickHandler.INSTANCE.registerCraftingSimulation(this.world, this); + this.handlePausing(); - final MECraftingInventory craftingInventory = new MECraftingInventory( this.original, true, false, true ); - craftingInventory.ignore( this.output ); + final MECraftingInventory craftingInventory = new MECraftingInventory(this.original, true, false, true); + craftingInventory.ignore(this.output); - this.availableCheck = new MECraftingInventory( this.original, false, false, false ); - craftingTreeWatch.start(); - this.getTree().request( craftingInventory, this.output.getStackSize(), this.actionSrc ); - craftingTreeWatch.stop(); - this.getTree().dive( this ); + this.availableCheck = new MECraftingInventory(this.original, false, false, false); + craftingTreeWatch.start(); + this.getTree().request(craftingInventory, this.output.getStackSize(), this.actionSrc); + craftingTreeWatch.stop(); + this.getTree().dive(this); - for( final String s : this.opsAndMultiplier.keySet() ) - { - final TwoIntegers ti = this.opsAndMultiplier.get( s ); - AELog.crafting( s + " * " + ti.times + " = " + ( ti.perOp * ti.times ) ); - } + for (final String s : this.opsAndMultiplier.keySet()) { + final TwoIntegers ti = this.opsAndMultiplier.get(s); + AELog.crafting(s + " * " + ti.times + " = " + (ti.perOp * ti.times)); + } - if( actionSrc.player().isPresent() ) - { - this.logCraftingJob( "simulated, success", craftingTreeWatch ); - } - else - { - this.logCraftingJob( "real, success", craftingTreeWatch ); - } - } - catch( final CraftBranchFailure e ) - { - this.simulate = true; + if (actionSrc.player().isPresent()) { + this.logCraftingJob("simulated, success", craftingTreeWatch); + } else { + this.logCraftingJob("real, success", craftingTreeWatch); + } + } catch (final CraftBranchFailure e) { + this.simulate = true; - try - { - if( actionSrc.player().isPresent() ) - { - final MECraftingInventory craftingInventory = new MECraftingInventory( this.original, true, false, true ); - craftingInventory.ignore( this.output ); + try { + if (actionSrc.player().isPresent()) { + final MECraftingInventory craftingInventory = new MECraftingInventory(this.original, true, false, true); + craftingInventory.ignore(this.output); - this.getTree().setSimulate(); - this.availableCheck = new MECraftingInventory( this.original, false, false, false ); - craftingTreeWatch.reset().start(); - this.getTree().request( craftingInventory, this.output.getStackSize(), this.actionSrc ); - craftingTreeWatch.stop(); - this.getTree().dive( this ); + this.getTree().setSimulate(); + this.availableCheck = new MECraftingInventory(this.original, false, false, false); + craftingTreeWatch.reset().start(); + this.getTree().request(craftingInventory, this.output.getStackSize(), this.actionSrc); + craftingTreeWatch.stop(); + this.getTree().dive(this); - for( final String s : this.opsAndMultiplier.keySet() ) - { - final TwoIntegers ti = this.opsAndMultiplier.get( s ); - AELog.crafting( s + " * " + ti.times + " = " + ( ti.perOp * ti.times ) ); - } + for (final String s : this.opsAndMultiplier.keySet()) { + final TwoIntegers ti = this.opsAndMultiplier.get(s); + AELog.crafting(s + " * " + ti.times + " = " + (ti.perOp * ti.times)); + } - this.logCraftingJob( "simulated, failed", craftingTreeWatch ); - } - else - { - this.logCraftingJob( "real, failed", craftingTreeWatch ); - } - } - catch( final CraftBranchFailure e1 ) - { - AELog.debug( e1 ); - } - catch( final CraftingCalculationFailure f ) - { - AELog.debug( f ); - } - catch( final InterruptedException e1 ) - { - AELog.crafting( "Crafting calculation canceled." ); - this.finish(); - return; - } - } - catch( final CraftingCalculationFailure f ) - { - AELog.debug( f ); - } - catch( final InterruptedException e1 ) - { - AELog.crafting( "Crafting calculation canceled." ); - this.finish(); - return; - } + this.logCraftingJob("simulated, failed", craftingTreeWatch); + } else { + this.logCraftingJob("real, failed", craftingTreeWatch); + } + } catch (final CraftBranchFailure e1) { + AELog.debug(e1); + } catch (final CraftingCalculationFailure f) { + AELog.debug(f); + } catch (final InterruptedException e1) { + AELog.crafting("Crafting calculation canceled."); + this.finish(); + return; + } + } catch (final CraftingCalculationFailure f) { + AELog.debug(f); + } catch (final InterruptedException e1) { + AELog.crafting("Crafting calculation canceled."); + this.finish(); + return; + } - AELog.craftingDebug( "crafting job now done" ); - } - catch( final Throwable t ) - { - this.finish(); - throw new IllegalStateException( t ); - } + AELog.craftingDebug("crafting job now done"); + } catch (final Throwable t) { + this.finish(); + throw new IllegalStateException(t); + } - this.finish(); - } + this.finish(); + } - void handlePausing() throws InterruptedException - { - if( !this.actionSrc.player().isPresent() && this.incTime > 100 ) - { - this.incTime = 0; - synchronized ( this.monitor ) - { - if( this.tickSpreadingWatch.elapsed( TimeUnit.MICROSECONDS ) > this.time ) - { - this.running = false; - this.craftingTreeWatch.stop(); - this.tickSpreadingWatch.stop(); - this.monitor.notify(); - } + void handlePausing() throws InterruptedException { + if (!this.actionSrc.player().isPresent() && this.incTime > 100) { + this.incTime = 0; + synchronized (this.monitor) { + if (this.tickSpreadingWatch.elapsed(TimeUnit.MICROSECONDS) > this.time) { + this.running = false; + this.craftingTreeWatch.stop(); + this.tickSpreadingWatch.stop(); + this.monitor.notify(); + } - if( !this.running ) - { - AELog.craftingDebug( "crafting job will now sleep" ); + if (!this.running) { + AELog.craftingDebug("crafting job will now sleep"); - while ( !this.running ) - { - this.monitor.wait(); - } + while (!this.running) { + this.monitor.wait(); + } - AELog.craftingDebug( "crafting job now active" ); - } - } - } + AELog.craftingDebug("crafting job now active"); + } + } + } - if( Thread.interrupted() ) - { - throw new InterruptedException(); - } + if (Thread.interrupted()) { + throw new InterruptedException(); + } - this.incTime++; - } + this.incTime++; + } - private void finish() - { - if( this.callback != null ) - { - this.callback.calculationComplete( this ); - } + private void finish() { + if (this.callback != null) { + this.callback.calculationComplete(this); + } - this.availableCheck = null; + this.availableCheck = null; - synchronized ( this.monitor ) - { - this.running = false; - this.done = true; - this.monitor.notify(); - } - } + synchronized (this.monitor) { + this.running = false; + this.done = true; + this.monitor.notify(); + } + } - @Override - public boolean isSimulation() - { - return this.simulate; - } + @Override + public boolean isSimulation() { + return this.simulate; + } - @Override - public long getByteTotal() - { - return this.bytes; - } + @Override + public long getByteTotal() { + return this.bytes; + } - @Override - public void populatePlan( final IItemList plan ) - { - if( this.getTree() != null ) - { - this.getTree().getPlan( plan ); - } - } + @Override + public void populatePlan(final IItemList plan) { + if (this.getTree() != null) { + this.getTree().getPlan(plan); + } + } - @Override - public IAEItemStack getOutput() - { - return this.output; - } + @Override + public IAEItemStack getOutput() { + return this.output; + } - public boolean isDone() - { - return this.done; - } + public boolean isDone() { + return this.done; + } - World getWorld() - { - return this.world; - } + World getWorld() { + return this.world; + } - /** - * @return true if this needs more simulation - */ - public boolean simulateFor( final int milli ) - { - this.time = milli; + /** + * @return true if this needs more simulation + */ + public boolean simulateFor(final int milli) { + this.time = milli; - synchronized ( this.monitor ) - { - if( this.done ) - { - return false; - } - if( !this.actionSrc.player().isPresent() ) - { - this.tickSpreadingWatch.reset(); - this.tickSpreadingWatch.start(); - this.monitor.notify(); - } - this.running = true; - } + synchronized (this.monitor) { + if (this.done) { + return false; + } + if (!this.actionSrc.player().isPresent()) { + this.tickSpreadingWatch.reset(); + this.tickSpreadingWatch.start(); + this.monitor.notify(); + } + this.running = true; + } - return true; - } + return true; + } - void addBytes( final long crafts ) - { - this.bytes += crafts; - } + void addBytes(final long crafts) { + this.bytes += crafts; + } - public CraftingTreeNode getTree() - { - return this.tree; - } + public CraftingTreeNode getTree() { + return this.tree; + } - private void setTree( final CraftingTreeNode tree ) - { - this.tree = tree; - } + private void setTree(final CraftingTreeNode tree) { + this.tree = tree; + } - private void logCraftingJob( String type, Stopwatch timer ) - { - if( AELog.isCraftingLogEnabled() ) - { - final String itemToOutput = this.output.toString(); - final long elapsedTime = timer.elapsed( TimeUnit.MICROSECONDS ); - final String actionSource; + private void logCraftingJob(String type, Stopwatch timer) { + if (AELog.isCraftingLogEnabled()) { + final String itemToOutput = this.output.toString(); + final long elapsedTime = timer.elapsed(TimeUnit.MICROSECONDS); + final String actionSource; - if( this.actionSrc.player().isPresent() ) - { - final EntityPlayer player = this.actionSrc.player().get(); + if (this.actionSrc.player().isPresent()) { + final EntityPlayer player = this.actionSrc.player().get(); - actionSource = player.toString(); - } - else if( this.actionSrc.machine().isPresent() ) - { - final IActionHost machineSource = this.actionSrc.machine().get(); - final IGridNode actionableNode = machineSource.getActionableNode(); - final IGridHost machine = actionableNode.getMachine(); - final DimensionalCoord location = actionableNode.getGridBlock().getLocation(); + actionSource = player.toString(); + } else if (this.actionSrc.machine().isPresent()) { + final IActionHost machineSource = this.actionSrc.machine().get(); + final IGridNode actionableNode = machineSource.getActionableNode(); + final IGridHost machine = actionableNode.getMachine(); + final DimensionalCoord location = actionableNode.getGridBlock().getLocation(); - actionSource = String.format( LOG_MACHINE_SOURCE_DETAILS, machine, location ); - } - else - { - actionSource = "[unknown source]"; - } + actionSource = String.format(LOG_MACHINE_SOURCE_DETAILS, machine, location); + } else { + actionSource = "[unknown source]"; + } - AELog.crafting( LOG_CRAFTING_JOB, type, actionSource, itemToOutput, this.bytes, elapsedTime ); - } - } + AELog.crafting(LOG_CRAFTING_JOB, type, actionSource, itemToOutput, this.bytes, elapsedTime); + } + } - private static class TwoIntegers - { - private final long perOp = 0; - private final long times = 0; - } + private static class TwoIntegers { + private final long perOp = 0; + private final long times = 0; + } } diff --git a/src/main/java/appeng/crafting/CraftingLink.java b/src/main/java/appeng/crafting/CraftingLink.java index 56fb5d500..d9a766d12 100644 --- a/src/main/java/appeng/crafting/CraftingLink.java +++ b/src/main/java/appeng/crafting/CraftingLink.java @@ -19,197 +19,165 @@ package appeng.crafting; -import net.minecraft.nbt.NBTTagCompound; - import appeng.api.config.Actionable; import appeng.api.networking.crafting.ICraftingCPU; import appeng.api.networking.crafting.ICraftingLink; import appeng.api.networking.crafting.ICraftingRequester; import appeng.api.storage.data.IAEItemStack; +import net.minecraft.nbt.NBTTagCompound; -public class CraftingLink implements ICraftingLink -{ +public class CraftingLink implements ICraftingLink { - private final ICraftingRequester req; - private final ICraftingCPU cpu; - private final String CraftID; - private final boolean standalone; - private boolean canceled = false; - private boolean done = false; - private CraftingLinkNexus tie; + private final ICraftingRequester req; + private final ICraftingCPU cpu; + private final String CraftID; + private final boolean standalone; + private boolean canceled = false; + private boolean done = false; + private CraftingLinkNexus tie; - public CraftingLink( final NBTTagCompound data, final ICraftingRequester req ) - { - this.CraftID = data.getString( "CraftID" ); - this.setCanceled( data.getBoolean( "canceled" ) ); - this.setDone( data.getBoolean( "done" ) ); - this.standalone = data.getBoolean( "standalone" ); + public CraftingLink(final NBTTagCompound data, final ICraftingRequester req) { + this.CraftID = data.getString("CraftID"); + this.setCanceled(data.getBoolean("canceled")); + this.setDone(data.getBoolean("done")); + this.standalone = data.getBoolean("standalone"); - if( !data.hasKey( "req" ) || !data.getBoolean( "req" ) ) - { - throw new IllegalStateException( "Invalid Crafting Link for Object" ); - } + if (!data.hasKey("req") || !data.getBoolean("req")) { + throw new IllegalStateException("Invalid Crafting Link for Object"); + } - this.req = req; - this.cpu = null; - } + this.req = req; + this.cpu = null; + } - public CraftingLink( final NBTTagCompound data, final ICraftingCPU cpu ) - { - this.CraftID = data.getString( "CraftID" ); - this.setCanceled( data.getBoolean( "canceled" ) ); - this.setDone( data.getBoolean( "done" ) ); - this.standalone = data.getBoolean( "standalone" ); + public CraftingLink(final NBTTagCompound data, final ICraftingCPU cpu) { + this.CraftID = data.getString("CraftID"); + this.setCanceled(data.getBoolean("canceled")); + this.setDone(data.getBoolean("done")); + this.standalone = data.getBoolean("standalone"); - if( !data.hasKey( "req" ) || data.getBoolean( "req" ) ) - { - throw new IllegalStateException( "Invalid Crafting Link for Object" ); - } + if (!data.hasKey("req") || data.getBoolean("req")) { + throw new IllegalStateException("Invalid Crafting Link for Object"); + } - this.cpu = cpu; - this.req = null; - } + this.cpu = cpu; + this.req = null; + } - @Override - public boolean isCanceled() - { - if( this.canceled ) - { - return true; - } + @Override + public boolean isCanceled() { + if (this.canceled) { + return true; + } - if( this.done ) - { - return false; - } + if (this.done) { + return false; + } - if( this.tie == null ) - { - return false; - } + if (this.tie == null) { + return false; + } - return this.tie.isCanceled(); - } + return this.tie.isCanceled(); + } - @Override - public boolean isDone() - { - if( this.done ) - { - return true; - } + @Override + public boolean isDone() { + if (this.done) { + return true; + } - if( this.canceled ) - { - return false; - } + if (this.canceled) { + return false; + } - if( this.tie == null ) - { - return false; - } + if (this.tie == null) { + return false; + } - return this.tie.isDone(); - } + return this.tie.isDone(); + } - @Override - public void cancel() - { - if( this.done ) - { - return; - } + @Override + public void cancel() { + if (this.done) { + return; + } - this.setCanceled( true ); + this.setCanceled(true); - if( this.tie != null ) - { - this.tie.cancel(); - } + if (this.tie != null) { + this.tie.cancel(); + } - this.tie = null; - } + this.tie = null; + } - @Override - public boolean isStandalone() - { - return this.standalone; - } + @Override + public boolean isStandalone() { + return this.standalone; + } - @Override - public void writeToNBT( final NBTTagCompound tag ) - { - tag.setString( "CraftID", this.CraftID ); - tag.setBoolean( "canceled", this.isCanceled() ); - tag.setBoolean( "done", this.isDone() ); - tag.setBoolean( "standalone", this.standalone ); - tag.setBoolean( "req", this.getRequester() != null ); - } + @Override + public void writeToNBT(final NBTTagCompound tag) { + tag.setString("CraftID", this.CraftID); + tag.setBoolean("canceled", this.isCanceled()); + tag.setBoolean("done", this.isDone()); + tag.setBoolean("standalone", this.standalone); + tag.setBoolean("req", this.getRequester() != null); + } - @Override - public String getCraftingID() - { - return this.CraftID; - } + @Override + public String getCraftingID() { + return this.CraftID; + } - public void setNexus( final CraftingLinkNexus n ) - { - if( this.tie != null ) - { - this.tie.remove( this ); - } + public void setNexus(final CraftingLinkNexus n) { + if (this.tie != null) { + this.tie.remove(this); + } - if( this.isCanceled() && n != null ) - { - n.cancel(); - this.tie = null; - return; - } + if (this.isCanceled() && n != null) { + n.cancel(); + this.tie = null; + return; + } - this.tie = n; + this.tie = n; - if( n != null ) - { - n.add( this ); - } - } + if (n != null) { + n.add(this); + } + } - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode ) - { - if( this.tie == null || this.tie.getRequest() == null || this.tie.getRequest().getRequester() == null ) - { - return input; - } + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode) { + if (this.tie == null || this.tie.getRequest() == null || this.tie.getRequest().getRequester() == null) { + return input; + } - return this.tie.getRequest().getRequester().injectCraftedItems( this.tie.getRequest(), input, mode ); - } + return this.tie.getRequest().getRequester().injectCraftedItems(this.tie.getRequest(), input, mode); + } - public void markDone() - { - if( this.tie != null ) - { - this.tie.markDone(); - } - } + public void markDone() { + if (this.tie != null) { + this.tie.markDone(); + } + } - void setCanceled( final boolean canceled ) - { - this.canceled = canceled; - } + void setCanceled(final boolean canceled) { + this.canceled = canceled; + } - ICraftingRequester getRequester() - { - return this.req; - } + ICraftingRequester getRequester() { + return this.req; + } - ICraftingCPU getCpu() - { - return this.cpu; - } + ICraftingCPU getCpu() { + return this.cpu; + } - void setDone( final boolean done ) - { - this.done = done; - } + void setDone(final boolean done) { + this.done = done; + } } diff --git a/src/main/java/appeng/crafting/CraftingLinkNexus.java b/src/main/java/appeng/crafting/CraftingLinkNexus.java index 1f8eb8a7e..506e4168f 100644 --- a/src/main/java/appeng/crafting/CraftingLinkNexus.java +++ b/src/main/java/appeng/crafting/CraftingLinkNexus.java @@ -24,151 +24,117 @@ import appeng.api.networking.IGridHost; import appeng.me.cache.CraftingGridCache; -public class CraftingLinkNexus -{ +public class CraftingLinkNexus { - private final String craftID; - private boolean canceled = false; - private boolean done = false; - private int tickOfDeath = 0; - private CraftingLink req; - private CraftingLink cpu; + private final String craftID; + private boolean canceled = false; + private boolean done = false; + private int tickOfDeath = 0; + private CraftingLink req; + private CraftingLink cpu; - public CraftingLinkNexus( final String craftID ) - { - this.craftID = craftID; - } + public CraftingLinkNexus(final String craftID) { + this.craftID = craftID; + } - public boolean isDead( final IGrid g, final CraftingGridCache craftingGridCache ) - { - if( this.canceled || this.done ) - { - return true; - } + public boolean isDead(final IGrid g, final CraftingGridCache craftingGridCache) { + if (this.canceled || this.done) { + return true; + } - if( this.getRequest() == null || this.cpu == null ) - { - this.tickOfDeath++; - } - else - { - final boolean hasCpu = craftingGridCache.hasCpu( this.cpu.getCpu() ); - final boolean hasMachine = this.getRequest().getRequester().getActionableNode().getGrid() == g; + if (this.getRequest() == null || this.cpu == null) { + this.tickOfDeath++; + } else { + final boolean hasCpu = craftingGridCache.hasCpu(this.cpu.getCpu()); + final boolean hasMachine = this.getRequest().getRequester().getActionableNode().getGrid() == g; - if( hasCpu && hasMachine ) - { - this.tickOfDeath = 0; - } - else - { - this.tickOfDeath += 60; - } - } + if (hasCpu && hasMachine) { + this.tickOfDeath = 0; + } else { + this.tickOfDeath += 60; + } + } - if( this.tickOfDeath > 60 ) - { - this.cancel(); - return true; - } + if (this.tickOfDeath > 60) { + this.cancel(); + return true; + } - return false; - } + return false; + } - void cancel() - { - this.canceled = true; + void cancel() { + this.canceled = true; - if( this.getRequest() != null ) - { - this.getRequest().setCanceled( true ); - if( this.getRequest().getRequester() != null ) - { - this.getRequest().getRequester().jobStateChange( this.getRequest() ); - } - } + if (this.getRequest() != null) { + this.getRequest().setCanceled(true); + if (this.getRequest().getRequester() != null) { + this.getRequest().getRequester().jobStateChange(this.getRequest()); + } + } - if( this.cpu != null ) - { - this.cpu.setCanceled( true ); - } - } + if (this.cpu != null) { + this.cpu.setCanceled(true); + } + } - void remove( final CraftingLink craftingLink ) - { - if( this.getRequest() == craftingLink ) - { - this.setRequest( null ); - } - else if( this.cpu == craftingLink ) - { - this.cpu = null; - } - } + void remove(final CraftingLink craftingLink) { + if (this.getRequest() == craftingLink) { + this.setRequest(null); + } else if (this.cpu == craftingLink) { + this.cpu = null; + } + } - void add( final CraftingLink craftingLink ) - { - if( craftingLink.getCpu() != null ) - { - this.cpu = craftingLink; - } - else if( craftingLink.getRequester() != null ) - { - this.setRequest( craftingLink ); - } - } + void add(final CraftingLink craftingLink) { + if (craftingLink.getCpu() != null) { + this.cpu = craftingLink; + } else if (craftingLink.getRequester() != null) { + this.setRequest(craftingLink); + } + } - boolean isCanceled() - { - return this.canceled; - } + boolean isCanceled() { + return this.canceled; + } - boolean isDone() - { - return this.done; - } + boolean isDone() { + return this.done; + } - void markDone() - { - this.done = true; + void markDone() { + this.done = true; - if( this.getRequest() != null ) - { - this.getRequest().setDone( true ); - if( this.getRequest().getRequester() != null ) - { - this.getRequest().getRequester().jobStateChange( this.getRequest() ); - } - } + if (this.getRequest() != null) { + this.getRequest().setDone(true); + if (this.getRequest().getRequester() != null) { + this.getRequest().getRequester().jobStateChange(this.getRequest()); + } + } - if( this.cpu != null ) - { - this.cpu.setDone( true ); - } - } + if (this.cpu != null) { + this.cpu.setDone(true); + } + } - public boolean isMachine( final IGridHost machine ) - { - return this.getRequest() == machine; - } + public boolean isMachine(final IGridHost machine) { + return this.getRequest() == machine; + } - public void removeNode() - { - if( this.getRequest() != null ) - { - this.getRequest().setNexus( null ); - } + public void removeNode() { + if (this.getRequest() != null) { + this.getRequest().setNexus(null); + } - this.setRequest( null ); - this.tickOfDeath = 0; - } + this.setRequest(null); + this.tickOfDeath = 0; + } - public CraftingLink getRequest() - { - return this.req; - } + public CraftingLink getRequest() { + return this.req; + } - public void setRequest( final CraftingLink req ) - { - this.req = req; - } + public void setRequest(final CraftingLink req) { + this.req = req; + } } diff --git a/src/main/java/appeng/crafting/CraftingTreeNode.java b/src/main/java/appeng/crafting/CraftingTreeNode.java index 25da82284..b5fbc77b5 100644 --- a/src/main/java/appeng/crafting/CraftingTreeNode.java +++ b/src/main/java/appeng/crafting/CraftingTreeNode.java @@ -41,395 +41,317 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -@Optional.Interface( iface = "gregtech.api.items.IToolItem", modid = "gregtech" ) -public class CraftingTreeNode -{ +@Optional.Interface(iface = "gregtech.api.items.IToolItem", modid = "gregtech") +public class CraftingTreeNode { - // what slot! - private final int slot; - private final CraftingJob job; - private final IItemList used = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - // parent node. - private final CraftingTreeProcess parent; - private final World world; - // what item is this? - private final IAEItemStack what; - // what are the crafting patterns for this? - private final ArrayList nodes = new ArrayList<>(); - private final ICraftingGrid cc; - private final int depth; - private int bytes = 0; - private boolean canEmit = false; - private long missing = 0; - private long howManyEmitted = 0; - private boolean exhausted = false; + // what slot! + private final int slot; + private final CraftingJob job; + private final IItemList used = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + // parent node. + private final CraftingTreeProcess parent; + private final World world; + // what item is this? + private final IAEItemStack what; + // what are the crafting patterns for this? + private final ArrayList nodes = new ArrayList<>(); + private final ICraftingGrid cc; + private final int depth; + private int bytes = 0; + private boolean canEmit = false; + private long missing = 0; + private long howManyEmitted = 0; + private boolean exhausted = false; - public CraftingTreeNode( final ICraftingGrid cc, final CraftingJob job, final IAEItemStack wat, final CraftingTreeProcess par, final int slot, final int depth ) - { - this.what = wat; - this.parent = par; - this.slot = slot; - this.world = job.getWorld(); - this.job = job; - this.cc = cc; - this.depth = depth; + public CraftingTreeNode(final ICraftingGrid cc, final CraftingJob job, final IAEItemStack wat, final CraftingTreeProcess par, final int slot, final int depth) { + this.what = wat; + this.parent = par; + this.slot = slot; + this.world = job.getWorld(); + this.job = job; + this.cc = cc; + this.depth = depth; - this.canEmit = cc.canEmitFor( this.what ); - } + this.canEmit = cc.canEmitFor(this.what); + } - public void addNode() - { - if( !nodes.isEmpty() ) - { - return; - } + public void addNode() { + if (!nodes.isEmpty()) { + return; + } - if( this.canEmit ) - { - return; // if you can emit for something, you can't make it with patterns. - } + if (this.canEmit) { + return; // if you can emit for something, you can't make it with patterns. + } - for( final ICraftingPatternDetails details : cc.getCraftingFor( this.what, this.parent == null ? null : this.parent.details, slot, this.world ) )// in - // order. - { - if( this.parent == null || notRecursive( details ) && this.parent.details != details ) - { - this.nodes.add( new CraftingTreeProcess( cc, job, details, this, depth + 1 ) ); - } - } - } + for (final ICraftingPatternDetails details : cc.getCraftingFor(this.what, this.parent == null ? null : this.parent.details, slot, this.world))// in + // order. + { + if (this.parent == null || notRecursive(details) && this.parent.details != details) { + this.nodes.add(new CraftingTreeProcess(cc, job, details, this, depth + 1)); + } + } + } - IAEItemStack request( final MECraftingInventory inv, long l, final IActionSource src ) throws CraftBranchFailure, InterruptedException - { - addNode(); - this.job.handlePausing(); - if( this.canEmit ) - { - final IAEItemStack wat = this.what.copy(); - wat.setStackSize( l ); + IAEItemStack request(final MECraftingInventory inv, long l, final IActionSource src) throws CraftBranchFailure, InterruptedException { + addNode(); + this.job.handlePausing(); + if (this.canEmit) { + final IAEItemStack wat = this.what.copy(); + wat.setStackSize(l); - this.howManyEmitted = wat.getStackSize(); - this.bytes += wat.getStackSize(); + this.howManyEmitted = wat.getStackSize(); + this.bytes += wat.getStackSize(); - return wat; - } + return wat; + } - final IItemList inventoryList = inv.getItemList(); - final List thingsUsed = new ArrayList<>(); + final IItemList inventoryList = inv.getItemList(); + final List thingsUsed = new ArrayList<>(); - this.what.setStackSize( l ); + this.what.setStackSize(l); - if( this.getSlot() >= 0 && this.parent != null && this.parent.details.isCraftable() ) - { - Collection itemList = new ArrayList<>(); + if (this.getSlot() >= 0 && this.parent != null && this.parent.details.isCraftable()) { + Collection itemList = new ArrayList<>(); - boolean damageableItem = this.what.getItem().isDamageable() || Platform.isGTDamageableItem( this.what.getItem() ); + boolean damageableItem = this.what.getItem().isDamageable() || Platform.isGTDamageableItem(this.what.getItem()); - if( this.parent.details.canSubstitute() ) - { - for( IAEItemStack subs : this.parent.details.getSubstituteInputs( this.slot ) ) - { - if( damageableItem ) - { - itemList.addAll( inventoryList.findFuzzy( subs, FuzzyMode.IGNORE_ALL ) ); - } - subs = inventoryList.findPrecise( subs ); - if( subs != null ) - { - itemList.add( subs ); - } - } - } - else - { - if( damageableItem ) - { - itemList.addAll( inventoryList.findFuzzy( this.what, FuzzyMode.IGNORE_ALL ) ); - } - else - { - final IAEItemStack item = inventoryList.findPrecise( this.what ); - if( item != null ) - { - itemList.add( item ); - } - } - } + if (this.parent.details.canSubstitute()) { + for (IAEItemStack subs : this.parent.details.getSubstituteInputs(this.slot)) { + if (damageableItem) { + itemList.addAll(inventoryList.findFuzzy(subs, FuzzyMode.IGNORE_ALL)); + } + subs = inventoryList.findPrecise(subs); + if (subs != null) { + itemList.add(subs); + } + } + } else { + if (damageableItem) { + itemList.addAll(inventoryList.findFuzzy(this.what, FuzzyMode.IGNORE_ALL)); + } else { + final IAEItemStack item = inventoryList.findPrecise(this.what); + if (item != null) { + itemList.add(item); + } + } + } - for( IAEItemStack fuzz : itemList ) - { - if( this.parent.details.isValidItemForSlot( this.getSlot(), fuzz.copy().getCachedItemStack( 1 ), this.world ) ) - { - fuzz = fuzz.copy(); - fuzz.setStackSize( l ); + for (IAEItemStack fuzz : itemList) { + if (this.parent.details.isValidItemForSlot(this.getSlot(), fuzz.copy().getCachedItemStack(1), this.world)) { + fuzz = fuzz.copy(); + fuzz.setStackSize(l); - final IAEItemStack available = inv.extractItems( fuzz, Actionable.MODULATE, src ); + final IAEItemStack available = inv.extractItems(fuzz, Actionable.MODULATE, src); - if( available != null ) - { - if( !this.exhausted ) - { - final IAEItemStack is = this.job.checkUse( available ); + if (available != null) { + if (!this.exhausted) { + final IAEItemStack is = this.job.checkUse(available); - if( is != null ) - { - thingsUsed.add( is.copy() ); - this.used.add( is ); - } - } + if (is != null) { + thingsUsed.add(is.copy()); + this.used.add(is); + } + } - this.bytes += available.getStackSize(); - l -= available.getStackSize(); + this.bytes += available.getStackSize(); + l -= available.getStackSize(); - if( l == 0 ) - { - return available; - } - } - } - } - } - else - { - final IAEItemStack available = inv.extractItems( this.what, Actionable.MODULATE, src ); + if (l == 0) { + return available; + } + } + } + } + } else { + final IAEItemStack available = inv.extractItems(this.what, Actionable.MODULATE, src); - if( available != null ) - { - if( !this.exhausted ) - { - final IAEItemStack is = this.job.checkUse( available ); + if (available != null) { + if (!this.exhausted) { + final IAEItemStack is = this.job.checkUse(available); - if( is != null ) - { - thingsUsed.add( is.copy() ); - this.used.add( is ); - } - } + if (is != null) { + thingsUsed.add(is.copy()); + this.used.add(is); + } + } - this.bytes += available.getStackSize(); - l -= available.getStackSize(); + this.bytes += available.getStackSize(); + l -= available.getStackSize(); - if( l == 0 ) - { - return available; - } - } - } + if (l == 0) { + return available; + } + } + } - this.exhausted = true; + this.exhausted = true; - if( this.nodes.size() == 1 ) - { - final CraftingTreeProcess pro = this.nodes.get( 0 ); + if (this.nodes.size() == 1) { + final CraftingTreeProcess pro = this.nodes.get(0); - while ( pro.possible && l > 0 ) - { - final IAEItemStack madeWhat = pro.getAmountCrafted( this.what ); - pro.request( inv, pro.getTimes( l, madeWhat.getStackSize() ), src ); + while (pro.possible && l > 0) { + final IAEItemStack madeWhat = pro.getAmountCrafted(this.what); + pro.request(inv, pro.getTimes(l, madeWhat.getStackSize()), src); - madeWhat.setStackSize( l ); - final IAEItemStack available = inv.extractItems( madeWhat, Actionable.MODULATE, src ); + madeWhat.setStackSize(l); + final IAEItemStack available = inv.extractItems(madeWhat, Actionable.MODULATE, src); - if( available != null ) - { - this.bytes += available.getStackSize(); - l -= available.getStackSize(); + if (available != null) { + this.bytes += available.getStackSize(); + l -= available.getStackSize(); - if( l <= 0 ) - { - return available; - } - } - else - { - pro.possible = false; // ;P - } - } - } - else if( this.nodes.size() > 1 ) - { - for( final CraftingTreeProcess pro : this.nodes ) - { - try - { - while ( pro.possible && l > 0 ) - { - final MECraftingInventory subInv = new MECraftingInventory( inv, true, true, true ); - pro.request( subInv, 1, src ); + if (l <= 0) { + return available; + } + } else { + pro.possible = false; // ;P + } + } + } else if (this.nodes.size() > 1) { + for (final CraftingTreeProcess pro : this.nodes) { + try { + while (pro.possible && l > 0) { + final MECraftingInventory subInv = new MECraftingInventory(inv, true, true, true); + pro.request(subInv, 1, src); - this.what.setStackSize( l ); - final IAEItemStack available = subInv.extractItems( this.what, Actionable.MODULATE, src ); + this.what.setStackSize(l); + final IAEItemStack available = subInv.extractItems(this.what, Actionable.MODULATE, src); - if( available != null ) - { - if( !subInv.commit( src ) ) - { - throw new CraftBranchFailure( this.what, l ); - } + if (available != null) { + if (!subInv.commit(src)) { + throw new CraftBranchFailure(this.what, l); + } - this.bytes += available.getStackSize(); - l -= available.getStackSize(); + this.bytes += available.getStackSize(); + l -= available.getStackSize(); - if( l <= 0 ) - { - return available; - } - } - else - { - pro.possible = false; // ;P - } - } - } - catch( final CraftBranchFailure fail ) - { - pro.possible = true; - } - } - } + if (l <= 0) { + return available; + } + } else { + pro.possible = false; // ;P + } + } + } catch (final CraftBranchFailure fail) { + pro.possible = true; + } + } + } - if( job.isSimulation() ) - { - this.bytes += l; - this.missing += l; - final IAEItemStack rv = this.what.copy(); - rv.setStackSize( l ); - return rv; - } + if (job.isSimulation()) { + this.bytes += l; + this.missing += l; + final IAEItemStack rv = this.what.copy(); + rv.setStackSize(l); + return rv; + } - for( final IAEItemStack o : thingsUsed ) - { - this.job.refund( o.copy() ); - o.setStackSize( -o.getStackSize() ); - this.used.add( o ); - } + for (final IAEItemStack o : thingsUsed) { + this.job.refund(o.copy()); + o.setStackSize(-o.getStackSize()); + this.used.add(o); + } - throw new CraftBranchFailure( this.what, l ); - } + throw new CraftBranchFailure(this.what, l); + } - boolean notRecursive( ICraftingPatternDetails details ) - { - if( this.parent == null ) - { - return true; - } - if( this.parent.details == details ) - { - return false; - } - return this.parent.notRecursive( details ); - } + boolean notRecursive(ICraftingPatternDetails details) { + if (this.parent == null) { + return true; + } + if (this.parent.details == details) { + return false; + } + return this.parent.notRecursive(details); + } - void dive( final CraftingJob job ) - { - if( this.missing > 0 ) - { - job.addMissing( this.getStack( this.missing ) ); - } - // missing = 0; + void dive(final CraftingJob job) { + if (this.missing > 0) { + job.addMissing(this.getStack(this.missing)); + } + // missing = 0; - job.addBytes( this.bytes ); + job.addBytes(this.bytes); - for( final CraftingTreeProcess pro : this.nodes ) - { - pro.dive( job ); - } - } + for (final CraftingTreeProcess pro : this.nodes) { + pro.dive(job); + } + } - IAEItemStack getStack( final long size ) - { - final IAEItemStack is = this.what.copy(); - is.setStackSize( size ); - return is; - } + IAEItemStack getStack(final long size) { + final IAEItemStack is = this.what.copy(); + is.setStackSize(size); + return is; + } - void setSimulate() - { - this.missing = 0; - this.bytes = 0; - this.used.resetStatus(); - this.exhausted = false; + void setSimulate() { + this.missing = 0; + this.bytes = 0; + this.used.resetStatus(); + this.exhausted = false; - for( final CraftingTreeProcess pro : this.nodes ) - { - pro.setSimulate(); - } - } + for (final CraftingTreeProcess pro : this.nodes) { + pro.setSimulate(); + } + } - public void setJob( final MECraftingInventory storage, final CraftingCPUCluster craftingCPUCluster, final IActionSource src ) throws CraftBranchFailure - { - for( final IAEItemStack i : this.used ) - { - final IAEItemStack actuallyExtracted = storage.extractItems( i, Actionable.MODULATE, src ); + public void setJob(final MECraftingInventory storage, final CraftingCPUCluster craftingCPUCluster, final IActionSource src) throws CraftBranchFailure { + for (final IAEItemStack i : this.used) { + final IAEItemStack actuallyExtracted = storage.extractItems(i, Actionable.MODULATE, src); - if( actuallyExtracted == null || actuallyExtracted.getStackSize() != i.getStackSize() ) - { - if( src.player().isPresent() ) - { - try - { - if( actuallyExtracted == null ) - { - NetworkHandler.instance().sendTo( new PacketInformPlayer( i, null, PacketInformPlayer.InfoType.NO_ITEMS_EXTRACTED ), (EntityPlayerMP) src.player().get() ); - } - else - { - NetworkHandler.instance().sendTo( new PacketInformPlayer( i, actuallyExtracted, PacketInformPlayer.InfoType.PARTIAL_ITEM_EXTRACTION ), (EntityPlayerMP) src.player().get() ); - } - } - catch( IOException e ) - { - e.printStackTrace(); - } - } - throw new CraftBranchFailure( i, i.getStackSize() ); - } + if (actuallyExtracted == null || actuallyExtracted.getStackSize() != i.getStackSize()) { + if (src.player().isPresent()) { + try { + if (actuallyExtracted == null) { + NetworkHandler.instance().sendTo(new PacketInformPlayer(i, null, PacketInformPlayer.InfoType.NO_ITEMS_EXTRACTED), (EntityPlayerMP) src.player().get()); + } else { + NetworkHandler.instance().sendTo(new PacketInformPlayer(i, actuallyExtracted, PacketInformPlayer.InfoType.PARTIAL_ITEM_EXTRACTION), (EntityPlayerMP) src.player().get()); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + throw new CraftBranchFailure(i, i.getStackSize()); + } - craftingCPUCluster.addStorage( actuallyExtracted ); - } + craftingCPUCluster.addStorage(actuallyExtracted); + } - if( this.howManyEmitted > 0 ) - { - final IAEItemStack i = this.what.copy().reset(); - i.setStackSize( this.howManyEmitted ); - craftingCPUCluster.addEmitable( i ); - } + if (this.howManyEmitted > 0) { + final IAEItemStack i = this.what.copy().reset(); + i.setStackSize(this.howManyEmitted); + craftingCPUCluster.addEmitable(i); + } - for( final CraftingTreeProcess pro : this.nodes ) - { - pro.setJob( storage, craftingCPUCluster, src ); - } - } + for (final CraftingTreeProcess pro : this.nodes) { + pro.setJob(storage, craftingCPUCluster, src); + } + } - void getPlan( final IItemList plan ) - { - if( this.missing > 0 ) - { - final IAEItemStack o = this.what.copy(); - o.setStackSize( this.missing ); - plan.add( o ); - } + void getPlan(final IItemList plan) { + if (this.missing > 0) { + final IAEItemStack o = this.what.copy(); + o.setStackSize(this.missing); + plan.add(o); + } - if( this.howManyEmitted > 0 ) - { - final IAEItemStack i = this.what.copy(); - i.setCountRequestable( this.howManyEmitted ); - plan.addRequestable( i ); - } + if (this.howManyEmitted > 0) { + final IAEItemStack i = this.what.copy(); + i.setCountRequestable(this.howManyEmitted); + plan.addRequestable(i); + } - for( final IAEItemStack i : this.used ) - { - plan.add( i.copy() ); - } + for (final IAEItemStack i : this.used) { + plan.add(i.copy()); + } - for( final CraftingTreeProcess pro : this.nodes ) - { - pro.getPlan( plan ); - } - } + for (final CraftingTreeProcess pro : this.nodes) { + pro.getPlan(plan); + } + } - int getSlot() - { - return this.slot; - } + int getSlot() { + return this.slot; + } } diff --git a/src/main/java/appeng/crafting/CraftingTreeProcess.java b/src/main/java/appeng/crafting/CraftingTreeProcess.java index 99d170e6a..469ca0a8e 100644 --- a/src/main/java/appeng/crafting/CraftingTreeProcess.java +++ b/src/main/java/appeng/crafting/CraftingTreeProcess.java @@ -39,325 +39,258 @@ import java.util.List; import java.util.Map.Entry; -public class CraftingTreeProcess -{ - private final CraftingTreeNode parent; - final ICraftingPatternDetails details; - private final CraftingJob job; - private final Object2LongArrayMap nodes = new Object2LongArrayMap<>(); - private final int depth; - private final ICraftingGrid cc; - private final World world; - boolean possible = true; - private long crafts = 0; - private long bytes = 0; +public class CraftingTreeProcess { + private final CraftingTreeNode parent; + final ICraftingPatternDetails details; + private final CraftingJob job; + private final Object2LongArrayMap nodes = new Object2LongArrayMap<>(); + private final int depth; + private final ICraftingGrid cc; + private final World world; + boolean possible = true; + private long crafts = 0; + private long bytes = 0; - public CraftingTreeProcess( final ICraftingGrid cc, final CraftingJob job, final ICraftingPatternDetails details, final CraftingTreeNode craftingTreeNode, final int depth ) - { - this.parent = craftingTreeNode; - this.details = details; - this.job = job; - this.depth = depth; - this.cc = cc; - this.world = job.getWorld(); - } + public CraftingTreeProcess(final ICraftingGrid cc, final CraftingJob job, final ICraftingPatternDetails details, final CraftingTreeNode craftingTreeNode, final int depth) { + this.parent = craftingTreeNode; + this.details = details; + this.job = job; + this.depth = depth; + this.cc = cc; + this.world = job.getWorld(); + } - public void addProcess() - { - if( !nodes.isEmpty() ) - { - return; - } + public void addProcess() { + if (!nodes.isEmpty()) { + return; + } - final IAEItemStack[] list = details.getInputs(); + final IAEItemStack[] list = details.getInputs(); - // this is minor different then below, this slot uses the pattern, but kinda fudges it. - for( IAEItemStack part : details.getCondensedInputs() ) - { - if( part == null ) - { - continue; - } - for( int x = 0; x < list.length; x++ ) - { - final IAEItemStack comparePart = list[x]; - if( part.equals( comparePart ) ) - { - boolean isPartContainer = false; - if( part.getItem().hasContainerItem( part.getDefinition() ) ) - { - part = list[x]; - isPartContainer = true; - } + // this is minor different then below, this slot uses the pattern, but kinda fudges it. + for (IAEItemStack part : details.getCondensedInputs()) { + if (part == null) { + continue; + } + for (int x = 0; x < list.length; x++) { + final IAEItemStack comparePart = list[x]; + if (part.equals(comparePart)) { + boolean isPartContainer = false; + if (part.getItem().hasContainerItem(part.getDefinition())) { + part = list[x]; + isPartContainer = true; + } - long wantedSize = part.getStackSize(); + long wantedSize = part.getStackSize(); - if( AEConfig.instance().getEnableCraftingSubstitutes() ) - { - IAEItemStack found; - long remaining; - long requestAmount; + if (AEConfig.instance().getEnableCraftingSubstitutes()) { + IAEItemStack found; + long remaining; + long requestAmount; - if( details.canSubstitute() ) - { - for( IAEItemStack subs : details.getSubstituteInputs( x ) ) - { - found = job.checkAvailable( subs ); + if (details.canSubstitute()) { + for (IAEItemStack subs : details.getSubstituteInputs(x)) { + found = job.checkAvailable(subs); - if( found != null ) - { - remaining = found.getStackSize(); - } - else - { - remaining = 0; - } + if (found != null) { + remaining = found.getStackSize(); + } else { + remaining = 0; + } - if( remaining > 0 ) - { - if( remaining >= wantedSize ) - { - requestAmount = wantedSize; - wantedSize = 0; - //we have the items - } - else - { - requestAmount = remaining; - wantedSize -= remaining; - } - subs = subs.copy().setStackSize( requestAmount ); - CraftingTreeNode node = new CraftingTreeNode( cc, job, subs, this, x, depth + 1 ); - this.nodes.put( node, requestAmount ); - if( wantedSize == 0 ) - { - break; - } - } - } - } - else - { - found = job.checkAvailable( part ); + if (remaining > 0) { + if (remaining >= wantedSize) { + requestAmount = wantedSize; + wantedSize = 0; + //we have the items + } else { + requestAmount = remaining; + wantedSize -= remaining; + } + subs = subs.copy().setStackSize(requestAmount); + CraftingTreeNode node = new CraftingTreeNode(cc, job, subs, this, x, depth + 1); + this.nodes.put(node, requestAmount); + if (wantedSize == 0) { + break; + } + } + } + } else { + found = job.checkAvailable(part); - if( found != null ) - { - remaining = found.getStackSize(); - } - else - { - remaining = 0; - } + if (found != null) { + remaining = found.getStackSize(); + } else { + remaining = 0; + } - if( remaining > 0 ) - { - if( remaining >= wantedSize ) - { - requestAmount = wantedSize; - wantedSize = 0; - //we have the items - } - else - { - requestAmount = remaining; - wantedSize -= remaining; - } - part = part.copy().setStackSize( requestAmount ); - this.nodes.put( new CraftingTreeNode( cc, job, part, this, x, depth + 1 ), requestAmount ); - } - } - if( wantedSize > 0 ) - { - if( details.canSubstitute() && cc.getCraftingFor( part, details, x, world ).isEmpty() ) - { - //try to order the crafting of a substitute - ICraftingPatternDetails prioritizedPattern = null; - IAEItemStack prioritizedIAE = null; - for( IAEItemStack subs : details.getSubstituteInputs( x ) ) - { - ImmutableCollection detailCollection = cc.getCraftingFor( subs, details, x, world ); + if (remaining > 0) { + if (remaining >= wantedSize) { + requestAmount = wantedSize; + wantedSize = 0; + //we have the items + } else { + requestAmount = remaining; + wantedSize -= remaining; + } + part = part.copy().setStackSize(requestAmount); + this.nodes.put(new CraftingTreeNode(cc, job, part, this, x, depth + 1), requestAmount); + } + } + if (wantedSize > 0) { + if (details.canSubstitute() && cc.getCraftingFor(part, details, x, world).isEmpty()) { + //try to order the crafting of a substitute + ICraftingPatternDetails prioritizedPattern = null; + IAEItemStack prioritizedIAE = null; + for (IAEItemStack subs : details.getSubstituteInputs(x)) { + ImmutableCollection detailCollection = cc.getCraftingFor(subs, details, x, world); - for( ICraftingPatternDetails sp : detailCollection ) - { - if( prioritizedPattern == null ) - { - prioritizedPattern = sp; - prioritizedIAE = subs; - } - else - { - if( sp.getPriority() > prioritizedPattern.getPriority() ) - { - prioritizedPattern = sp; - } - } - } - if( prioritizedIAE != null ) - { - subs = subs.copy().setStackSize( wantedSize ); - CraftingTreeNode node = new CraftingTreeNode( cc, job, subs, this, x, depth + 1 ); - this.nodes.put( node, wantedSize ); - wantedSize = 0; - break; - } - } - } - } - } - if( wantedSize > 0 ) - { - part = part.copy().setStackSize( wantedSize ); - // use the first slot... - this.nodes.put( new CraftingTreeNode( cc, job, part, this, x, depth + 1 ), wantedSize ); - wantedSize = 0; - } - if( !isPartContainer && wantedSize == 0 ) - { - break; - } - } - } - } - } + for (ICraftingPatternDetails sp : detailCollection) { + if (prioritizedPattern == null) { + prioritizedPattern = sp; + prioritizedIAE = subs; + } else { + if (sp.getPriority() > prioritizedPattern.getPriority()) { + prioritizedPattern = sp; + } + } + } + if (prioritizedIAE != null) { + subs = subs.copy().setStackSize(wantedSize); + CraftingTreeNode node = new CraftingTreeNode(cc, job, subs, this, x, depth + 1); + this.nodes.put(node, wantedSize); + wantedSize = 0; + break; + } + } + } + } + } + if (wantedSize > 0) { + part = part.copy().setStackSize(wantedSize); + // use the first slot... + this.nodes.put(new CraftingTreeNode(cc, job, part, this, x, depth + 1), wantedSize); + wantedSize = 0; + } + if (!isPartContainer && wantedSize == 0) { + break; + } + } + } + } + } - boolean notRecursive( ICraftingPatternDetails details ) - { - return this.parent == null || this.parent.notRecursive( details ); - } + boolean notRecursive(ICraftingPatternDetails details) { + return this.parent == null || this.parent.notRecursive(details); + } - long getTimes( final long remaining, final long stackSize ) - { - for( final IAEItemStack part : details.getCondensedOutputs() ) - { - for( final IAEItemStack o : details.getCondensedInputs() ) - { - if( part.equals( o ) || o.getItem().hasContainerItem( part.getDefinition() ) ) - { - return 1; - } - } - } - return ( remaining / stackSize ) + ( remaining % stackSize != 0 ? 1 : 0 ); - } + long getTimes(final long remaining, final long stackSize) { + for (final IAEItemStack part : details.getCondensedOutputs()) { + for (final IAEItemStack o : details.getCondensedInputs()) { + if (part.equals(o) || o.getItem().hasContainerItem(part.getDefinition())) { + return 1; + } + } + } + return (remaining / stackSize) + (remaining % stackSize != 0 ? 1 : 0); + } - void request( final MECraftingInventory inv, final long amountOfTimes, final IActionSource src ) throws CraftBranchFailure, InterruptedException - { - addProcess(); - this.job.handlePausing(); - List containerItems = null; + void request(final MECraftingInventory inv, final long amountOfTimes, final IActionSource src) throws CraftBranchFailure, InterruptedException { + addProcess(); + this.job.handlePausing(); + List containerItems = null; - // request and remove inputs... - for( final Entry entry : this.nodes.object2LongEntrySet() ) - { - final IAEItemStack stack = entry.getKey().request( inv, entry.getValue() * amountOfTimes, src ); + // request and remove inputs... + for (final Entry entry : this.nodes.object2LongEntrySet()) { + final IAEItemStack stack = entry.getKey().request(inv, entry.getValue() * amountOfTimes, src); - if( this.details.isCraftable() && stack.getItem().hasContainerItem( stack.getDefinition() ) ) - { - final ItemStack is = Platform.getContainerItem( stack.createItemStack() ); - final IAEItemStack o = AEItemStack.fromItemStack( is ); - if( o != null ) - { - if( containerItems == null ) - { - containerItems = new ArrayList<>(); - } - this.bytes++; - o.setCachedItemStack( is ); - containerItems.add( o ); - } - } - } + if (this.details.isCraftable() && stack.getItem().hasContainerItem(stack.getDefinition())) { + final ItemStack is = Platform.getContainerItem(stack.createItemStack()); + final IAEItemStack o = AEItemStack.fromItemStack(is); + if (o != null) { + if (containerItems == null) { + containerItems = new ArrayList<>(); + } + this.bytes++; + o.setCachedItemStack(is); + containerItems.add(o); + } + } + } - if( containerItems != null ) - { - for( IAEItemStack i : containerItems ) - { - inv.injectItems( i, Actionable.MODULATE, src ); - } - } + if (containerItems != null) { + for (IAEItemStack i : containerItems) { + inv.injectItems(i, Actionable.MODULATE, src); + } + } - // assume its possible. + // assume its possible. - // add crafting results.. - for( final IAEItemStack out : this.details.getCondensedOutputs() ) - { - final IAEItemStack o = out.copy(); - o.setStackSize( o.getStackSize() * amountOfTimes ); - inv.injectItems( o, Actionable.MODULATE, src ); - } - this.crafts += amountOfTimes; - } + // add crafting results.. + for (final IAEItemStack out : this.details.getCondensedOutputs()) { + final IAEItemStack o = out.copy(); + o.setStackSize(o.getStackSize() * amountOfTimes); + inv.injectItems(o, Actionable.MODULATE, src); + } + this.crafts += amountOfTimes; + } - void dive( final CraftingJob job ) - { - job.addTask( this.getAmountCrafted( this.parent.getStack( 1 ) ), this.crafts, this.details, this.depth ); - for( final Entry entry : this.nodes.object2LongEntrySet() ) - { - entry.getKey().dive( job ); - } + void dive(final CraftingJob job) { + job.addTask(this.getAmountCrafted(this.parent.getStack(1)), this.crafts, this.details, this.depth); + for (final Entry entry : this.nodes.object2LongEntrySet()) { + entry.getKey().dive(job); + } - job.addBytes( this.crafts * 8 + this.bytes ); - } + job.addBytes(this.crafts * 8 + this.bytes); + } - IAEItemStack getAmountCrafted( IAEItemStack what2 ) - { - for( final IAEItemStack is : this.details.getCondensedOutputs() ) - { - if( is.isSameType( what2 ) ) - { - what2 = what2.copy(); - what2.setStackSize( is.getStackSize() ); - return what2; - } - } + IAEItemStack getAmountCrafted(IAEItemStack what2) { + for (final IAEItemStack is : this.details.getCondensedOutputs()) { + if (is.isSameType(what2)) { + what2 = what2.copy(); + what2.setStackSize(is.getStackSize()); + return what2; + } + } - // more fuzzy! - for( final IAEItemStack is : this.details.getCondensedOutputs() ) - { - if( is.getItem() == what2.getItem() && ( is.getItem().isDamageable() || is.getItemDamage() == what2.getItemDamage() ) ) - { - what2 = is.copy(); - what2.setStackSize( is.getStackSize() ); - return what2; - } - } + // more fuzzy! + for (final IAEItemStack is : this.details.getCondensedOutputs()) { + if (is.getItem() == what2.getItem() && (is.getItem().isDamageable() || is.getItemDamage() == what2.getItemDamage())) { + what2 = is.copy(); + what2.setStackSize(is.getStackSize()); + return what2; + } + } - throw new IllegalStateException( "Crafting Tree construction failed." ); - } + throw new IllegalStateException("Crafting Tree construction failed."); + } - void setSimulate() - { - this.crafts = 0; - this.bytes = 0; + void setSimulate() { + this.crafts = 0; + this.bytes = 0; - for( final Entry entry : this.nodes.object2LongEntrySet() ) - { - entry.getKey().setSimulate(); - } - } + for (final Entry entry : this.nodes.object2LongEntrySet()) { + entry.getKey().setSimulate(); + } + } - void setJob( final MECraftingInventory storage, final CraftingCPUCluster craftingCPUCluster, final IActionSource src ) throws CraftBranchFailure - { - craftingCPUCluster.addCrafting( this.details, this.crafts ); + void setJob(final MECraftingInventory storage, final CraftingCPUCluster craftingCPUCluster, final IActionSource src) throws CraftBranchFailure { + craftingCPUCluster.addCrafting(this.details, this.crafts); - for( final Entry entry : this.nodes.object2LongEntrySet() ) - { - entry.getKey().setJob( storage, craftingCPUCluster, src ); - } - } + for (final Entry entry : this.nodes.object2LongEntrySet()) { + entry.getKey().setJob(storage, craftingCPUCluster, src); + } + } - void getPlan( final IItemList plan ) - { - for( IAEItemStack i : this.details.getOutputs() ) - { - i = i.copy(); - i.setCountRequestable( i.getStackSize() * this.crafts ); - plan.addRequestable( i ); - } + void getPlan(final IItemList plan) { + for (IAEItemStack i : this.details.getOutputs()) { + i = i.copy(); + i.setCountRequestable(i.getStackSize() * this.crafts); + plan.addRequestable(i); + } - for( final Entry entry : this.nodes.object2LongEntrySet() ) - { - entry.getKey().getPlan( plan ); - } - } + for (final Entry entry : this.nodes.object2LongEntrySet()) { + entry.getKey().getPlan(plan); + } + } } diff --git a/src/main/java/appeng/crafting/CraftingWatcher.java b/src/main/java/appeng/crafting/CraftingWatcher.java index 45e9ccd03..3c9fe6cfa 100644 --- a/src/main/java/appeng/crafting/CraftingWatcher.java +++ b/src/main/java/appeng/crafting/CraftingWatcher.java @@ -19,63 +19,55 @@ package appeng.crafting; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - import appeng.api.networking.crafting.ICraftingWatcher; import appeng.api.networking.crafting.ICraftingWatcherHost; import appeng.api.storage.data.IAEStack; import appeng.me.cache.CraftingGridCache; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + /** * Maintain my interests, and a global watch list, they should always be fully synchronized. */ -public class CraftingWatcher implements ICraftingWatcher -{ +public class CraftingWatcher implements ICraftingWatcher { - private final CraftingGridCache gsc; - private final ICraftingWatcherHost host; - private final Set myInterests = new HashSet<>(); + private final CraftingGridCache gsc; + private final ICraftingWatcherHost host; + private final Set myInterests = new HashSet<>(); - public CraftingWatcher( final CraftingGridCache cache, final ICraftingWatcherHost host ) - { - this.gsc = cache; - this.host = host; - } + public CraftingWatcher(final CraftingGridCache cache, final ICraftingWatcherHost host) { + this.gsc = cache; + this.host = host; + } - public ICraftingWatcherHost getHost() - { - return this.host; - } + public ICraftingWatcherHost getHost() { + return this.host; + } - @Override - public boolean add( final IAEStack e ) - { - if( this.myInterests.contains( e ) ) - { - return false; - } + @Override + public boolean add(final IAEStack e) { + if (this.myInterests.contains(e)) { + return false; + } - return this.myInterests.add( e.copy() ) && this.gsc.getInterestManager().put( e, this ); - } + return this.myInterests.add(e.copy()) && this.gsc.getInterestManager().put(e, this); + } - @Override - public boolean remove( final IAEStack o ) - { - return this.myInterests.remove( o ) && this.gsc.getInterestManager().remove( o, this ); - } + @Override + public boolean remove(final IAEStack o) { + return this.myInterests.remove(o) && this.gsc.getInterestManager().remove(o, this); + } - @Override - public void reset() - { - final Iterator i = this.myInterests.iterator(); + @Override + public void reset() { + final Iterator i = this.myInterests.iterator(); - while( i.hasNext() ) - { - this.gsc.getInterestManager().remove( i.next(), this ); - i.remove(); - } - } + while (i.hasNext()) { + this.gsc.getInterestManager().remove(i.next(), this); + i.remove(); + } + } } diff --git a/src/main/java/appeng/crafting/MECraftingInventory.java b/src/main/java/appeng/crafting/MECraftingInventory.java index a5d98dcb4..dc8f00771 100644 --- a/src/main/java/appeng/crafting/MECraftingInventory.java +++ b/src/main/java/appeng/crafting/MECraftingInventory.java @@ -32,365 +32,289 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketInformPlayer; import appeng.util.inv.ItemListIgnoreCrafting; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.util.text.TextComponentString; import java.io.IOException; -public class MECraftingInventory implements IMEInventory -{ +public class MECraftingInventory implements IMEInventory { - private final MECraftingInventory par; + private final MECraftingInventory par; - private final IMEInventory target; - private final IItemList localCache; + private final IMEInventory target; + private final IItemList localCache; - private final boolean logExtracted; - private final IItemList extractedCache; + private final boolean logExtracted; + private final IItemList extractedCache; - private final boolean logInjections; - private final IItemList injectedCache; + private final boolean logInjections; + private final IItemList injectedCache; - private final boolean logMissing; - private final IItemList missingCache; + private final boolean logMissing; + private final IItemList missingCache; - public MECraftingInventory() - { - this.localCache = new ItemListIgnoreCrafting<>( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList() ); - this.extractedCache = null; - this.injectedCache = null; - this.missingCache = null; - this.logExtracted = false; - this.logInjections = false; - this.logMissing = false; - this.target = null; - this.par = null; - } + public MECraftingInventory() { + this.localCache = new ItemListIgnoreCrafting<>(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList()); + this.extractedCache = null; + this.injectedCache = null; + this.missingCache = null; + this.logExtracted = false; + this.logInjections = false; + this.logMissing = false; + this.target = null; + this.par = null; + } - public MECraftingInventory( final MECraftingInventory parent ) - { - this.target = parent; - this.logExtracted = parent.logExtracted; - this.logInjections = parent.logInjections; - this.logMissing = parent.logMissing; + public MECraftingInventory(final MECraftingInventory parent) { + this.target = parent; + this.logExtracted = parent.logExtracted; + this.logInjections = parent.logInjections; + this.logMissing = parent.logMissing; - if( this.logMissing ) - { - this.missingCache = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - } - else - { - this.missingCache = null; - } + if (this.logMissing) { + this.missingCache = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + } else { + this.missingCache = null; + } - if( this.logExtracted ) - { - this.extractedCache = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - } - else - { - this.extractedCache = null; - } + if (this.logExtracted) { + this.extractedCache = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + } else { + this.extractedCache = null; + } - if( this.logInjections ) - { - this.injectedCache = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - } - else - { - this.injectedCache = null; - } + if (this.logInjections) { + this.injectedCache = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + } else { + this.injectedCache = null; + } - this.localCache = this.target.getAvailableItems( new ItemListIgnoreCrafting<>( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList() ) ); + this.localCache = this.target.getAvailableItems(new ItemListIgnoreCrafting<>(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList())); - this.par = parent; - } + this.par = parent; + } - public MECraftingInventory( final IMEMonitor target, final IActionSource src, final boolean logExtracted, final boolean logInjections, final boolean logMissing ) - { - this.target = target; - this.logExtracted = logExtracted; - this.logInjections = logInjections; - this.logMissing = logMissing; + public MECraftingInventory(final IMEMonitor target, final IActionSource src, final boolean logExtracted, final boolean logInjections, final boolean logMissing) { + this.target = target; + this.logExtracted = logExtracted; + this.logInjections = logInjections; + this.logMissing = logMissing; - if( logMissing ) - { - this.missingCache = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - } - else - { - this.missingCache = null; - } + if (logMissing) { + this.missingCache = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + } else { + this.missingCache = null; + } - if( logExtracted ) - { - this.extractedCache = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - } - else - { - this.extractedCache = null; - } + if (logExtracted) { + this.extractedCache = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + } else { + this.extractedCache = null; + } - if( logInjections ) - { - this.injectedCache = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - } - else - { - this.injectedCache = null; - } + if (logInjections) { + this.injectedCache = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + } else { + this.injectedCache = null; + } - this.localCache = new ItemListIgnoreCrafting<>( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList() ); - for( final IAEItemStack is : target.getStorageList() ) - { - this.localCache.add( target.extractItems( is, Actionable.SIMULATE, src ) ); - } + this.localCache = new ItemListIgnoreCrafting<>(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList()); + for (final IAEItemStack is : target.getStorageList()) { + this.localCache.add(target.extractItems(is, Actionable.SIMULATE, src)); + } - this.par = null; - } + this.par = null; + } - public MECraftingInventory( final IMEInventory target, final boolean logExtracted, final boolean logInjections, final boolean logMissing ) - { - this.target = target; - this.logExtracted = logExtracted; - this.logInjections = logInjections; - this.logMissing = logMissing; + public MECraftingInventory(final IMEInventory target, final boolean logExtracted, final boolean logInjections, final boolean logMissing) { + this.target = target; + this.logExtracted = logExtracted; + this.logInjections = logInjections; + this.logMissing = logMissing; - if( logMissing ) - { - this.missingCache = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - } - else - { - this.missingCache = null; - } + if (logMissing) { + this.missingCache = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + } else { + this.missingCache = null; + } - if( logExtracted ) - { - this.extractedCache = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - } - else - { - this.extractedCache = null; - } + if (logExtracted) { + this.extractedCache = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + } else { + this.extractedCache = null; + } - if( logInjections ) - { - this.injectedCache = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - } - else - { - this.injectedCache = null; - } + if (logInjections) { + this.injectedCache = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + } else { + this.injectedCache = null; + } - this.localCache = target.getAvailableItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList() ); - this.par = null; - } + this.localCache = target.getAvailableItems(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList()); + this.par = null; + } - public MECraftingInventory( final IItemList itemList ) - { - this.localCache = new ItemListIgnoreCrafting<>( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList() ); - this.target = null; - this.logExtracted = false; - this.logInjections = false; - this.logMissing = false; - this.missingCache = null; - this.extractedCache = null; - this.injectedCache = null; + public MECraftingInventory(final IItemList itemList) { + this.localCache = new ItemListIgnoreCrafting<>(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList()); + this.target = null; + this.logExtracted = false; + this.logInjections = false; + this.logMissing = false; + this.missingCache = null; + this.extractedCache = null; + this.injectedCache = null; - for( IAEItemStack iaeItemStack : itemList ) - { - this.localCache.add( iaeItemStack ); - } + for (IAEItemStack iaeItemStack : itemList) { + this.localCache.add(iaeItemStack); + } - this.par = null; - } + this.par = null; + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final IActionSource src ) - { - if( input == null ) - { - return null; - } + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, final IActionSource src) { + if (input == null) { + return null; + } - if( mode == Actionable.MODULATE ) - { - if( this.logInjections ) - { - this.injectedCache.add( input ); - } - this.localCache.add( input ); - } + if (mode == Actionable.MODULATE) { + if (this.logInjections) { + this.injectedCache.add(input); + } + this.localCache.add(input); + } - return null; - } + return null; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final IActionSource src ) - { - if( request == null ) - { - return null; - } + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final IActionSource src) { + if (request == null) { + return null; + } - final IAEItemStack list = this.localCache.findPrecise( request ); - if( list == null || list.getStackSize() == 0 ) - { - return null; - } + final IAEItemStack list = this.localCache.findPrecise(request); + if (list == null || list.getStackSize() == 0) { + return null; + } - if( list.getStackSize() >= request.getStackSize() ) - { - if( mode == Actionable.MODULATE ) - { - list.decStackSize( request.getStackSize() ); - if( this.logExtracted ) - { - this.extractedCache.add( request ); - } - } + if (list.getStackSize() >= request.getStackSize()) { + if (mode == Actionable.MODULATE) { + list.decStackSize(request.getStackSize()); + if (this.logExtracted) { + this.extractedCache.add(request); + } + } - return request; - } + return request; + } - final IAEItemStack ret = request.copy(); - ret.setStackSize( list.getStackSize() ); + final IAEItemStack ret = request.copy(); + ret.setStackSize(list.getStackSize()); - if( mode == Actionable.MODULATE ) - { - list.reset(); - if( this.logExtracted ) - { - this.extractedCache.add( ret ); - } - } + if (mode == Actionable.MODULATE) { + list.reset(); + if (this.logExtracted) { + this.extractedCache.add(ret); + } + } - return ret; - } + return ret; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final IAEItemStack is : this.localCache ) - { - out.add( is ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final IAEItemStack is : this.localCache) { + out.add(is); + } - return out; - } + return out; + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } - public IItemList getItemList() - { - return this.localCache; - } + public IItemList getItemList() { + return this.localCache; + } - public boolean commit( final IActionSource src ) - { - final IItemList added = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - final IItemList pulled = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - boolean failed = false; + public boolean commit(final IActionSource src) { + final IItemList added = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + final IItemList pulled = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + boolean failed = false; - if( this.logInjections ) - { - for( final IAEItemStack inject : this.injectedCache ) - { - IAEItemStack result = null; - added.add( result = this.target.injectItems( inject, Actionable.MODULATE, src ) ); + if (this.logInjections) { + for (final IAEItemStack inject : this.injectedCache) { + IAEItemStack result = null; + added.add(result = this.target.injectItems(inject, Actionable.MODULATE, src)); - if( result != null ) - { - failed = true; - break; - } - } - } + if (result != null) { + failed = true; + break; + } + } + } - if( failed ) - { - for( final IAEItemStack is : added ) - { - this.target.extractItems( is, Actionable.MODULATE, src ); - } + if (failed) { + for (final IAEItemStack is : added) { + this.target.extractItems(is, Actionable.MODULATE, src); + } - return false; - } + return false; + } - if( this.logExtracted ) - { - for( final IAEItemStack extra : this.extractedCache ) - { - IAEItemStack result = null; - pulled.add( result = this.target.extractItems( extra, Actionable.MODULATE, src ) ); + if (this.logExtracted) { + for (final IAEItemStack extra : this.extractedCache) { + IAEItemStack result = null; + pulled.add(result = this.target.extractItems(extra, Actionable.MODULATE, src)); - if( result == null || result.getStackSize() != extra.getStackSize() ) - { - if( src.player().isPresent() ) - { - try - { - if( result == null ) - { - NetworkHandler.instance().sendTo( new PacketInformPlayer( extra, null, PacketInformPlayer.InfoType.NO_ITEMS_EXTRACTED ), (EntityPlayerMP) src.player().get() ); - } - else - { - NetworkHandler.instance().sendTo( new PacketInformPlayer( extra, result, PacketInformPlayer.InfoType.PARTIAL_ITEM_EXTRACTION ), (EntityPlayerMP) src.player().get() ); - } - } - catch( IOException e ) - { - e.printStackTrace(); - } - } - failed = true; - } - } - } + if (result == null || result.getStackSize() != extra.getStackSize()) { + if (src.player().isPresent()) { + try { + if (result == null) { + NetworkHandler.instance().sendTo(new PacketInformPlayer(extra, null, PacketInformPlayer.InfoType.NO_ITEMS_EXTRACTED), (EntityPlayerMP) src.player().get()); + } else { + NetworkHandler.instance().sendTo(new PacketInformPlayer(extra, result, PacketInformPlayer.InfoType.PARTIAL_ITEM_EXTRACTION), (EntityPlayerMP) src.player().get()); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + failed = true; + } + } + } - if( failed ) - { - for( final IAEItemStack is : added ) - { - this.target.extractItems( is, Actionable.MODULATE, src ); - } + if (failed) { + for (final IAEItemStack is : added) { + this.target.extractItems(is, Actionable.MODULATE, src); + } - for( final IAEItemStack is : pulled ) - { - this.target.injectItems( is, Actionable.MODULATE, src ); - } + for (final IAEItemStack is : pulled) { + this.target.injectItems(is, Actionable.MODULATE, src); + } - return false; - } + return false; + } - if( this.logMissing && this.par != null ) - { - for( final IAEItemStack extra : this.missingCache ) - { - this.par.addMissing( extra ); - } - } + if (this.logMissing && this.par != null) { + for (final IAEItemStack extra : this.missingCache) { + this.par.addMissing(extra); + } + } - return true; - } + return true; + } - private void addMissing( final IAEItemStack extra ) - { - this.missingCache.add( extra ); - } + private void addMissing(final IAEItemStack extra) { + this.missingCache.add(extra); + } - void ignore( final IAEItemStack what ) - { - final IAEItemStack list = this.localCache.findPrecise( what ); - if( list != null ) - { - list.setStackSize( 0 ); - } - } + void ignore(final IAEItemStack what) { + final IAEItemStack list = this.localCache.findPrecise(what); + if (list != null) { + list.setStackSize(0); + } + } } diff --git a/src/main/java/appeng/debug/BlockChunkloader.java b/src/main/java/appeng/debug/BlockChunkloader.java index f3e2836da..4d5e1c6f1 100644 --- a/src/main/java/appeng/debug/BlockChunkloader.java +++ b/src/main/java/appeng/debug/BlockChunkloader.java @@ -19,31 +19,27 @@ package appeng.debug; -import java.util.List; - +import appeng.block.AEBaseTileBlock; +import appeng.core.AppEng; import net.minecraft.block.material.Material; import net.minecraft.world.World; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.ForgeChunkManager.LoadingCallback; import net.minecraftforge.common.ForgeChunkManager.Ticket; -import appeng.block.AEBaseTileBlock; -import appeng.core.AppEng; +import java.util.List; -public class BlockChunkloader extends AEBaseTileBlock implements LoadingCallback -{ +public class BlockChunkloader extends AEBaseTileBlock implements LoadingCallback { - public BlockChunkloader() - { - super( Material.IRON ); - ForgeChunkManager.setForcedChunkLoadingCallback( AppEng.instance(), this ); - } + public BlockChunkloader() { + super(Material.IRON); + ForgeChunkManager.setForcedChunkLoadingCallback(AppEng.instance(), this); + } - @Override - public void ticketsLoaded( final List tickets, final World world ) - { + @Override + public void ticketsLoaded(final List tickets, final World world) { - } + } } diff --git a/src/main/java/appeng/debug/BlockCubeGenerator.java b/src/main/java/appeng/debug/BlockCubeGenerator.java index bd0583b7e..af666092c 100644 --- a/src/main/java/appeng/debug/BlockCubeGenerator.java +++ b/src/main/java/appeng/debug/BlockCubeGenerator.java @@ -19,8 +19,7 @@ package appeng.debug; -import javax.annotation.Nullable; - +import appeng.block.AEBaseTileBlock; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -29,27 +28,23 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.block.AEBaseTileBlock; +import javax.annotation.Nullable; -public class BlockCubeGenerator extends AEBaseTileBlock -{ +public class BlockCubeGenerator extends AEBaseTileBlock { - public BlockCubeGenerator() - { - super( Material.IRON ); - } + public BlockCubeGenerator() { + super(Material.IRON); + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - final TileCubeGenerator tcg = this.getTileEntity( w, pos ); - if( tcg != null ) - { - tcg.click( player ); - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + final TileCubeGenerator tcg = this.getTileEntity(w, pos); + if (tcg != null) { + tcg.click(player); + } - return true; - } + return true; + } } diff --git a/src/main/java/appeng/debug/BlockEnergyGenerator.java b/src/main/java/appeng/debug/BlockEnergyGenerator.java index 6aca39706..fd134694a 100644 --- a/src/main/java/appeng/debug/BlockEnergyGenerator.java +++ b/src/main/java/appeng/debug/BlockEnergyGenerator.java @@ -19,17 +19,14 @@ package appeng.debug; +import appeng.block.AEBaseTileBlock; import net.minecraft.block.material.Material; -import appeng.block.AEBaseTileBlock; +public class BlockEnergyGenerator extends AEBaseTileBlock { -public class BlockEnergyGenerator extends AEBaseTileBlock -{ - - public BlockEnergyGenerator() - { - super( Material.IRON ); - } + public BlockEnergyGenerator() { + super(Material.IRON); + } } diff --git a/src/main/java/appeng/debug/BlockItemGen.java b/src/main/java/appeng/debug/BlockItemGen.java index 59401b8a3..42b4781cd 100644 --- a/src/main/java/appeng/debug/BlockItemGen.java +++ b/src/main/java/appeng/debug/BlockItemGen.java @@ -19,17 +19,14 @@ package appeng.debug; +import appeng.block.AEBaseTileBlock; import net.minecraft.block.material.Material; -import appeng.block.AEBaseTileBlock; +public class BlockItemGen extends AEBaseTileBlock { -public class BlockItemGen extends AEBaseTileBlock -{ - - public BlockItemGen() - { - super( Material.IRON ); - } + public BlockItemGen() { + super(Material.IRON); + } } diff --git a/src/main/java/appeng/debug/BlockPhantomNode.java b/src/main/java/appeng/debug/BlockPhantomNode.java index 88a8a14b6..75dc89317 100644 --- a/src/main/java/appeng/debug/BlockPhantomNode.java +++ b/src/main/java/appeng/debug/BlockPhantomNode.java @@ -19,8 +19,7 @@ package appeng.debug; -import javax.annotation.Nullable; - +import appeng.block.AEBaseTileBlock; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -29,23 +28,20 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.block.AEBaseTileBlock; +import javax.annotation.Nullable; -public class BlockPhantomNode extends AEBaseTileBlock -{ +public class BlockPhantomNode extends AEBaseTileBlock { - public BlockPhantomNode() - { - super( Material.IRON ); - } + public BlockPhantomNode() { + super(Material.IRON); + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - final TilePhantomNode tpn = this.getTileEntity( w, pos ); - tpn.triggerCrashMode(); - return true; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer player, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + final TilePhantomNode tpn = this.getTileEntity(w, pos); + tpn.triggerCrashMode(); + return true; + } } diff --git a/src/main/java/appeng/debug/TileChunkLoader.java b/src/main/java/appeng/debug/TileChunkLoader.java index 0fcb5e7c2..ef26df4d8 100644 --- a/src/main/java/appeng/debug/TileChunkLoader.java +++ b/src/main/java/appeng/debug/TileChunkLoader.java @@ -19,8 +19,10 @@ package appeng.debug; -import java.util.List; - +import appeng.core.AELog; +import appeng.core.AppEng; +import appeng.tile.AEBaseTile; +import appeng.util.Platform; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.ITickable; @@ -31,64 +33,51 @@ import net.minecraftforge.common.ForgeChunkManager.Ticket; import net.minecraftforge.common.ForgeChunkManager.Type; import net.minecraftforge.fml.common.FMLCommonHandler; -import appeng.core.AELog; -import appeng.core.AppEng; -import appeng.tile.AEBaseTile; -import appeng.util.Platform; +import java.util.List; -public class TileChunkLoader extends AEBaseTile implements ITickable -{ +public class TileChunkLoader extends AEBaseTile implements ITickable { - private boolean requestTicket = true; - private Ticket ct = null; + private boolean requestTicket = true; + private Ticket ct = null; - @Override - public void update() - { - if( this.requestTicket ) - { - this.requestTicket = false; - this.initTicket(); - } - } + @Override + public void update() { + if (this.requestTicket) { + this.requestTicket = false; + this.initTicket(); + } + } - private void initTicket() - { - if( Platform.isClient() ) - { - return; - } + private void initTicket() { + if (Platform.isClient()) { + return; + } - this.ct = ForgeChunkManager.requestTicket( AppEng.instance(), this.world, Type.NORMAL ); + this.ct = ForgeChunkManager.requestTicket(AppEng.instance(), this.world, Type.NORMAL); - if( this.ct == null ) - { - final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - if( server != null ) - { - final List pl = server.getPlayerList().getPlayers(); - for( final EntityPlayerMP p : pl ) - { - p.sendMessage( new TextComponentString( "Can't chunk load.." ) ); - } - } - return; - } + if (this.ct == null) { + final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + if (server != null) { + final List pl = server.getPlayerList().getPlayers(); + for (final EntityPlayerMP p : pl) { + p.sendMessage(new TextComponentString("Can't chunk load..")); + } + } + return; + } - AELog.info( "New Ticket " + this.ct.toString() ); - ForgeChunkManager.forceChunk( this.ct, new ChunkPos( this.pos.getX() >> 4, this.pos.getZ() >> 4 ) ); - } + AELog.info("New Ticket " + this.ct); + ForgeChunkManager.forceChunk(this.ct, new ChunkPos(this.pos.getX() >> 4, this.pos.getZ() >> 4)); + } - @Override - public void invalidate() - { - if( Platform.isClient() ) - { - return; - } + @Override + public void invalidate() { + if (Platform.isClient()) { + return; + } - AELog.info( "Released Ticket " + this.ct.toString() ); - ForgeChunkManager.releaseTicket( this.ct ); - } + AELog.info("Released Ticket " + this.ct.toString()); + ForgeChunkManager.releaseTicket(this.ct); + } } diff --git a/src/main/java/appeng/debug/TileCubeGenerator.java b/src/main/java/appeng/debug/TileCubeGenerator.java index 23b6b1816..15b133cb1 100644 --- a/src/main/java/appeng/debug/TileCubeGenerator.java +++ b/src/main/java/appeng/debug/TileCubeGenerator.java @@ -19,6 +19,9 @@ package appeng.debug; +import appeng.core.AppEng; +import appeng.tile.AEBaseTile; +import appeng.util.Platform; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -28,99 +31,75 @@ import net.minecraft.util.ITickable; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentString; -import appeng.core.AppEng; -import appeng.tile.AEBaseTile; -import appeng.util.Platform; +public class TileCubeGenerator extends AEBaseTile implements ITickable { -public class TileCubeGenerator extends AEBaseTile implements ITickable -{ + private int size = 3; + private ItemStack is = ItemStack.EMPTY; + private int countdown = 20 * 10; + private EntityPlayer who = null; - private int size = 3; - private ItemStack is = ItemStack.EMPTY; - private int countdown = 20 * 10; - private EntityPlayer who = null; + @Override + public void update() { + if (!this.is.isEmpty() && Platform.isServer()) { + this.countdown--; - @Override - public void update() - { - if( !this.is.isEmpty() && Platform.isServer() ) - { - this.countdown--; + if (this.countdown % 20 == 0) { + for (final EntityPlayer e : AppEng.proxy.getPlayers()) { + e.sendMessage(new TextComponentString("Spawning in... " + (this.countdown / 20))); + } + } - if( this.countdown % 20 == 0 ) - { - for( final EntityPlayer e : AppEng.proxy.getPlayers() ) - { - e.sendMessage( new TextComponentString( "Spawning in... " + ( this.countdown / 20 ) ) ); - } - } + if (this.countdown <= 0) { + this.spawn(); + } + } + } - if( this.countdown <= 0 ) - { - this.spawn(); - } - } - } + private void spawn() { + this.world.setBlockToAir(this.pos); - private void spawn() - { - this.world.setBlockToAir( this.pos ); + final Item i = this.is.getItem(); + final EnumFacing side = EnumFacing.UP; - final Item i = this.is.getItem(); - final EnumFacing side = EnumFacing.UP; + final int half = (int) Math.floor(this.size / 2); - final int half = (int) Math.floor( this.size / 2 ); + for (int y = 0; y < this.size; y++) { + for (int x = -half; x < half; x++) { + for (int z = -half; z < half; z++) { + final BlockPos p = this.pos.add(x, y - 1, z); + i.onItemUse(this.who, this.world, p, EnumHand.MAIN_HAND, side, 0.5f, 0.0f, 0.5f); + } + } + } + } - for( int y = 0; y < this.size; y++ ) - { - for( int x = -half; x < half; x++ ) - { - for( int z = -half; z < half; z++ ) - { - final BlockPos p = this.pos.add( x, y - 1, z ); - i.onItemUse( this.who, this.world, p, EnumHand.MAIN_HAND, side, 0.5f, 0.0f, 0.5f ); - } - } - } - } + void click(final EntityPlayer player) { + if (Platform.isServer()) { + final ItemStack hand = player.inventory.getCurrentItem(); + this.who = player; - void click( final EntityPlayer player ) - { - if( Platform.isServer() ) - { - final ItemStack hand = player.inventory.getCurrentItem(); - this.who = player; + if (hand.isEmpty()) { + this.is = ItemStack.EMPTY; - if( hand.isEmpty() ) - { - this.is = ItemStack.EMPTY; + if (player.isSneaking()) { + this.size--; + } else { + this.size++; + } - if( player.isSneaking() ) - { - this.size--; - } - else - { - this.size++; - } + if (this.size < 3) { + this.size = 3; + } + if (this.size > 64) { + this.size = 64; + } - if( this.size < 3 ) - { - this.size = 3; - } - if( this.size > 64 ) - { - this.size = 64; - } - - player.sendMessage( new TextComponentString( "Size: " + this.size ) ); - } - else - { - this.countdown = 20 * 10; - this.is = hand; - } - } - } + player.sendMessage(new TextComponentString("Size: " + this.size)); + } else { + this.countdown = 20 * 10; + this.is = hand; + } + } + } } diff --git a/src/main/java/appeng/debug/TileEnergyGenerator.java b/src/main/java/appeng/debug/TileEnergyGenerator.java index ce78a78fc..b1f5ddd59 100644 --- a/src/main/java/appeng/debug/TileEnergyGenerator.java +++ b/src/main/java/appeng/debug/TileEnergyGenerator.java @@ -19,12 +19,8 @@ package appeng.debug; -import java.util.EnumSet; - -import javax.annotation.Nullable; - +import appeng.tile.AEBaseTile; import com.google.common.math.IntMath; - import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; @@ -32,108 +28,92 @@ import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.energy.CapabilityEnergy; import net.minecraftforge.energy.IEnergyStorage; -import appeng.tile.AEBaseTile; +import javax.annotation.Nullable; +import java.util.EnumSet; -public class TileEnergyGenerator extends AEBaseTile implements ITickable, IEnergyStorage -{ - /** - * The base energy injected each tick. - * Adjacent TileEnergyGenerators will increase it to pow(base, #generators). - */ - private static final int BASE_ENERGY = 8; +public class TileEnergyGenerator extends AEBaseTile implements ITickable, IEnergyStorage { + /** + * The base energy injected each tick. + * Adjacent TileEnergyGenerators will increase it to pow(base, #generators). + */ + private static final int BASE_ENERGY = 8; - @Override - public void update() - { - int tier = 1; - final EnumSet validEnergyReceivers = EnumSet.noneOf( EnumFacing.class ); + @Override + public void update() { + int tier = 1; + final EnumSet validEnergyReceivers = EnumSet.noneOf(EnumFacing.class); - for( EnumFacing facing : EnumFacing.values() ) - { - final TileEntity te = this.getWorld().getTileEntity( this.getPos().offset( facing ) ); + for (EnumFacing facing : EnumFacing.values()) { + final TileEntity te = this.getWorld().getTileEntity(this.getPos().offset(facing)); - if( te instanceof TileEnergyGenerator ) - { - tier++; - } + if (te instanceof TileEnergyGenerator) { + tier++; + } - if( te != null && te.hasCapability( CapabilityEnergy.ENERGY, facing.getOpposite() ) ) - { - validEnergyReceivers.add( facing ); - } + if (te != null && te.hasCapability(CapabilityEnergy.ENERGY, facing.getOpposite())) { + validEnergyReceivers.add(facing); + } - } + } - final int energyToInsert = IntMath.pow( BASE_ENERGY, tier ); + final int energyToInsert = IntMath.pow(BASE_ENERGY, tier); - for( EnumFacing facing : validEnergyReceivers ) - { - final TileEntity te = this.getWorld().getTileEntity( this.getPos().offset( facing ) ); - final IEnergyStorage cap = te.getCapability( CapabilityEnergy.ENERGY, facing.getOpposite() ); + for (EnumFacing facing : validEnergyReceivers) { + final TileEntity te = this.getWorld().getTileEntity(this.getPos().offset(facing)); + final IEnergyStorage cap = te.getCapability(CapabilityEnergy.ENERGY, facing.getOpposite()); - if( cap.canReceive() ) - { + if (cap.canReceive()) { - cap.receiveEnergy( energyToInsert, false ); - } - } - } + cap.receiveEnergy(energyToInsert, false); + } + } + } - @Override - public boolean hasCapability( Capability capability, @Nullable EnumFacing facing ) - { - if( capability == CapabilityEnergy.ENERGY ) - { - return true; - } - return super.hasCapability( capability, facing ); - } + @Override + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { + if (capability == CapabilityEnergy.ENERGY) { + return true; + } + return super.hasCapability(capability, facing); + } - @Override - @Nullable - public T getCapability( Capability capability, @Nullable EnumFacing facing ) - { - if( capability == CapabilityEnergy.ENERGY ) - { - return (T) this; - } - return super.getCapability( capability, facing ); - } + @Override + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { + if (capability == CapabilityEnergy.ENERGY) { + return (T) this; + } + return super.getCapability(capability, facing); + } - @Override - public int receiveEnergy( int maxReceive, boolean simulate ) - { - return 0; - } + @Override + public int receiveEnergy(int maxReceive, boolean simulate) { + return 0; + } - @Override - public int extractEnergy( int maxExtract, boolean simulate ) - { - return maxExtract; - } + @Override + public int extractEnergy(int maxExtract, boolean simulate) { + return maxExtract; + } - @Override - public int getEnergyStored() - { - return Integer.MAX_VALUE; - } + @Override + public int getEnergyStored() { + return Integer.MAX_VALUE; + } - @Override - public int getMaxEnergyStored() - { - return Integer.MAX_VALUE; - } + @Override + public int getMaxEnergyStored() { + return Integer.MAX_VALUE; + } - @Override - public boolean canExtract() - { - return true; - } + @Override + public boolean canExtract() { + return true; + } - @Override - public boolean canReceive() - { - return false; - } + @Override + public boolean canReceive() { + return false; + } } diff --git a/src/main/java/appeng/debug/TileItemGen.java b/src/main/java/appeng/debug/TileItemGen.java index 92819aedb..c32ac59fd 100644 --- a/src/main/java/appeng/debug/TileItemGen.java +++ b/src/main/java/appeng/debug/TileItemGen.java @@ -19,12 +19,7 @@ package appeng.debug; -import java.util.ArrayDeque; -import java.util.Queue; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - +import appeng.tile.AEBaseTile; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -34,113 +29,96 @@ import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; -import appeng.tile.AEBaseTile; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayDeque; +import java.util.Queue; -public class TileItemGen extends AEBaseTile -{ +public class TileItemGen extends AEBaseTile { - private static final Queue POSSIBLE_ITEMS = new ArrayDeque<>(); + private static final Queue POSSIBLE_ITEMS = new ArrayDeque<>(); - private final IItemHandler handler = new QueuedItemHandler(); + private final IItemHandler handler = new QueuedItemHandler(); - public TileItemGen() - { - if( POSSIBLE_ITEMS.isEmpty() ) - { - for( final Object obj : Item.REGISTRY ) - { - final Item mi = (Item) obj; - if( mi != null && mi != Items.AIR ) - { - if( mi.isDamageable() ) - { - for( int dmg = 0; dmg < mi.getMaxDamage(); dmg++ ) - { - POSSIBLE_ITEMS.add( new ItemStack( mi, 1, dmg ) ); - } - } - else - { - final NonNullList list = NonNullList.create(); - mi.getSubItems( mi.getCreativeTab(), list ); - POSSIBLE_ITEMS.addAll( list ); - } - } - } - } - } + public TileItemGen() { + if (POSSIBLE_ITEMS.isEmpty()) { + for (final Object obj : Item.REGISTRY) { + final Item mi = (Item) obj; + if (mi != null && mi != Items.AIR) { + if (mi.isDamageable()) { + for (int dmg = 0; dmg < mi.getMaxDamage(); dmg++) { + POSSIBLE_ITEMS.add(new ItemStack(mi, 1, dmg)); + } + } else { + final NonNullList list = NonNullList.create(); + mi.getSubItems(mi.getCreativeTab(), list); + POSSIBLE_ITEMS.addAll(list); + } + } + } + } + } - @Override - public boolean hasCapability( Capability capability, @Nullable EnumFacing facing ) - { - if( CapabilityItemHandler.ITEM_HANDLER_CAPABILITY == capability ) - { - return true; - } - return super.hasCapability( capability, facing ); - } + @Override + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { + if (CapabilityItemHandler.ITEM_HANDLER_CAPABILITY == capability) { + return true; + } + return super.hasCapability(capability, facing); + } - @Override - @Nullable - public T getCapability( Capability capability, @Nullable EnumFacing facing ) - { - if( CapabilityItemHandler.ITEM_HANDLER_CAPABILITY == capability ) - { - return (T) this.handler; - } - return super.getCapability( capability, facing ); - } + @Override + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { + if (CapabilityItemHandler.ITEM_HANDLER_CAPABILITY == capability) { + return (T) this.handler; + } + return super.getCapability(capability, facing); + } - class QueuedItemHandler implements IItemHandler - { + class QueuedItemHandler implements IItemHandler { - @Override - @Nonnull - public ItemStack insertItem( int slot, @Nonnull ItemStack stack, boolean simulate ) - { - return stack; - } + @Override + @Nonnull + public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) { + return stack; + } - @Override - @Nonnull - public ItemStack getStackInSlot( int slot ) - { - return POSSIBLE_ITEMS.peek() != null ? POSSIBLE_ITEMS.peek().copy() : ItemStack.EMPTY; - } + @Override + @Nonnull + public ItemStack getStackInSlot(int slot) { + return POSSIBLE_ITEMS.peek() != null ? POSSIBLE_ITEMS.peek().copy() : ItemStack.EMPTY; + } - @Override - public int getSlots() - { - return 1; - } + @Override + public int getSlots() { + return 1; + } - @Override - public int getSlotLimit( int slot ) - { - return 1; - } + @Override + public int getSlotLimit(int slot) { + return 1; + } - @Override - @Nonnull - public ItemStack extractItem( int slot, int amount, boolean simulate ) - { - final ItemStack is = POSSIBLE_ITEMS.peek(); + @Override + @Nonnull + public ItemStack extractItem(int slot, int amount, boolean simulate) { + final ItemStack is = POSSIBLE_ITEMS.peek(); - if( is == null ) - { - return ItemStack.EMPTY; - } + if (is == null) { + return ItemStack.EMPTY; + } - return simulate ? is.copy() : this.getNextItem(); - } + return simulate ? is.copy() : this.getNextItem(); + } - private ItemStack getNextItem() - { - final ItemStack is = POSSIBLE_ITEMS.poll(); + private ItemStack getNextItem() { + final ItemStack is = POSSIBLE_ITEMS.poll(); + + POSSIBLE_ITEMS.add(is); + return is.copy(); + } + } - POSSIBLE_ITEMS.add( is ); - return is.copy(); - } - }; } diff --git a/src/main/java/appeng/debug/TilePhantomNode.java b/src/main/java/appeng/debug/TilePhantomNode.java index 2e84c2fd6..b50ac0d58 100644 --- a/src/main/java/appeng/debug/TilePhantomNode.java +++ b/src/main/java/appeng/debug/TilePhantomNode.java @@ -19,48 +19,41 @@ package appeng.debug; -import java.util.EnumSet; - -import net.minecraft.util.EnumFacing; - import appeng.api.networking.IGridNode; import appeng.api.util.AEPartLocation; import appeng.me.helpers.AENetworkProxy; import appeng.tile.grid.AENetworkTile; +import net.minecraft.util.EnumFacing; + +import java.util.EnumSet; -public class TilePhantomNode extends AENetworkTile -{ +public class TilePhantomNode extends AENetworkTile { - private AENetworkProxy proxy = null; - private boolean crashMode = false; + private AENetworkProxy proxy = null; + private boolean crashMode = false; - @Override - public IGridNode getGridNode( final AEPartLocation dir ) - { - if( !this.crashMode ) - { - return super.getGridNode( dir ); - } + @Override + public IGridNode getGridNode(final AEPartLocation dir) { + if (!this.crashMode) { + return super.getGridNode(dir); + } - return this.proxy.getNode(); - } + return this.proxy.getNode(); + } - @Override - public void onReady() - { - super.onReady(); - this.proxy = this.createProxy(); - this.proxy.onReady(); - this.crashMode = true; - } + @Override + public void onReady() { + super.onReady(); + this.proxy = this.createProxy(); + this.proxy.onReady(); + this.crashMode = true; + } - void triggerCrashMode() - { - if( this.proxy != null ) - { - this.crashMode = true; - this.proxy.setValidSides( EnumSet.allOf( EnumFacing.class ) ); - } - } + void triggerCrashMode() { + if (this.proxy != null) { + this.crashMode = true; + this.proxy.setValidSides(EnumSet.allOf(EnumFacing.class)); + } + } } diff --git a/src/main/java/appeng/debug/ToolDebugCard.java b/src/main/java/appeng/debug/ToolDebugCard.java index 57c8e4767..d7ce97faa 100644 --- a/src/main/java/appeng/debug/ToolDebugCard.java +++ b/src/main/java/appeng/debug/ToolDebugCard.java @@ -19,19 +19,6 @@ package appeng.debug; -import java.util.HashSet; -import java.util.Set; - -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.world.World; - import appeng.api.networking.IGridConnection; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -51,172 +38,149 @@ import appeng.me.cache.TickManagerCache; import appeng.parts.p2p.PartP2PTunnel; import appeng.tile.networking.TileController; import appeng.util.Platform; +import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.world.World; + +import java.util.HashSet; +import java.util.Set; -public class ToolDebugCard extends AEBaseItem -{ - @Override - public EnumActionResult onItemUseFirst( final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand ) - { - if( Platform.isClient() ) - { - return EnumActionResult.PASS; - } +public class ToolDebugCard extends AEBaseItem { + @Override + public EnumActionResult onItemUseFirst(final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand) { + if (Platform.isClient()) { + return EnumActionResult.PASS; + } - if( player.isSneaking() ) - { - int grids = 0; - int totalNodes = 0; + if (player.isSneaking()) { + int grids = 0; + int totalNodes = 0; - for( final Grid g : TickHandler.INSTANCE.getGridList() ) - { - grids++; - totalNodes += g.getNodes().size(); - } + for (final Grid g : TickHandler.INSTANCE.getGridList()) { + grids++; + totalNodes += g.getNodes().size(); + } - this.outputMsg( player, "Grids: " + grids ); - this.outputMsg( player, "Total Nodes: " + totalNodes ); - } - else - { - final TileEntity te = world.getTileEntity( pos ); + this.outputMsg(player, "Grids: " + grids); + this.outputMsg(player, "Total Nodes: " + totalNodes); + } else { + final TileEntity te = world.getTileEntity(pos); - if( te instanceof IGridHost ) - { - final GridNode node = (GridNode) ( (IGridHost) te ).getGridNode( AEPartLocation.fromFacing( side ) ); - if( node != null ) - { - final Grid g = node.getInternalGrid(); - final IGridNode center = g.getPivot(); - this.outputMsg( player, "This Node: " + node.toString() ); - this.outputMsg( player, "Center Node: " + center.toString() ); + if (te instanceof IGridHost) { + final GridNode node = (GridNode) ((IGridHost) te).getGridNode(AEPartLocation.fromFacing(side)); + if (node != null) { + final Grid g = node.getInternalGrid(); + final IGridNode center = g.getPivot(); + this.outputMsg(player, "This Node: " + node); + this.outputMsg(player, "Center Node: " + center); - final IPathingGrid pg = g.getCache( IPathingGrid.class ); - if( pg.getControllerState() == ControllerState.CONTROLLER_ONLINE ) - { + final IPathingGrid pg = g.getCache(IPathingGrid.class); + if (pg.getControllerState() == ControllerState.CONTROLLER_ONLINE) { - Set next = new HashSet<>(); - next.add( node ); + Set next = new HashSet<>(); + next.add(node); - final int maxLength = 10000; + final int maxLength = 10000; - int length = 0; - outer: - while( !next.isEmpty() ) - { - final Iterable current = next; - next = new HashSet<>(); + int length = 0; + outer: + while (!next.isEmpty()) { + final Iterable current = next; + next = new HashSet<>(); - for( final IGridNode n : current ) - { - if( n.getMachine() instanceof TileController ) - { - break outer; - } + for (final IGridNode n : current) { + if (n.getMachine() instanceof TileController) { + break outer; + } - for( final IGridConnection c : n.getConnections() ) - { - next.add( c.getOtherSide( n ) ); - } - } + for (final IGridConnection c : n.getConnections()) { + next.add(c.getOtherSide(n)); + } + } - length++; + length++; - if( length > maxLength ) - { - break; - } - } + if (length > maxLength) { + break; + } + } - this.outputMsg( player, "Cable Distance: " + length ); - } + this.outputMsg(player, "Cable Distance: " + length); + } - if( center.getMachine() instanceof PartP2PTunnel ) - { - this.outputMsg( player, "Freq: " + ( (PartP2PTunnel) center.getMachine() ).getFrequency() ); - } + if (center.getMachine() instanceof PartP2PTunnel) { + this.outputMsg(player, "Freq: " + ((PartP2PTunnel) center.getMachine()).getFrequency()); + } - final TickManagerCache tmc = g.getCache( ITickManager.class ); - for( final Class c : g.getMachineClasses() ) - { - int o = 0; - long nanos = 0; - for( final IGridNode oj : g.getMachines( c ) ) - { - o++; - nanos += tmc.getAvgNanoTime( oj ); - } + final TickManagerCache tmc = g.getCache(ITickManager.class); + for (final Class c : g.getMachineClasses()) { + int o = 0; + long nanos = 0; + for (final IGridNode oj : g.getMachines(c)) { + o++; + nanos += tmc.getAvgNanoTime(oj); + } - if( nanos < 0 ) - { - this.outputMsg( player, c.getSimpleName() + " - " + o ); - } - else - { - this.outputMsg( player, c.getSimpleName() + " - " + o + "; " + this.timeMeasurement( nanos ) ); - } - } - } - else - { - this.outputMsg( player, "No Node Available." ); - } - } - else - { - this.outputMsg( player, "Not Networked Block" ); - } + if (nanos < 0) { + this.outputMsg(player, c.getSimpleName() + " - " + o); + } else { + this.outputMsg(player, c.getSimpleName() + " - " + o + "; " + this.timeMeasurement(nanos)); + } + } + } else { + this.outputMsg(player, "No Node Available."); + } + } else { + this.outputMsg(player, "Not Networked Block"); + } - if( te instanceof IPartHost ) - { - final IPart center = ( (IPartHost) te ).getPart( AEPartLocation.INTERNAL ); - ( (IPartHost) te ).markForUpdate(); - if( center != null ) - { - final GridNode n = (GridNode) center.getGridNode(); - this.outputMsg( player, "Node Channels: " + n.usedChannels() ); - for( final IGridConnection gc : n.getConnections() ) - { - final AEPartLocation fd = gc.getDirection( n ); - if( fd != AEPartLocation.INTERNAL ) - { - this.outputMsg( player, fd.toString() + ": " + gc.getUsedChannels() ); - } - } - } - } + if (te instanceof IPartHost) { + final IPart center = ((IPartHost) te).getPart(AEPartLocation.INTERNAL); + ((IPartHost) te).markForUpdate(); + if (center != null) { + final GridNode n = (GridNode) center.getGridNode(); + this.outputMsg(player, "Node Channels: " + n.usedChannels()); + for (final IGridConnection gc : n.getConnections()) { + final AEPartLocation fd = gc.getDirection(n); + if (fd != AEPartLocation.INTERNAL) { + this.outputMsg(player, fd + ": " + gc.getUsedChannels()); + } + } + } + } - if( te instanceof IAEPowerStorage ) - { - final IAEPowerStorage ps = (IAEPowerStorage) te; - this.outputMsg( player, "Energy: " + ps.getAECurrentPower() + " / " + ps.getAEMaxPower() ); + if (te instanceof IAEPowerStorage) { + final IAEPowerStorage ps = (IAEPowerStorage) te; + this.outputMsg(player, "Energy: " + ps.getAECurrentPower() + " / " + ps.getAEMaxPower()); - if( te instanceof IGridHost ) - { - final IGridNode node = ( (IGridHost) te ).getGridNode( AEPartLocation.fromFacing( side ) ); - if( node != null && node.getGrid() != null ) - { - final IEnergyGrid eg = node.getGrid().getCache( IEnergyGrid.class ); - this.outputMsg( player, "GridEnergy: " + eg.getStoredPower() + " : " + eg.getEnergyDemand( Double.MAX_VALUE ) ); - } - } - } - } - return EnumActionResult.SUCCESS; - } + if (te instanceof IGridHost) { + final IGridNode node = ((IGridHost) te).getGridNode(AEPartLocation.fromFacing(side)); + if (node != null && node.getGrid() != null) { + final IEnergyGrid eg = node.getGrid().getCache(IEnergyGrid.class); + this.outputMsg(player, "GridEnergy: " + eg.getStoredPower() + " : " + eg.getEnergyDemand(Double.MAX_VALUE)); + } + } + } + } + return EnumActionResult.SUCCESS; + } - private void outputMsg( final ICommandSender player, final String string ) - { - player.sendMessage( new TextComponentString( string ) ); - } + private void outputMsg(final ICommandSender player, final String string) { + player.sendMessage(new TextComponentString(string)); + } - private String timeMeasurement( final long nanos ) - { - final long ms = nanos / 100000; - if( nanos <= 100000 ) - { - return nanos + "ns"; - } - return ( ms / 10.0f ) + "ms"; - } + private String timeMeasurement(final long nanos) { + final long ms = nanos / 100000; + if (nanos <= 100000) { + return nanos + "ns"; + } + return (ms / 10.0f) + "ms"; + } } diff --git a/src/main/java/appeng/debug/ToolEraser.java b/src/main/java/appeng/debug/ToolEraser.java index 4d4f29f1b..7c2648ad1 100644 --- a/src/main/java/appeng/debug/ToolEraser.java +++ b/src/main/java/appeng/debug/ToolEraser.java @@ -19,9 +19,9 @@ package appeng.debug; -import java.util.ArrayList; -import java.util.List; - +import appeng.core.AELog; +import appeng.items.AEBaseItem; +import appeng.util.Platform; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumActionResult; @@ -30,56 +30,49 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.core.AELog; -import appeng.items.AEBaseItem; -import appeng.util.Platform; +import java.util.ArrayList; +import java.util.List; -public class ToolEraser extends AEBaseItem -{ +public class ToolEraser extends AEBaseItem { - private static final int BLOCK_ERASE_LIMIT = 90000; + private static final int BLOCK_ERASE_LIMIT = 90000; - @Override - public EnumActionResult onItemUseFirst( final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand ) - { - if( Platform.isClient() ) - { - return EnumActionResult.PASS; - } + @Override + public EnumActionResult onItemUseFirst(final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand) { + if (Platform.isClient()) { + return EnumActionResult.PASS; + } - final IBlockState state = world.getBlockState( pos ); + final IBlockState state = world.getBlockState(pos); - List next = new ArrayList<>(); - next.add( pos ); + List next = new ArrayList<>(); + next.add(pos); - int blocks = 0; - while( blocks < BLOCK_ERASE_LIMIT && !next.isEmpty() ) - { - final List c = next; - next = new ArrayList<>(); + int blocks = 0; + while (blocks < BLOCK_ERASE_LIMIT && !next.isEmpty()) { + final List c = next; + next = new ArrayList<>(); - for( final BlockPos wc : c ) - { - final IBlockState c_state = world.getBlockState( wc ); + for (final BlockPos wc : c) { + final IBlockState c_state = world.getBlockState(wc); - if( state == c_state ) - { - blocks++; - world.setBlockToAir( wc ); + if (state == c_state) { + blocks++; + world.setBlockToAir(wc); - next.add( wc.add( 1, 0, 0 ) ); - next.add( wc.add( -1, 0, 0 ) ); - next.add( wc.add( 0, 1, 0 ) ); - next.add( wc.add( 0, -1, 0 ) ); - next.add( wc.add( 0, 0, 1 ) ); - next.add( wc.add( 0, 0, -1 ) ); - } - } - } + next.add(wc.add(1, 0, 0)); + next.add(wc.add(-1, 0, 0)); + next.add(wc.add(0, 1, 0)); + next.add(wc.add(0, -1, 0)); + next.add(wc.add(0, 0, 1)); + next.add(wc.add(0, 0, -1)); + } + } + } - AELog.info( "Delete " + blocks + " blocks" ); + AELog.info("Delete " + blocks + " blocks"); - return EnumActionResult.SUCCESS; - } + return EnumActionResult.SUCCESS; + } } diff --git a/src/main/java/appeng/debug/ToolMeteoritePlacer.java b/src/main/java/appeng/debug/ToolMeteoritePlacer.java index af7dbecf2..a87f7e345 100644 --- a/src/main/java/appeng/debug/ToolMeteoritePlacer.java +++ b/src/main/java/appeng/debug/ToolMeteoritePlacer.java @@ -19,6 +19,10 @@ package appeng.debug; +import appeng.items.AEBaseItem; +import appeng.util.Platform; +import appeng.worldgen.MeteoritePlacer; +import appeng.worldgen.meteorite.StandardWorld; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; @@ -27,30 +31,21 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentString; import net.minecraft.world.World; -import appeng.items.AEBaseItem; -import appeng.util.Platform; -import appeng.worldgen.MeteoritePlacer; -import appeng.worldgen.meteorite.StandardWorld; +public class ToolMeteoritePlacer extends AEBaseItem { + @Override + public EnumActionResult onItemUseFirst(final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand) { + if (Platform.isClient()) { + return EnumActionResult.PASS; + } -public class ToolMeteoritePlacer extends AEBaseItem -{ - @Override - public EnumActionResult onItemUseFirst( final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand ) - { - if( Platform.isClient() ) - { - return EnumActionResult.PASS; - } + final MeteoritePlacer mp = new MeteoritePlacer(); + final boolean worked = mp.spawnMeteorite(new StandardWorld(world), pos.getX(), pos.getY(), pos.getZ()); - final MeteoritePlacer mp = new MeteoritePlacer(); - final boolean worked = mp.spawnMeteorite( new StandardWorld( world ), pos.getX(), pos.getY(), pos.getZ() ); + if (!worked) { + player.sendMessage(new TextComponentString("Un-suitable Location.")); + } - if( !worked ) - { - player.sendMessage( new TextComponentString( "Un-suitable Location." ) ); - } - - return EnumActionResult.SUCCESS; - } + return EnumActionResult.SUCCESS; + } } diff --git a/src/main/java/appeng/debug/ToolReplicatorCard.java b/src/main/java/appeng/debug/ToolReplicatorCard.java index 9b1f834ec..d7559a392 100644 --- a/src/main/java/appeng/debug/ToolReplicatorCard.java +++ b/src/main/java/appeng/debug/ToolReplicatorCard.java @@ -19,6 +19,14 @@ package appeng.debug; +import appeng.api.networking.IGrid; +import appeng.api.networking.IGridHost; +import appeng.api.networking.IGridNode; +import appeng.api.networking.spatial.ISpatialCache; +import appeng.api.util.AEPartLocation; +import appeng.api.util.DimensionalCoord; +import appeng.items.AEBaseItem; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.command.ICommandSender; @@ -33,150 +41,112 @@ import net.minecraft.util.text.TextComponentString; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; -import appeng.api.networking.IGrid; -import appeng.api.networking.IGridHost; -import appeng.api.networking.IGridNode; -import appeng.api.networking.spatial.ISpatialCache; -import appeng.api.util.AEPartLocation; -import appeng.api.util.DimensionalCoord; -import appeng.items.AEBaseItem; -import appeng.util.Platform; +public class ToolReplicatorCard extends AEBaseItem { + @Override + public EnumActionResult onItemUseFirst(final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand) { + if (Platform.isClient()) { + return EnumActionResult.PASS; + } -public class ToolReplicatorCard extends AEBaseItem -{ - @Override - public EnumActionResult onItemUseFirst( final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand ) - { - if( Platform.isClient() ) - { - return EnumActionResult.PASS; - } + int x = pos.getX(); + int y = pos.getY(); + int z = pos.getZ(); - int x = pos.getX(); - int y = pos.getY(); - int z = pos.getZ(); + if (player.isSneaking()) { + if (world.getTileEntity(pos) instanceof IGridHost) { + final NBTTagCompound tag = new NBTTagCompound(); + tag.setInteger("x", x); + tag.setInteger("y", y); + tag.setInteger("z", z); + tag.setInteger("side", side.ordinal()); + tag.setInteger("dimid", world.provider.getDimension()); + player.getHeldItem(hand).setTagCompound(tag); + } else { + this.outputMsg(player, "This is not a Grid Tile."); + } + } else { + final NBTTagCompound ish = player.getHeldItem(hand).getTagCompound(); + if (ish != null) { + final int src_x = ish.getInteger("x"); + final int src_y = ish.getInteger("y"); + final int src_z = ish.getInteger("z"); + final int src_side = ish.getInteger("side"); + final int dimid = ish.getInteger("dimid"); + final World src_w = DimensionManager.getWorld(dimid); - if( player.isSneaking() ) - { - if( world.getTileEntity( pos ) instanceof IGridHost ) - { - final NBTTagCompound tag = new NBTTagCompound(); - tag.setInteger( "x", x ); - tag.setInteger( "y", y ); - tag.setInteger( "z", z ); - tag.setInteger( "side", side.ordinal() ); - tag.setInteger( "dimid", world.provider.getDimension() ); - player.getHeldItem( hand ).setTagCompound( tag ); - } - else - { - this.outputMsg( player, "This is not a Grid Tile." ); - } - } - else - { - final NBTTagCompound ish = player.getHeldItem( hand ).getTagCompound(); - if( ish != null ) - { - final int src_x = ish.getInteger( "x" ); - final int src_y = ish.getInteger( "y" ); - final int src_z = ish.getInteger( "z" ); - final int src_side = ish.getInteger( "side" ); - final int dimid = ish.getInteger( "dimid" ); - final World src_w = DimensionManager.getWorld( dimid ); + final TileEntity te = src_w.getTileEntity(new BlockPos(src_x, src_y, src_z)); + if (te instanceof IGridHost) { + final IGridHost gh = (IGridHost) te; + final EnumFacing sideOff = EnumFacing.VALUES[src_side]; + final EnumFacing currentSideOff = side; + final IGridNode n = gh.getGridNode(AEPartLocation.fromFacing(sideOff)); + if (n != null) { + final IGrid g = n.getGrid(); + if (g != null) { + final ISpatialCache sc = g.getCache(ISpatialCache.class); + if (sc.isValidRegion()) { + final DimensionalCoord min = sc.getMin(); + final DimensionalCoord max = sc.getMax(); - final TileEntity te = src_w.getTileEntity( new BlockPos( src_x, src_y, src_z ) ); - if( te instanceof IGridHost ) - { - final IGridHost gh = (IGridHost) te; - final EnumFacing sideOff = EnumFacing.VALUES[src_side]; - final EnumFacing currentSideOff = side; - final IGridNode n = gh.getGridNode( AEPartLocation.fromFacing( sideOff ) ); - if( n != null ) - { - final IGrid g = n.getGrid(); - if( g != null ) - { - final ISpatialCache sc = g.getCache( ISpatialCache.class ); - if( sc.isValidRegion() ) - { - final DimensionalCoord min = sc.getMin(); - final DimensionalCoord max = sc.getMax(); + x += currentSideOff.getFrontOffsetX(); + y += currentSideOff.getFrontOffsetY(); + z += currentSideOff.getFrontOffsetZ(); - x += currentSideOff.getFrontOffsetX(); - y += currentSideOff.getFrontOffsetY(); - z += currentSideOff.getFrontOffsetZ(); + final int min_x = min.x; + final int min_y = min.y; + final int min_z = min.z; - final int min_x = min.x; - final int min_y = min.y; - final int min_z = min.z; + final int rel_x = min.x - src_x + x; + final int rel_y = min.y - src_y + y; + final int rel_z = min.z - src_z + z; - final int rel_x = min.x - src_x + x; - final int rel_y = min.y - src_y + y; - final int rel_z = min.z - src_z + z; + final int scale_x = max.x - min.x; + final int scale_y = max.y - min.y; + final int scale_z = max.z - min.z; - final int scale_x = max.x - min.x; - final int scale_y = max.y - min.y; - final int scale_z = max.z - min.z; + for (int i = 1; i < scale_x; i++) { + for (int j = 1; j < scale_y; j++) { + for (int k = 1; k < scale_z; k++) { + final BlockPos p = new BlockPos(min_x + i, min_y + j, min_z + k); + final BlockPos d = new BlockPos(i + rel_x, j + rel_y, k + rel_z); + final IBlockState state = src_w.getBlockState(p); + final Block blk = state.getBlock(); + final IBlockState prev = world.getBlockState(d); - for( int i = 1; i < scale_x; i++ ) - { - for( int j = 1; j < scale_y; j++ ) - { - for( int k = 1; k < scale_z; k++ ) - { - final BlockPos p = new BlockPos( min_x + i, min_y + j, min_z + k ); - final BlockPos d = new BlockPos( i + rel_x, j + rel_y, k + rel_z ); - final IBlockState state = src_w.getBlockState( p ); - final Block blk = state.getBlock(); - final IBlockState prev = world.getBlockState( d ); + world.setBlockState(d, state); + if (blk != null && blk.hasTileEntity(state)) { + final TileEntity ote = src_w.getTileEntity(p); + final TileEntity nte = blk.createTileEntity(world, state); + final NBTTagCompound data = new NBTTagCompound(); + ote.writeToNBT(data); + nte.readFromNBT(data.copy()); + world.setTileEntity(d, nte); + } + world.notifyBlockUpdate(d, prev, state, 3); + } + } + } + } else { + this.outputMsg(player, "requires valid spatial pylon setup."); + } + } else { + this.outputMsg(player, "no grid?"); + } + } else { + this.outputMsg(player, "No grid node?"); + } + } else { + this.outputMsg(player, "Src is no longer a grid block?"); + } + } else { + this.outputMsg(player, "No Source Defined"); + } + } + return EnumActionResult.SUCCESS; + } - world.setBlockState( d, state ); - if( blk != null && blk.hasTileEntity( state ) ) - { - final TileEntity ote = src_w.getTileEntity( p ); - final TileEntity nte = blk.createTileEntity( world, state ); - final NBTTagCompound data = new NBTTagCompound(); - ote.writeToNBT( data ); - nte.readFromNBT( data.copy() ); - world.setTileEntity( d, nte ); - } - world.notifyBlockUpdate( d, prev, state, 3 ); - } - } - } - } - else - { - this.outputMsg( player, "requires valid spatial pylon setup." ); - } - } - else - { - this.outputMsg( player, "no grid?" ); - } - } - else - { - this.outputMsg( player, "No grid node?" ); - } - } - else - { - this.outputMsg( player, "Src is no longer a grid block?" ); - } - } - else - { - this.outputMsg( player, "No Source Defined" ); - } - } - return EnumActionResult.SUCCESS; - } - - private void outputMsg( final ICommandSender player, final String string ) - { - player.sendMessage( new TextComponentString( string ) ); - } + private void outputMsg(final ICommandSender player, final String string) { + player.sendMessage(new TextComponentString(string)); + } } diff --git a/src/main/java/appeng/decorative/slab/BlockSlabCommon.java b/src/main/java/appeng/decorative/slab/BlockSlabCommon.java index 56d3e5035..f6d81e6f5 100644 --- a/src/main/java/appeng/decorative/slab/BlockSlabCommon.java +++ b/src/main/java/appeng/decorative/slab/BlockSlabCommon.java @@ -1,11 +1,6 @@ - package appeng.decorative.slab; -import java.util.Random; - -import javax.annotation.Nullable; - import net.minecraft.block.Block; import net.minecraft.block.BlockSlab; import net.minecraft.block.properties.IProperty; @@ -19,154 +14,134 @@ import net.minecraft.util.IStringSerializable; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import javax.annotation.Nullable; +import java.util.Random; -public abstract class BlockSlabCommon extends BlockSlab -{ - static final PropertyEnum VARIANT = PropertyEnum.create( "variant", Variant.class ); +public abstract class BlockSlabCommon extends BlockSlab { - private BlockSlabCommon( Block block ) - { - super( block.getMaterial( block.getDefaultState() ) ); - this.setHardness( block.getBlockHardness( block.getDefaultState(), null, null ) ); - this.setResistance( block.getExplosionResistance( null ) * 5.0F / 3.0F ); + static final PropertyEnum VARIANT = PropertyEnum.create("variant", Variant.class); - IBlockState iblockstate = this.blockState.getBaseState(); + private BlockSlabCommon(Block block) { + super(block.getMaterial(block.getDefaultState())); + this.setHardness(block.getBlockHardness(block.getDefaultState(), null, null)); + this.setResistance(block.getExplosionResistance(null) * 5.0F / 3.0F); - if( !this.isDouble() ) - { - iblockstate = iblockstate.withProperty( HALF, BlockSlab.EnumBlockHalf.BOTTOM ); - } + IBlockState iblockstate = this.blockState.getBaseState(); - this.setDefaultState( iblockstate.withProperty( VARIANT, Variant.DEFAULT ) ); - this.setCreativeTab( CreativeTabs.BUILDING_BLOCKS ); - this.useNeighborBrightness = true; - } + if (!this.isDouble()) { + iblockstate = iblockstate.withProperty(HALF, BlockSlab.EnumBlockHalf.BOTTOM); + } - /** - * Convert the given metadata into a BlockState for this Block - */ - @Override - public IBlockState getStateFromMeta( int meta ) - { - IBlockState iblockstate = this.getDefaultState().withProperty( VARIANT, Variant.DEFAULT ); + this.setDefaultState(iblockstate.withProperty(VARIANT, Variant.DEFAULT)); + this.setCreativeTab(CreativeTabs.BUILDING_BLOCKS); + this.useNeighborBrightness = true; + } - if( !this.isDouble() ) - { - iblockstate = iblockstate.withProperty( HALF, ( meta & 8 ) == 0 ? BlockSlab.EnumBlockHalf.BOTTOM : BlockSlab.EnumBlockHalf.TOP ); - } + /** + * Convert the given metadata into a BlockState for this Block + */ + @Override + public IBlockState getStateFromMeta(int meta) { + IBlockState iblockstate = this.getDefaultState().withProperty(VARIANT, Variant.DEFAULT); - return iblockstate; - } + if (!this.isDouble()) { + iblockstate = iblockstate.withProperty(HALF, (meta & 8) == 0 ? BlockSlab.EnumBlockHalf.BOTTOM : BlockSlab.EnumBlockHalf.TOP); + } - /** - * Convert the BlockState into the correct metadata value - */ - @Override - public int getMetaFromState( IBlockState state ) - { - int i = 0; + return iblockstate; + } - if( !this.isDouble() && state.getValue( HALF ) == BlockSlab.EnumBlockHalf.TOP ) - { - i |= 8; - } + /** + * Convert the BlockState into the correct metadata value + */ + @Override + public int getMetaFromState(IBlockState state) { + int i = 0; - return i; - } + if (!this.isDouble() && state.getValue(HALF) == BlockSlab.EnumBlockHalf.TOP) { + i |= 8; + } - @Override - protected BlockStateContainer createBlockState() - { - return this.isDouble() ? new BlockStateContainer( this, VARIANT ) : new BlockStateContainer( this, HALF, VARIANT ); - } + return i; + } - @Override - @Nullable - public Item getItemDropped( IBlockState state, Random rand, int fortune ) - { - return Item.getItemFromBlock( this ); - } + @Override + protected BlockStateContainer createBlockState() { + return this.isDouble() ? new BlockStateContainer(this, VARIANT) : new BlockStateContainer(this, HALF, VARIANT); + } - @Override - public ItemStack getItem( World worldIn, BlockPos pos, IBlockState state ) - { - return new ItemStack( this, 1, 0 ); - } + @Override + @Nullable + public Item getItemDropped(IBlockState state, Random rand, int fortune) { + return Item.getItemFromBlock(this); + } - @Override - public String getUnlocalizedName( int meta ) - { - return this.getUnlocalizedName(); - } + @Override + public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state) { + return new ItemStack(this, 1, 0); + } - @Override - public IProperty getVariantProperty() - { - return VARIANT; - } + @Override + public String getUnlocalizedName(int meta) { + return this.getUnlocalizedName(); + } - @Override - public Comparable getTypeForItem( ItemStack stack ) - { - return Variant.DEFAULT; - } + @Override + public IProperty getVariantProperty() { + return VARIANT; + } - public static class Double extends BlockSlabCommon - { + @Override + public Comparable getTypeForItem(ItemStack stack) { + return Variant.DEFAULT; + } - private final Block halfSlabBlock; + public static class Double extends BlockSlabCommon { - public Double( Block halfSlabBlock, Block block ) - { - super( block ); - this.halfSlabBlock = halfSlabBlock; - } + private final Block halfSlabBlock; - @Override - public boolean isDouble() - { - return true; - } + public Double(Block halfSlabBlock, Block block) { + super(block); + this.halfSlabBlock = halfSlabBlock; + } - @Override - @Nullable - public Item getItemDropped( IBlockState state, Random rand, int fortune ) - { - return Item.getItemFromBlock( this.halfSlabBlock ); - } + @Override + public boolean isDouble() { + return true; + } - @Override - public ItemStack getItem( World worldIn, BlockPos pos, IBlockState state ) - { - return new ItemStack( this.halfSlabBlock, 1, 0 ); - } + @Override + @Nullable + public Item getItemDropped(IBlockState state, Random rand, int fortune) { + return Item.getItemFromBlock(this.halfSlabBlock); + } - } + @Override + public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state) { + return new ItemStack(this.halfSlabBlock, 1, 0); + } - public static class Half extends BlockSlabCommon - { + } - public Half( Block block ) - { - super( block ); - } + public static class Half extends BlockSlabCommon { - @Override - public boolean isDouble() - { - return false; - } - } + public Half(Block block) { + super(block); + } - public enum Variant implements IStringSerializable - { - DEFAULT; + @Override + public boolean isDouble() { + return false; + } + } - @Override - public String getName() - { - return "default"; - } - } + public enum Variant implements IStringSerializable { + DEFAULT; + + @Override + public String getName() { + return "default"; + } + } } diff --git a/src/main/java/appeng/decorative/solid/BlockChargedQuartzOre.java b/src/main/java/appeng/decorative/solid/BlockChargedQuartzOre.java index c697e43e0..4e9b8ea10 100644 --- a/src/main/java/appeng/decorative/solid/BlockChargedQuartzOre.java +++ b/src/main/java/appeng/decorative/solid/BlockChargedQuartzOre.java @@ -19,8 +19,11 @@ package appeng.decorative.solid; -import java.util.Random; - +import appeng.api.AEApi; +import appeng.api.exceptions.MissingDefinitionException; +import appeng.client.render.effects.ChargedOreFX; +import appeng.core.AEConfig; +import appeng.core.AppEng; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; @@ -32,91 +35,79 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.AEApi; -import appeng.api.exceptions.MissingDefinitionException; -import appeng.client.render.effects.ChargedOreFX; -import appeng.core.AEConfig; -import appeng.core.AppEng; +import java.util.Random; -public class BlockChargedQuartzOre extends BlockQuartzOre -{ - @Override - public Item getItemDropped( final IBlockState state, final Random rand, final int fortune ) - { - return AEApi.instance() - .definitions() - .materials() - .certusQuartzCrystalCharged() - .maybeItem() - .orElseThrow( () -> new MissingDefinitionException( "Tried to access charged certus quartz crystal, even though they are disabled" ) ); - } +public class BlockChargedQuartzOre extends BlockQuartzOre { + @Override + public Item getItemDropped(final IBlockState state, final Random rand, final int fortune) { + return AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystalCharged() + .maybeItem() + .orElseThrow(() -> new MissingDefinitionException("Tried to access charged certus quartz crystal, even though they are disabled")); + } - @Override - public int damageDropped( final IBlockState state ) - { - return AEApi.instance() - .definitions() - .materials() - .certusQuartzCrystalCharged() - .maybeStack( 1 ) - .orElseThrow( () -> new MissingDefinitionException( "Tried to access charged certus quartz crystal, even though they are disabled" ) ) - .getItemDamage(); - } + @Override + public int damageDropped(final IBlockState state) { + return AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystalCharged() + .maybeStack(1) + .orElseThrow(() -> new MissingDefinitionException("Tried to access charged certus quartz crystal, even though they are disabled")) + .getItemDamage(); + } - @Override - public ItemStack getPickBlock( IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player ) - { - return AEApi.instance() - .definitions() - .blocks() - .quartzOreCharged() - .maybeStack( 1 ) - .orElseThrow( () -> new MissingDefinitionException( "Tried to access charged certus quartz ore, even though they are disabled" ) ); - } + @Override + public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { + return AEApi.instance() + .definitions() + .blocks() + .quartzOreCharged() + .maybeStack(1) + .orElseThrow(() -> new MissingDefinitionException("Tried to access charged certus quartz ore, even though they are disabled")); + } - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final IBlockState state, final World w, final BlockPos pos, final Random r ) - { - if( !AEConfig.instance().isEnableEffects() ) - { - return; - } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final IBlockState state, final World w, final BlockPos pos, final Random r) { + if (!AEConfig.instance().isEnableEffects()) { + return; + } - double xOff = ( r.nextFloat() ); - double yOff = ( r.nextFloat() ); - double zOff = ( r.nextFloat() ); + double xOff = (r.nextFloat()); + double yOff = (r.nextFloat()); + double zOff = (r.nextFloat()); - switch( r.nextInt( 6 ) ) - { - case 0: - xOff = -0.01; - break; - case 1: - yOff = -0.01; - break; - case 2: - xOff = -0.01; - break; - case 3: - zOff = -0.01; - break; - case 4: - xOff = 1.01; - break; - case 5: - yOff = 1.01; - break; - case 6: - zOff = 1.01; - break; - } + switch (r.nextInt(6)) { + case 0: + xOff = -0.01; + break; + case 1: + yOff = -0.01; + break; + case 2: + xOff = -0.01; + break; + case 3: + zOff = -0.01; + break; + case 4: + xOff = 1.01; + break; + case 5: + yOff = 1.01; + break; + case 6: + zOff = 1.01; + break; + } - if( AppEng.proxy.shouldAddParticles( r ) ) - { - final ChargedOreFX fx = new ChargedOreFX( w, pos.getX() + xOff, pos.getY() + yOff, pos.getZ() + zOff, 0.0f, 0.0f, 0.0f ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } + if (AppEng.proxy.shouldAddParticles(r)) { + final ChargedOreFX fx = new ChargedOreFX(w, pos.getX() + xOff, pos.getY() + yOff, pos.getZ() + zOff, 0.0f, 0.0f, 0.0f); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } } diff --git a/src/main/java/appeng/decorative/solid/BlockChiseledQuartz.java b/src/main/java/appeng/decorative/solid/BlockChiseledQuartz.java index 23860df01..fd80b1069 100644 --- a/src/main/java/appeng/decorative/solid/BlockChiseledQuartz.java +++ b/src/main/java/appeng/decorative/solid/BlockChiseledQuartz.java @@ -19,15 +19,12 @@ package appeng.decorative.solid; +import appeng.block.AEDecorativeBlock; import net.minecraft.block.material.Material; -import appeng.block.AEDecorativeBlock; - -public final class BlockChiseledQuartz extends AEDecorativeBlock -{ - public BlockChiseledQuartz() - { - super( Material.ROCK ); - } +public final class BlockChiseledQuartz extends AEDecorativeBlock { + public BlockChiseledQuartz() { + super(Material.ROCK); + } } diff --git a/src/main/java/appeng/decorative/solid/BlockFluix.java b/src/main/java/appeng/decorative/solid/BlockFluix.java index bf063ed0c..1c512c70e 100644 --- a/src/main/java/appeng/decorative/solid/BlockFluix.java +++ b/src/main/java/appeng/decorative/solid/BlockFluix.java @@ -19,15 +19,12 @@ package appeng.decorative.solid; +import appeng.block.AEDecorativeBlock; import net.minecraft.block.material.Material; -import appeng.block.AEDecorativeBlock; - -public final class BlockFluix extends AEDecorativeBlock -{ - public BlockFluix() - { - super( Material.ROCK ); - } +public final class BlockFluix extends AEDecorativeBlock { + public BlockFluix() { + super(Material.ROCK); + } } diff --git a/src/main/java/appeng/decorative/solid/BlockQuartz.java b/src/main/java/appeng/decorative/solid/BlockQuartz.java index aab29e92d..dafc23fab 100644 --- a/src/main/java/appeng/decorative/solid/BlockQuartz.java +++ b/src/main/java/appeng/decorative/solid/BlockQuartz.java @@ -19,15 +19,12 @@ package appeng.decorative.solid; +import appeng.block.AEDecorativeBlock; import net.minecraft.block.material.Material; -import appeng.block.AEDecorativeBlock; - -public final class BlockQuartz extends AEDecorativeBlock -{ - public BlockQuartz() - { - super( Material.ROCK ); - } +public final class BlockQuartz extends AEDecorativeBlock { + public BlockQuartz() { + super(Material.ROCK); + } } diff --git a/src/main/java/appeng/decorative/solid/BlockQuartzGlass.java b/src/main/java/appeng/decorative/solid/BlockQuartzGlass.java index e1e959f6e..3783e2e1d 100644 --- a/src/main/java/appeng/decorative/solid/BlockQuartzGlass.java +++ b/src/main/java/appeng/decorative/solid/BlockQuartzGlass.java @@ -19,8 +19,8 @@ package appeng.decorative.solid; -import java.util.EnumSet; - +import appeng.block.AEBaseBlock; +import appeng.helpers.AEGlassMaterial; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.BlockStateContainer; @@ -33,84 +33,71 @@ import net.minecraftforge.common.property.ExtendedBlockState; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.common.property.IUnlistedProperty; -import appeng.block.AEBaseBlock; -import appeng.helpers.AEGlassMaterial; +import java.util.EnumSet; -public class BlockQuartzGlass extends AEBaseBlock -{ +public class BlockQuartzGlass extends AEBaseBlock { - // This unlisted property is used to determine the actual block that should be rendered - public static final UnlistedGlassStateProperty GLASS_STATE = new UnlistedGlassStateProperty(); + // This unlisted property is used to determine the actual block that should be rendered + public static final UnlistedGlassStateProperty GLASS_STATE = new UnlistedGlassStateProperty(); - public BlockQuartzGlass() - { - super( Material.GLASS ); - this.setLightOpacity( 0 ); - this.setOpaque( false ); - } + public BlockQuartzGlass() { + super(Material.GLASS); + this.setLightOpacity(0); + this.setOpaque(false); + } - @Override - protected BlockStateContainer createBlockState() - { - IProperty[] listedProperties = new IProperty[0]; - IUnlistedProperty[] unlistedProperties = new IUnlistedProperty[] { GLASS_STATE }; - return new ExtendedBlockState( this, listedProperties, unlistedProperties ); - } + @Override + protected BlockStateContainer createBlockState() { + IProperty[] listedProperties = new IProperty[0]; + IUnlistedProperty[] unlistedProperties = new IUnlistedProperty[]{GLASS_STATE}; + return new ExtendedBlockState(this, listedProperties, unlistedProperties); + } - @Override - public IBlockState getExtendedState( IBlockState state, IBlockAccess world, BlockPos pos ) - { + @Override + public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { - EnumSet flushWith = EnumSet.noneOf( EnumFacing.class ); - // Test every direction for another glass block - for( EnumFacing facing : EnumFacing.values() ) - { - if( isGlassBlock( world, pos, facing ) ) - { - flushWith.add( facing ); - } - } + EnumSet flushWith = EnumSet.noneOf(EnumFacing.class); + // Test every direction for another glass block + for (EnumFacing facing : EnumFacing.values()) { + if (isGlassBlock(world, pos, facing)) { + flushWith.add(facing); + } + } - GlassState glassState = new GlassState( pos.getX(), pos.getY(), pos.getZ(), flushWith ); + GlassState glassState = new GlassState(pos.getX(), pos.getY(), pos.getZ(), flushWith); - IExtendedBlockState extState = (IExtendedBlockState) state; + IExtendedBlockState extState = (IExtendedBlockState) state; - return extState.withProperty( GLASS_STATE, glassState ); - } + return extState.withProperty(GLASS_STATE, glassState); + } - private static boolean isGlassBlock( IBlockAccess world, BlockPos pos, EnumFacing facing ) - { - return world.getBlockState( pos.offset( facing ) ).getBlock() instanceof BlockQuartzGlass; - } + private static boolean isGlassBlock(IBlockAccess world, BlockPos pos, EnumFacing facing) { + return world.getBlockState(pos.offset(facing)).getBlock() instanceof BlockQuartzGlass; + } - @Override - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } + @Override + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } - @Override - public boolean shouldSideBeRendered( final IBlockState state, final IBlockAccess w, final BlockPos pos, final EnumFacing side ) - { - BlockPos adjacentPos = pos.offset( side ); + @Override + public boolean shouldSideBeRendered(final IBlockState state, final IBlockAccess w, final BlockPos pos, final EnumFacing side) { + BlockPos adjacentPos = pos.offset(side); - final Material mat = w.getBlockState( adjacentPos ).getMaterial(); + final Material mat = w.getBlockState(adjacentPos).getMaterial(); - if( mat == Material.GLASS || mat == AEGlassMaterial.INSTANCE ) - { - if( w.getBlockState( adjacentPos ).getRenderType() == this.getRenderType( state ) ) - { - return false; - } - } + if (mat == Material.GLASS || mat == AEGlassMaterial.INSTANCE) { + if (w.getBlockState(adjacentPos).getRenderType() == this.getRenderType(state)) { + return false; + } + } - return super.shouldSideBeRendered( state, w, pos, side ); - } + return super.shouldSideBeRendered(state, w, pos, side); + } - @Override - public boolean isFullCube( IBlockState state ) - { - return false; - } + @Override + public boolean isFullCube(IBlockState state) { + return false; + } } diff --git a/src/main/java/appeng/decorative/solid/BlockQuartzLamp.java b/src/main/java/appeng/decorative/solid/BlockQuartzLamp.java index 5c13093f5..158af629b 100644 --- a/src/main/java/appeng/decorative/solid/BlockQuartzLamp.java +++ b/src/main/java/appeng/decorative/solid/BlockQuartzLamp.java @@ -19,8 +19,9 @@ package appeng.decorative.solid; -import java.util.Random; - +import appeng.client.render.effects.VibrantFX; +import appeng.core.AEConfig; +import appeng.core.AppEng; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.util.math.BlockPos; @@ -28,37 +29,30 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.client.render.effects.VibrantFX; -import appeng.core.AEConfig; -import appeng.core.AppEng; +import java.util.Random; -public class BlockQuartzLamp extends BlockQuartzGlass -{ +public class BlockQuartzLamp extends BlockQuartzGlass { - public BlockQuartzLamp() - { - this.setLightLevel( 1.0f ); - } + public BlockQuartzLamp() { + this.setLightLevel(1.0f); + } - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final IBlockState state, final World w, final BlockPos pos, final Random r ) - { - if( !AEConfig.instance().isEnableEffects() ) - { - return; - } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final IBlockState state, final World w, final BlockPos pos, final Random r) { + if (!AEConfig.instance().isEnableEffects()) { + return; + } - if( AppEng.proxy.shouldAddParticles( r ) ) - { - final double d0 = ( r.nextFloat() - 0.5F ) * 0.96D; - final double d1 = ( r.nextFloat() - 0.5F ) * 0.96D; - final double d2 = ( r.nextFloat() - 0.5F ) * 0.96D; + if (AppEng.proxy.shouldAddParticles(r)) { + final double d0 = (r.nextFloat() - 0.5F) * 0.96D; + final double d1 = (r.nextFloat() - 0.5F) * 0.96D; + final double d2 = (r.nextFloat() - 0.5F) * 0.96D; - final VibrantFX fx = new VibrantFX( w, 0.5 + pos.getX() + d0, 0.5 + pos.getY() + d1, 0.5 + pos.getZ() + d2, 0.0D, 0.0D, 0.0D ); + final VibrantFX fx = new VibrantFX(w, 0.5 + pos.getX() + d0, 0.5 + pos.getY() + d1, 0.5 + pos.getZ() + d2, 0.0D, 0.0D, 0.0D); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } } diff --git a/src/main/java/appeng/decorative/solid/BlockQuartzOre.java b/src/main/java/appeng/decorative/solid/BlockQuartzOre.java index b4e631ad5..ac76ed655 100644 --- a/src/main/java/appeng/decorative/solid/BlockQuartzOre.java +++ b/src/main/java/appeng/decorative/solid/BlockQuartzOre.java @@ -19,8 +19,9 @@ package appeng.decorative.solid; -import java.util.Random; - +import appeng.api.AEApi; +import appeng.api.exceptions.MissingDefinitionException; +import appeng.block.AEBaseBlock; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.item.Item; @@ -30,84 +31,69 @@ import net.minecraft.util.math.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import appeng.api.AEApi; -import appeng.api.exceptions.MissingDefinitionException; -import appeng.block.AEBaseBlock; +import java.util.Random; -public class BlockQuartzOre extends AEBaseBlock -{ - public BlockQuartzOre() - { - super( Material.ROCK ); - this.setHardness( 3.0F ); - this.setResistance( 5.0F ); - } +public class BlockQuartzOre extends AEBaseBlock { + public BlockQuartzOre() { + super(Material.ROCK); + this.setHardness(3.0F); + this.setResistance(5.0F); + } - @Override - public BlockRenderLayer getBlockLayer() - { - return BlockRenderLayer.CUTOUT; - } + @Override + public BlockRenderLayer getBlockLayer() { + return BlockRenderLayer.CUTOUT; + } - @Override - public int quantityDropped( IBlockState state, int fortune, Random rand ) - { - if( fortune > 0 && Item.getItemFromBlock( this ) != this.getItemDropped( null, rand, fortune ) ) - { - int j = rand.nextInt( fortune + 2 ) - 1; + @Override + public int quantityDropped(IBlockState state, int fortune, Random rand) { + if (fortune > 0 && Item.getItemFromBlock(this) != this.getItemDropped(null, rand, fortune)) { + int j = rand.nextInt(fortune + 2) - 1; - if( j < 0 ) - { - j = 0; - } + if (j < 0) { + j = 0; + } - return this.quantityDropped( rand ) * ( j + 1 ); - } - else - { - return this.quantityDropped( rand ); - } - } + return this.quantityDropped(rand) * (j + 1); + } else { + return this.quantityDropped(rand); + } + } - @Override - public int quantityDropped( final Random rand ) - { - return 1 + rand.nextInt( 2 ); - } + @Override + public int quantityDropped(final Random rand) { + return 1 + rand.nextInt(2); + } - @Override - public int getExpDrop( IBlockState state, IBlockAccess world, BlockPos pos, int fortune ) - { - Random rand = world instanceof World ? ( (World) world ).rand : new Random(); + @Override + public int getExpDrop(IBlockState state, IBlockAccess world, BlockPos pos, int fortune) { + Random rand = world instanceof World ? ((World) world).rand : new Random(); - if( this.getItemDropped( state, rand, fortune ) != Item.getItemFromBlock( this ) ) - { - return MathHelper.getInt( rand, 2, 5 ); - } - return super.getExpDrop( state, world, pos, fortune ); - } + if (this.getItemDropped(state, rand, fortune) != Item.getItemFromBlock(this)) { + return MathHelper.getInt(rand, 2, 5); + } + return super.getExpDrop(state, world, pos, fortune); + } - @Override - public Item getItemDropped( final IBlockState state, final Random rand, final int fortune ) - { - return AEApi.instance() - .definitions() - .materials() - .certusQuartzCrystal() - .maybeItem() - .orElseThrow( () -> new MissingDefinitionException( "Tried to access certus quartz crystal, even though they are disabled" ) ); - } + @Override + public Item getItemDropped(final IBlockState state, final Random rand, final int fortune) { + return AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystal() + .maybeItem() + .orElseThrow(() -> new MissingDefinitionException("Tried to access certus quartz crystal, even though they are disabled")); + } - @Override - public int damageDropped( final IBlockState state ) - { - return AEApi.instance() - .definitions() - .materials() - .certusQuartzCrystal() - .maybeStack( 1 ) - .orElseThrow( () -> new MissingDefinitionException( "Tried to access certus quartz crystal, even though they are disabled" ) ) - .getItemDamage(); - } + @Override + public int damageDropped(final IBlockState state) { + return AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystal() + .maybeStack(1) + .orElseThrow(() -> new MissingDefinitionException("Tried to access certus quartz crystal, even though they are disabled")) + .getItemDamage(); + } } diff --git a/src/main/java/appeng/decorative/solid/BlockQuartzPillar.java b/src/main/java/appeng/decorative/solid/BlockQuartzPillar.java index 479c9e6c2..15b51fdf3 100644 --- a/src/main/java/appeng/decorative/solid/BlockQuartzPillar.java +++ b/src/main/java/appeng/decorative/solid/BlockQuartzPillar.java @@ -19,6 +19,10 @@ package appeng.decorative.solid; +import appeng.api.util.IOrientable; +import appeng.api.util.IOrientableBlock; +import appeng.block.AEBaseBlock; +import appeng.helpers.MetaRotation; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; @@ -27,53 +31,41 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; -import appeng.api.util.IOrientable; -import appeng.api.util.IOrientableBlock; -import appeng.block.AEBaseBlock; -import appeng.helpers.MetaRotation; +public class BlockQuartzPillar extends AEBaseBlock implements IOrientableBlock { + public static final PropertyEnum AXIS_ORIENTATION = PropertyEnum.create("axis", EnumFacing.Axis.class); -public class BlockQuartzPillar extends AEBaseBlock implements IOrientableBlock -{ - public static final PropertyEnum AXIS_ORIENTATION = PropertyEnum.create( "axis", EnumFacing.Axis.class ); + public BlockQuartzPillar() { + super(Material.ROCK); + // The upwards facing pillar is the default (i.e. for the item model) + this.setDefaultState(this.getDefaultState().withProperty(AXIS_ORIENTATION, EnumFacing.Axis.Y)); + } - public BlockQuartzPillar() - { - super( Material.ROCK ); - // The upwards facing pillar is the default (i.e. for the item model) - this.setDefaultState( this.getDefaultState().withProperty( AXIS_ORIENTATION, EnumFacing.Axis.Y ) ); - } + @Override + public int getMetaFromState(final IBlockState state) { + return state.getValue(AXIS_ORIENTATION).ordinal(); + } - @Override - public int getMetaFromState( final IBlockState state ) - { - return state.getValue( AXIS_ORIENTATION ).ordinal(); - } + @Override + public IBlockState getStateFromMeta(final int meta) { + // Simply use the ordinal here + EnumFacing.Axis axis = EnumFacing.Axis.values()[meta]; + return this.getDefaultState().withProperty(AXIS_ORIENTATION, axis); + } - @Override - public IBlockState getStateFromMeta( final int meta ) - { - // Simply use the ordinal here - EnumFacing.Axis axis = EnumFacing.Axis.values()[meta]; - return this.getDefaultState().withProperty( AXIS_ORIENTATION, axis ); - } + @Override + protected IProperty[] getAEStates() { + return new IProperty[]{AXIS_ORIENTATION}; + } - @Override - protected IProperty[] getAEStates() - { - return new IProperty[] { AXIS_ORIENTATION }; - } + @Override + public boolean usesMetadata() { + return true; + } - @Override - public boolean usesMetadata() - { - return true; - } - - @Override - public IOrientable getOrientable( final IBlockAccess w, final BlockPos pos ) - { - return new MetaRotation( w, pos, null ); - } + @Override + public IOrientable getOrientable(final IBlockAccess w, final BlockPos pos) { + return new MetaRotation(w, pos, null); + } } diff --git a/src/main/java/appeng/decorative/solid/BlockSkyStone.java b/src/main/java/appeng/decorative/solid/BlockSkyStone.java index aee4b76b3..fea461893 100644 --- a/src/main/java/appeng/decorative/solid/BlockSkyStone.java +++ b/src/main/java/appeng/decorative/solid/BlockSkyStone.java @@ -19,6 +19,9 @@ package appeng.decorative.solid; +import appeng.block.AEBaseBlock; +import appeng.core.worlddata.WorldData; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.inventory.EntityEquipmentSlot; @@ -29,76 +32,60 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import appeng.block.AEBaseBlock; -import appeng.core.worlddata.WorldData; -import appeng.util.Platform; +public class BlockSkyStone extends AEBaseBlock { + private static final float BLOCK_RESISTANCE = 150.0f; + private static final float BREAK_SPEAK_SCALAR = 0.1f; + private static final double BREAK_SPEAK_THRESHOLD = 7.0; + private final SkystoneType type; -public class BlockSkyStone extends AEBaseBlock -{ - private static final float BLOCK_RESISTANCE = 150.0f; - private static final float BREAK_SPEAK_SCALAR = 0.1f; - private static final double BREAK_SPEAK_THRESHOLD = 7.0; - private final SkystoneType type; + public BlockSkyStone(final SkystoneType type) { + super(Material.ROCK); + this.setHardness(50); + this.blockResistance = BLOCK_RESISTANCE; + if (type == SkystoneType.STONE) { + this.setHarvestLevel("pickaxe", 3); + } - public BlockSkyStone( final SkystoneType type ) - { - super( Material.ROCK ); - this.setHardness( 50 ); - this.blockResistance = BLOCK_RESISTANCE; - if( type == SkystoneType.STONE ) - { - this.setHarvestLevel( "pickaxe", 3 ); - } + this.type = type; - this.type = type; + MinecraftForge.EVENT_BUS.register(this); + } - MinecraftForge.EVENT_BUS.register( this ); - } + @SubscribeEvent + public void breakFaster(final PlayerEvent.BreakSpeed event) { + if (event.getState().getBlock() == this && event.getEntityPlayer() != null) { + final ItemStack is = event.getEntityPlayer().getItemStackFromSlot(EntityEquipmentSlot.MAINHAND); + int level = -1; - @SubscribeEvent - public void breakFaster( final PlayerEvent.BreakSpeed event ) - { - if( event.getState().getBlock() == this && event.getEntityPlayer() != null ) - { - final ItemStack is = event.getEntityPlayer().getItemStackFromSlot( EntityEquipmentSlot.MAINHAND ); - int level = -1; + if (!is.isEmpty()) { + level = is.getItem().getHarvestLevel(is, "pickaxe", event.getEntityPlayer(), event.getState()); + } - if( !is.isEmpty() ) - { - level = is.getItem().getHarvestLevel( is, "pickaxe", event.getEntityPlayer(), event.getState() ); - } + if (this.type != SkystoneType.STONE || level >= 3 || event.getOriginalSpeed() > BREAK_SPEAK_THRESHOLD) { + event.setNewSpeed(event.getNewSpeed() / BREAK_SPEAK_SCALAR); + } + } + } - if( this.type != SkystoneType.STONE || level >= 3 || event.getOriginalSpeed() > BREAK_SPEAK_THRESHOLD ) - { - event.setNewSpeed( event.getNewSpeed() / BREAK_SPEAK_SCALAR ); - } - } - } + @Override + public void onBlockAdded(final World w, final BlockPos pos, final IBlockState state) { + super.onBlockAdded(w, pos, state); + if (Platform.isServer()) { + WorldData.instance().compassData().service().updateArea(w, pos.getX(), pos.getY(), pos.getZ()); + } + } - @Override - public void onBlockAdded( final World w, final BlockPos pos, final IBlockState state ) - { - super.onBlockAdded( w, pos, state ); - if( Platform.isServer() ) - { - WorldData.instance().compassData().service().updateArea( w, pos.getX(), pos.getY(), pos.getZ() ); - } - } + @Override + public void breakBlock(final World w, final BlockPos pos, final IBlockState state) { + super.breakBlock(w, pos, state); - @Override - public void breakBlock( final World w, final BlockPos pos, final IBlockState state ) - { - super.breakBlock( w, pos, state ); + if (Platform.isServer()) { + WorldData.instance().compassData().service().updateArea(w, pos.getX(), pos.getY(), pos.getZ()); + } + } - if( Platform.isServer() ) - { - WorldData.instance().compassData().service().updateArea( w, pos.getX(), pos.getY(), pos.getZ() ); - } - } - - public enum SkystoneType - { - STONE, BLOCK, BRICK, SMALL_BRICK - } + public enum SkystoneType { + STONE, BLOCK, BRICK, SMALL_BRICK + } } diff --git a/src/main/java/appeng/decorative/solid/GlassState.java b/src/main/java/appeng/decorative/solid/GlassState.java index 11a4d93c9..8dda3f8d2 100644 --- a/src/main/java/appeng/decorative/solid/GlassState.java +++ b/src/main/java/appeng/decorative/solid/GlassState.java @@ -19,50 +19,44 @@ package appeng.decorative.solid; -import java.util.EnumSet; - import net.minecraft.util.EnumFacing; +import java.util.EnumSet; + /** * Immutable (and thus thread-safe) class that encapsulates the rendering state required for a connected texture * glass block. */ -public final class GlassState -{ +public final class GlassState { - private final int x; - private final int y; - private final int z; + private final int x; + private final int y; + private final int z; - private final EnumSet flushWith = EnumSet.noneOf( EnumFacing.class ); + private final EnumSet flushWith = EnumSet.noneOf(EnumFacing.class); - public GlassState( int x, int y, int z, EnumSet flushWith ) - { - this.x = x; - this.y = y; - this.z = z; - this.flushWith.addAll( flushWith ); - } + public GlassState(int x, int y, int z, EnumSet flushWith) { + this.x = x; + this.y = y; + this.z = z; + this.flushWith.addAll(flushWith); + } - public int getX() - { - return this.x; - } + public int getX() { + return this.x; + } - public int getY() - { - return this.y; - } + public int getY() { + return this.y; + } - public int getZ() - { - return this.z; - } + public int getZ() { + return this.z; + } - public boolean isFlushWith( EnumFacing side ) - { - return this.flushWith.contains( side ); - } + public boolean isFlushWith(EnumFacing side) { + return this.flushWith.contains(side); + } } diff --git a/src/main/java/appeng/decorative/solid/UnlistedGlassStateProperty.java b/src/main/java/appeng/decorative/solid/UnlistedGlassStateProperty.java index 4d240d5b7..221ba9093 100644 --- a/src/main/java/appeng/decorative/solid/UnlistedGlassStateProperty.java +++ b/src/main/java/appeng/decorative/solid/UnlistedGlassStateProperty.java @@ -25,30 +25,25 @@ import net.minecraftforge.common.property.IUnlistedProperty; /** * This unlisted property is used to transport the connected texture state into our model class. */ -public class UnlistedGlassStateProperty implements IUnlistedProperty -{ +public class UnlistedGlassStateProperty implements IUnlistedProperty { - @Override - public String getName() - { - return "glass_state"; - } + @Override + public String getName() { + return "glass_state"; + } - @Override - public boolean isValid( GlassState value ) - { - return true; - } + @Override + public boolean isValid(GlassState value) { + return true; + } - @Override - public Class getType() - { - return GlassState.class; - } + @Override + public Class getType() { + return GlassState.class; + } - @Override - public String valueToString( GlassState value ) - { - return null; - } + @Override + public String valueToString(GlassState value) { + return null; + } } diff --git a/src/main/java/appeng/decorative/stair/BlockStairCommon.java b/src/main/java/appeng/decorative/stair/BlockStairCommon.java index 976424662..eb774a9fc 100644 --- a/src/main/java/appeng/decorative/stair/BlockStairCommon.java +++ b/src/main/java/appeng/decorative/stair/BlockStairCommon.java @@ -19,15 +19,12 @@ package appeng.decorative.stair; +import appeng.block.AEBaseStairBlock; import net.minecraft.block.Block; -import appeng.block.AEBaseStairBlock; - -public class BlockStairCommon extends AEBaseStairBlock -{ - public BlockStairCommon( final Block block, final String type ) - { - super( block, type ); - } +public class BlockStairCommon extends AEBaseStairBlock { + public BlockStairCommon(final Block block, final String type) { + super(block, type); + } } diff --git a/src/main/java/appeng/entity/AEBaseEntityItem.java b/src/main/java/appeng/entity/AEBaseEntityItem.java index 7223e3cd1..bc1e6bce5 100644 --- a/src/main/java/appeng/entity/AEBaseEntityItem.java +++ b/src/main/java/appeng/entity/AEBaseEntityItem.java @@ -19,29 +19,25 @@ package appeng.entity; -import java.util.List; - import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.world.World; +import java.util.List; -public abstract class AEBaseEntityItem extends EntityItem -{ - public AEBaseEntityItem( final World world ) - { - super( world ); - } - public AEBaseEntityItem( final World world, final double x, final double y, final double z, final ItemStack stack ) - { - super( world, x, y, z, stack ); - } +public abstract class AEBaseEntityItem extends EntityItem { + public AEBaseEntityItem(final World world) { + super(world); + } - protected List getCheckedEntitiesWithinAABBExcludingEntity( final AxisAlignedBB region ) - { - return this.world.getEntitiesWithinAABBExcludingEntity( this, region ); - } + public AEBaseEntityItem(final World world, final double x, final double y, final double z, final ItemStack stack) { + super(world, x, y, z, stack); + } + + protected List getCheckedEntitiesWithinAABBExcludingEntity(final AxisAlignedBB region) { + return this.world.getEntitiesWithinAABBExcludingEntity(this, region); + } } diff --git a/src/main/java/appeng/entity/EntityChargedQuartz.java b/src/main/java/appeng/entity/EntityChargedQuartz.java index 50f69befe..2e3a62be7 100644 --- a/src/main/java/appeng/entity/EntityChargedQuartz.java +++ b/src/main/java/appeng/entity/EntityChargedQuartz.java @@ -19,8 +19,14 @@ package appeng.entity; -import java.util.List; - +import appeng.api.AEApi; +import appeng.api.definitions.IMaterials; +import appeng.client.EffectType; +import appeng.core.AEConfig; +import appeng.core.AppEng; +import appeng.core.features.AEFeature; +import appeng.helpers.Reflected; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; @@ -32,140 +38,111 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; -import appeng.api.AEApi; -import appeng.api.definitions.IMaterials; -import appeng.client.EffectType; -import appeng.core.AEConfig; -import appeng.core.AppEng; -import appeng.core.features.AEFeature; -import appeng.helpers.Reflected; -import appeng.util.Platform; +import java.util.List; -public final class EntityChargedQuartz extends AEBaseEntityItem -{ +public final class EntityChargedQuartz extends AEBaseEntityItem { - private int delay = 0; - private int transformTime = 0; + private int delay = 0; + private int transformTime = 0; - @Reflected - public EntityChargedQuartz( final World w ) - { - super( w ); - } + @Reflected + public EntityChargedQuartz(final World w) { + super(w); + } - public EntityChargedQuartz( final World w, final double x, final double y, final double z, final ItemStack is ) - { - super( w, x, y, z, is ); - } + public EntityChargedQuartz(final World w, final double x, final double y, final double z, final ItemStack is) { + super(w, x, y, z, is); + } - @Override - public void onUpdate() - { - super.onUpdate(); + @Override + public void onUpdate() { + super.onUpdate(); - if( this.isDead || !AEConfig.instance().isFeatureEnabled( AEFeature.IN_WORLD_FLUIX ) ) - { - return; - } + if (this.isDead || !AEConfig.instance().isFeatureEnabled(AEFeature.IN_WORLD_FLUIX)) { + return; + } - if( Platform.isClient() && this.delay > 30 && AEConfig.instance().isEnableEffects() ) - { - AppEng.proxy.spawnEffect( EffectType.Lightning, this.world, this.posX, this.posY, this.posZ, null ); - this.delay = 0; - } + if (Platform.isClient() && this.delay > 30 && AEConfig.instance().isEnableEffects()) { + AppEng.proxy.spawnEffect(EffectType.Lightning, this.world, this.posX, this.posY, this.posZ, null); + this.delay = 0; + } - this.delay++; + this.delay++; - final int j = MathHelper.floor( this.posX ); - final int i = MathHelper.floor( ( this.getEntityBoundingBox().minY + this.getEntityBoundingBox().maxY ) / 2.0D ); - final int k = MathHelper.floor( this.posZ ); + final int j = MathHelper.floor(this.posX); + final int i = MathHelper.floor((this.getEntityBoundingBox().minY + this.getEntityBoundingBox().maxY) / 2.0D); + final int k = MathHelper.floor(this.posZ); - IBlockState state = this.world.getBlockState( new BlockPos( j, i, k ) ); - final Material mat = state.getMaterial(); + IBlockState state = this.world.getBlockState(new BlockPos(j, i, k)); + final Material mat = state.getMaterial(); - if( Platform.isServer() && mat.isLiquid() ) - { - this.transformTime++; - if( this.transformTime > 60 ) - { - if( !this.transform() ) - { - this.transformTime = 0; - } - } - } - else - { - this.transformTime = 0; - } - } + if (Platform.isServer() && mat.isLiquid()) { + this.transformTime++; + if (this.transformTime > 60) { + if (!this.transform()) { + this.transformTime = 0; + } + } + } else { + this.transformTime = 0; + } + } - private boolean transform() - { - final ItemStack item = this.getItem(); - final IMaterials materials = AEApi.instance().definitions().materials(); + private boolean transform() { + final ItemStack item = this.getItem(); + final IMaterials materials = AEApi.instance().definitions().materials(); - if( materials.certusQuartzCrystalCharged().isSameAs( item ) ) - { - final AxisAlignedBB region = new AxisAlignedBB( this.posX - 1, this.posY - 1, this.posZ - 1, this.posX + 1, this.posY + 1, this.posZ + 1 ); - final List l = this.getCheckedEntitiesWithinAABBExcludingEntity( region ); + if (materials.certusQuartzCrystalCharged().isSameAs(item)) { + final AxisAlignedBB region = new AxisAlignedBB(this.posX - 1, this.posY - 1, this.posZ - 1, this.posX + 1, this.posY + 1, this.posZ + 1); + final List l = this.getCheckedEntitiesWithinAABBExcludingEntity(region); - EntityItem redstone = null; - EntityItem netherQuartz = null; + EntityItem redstone = null; + EntityItem netherQuartz = null; - for( final Entity e : l ) - { - if( e instanceof EntityItem && !e.isDead ) - { - final ItemStack other = ( (EntityItem) e ).getItem(); - if( !other.isEmpty() ) - { - if( ItemStack.areItemsEqual( other, new ItemStack( Items.REDSTONE ) ) ) - { - redstone = (EntityItem) e; - } + for (final Entity e : l) { + if (e instanceof EntityItem && !e.isDead) { + final ItemStack other = ((EntityItem) e).getItem(); + if (!other.isEmpty()) { + if (ItemStack.areItemsEqual(other, new ItemStack(Items.REDSTONE))) { + redstone = (EntityItem) e; + } - if( ItemStack.areItemsEqual( other, new ItemStack( Items.QUARTZ ) ) ) - { - netherQuartz = (EntityItem) e; - } - } - } - } + if (ItemStack.areItemsEqual(other, new ItemStack(Items.QUARTZ))) { + netherQuartz = (EntityItem) e; + } + } + } + } - if( redstone != null && netherQuartz != null ) - { - this.getItem().grow( -1 ); - redstone.getItem().grow( -1 ); - netherQuartz.getItem().grow( -1 ); + if (redstone != null && netherQuartz != null) { + this.getItem().grow(-1); + redstone.getItem().grow(-1); + netherQuartz.getItem().grow(-1); - if( this.getItem().getCount() <= 0 ) - { - this.setDead(); - } + if (this.getItem().getCount() <= 0) { + this.setDead(); + } - if( redstone.getItem().getCount() <= 0 ) - { - redstone.setDead(); - } + if (redstone.getItem().getCount() <= 0) { + redstone.setDead(); + } - if( netherQuartz.getItem().getCount() <= 0 ) - { - netherQuartz.setDead(); - } + if (netherQuartz.getItem().getCount() <= 0) { + netherQuartz.setDead(); + } - materials.fluixCrystal().maybeStack( 2 ).ifPresent( is -> - { - final EntityItem entity = new EntityItem( this.world, this.posX, this.posY, this.posZ, is ); + materials.fluixCrystal().maybeStack(2).ifPresent(is -> + { + final EntityItem entity = new EntityItem(this.world, this.posX, this.posY, this.posZ, is); - this.world.spawnEntity( entity ); - } ); + this.world.spawnEntity(entity); + }); - return true; - } - } + return true; + } + } - return false; - } + return false; + } } diff --git a/src/main/java/appeng/entity/EntityFloatingItem.java b/src/main/java/appeng/entity/EntityFloatingItem.java index 70be7c6ab..9204f9a0a 100644 --- a/src/main/java/appeng/entity/EntityFloatingItem.java +++ b/src/main/java/appeng/entity/EntityFloatingItem.java @@ -24,52 +24,44 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.World; -public final class EntityFloatingItem extends EntityItem -{ +public final class EntityFloatingItem extends EntityItem { - private final ICanDie parent; - private int superDeath = 0; - private float progress = 0; + private final ICanDie parent; + private int superDeath = 0; + private float progress = 0; - public EntityFloatingItem( final ICanDie parent, final World world, final double x, final double y, final double z, final ItemStack stack ) - { - super( world, x, y, z, stack ); - this.motionX = this.motionY = this.motionZ = 0.0d; - this.hoverStart = 0.5f; - this.rotationYaw = 0; - this.parent = parent; - } + public EntityFloatingItem(final ICanDie parent, final World world, final double x, final double y, final double z, final ItemStack stack) { + super(world, x, y, z, stack); + this.motionX = this.motionY = this.motionZ = 0.0d; + this.hoverStart = 0.5f; + this.rotationYaw = 0; + this.parent = parent; + } - // public boolean isEntityAlive() + // public boolean isEntityAlive() - @Override - public void onUpdate() - { - if( !this.isDead && this.parent.isDead() ) - { - this.setDead(); - } + @Override + public void onUpdate() { + if (!this.isDead && this.parent.isDead()) { + this.setDead(); + } - if( this.superDeath > 100 ) - { - this.setDead(); - } - this.superDeath++; + if (this.superDeath > 100) { + this.setDead(); + } + this.superDeath++; - this.setNoDespawn(); - } + this.setNoDespawn(); + } - public void setProgress( final float progress ) - { - this.progress = progress; - if( this.progress > 0.99 ) - { - this.setDead(); - } - } + public void setProgress(final float progress) { + this.progress = progress; + if (this.progress > 0.99) { + this.setDead(); + } + } - float getProgress() - { - return this.progress; - } + float getProgress() { + return this.progress; + } } diff --git a/src/main/java/appeng/entity/EntityGrowingCrystal.java b/src/main/java/appeng/entity/EntityGrowingCrystal.java index 3b3bf13c5..f9779fbb2 100644 --- a/src/main/java/appeng/entity/EntityGrowingCrystal.java +++ b/src/main/java/appeng/entity/EntityGrowingCrystal.java @@ -19,6 +19,13 @@ package appeng.entity; +import appeng.api.implementations.items.IGrowableCrystal; +import appeng.api.implementations.tiles.ICrystalGrowthAccelerator; +import appeng.client.EffectType; +import appeng.core.AEConfig; +import appeng.core.AppEng; +import appeng.core.features.AEFeature; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.item.EntityItem; @@ -29,170 +36,132 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; -import appeng.api.implementations.items.IGrowableCrystal; -import appeng.api.implementations.tiles.ICrystalGrowthAccelerator; -import appeng.client.EffectType; -import appeng.core.AEConfig; -import appeng.core.AppEng; -import appeng.core.features.AEFeature; -import appeng.util.Platform; +public final class EntityGrowingCrystal extends EntityItem { -public final class EntityGrowingCrystal extends EntityItem -{ + private int progress_1000 = 0; - private int progress_1000 = 0; + public EntityGrowingCrystal(final World w) { + super(w); + } - public EntityGrowingCrystal( final World w ) - { - super( w ); - } + public EntityGrowingCrystal(final World w, final double x, final double y, final double z, final ItemStack is) { + super(w, x, y, z, is); + this.setNoDespawn(); + } - public EntityGrowingCrystal( final World w, final double x, final double y, final double z, final ItemStack is ) - { - super( w, x, y, z, is ); - this.setNoDespawn(); - } + @Override + public void onUpdate() { + super.onUpdate(); - @Override - public void onUpdate() - { - super.onUpdate(); + if (!AEConfig.instance().isFeatureEnabled(AEFeature.IN_WORLD_PURIFICATION)) { + return; + } - if( !AEConfig.instance().isFeatureEnabled( AEFeature.IN_WORLD_PURIFICATION ) ) - { - return; - } + final ItemStack is = this.getItem(); + final Item gc = is.getItem(); - final ItemStack is = this.getItem(); - final Item gc = is.getItem(); + if (gc instanceof IGrowableCrystal) // if it changes this just stops being an issue... + { + final int j = MathHelper.floor(this.posX); + final int i = MathHelper.floor((this.getEntityBoundingBox().minY + this.getEntityBoundingBox().maxY) / 2.0D); + final int k = MathHelper.floor(this.posZ); - if( gc instanceof IGrowableCrystal ) // if it changes this just stops being an issue... - { - final int j = MathHelper.floor( this.posX ); - final int i = MathHelper.floor( ( this.getEntityBoundingBox().minY + this.getEntityBoundingBox().maxY ) / 2.0D ); - final int k = MathHelper.floor( this.posZ ); + final IBlockState state = this.world.getBlockState(new BlockPos(j, i, k)); + final Material mat = state.getMaterial(); + final IGrowableCrystal cry = (IGrowableCrystal) is.getItem(); - final IBlockState state = this.world.getBlockState( new BlockPos( j, i, k ) ); - final Material mat = state.getMaterial(); - final IGrowableCrystal cry = (IGrowableCrystal) is.getItem(); + final float multiplier = cry.getMultiplier(state.getBlock(), mat); + final int speed = (int) Math.max(1, this.getSpeed(j, i, k) * multiplier); - final float multiplier = cry.getMultiplier( state.getBlock(), mat ); - final int speed = (int) Math.max( 1, this.getSpeed( j, i, k ) * multiplier ); + final boolean isClient = Platform.isClient(); - final boolean isClient = Platform.isClient(); + if (mat.isLiquid()) { + if (isClient) { + this.progress_1000++; + } else { + this.progress_1000 += speed; + } + } else { + this.progress_1000 = 0; + } - if( mat.isLiquid() ) - { - if( isClient ) - { - this.progress_1000++; - } - else - { - this.progress_1000 += speed; - } - } - else - { - this.progress_1000 = 0; - } + if (isClient) { + int len = 40; - if( isClient ) - { - int len = 40; + if (speed > 2) { + len = 20; + } - if( speed > 2 ) - { - len = 20; - } + if (speed > 90) { + len = 15; + } - if( speed > 90 ) - { - len = 15; - } + if (speed > 150) { + len = 10; + } - if( speed > 150 ) - { - len = 10; - } + if (speed > 240) { + len = 7; + } - if( speed > 240 ) - { - len = 7; - } + if (speed > 360) { + len = 3; + } - if( speed > 360 ) - { - len = 3; - } + if (speed > 500) { + len = 1; + } - if( speed > 500 ) - { - len = 1; - } + if (this.progress_1000 >= len) { + this.progress_1000 = 0; + AppEng.proxy.spawnEffect(EffectType.Vibrant, this.world, this.posX, this.posY + 0.2, this.posZ, null); + } + } else { + if (this.progress_1000 > 1000) { + this.progress_1000 -= 1000; + this.setItem(cry.triggerGrowth(is)); + } + } + } + } - if( this.progress_1000 >= len ) - { - this.progress_1000 = 0; - AppEng.proxy.spawnEffect( EffectType.Vibrant, this.world, this.posX, this.posY + 0.2, this.posZ, null ); - } - } - else - { - if( this.progress_1000 > 1000 ) - { - this.progress_1000 -= 1000; - this.setItem( cry.triggerGrowth( is ) ); - } - } - } - } + private int getSpeed(final int x, final int y, final int z) { + final int per = 80; + final float mul = 0.3f; - private int getSpeed( final int x, final int y, final int z ) - { - final int per = 80; - final float mul = 0.3f; + int qty = 0; - int qty = 0; + if (this.isAccelerated(x + 1, y, z)) { + qty += per + qty * mul; + } - if( this.isAccelerated( x + 1, y, z ) ) - { - qty += per + qty * mul; - } + if (this.isAccelerated(x, y + 1, z)) { + qty += per + qty * mul; + } - if( this.isAccelerated( x, y + 1, z ) ) - { - qty += per + qty * mul; - } + if (this.isAccelerated(x, y, z + 1)) { + qty += per + qty * mul; + } - if( this.isAccelerated( x, y, z + 1 ) ) - { - qty += per + qty * mul; - } + if (this.isAccelerated(x - 1, y, z)) { + qty += per + qty * mul; + } - if( this.isAccelerated( x - 1, y, z ) ) - { - qty += per + qty * mul; - } + if (this.isAccelerated(x, y - 1, z)) { + qty += per + qty * mul; + } - if( this.isAccelerated( x, y - 1, z ) ) - { - qty += per + qty * mul; - } + if (this.isAccelerated(x, y, z - 1)) { + qty += per + qty * mul; + } - if( this.isAccelerated( x, y, z - 1 ) ) - { - qty += per + qty * mul; - } + return qty; + } - return qty; - } + private boolean isAccelerated(final int x, final int y, final int z) { + final TileEntity te = this.world.getTileEntity(new BlockPos(x, y, z)); - private boolean isAccelerated( final int x, final int y, final int z ) - { - final TileEntity te = this.world.getTileEntity( new BlockPos( x, y, z ) ); - - return te instanceof ICrystalGrowthAccelerator && ( (ICrystalGrowthAccelerator) te ).isPowered(); - } + return te instanceof ICrystalGrowthAccelerator && ((ICrystalGrowthAccelerator) te).isPowered(); + } } diff --git a/src/main/java/appeng/entity/EntityIds.java b/src/main/java/appeng/entity/EntityIds.java index a79ac012e..4c2cde5bc 100644 --- a/src/main/java/appeng/entity/EntityIds.java +++ b/src/main/java/appeng/entity/EntityIds.java @@ -22,36 +22,29 @@ package appeng.entity; import net.minecraft.entity.Entity; -public final class EntityIds -{ - private static final int TINY_TNT = 10; - private static final int SINGULARITY = 11; - private static final int CHARGED_QUARTZ = 12; - private static final int GROWING_CRYSTAL = 13; +public final class EntityIds { + private static final int TINY_TNT = 10; + private static final int SINGULARITY = 11; + private static final int CHARGED_QUARTZ = 12; + private static final int GROWING_CRYSTAL = 13; - private EntityIds() - { - } + private EntityIds() { + } - public static int get( final Class droppedEntity ) - { - if( droppedEntity == EntityTinyTNTPrimed.class ) - { - return TINY_TNT; - } - if( droppedEntity == EntitySingularity.class ) - { - return SINGULARITY; - } - if( droppedEntity == EntityChargedQuartz.class ) - { - return CHARGED_QUARTZ; - } - if( droppedEntity == EntityGrowingCrystal.class ) - { - return GROWING_CRYSTAL; - } + public static int get(final Class droppedEntity) { + if (droppedEntity == EntityTinyTNTPrimed.class) { + return TINY_TNT; + } + if (droppedEntity == EntitySingularity.class) { + return SINGULARITY; + } + if (droppedEntity == EntityChargedQuartz.class) { + return CHARGED_QUARTZ; + } + if (droppedEntity == EntityGrowingCrystal.class) { + return GROWING_CRYSTAL; + } - throw new IllegalStateException( "Missing entity id: " + droppedEntity.getName() ); - } + throw new IllegalStateException("Missing entity id: " + droppedEntity.getName()); + } } diff --git a/src/main/java/appeng/entity/EntitySingularity.java b/src/main/java/appeng/entity/EntitySingularity.java index 6b66224c4..06b70b027 100644 --- a/src/main/java/appeng/entity/EntitySingularity.java +++ b/src/main/java/appeng/entity/EntitySingularity.java @@ -19,9 +19,12 @@ package appeng.entity; -import java.util.Date; -import java.util.List; - +import appeng.api.AEApi; +import appeng.api.definitions.IMaterials; +import appeng.core.AEConfig; +import appeng.core.features.AEFeature; +import appeng.helpers.Reflected; +import appeng.util.Platform; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; @@ -31,124 +34,98 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; -import appeng.api.AEApi; -import appeng.api.definitions.IMaterials; -import appeng.core.AEConfig; -import appeng.core.features.AEFeature; -import appeng.helpers.Reflected; -import appeng.util.Platform; +import java.util.Date; +import java.util.List; -public final class EntitySingularity extends AEBaseEntityItem -{ +public final class EntitySingularity extends AEBaseEntityItem { - private static int randTickSeed = 0; + private static int randTickSeed = 0; - @Reflected - public EntitySingularity( final World w ) - { - super( w ); - } + @Reflected + public EntitySingularity(final World w) { + super(w); + } - public EntitySingularity( final World w, final double x, final double y, final double z, final ItemStack is ) - { - super( w, x, y, z, is ); - } + public EntitySingularity(final World w, final double x, final double y, final double z, final ItemStack is) { + super(w, x, y, z, is); + } - @Override - public boolean attackEntityFrom( final DamageSource src, final float dmg ) - { - if( src.isExplosion() ) - { - this.doExplosion(); - return false; - } + @Override + public boolean attackEntityFrom(final DamageSource src, final float dmg) { + if (src.isExplosion()) { + this.doExplosion(); + return false; + } - return super.attackEntityFrom( src, dmg ); - } + return super.attackEntityFrom(src, dmg); + } - private void doExplosion() - { - if( Platform.isClient() ) - { - return; - } + private void doExplosion() { + if (Platform.isClient()) { + return; + } - if( !AEConfig.instance().isFeatureEnabled( AEFeature.IN_WORLD_SINGULARITY ) ) - { - return; - } + if (!AEConfig.instance().isFeatureEnabled(AEFeature.IN_WORLD_SINGULARITY)) { + return; + } - final ItemStack item = this.getItem(); + final ItemStack item = this.getItem(); - final IMaterials materials = AEApi.instance().definitions().materials(); + final IMaterials materials = AEApi.instance().definitions().materials(); - if( materials.singularity().isSameAs( item ) ) - { - final AxisAlignedBB region = new AxisAlignedBB( this.posX - 4, this.posY - 4, this.posZ - 4, this.posX + 4, this.posY + 4, this.posZ + 4 ); - final List l = this.getCheckedEntitiesWithinAABBExcludingEntity( region ); + if (materials.singularity().isSameAs(item)) { + final AxisAlignedBB region = new AxisAlignedBB(this.posX - 4, this.posY - 4, this.posZ - 4, this.posX + 4, this.posY + 4, this.posZ + 4); + final List l = this.getCheckedEntitiesWithinAABBExcludingEntity(region); - for( final Entity e : l ) - { - if( e instanceof EntityItem ) - { - final ItemStack other = ( (EntityItem) e ).getItem(); - if( !other.isEmpty() ) - { - boolean matches = false; - for( final ItemStack is : OreDictionary.getOres( "dustEnder" ) ) - { - if( OreDictionary.itemMatches( other, is, false ) ) - { - matches = true; - break; - } - } + for (final Entity e : l) { + if (e instanceof EntityItem) { + final ItemStack other = ((EntityItem) e).getItem(); + if (!other.isEmpty()) { + boolean matches = false; + for (final ItemStack is : OreDictionary.getOres("dustEnder")) { + if (OreDictionary.itemMatches(other, is, false)) { + matches = true; + break; + } + } - // check... other name. - if( !matches ) - { - for( final ItemStack is : OreDictionary.getOres( "dustEnderPearl" ) ) - { - if( OreDictionary.itemMatches( other, is, false ) ) - { - matches = true; - break; - } - } - } + // check... other name. + if (!matches) { + for (final ItemStack is : OreDictionary.getOres("dustEnderPearl")) { + if (OreDictionary.itemMatches(other, is, false)) { + matches = true; + break; + } + } + } - if( matches ) - { - while( item.getCount() > 0 && other.getCount() > 0 ) - { - other.grow( -1 ); - ; - if( other.getCount() == 0 ) - { - e.setDead(); - } + if (matches) { + while (item.getCount() > 0 && other.getCount() > 0) { + other.grow(-1); + if (other.getCount() == 0) { + e.setDead(); + } - materials.qESingularity().maybeStack( 2 ).ifPresent( singularityStack -> - { - final NBTTagCompound cmp = Platform.openNbtData( singularityStack ); - cmp.setLong( "freq", ( new Date() ).getTime() * 100 + ( randTickSeed ) % 100 ); - randTickSeed++; - item.grow( -1 ); + materials.qESingularity().maybeStack(2).ifPresent(singularityStack -> + { + final NBTTagCompound cmp = Platform.openNbtData(singularityStack); + cmp.setLong("freq", (new Date()).getTime() * 100 + (randTickSeed) % 100); + randTickSeed++; + item.grow(-1); - final EntitySingularity entity = new EntitySingularity( this.world, this.posX, this.posY, this.posZ, singularityStack ); - this.world.spawnEntity( entity ); - } ); - } + final EntitySingularity entity = new EntitySingularity(this.world, this.posX, this.posY, this.posZ, singularityStack); + this.world.spawnEntity(entity); + }); + } - if( item.getCount() <= 0 ) - { - this.setDead(); - } - } - } - } - } - } - } + if (item.getCount() <= 0) { + this.setDead(); + } + } + } + } + } + } + } } diff --git a/src/main/java/appeng/entity/EntityTinyTNTPrimed.java b/src/main/java/appeng/entity/EntityTinyTNTPrimed.java index 383721296..f5b6962df 100644 --- a/src/main/java/appeng/entity/EntityTinyTNTPrimed.java +++ b/src/main/java/appeng/entity/EntityTinyTNTPrimed.java @@ -19,10 +19,14 @@ package appeng.entity; -import java.util.List; - +import appeng.api.AEApi; +import appeng.core.AEConfig; +import appeng.core.AppEng; +import appeng.core.features.AEFeature; +import appeng.core.sync.packets.PacketMockExplosion; +import appeng.helpers.Reflected; +import appeng.util.Platform; import io.netty.buffer.ByteBuf; - import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -41,166 +45,137 @@ import net.minecraft.world.Explosion; import net.minecraft.world.World; import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData; -import appeng.api.AEApi; -import appeng.core.AEConfig; -import appeng.core.AppEng; -import appeng.core.features.AEFeature; -import appeng.core.sync.packets.PacketMockExplosion; -import appeng.helpers.Reflected; -import appeng.util.Platform; +import java.util.List; -public final class EntityTinyTNTPrimed extends EntityTNTPrimed implements IEntityAdditionalSpawnData -{ +public final class EntityTinyTNTPrimed extends EntityTNTPrimed implements IEntityAdditionalSpawnData { - private static final float SIZE = .5f; + private static final float SIZE = .5f; - @Reflected - public EntityTinyTNTPrimed( final World w ) - { - super( w ); - this.setSize( SIZE, SIZE ); - } + @Reflected + public EntityTinyTNTPrimed(final World w) { + super(w); + this.setSize(SIZE, SIZE); + } - public EntityTinyTNTPrimed( final World w, final double x, final double y, final double z, final EntityLivingBase igniter ) - { - super( w, x, y, z, igniter ); - this.setSize( SIZE, SIZE ); - // this.yOffset = this.height / 2.0F; - } + public EntityTinyTNTPrimed(final World w, final double x, final double y, final double z, final EntityLivingBase igniter) { + super(w, x, y, z, igniter); + this.setSize(SIZE, SIZE); + // this.yOffset = this.height / 2.0F; + } - /** - * Called to update the entity's position/logic. - */ - @Override - public void onUpdate() - { - this.handleWaterMovement(); + /** + * Called to update the entity's position/logic. + */ + @Override + public void onUpdate() { + this.handleWaterMovement(); - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - this.motionY -= 0.03999999910593033D; - this.move( MoverType.SELF, this.motionX, this.motionY, this.motionZ ); - this.motionX *= 0.9800000190734863D; - this.motionY *= 0.9800000190734863D; - this.motionZ *= 0.9800000190734863D; + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + this.motionY -= 0.03999999910593033D; + this.move(MoverType.SELF, this.motionX, this.motionY, this.motionZ); + this.motionX *= 0.9800000190734863D; + this.motionY *= 0.9800000190734863D; + this.motionZ *= 0.9800000190734863D; - if( this.onGround ) - { - this.motionX *= 0.699999988079071D; - this.motionZ *= 0.699999988079071D; - this.motionY *= -0.5D; - } + if (this.onGround) { + this.motionX *= 0.699999988079071D; + this.motionZ *= 0.699999988079071D; + this.motionY *= -0.5D; + } - if( this.isInWater() && Platform.isServer() ) // put out the fuse. - { - AEApi.instance().definitions().blocks().tinyTNT().maybeStack( 1 ).ifPresent( tntStack -> - { - final EntityItem item = new EntityItem( this.world, this.posX, this.posY, this.posZ, tntStack ); + if (this.isInWater() && Platform.isServer()) // put out the fuse. + { + AEApi.instance().definitions().blocks().tinyTNT().maybeStack(1).ifPresent(tntStack -> + { + final EntityItem item = new EntityItem(this.world, this.posX, this.posY, this.posZ, tntStack); - item.motionX = this.motionX; - item.motionY = this.motionY; - item.motionZ = this.motionZ; - item.prevPosX = this.prevPosX; - item.prevPosY = this.prevPosY; - item.prevPosZ = this.prevPosZ; + item.motionX = this.motionX; + item.motionY = this.motionY; + item.motionZ = this.motionZ; + item.prevPosX = this.prevPosX; + item.prevPosY = this.prevPosY; + item.prevPosZ = this.prevPosZ; - this.world.spawnEntity( item ); - this.setDead(); - } ); - } + this.world.spawnEntity(item); + this.setDead(); + }); + } - if( this.getFuse() <= 0 ) - { - this.setDead(); + if (this.getFuse() <= 0) { + this.setDead(); - if( !this.world.isRemote ) - { - this.explode(); - } - } - else - { - this.world.spawnParticle( EnumParticleTypes.SMOKE_NORMAL, this.posX, this.posY, this.posZ, 0.0D, 0.0D, 0.0D ); - } - this.setFuse( this.getFuse() - 1 ); - } + if (!this.world.isRemote) { + this.explode(); + } + } else { + this.world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, this.posX, this.posY, this.posZ, 0.0D, 0.0D, 0.0D); + } + this.setFuse(this.getFuse() - 1); + } - // override :P - void explode() - { - this.world.playSound( null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_GENERIC_EXPLODE, SoundCategory.BLOCKS, 4.0F, - ( 1.0F + ( this.world.rand.nextFloat() - this.world.rand.nextFloat() ) * 0.2F ) * 32.9F ); + // override :P + void explode() { + this.world.playSound(null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_GENERIC_EXPLODE, SoundCategory.BLOCKS, 4.0F, + (1.0F + (this.world.rand.nextFloat() - this.world.rand.nextFloat()) * 0.2F) * 32.9F); - if( this.isInWater() ) - { - return; - } + if (this.isInWater()) { + return; + } - final Explosion ex = new Explosion( this.world, this, this.posX, this.posY, this.posZ, 0.2f, false, false ); - final AxisAlignedBB area = new AxisAlignedBB( this.posX - 1.5, this.posY - 1.5f, this.posZ - 1.5, this.posX + 1.5, this.posY + 1.5, this.posZ + 1.5 ); - final List list = this.world.getEntitiesWithinAABBExcludingEntity( this, area ); + final Explosion ex = new Explosion(this.world, this, this.posX, this.posY, this.posZ, 0.2f, false, false); + final AxisAlignedBB area = new AxisAlignedBB(this.posX - 1.5, this.posY - 1.5f, this.posZ - 1.5, this.posX + 1.5, this.posY + 1.5, this.posZ + 1.5); + final List list = this.world.getEntitiesWithinAABBExcludingEntity(this, area); - net.minecraftforge.event.ForgeEventFactory.onExplosionDetonate( this.world, ex, list, 0.2f * 2d ); + net.minecraftforge.event.ForgeEventFactory.onExplosionDetonate(this.world, ex, list, 0.2f * 2d); - for( final Entity e : list ) - { - e.attackEntityFrom( DamageSource.causeExplosionDamage( ex ), 6 ); - } + for (final Entity e : list) { + e.attackEntityFrom(DamageSource.causeExplosionDamage(ex), 6); + } - if( AEConfig.instance().isFeatureEnabled( AEFeature.TINY_TNT_BLOCK_DAMAGE ) ) - { - this.posY -= 0.25; + if (AEConfig.instance().isFeatureEnabled(AEFeature.TINY_TNT_BLOCK_DAMAGE)) { + this.posY -= 0.25; - for( int x = (int) ( this.posX - 2 ); x <= this.posX + 2; x++ ) - { - for( int y = (int) ( this.posY - 2 ); y <= this.posY + 2; y++ ) - { - for( int z = (int) ( this.posZ - 2 ); z <= this.posZ + 2; z++ ) - { - final BlockPos point = new BlockPos( x, y, z ); - final IBlockState state = this.world.getBlockState( point ); - final Block block = state.getBlock(); + for (int x = (int) (this.posX - 2); x <= this.posX + 2; x++) { + for (int y = (int) (this.posY - 2); y <= this.posY + 2; y++) { + for (int z = (int) (this.posZ - 2); z <= this.posZ + 2; z++) { + final BlockPos point = new BlockPos(x, y, z); + final IBlockState state = this.world.getBlockState(point); + final Block block = state.getBlock(); - if( block != null && !block.isAir( state, this.world, point ) ) - { - float strength = (float) ( 2.3f - ( ( ( x + 0.5f ) - this.posX ) * ( ( x + 0.5f ) - this.posX ) + ( ( y + 0.5f ) - this.posY ) * ( ( y + 0.5f ) - this.posY ) + ( ( z + 0.5f ) - this.posZ ) * ( ( z + 0.5f ) - this.posZ ) ) ); + if (block != null && !block.isAir(state, this.world, point)) { + float strength = (float) (2.3f - (((x + 0.5f) - this.posX) * ((x + 0.5f) - this.posX) + ((y + 0.5f) - this.posY) * ((y + 0.5f) - this.posY) + ((z + 0.5f) - this.posZ) * ((z + 0.5f) - this.posZ))); - final float resistance = block.getExplosionResistance( this.world, point, this, ex ); - strength -= ( resistance + 0.3F ) * 0.11f; + final float resistance = block.getExplosionResistance(this.world, point, this, ex); + strength -= (resistance + 0.3F) * 0.11f; - if( strength > 0.01 ) - { - if( block.getMaterial( state ) != Material.AIR ) - { - if( block.canDropFromExplosion( ex ) ) - { - block.dropBlockAsItemWithChance( this.world, point, state, 1.0F / 1.0f, 0 ); - } + if (strength > 0.01) { + if (block.getMaterial(state) != Material.AIR) { + if (block.canDropFromExplosion(ex)) { + block.dropBlockAsItemWithChance(this.world, point, state, 1.0F / 1.0f, 0); + } - block.onBlockExploded( this.world, point, ex ); - } - } - } - } - } - } - } + block.onBlockExploded(this.world, point, ex); + } + } + } + } + } + } + } - AppEng.proxy.sendToAllNearExcept( null, this.posX, this.posY, this.posZ, 64, this.world, new PacketMockExplosion( this.posX, this.posY, this.posZ ) ); - } + AppEng.proxy.sendToAllNearExcept(null, this.posX, this.posY, this.posZ, 64, this.world, new PacketMockExplosion(this.posX, this.posY, this.posZ)); + } - @Override - public void writeSpawnData( final ByteBuf data ) - { - data.writeByte( this.getFuse() ); - } + @Override + public void writeSpawnData(final ByteBuf data) { + data.writeByte(this.getFuse()); + } - @Override - public void readSpawnData( final ByteBuf data ) - { - this.setFuse( data.readByte() ); - ; - } + @Override + public void readSpawnData(final ByteBuf data) { + this.setFuse(data.readByte()); + } } diff --git a/src/main/java/appeng/entity/ICanDie.java b/src/main/java/appeng/entity/ICanDie.java index d46048724..df242a234 100644 --- a/src/main/java/appeng/entity/ICanDie.java +++ b/src/main/java/appeng/entity/ICanDie.java @@ -19,9 +19,8 @@ package appeng.entity; -public interface ICanDie -{ +public interface ICanDie { - public boolean isDead(); + boolean isDead(); } diff --git a/src/main/java/appeng/entity/RenderFloatingItem.java b/src/main/java/appeng/entity/RenderFloatingItem.java index 8668ea288..26be54e5a 100644 --- a/src/main/java/appeng/entity/RenderFloatingItem.java +++ b/src/main/java/appeng/entity/RenderFloatingItem.java @@ -29,44 +29,35 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -@SideOnly( Side.CLIENT ) -public class RenderFloatingItem extends RenderEntityItem -{ +@SideOnly(Side.CLIENT) +public class RenderFloatingItem extends RenderEntityItem { - public RenderFloatingItem( final RenderManager manager ) - { - super( manager, Minecraft.getMinecraft().getRenderItem() ); - this.shadowOpaque = 0.0F; - } + public RenderFloatingItem(final RenderManager manager) { + super(manager, Minecraft.getMinecraft().getRenderItem()); + this.shadowOpaque = 0.0F; + } - @Override - public void doRender( final EntityItem entityItem, final double x, final double y, final double z, final float yaw, final float partialTick ) - { - if( entityItem instanceof EntityFloatingItem ) - { - final EntityFloatingItem efi = (EntityFloatingItem) entityItem; - if( efi.getProgress() > 0.0 ) - { - GlStateManager.pushMatrix(); + @Override + public void doRender(final EntityItem entityItem, final double x, final double y, final double z, final float yaw, final float partialTick) { + if (entityItem instanceof EntityFloatingItem) { + final EntityFloatingItem efi = (EntityFloatingItem) entityItem; + if (efi.getProgress() > 0.0) { + GlStateManager.pushMatrix(); - if( !( efi.getItem().getItem() instanceof ItemBlock ) ) - { - GlStateManager.translate( 0, -0.3f, 0 ); - } - else - { - GlStateManager.translate( 0, -0.2f, 0 ); - } + if (!(efi.getItem().getItem() instanceof ItemBlock)) { + GlStateManager.translate(0, -0.3f, 0); + } else { + GlStateManager.translate(0, -0.2f, 0); + } - super.doRender( efi, x, y, z, yaw, 0 ); - GlStateManager.popMatrix(); - } - } - } + super.doRender(efi, x, y, z, yaw, 0); + GlStateManager.popMatrix(); + } + } + } - @Override - public boolean shouldBob() - { - return false; - } + @Override + public boolean shouldBob() { + return false; + } } diff --git a/src/main/java/appeng/entity/RenderTinyTNTPrimed.java b/src/main/java/appeng/entity/RenderTinyTNTPrimed.java index 00debfd11..538026084 100644 --- a/src/main/java/appeng/entity/RenderTinyTNTPrimed.java +++ b/src/main/java/appeng/entity/RenderTinyTNTPrimed.java @@ -31,76 +31,68 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -@SideOnly( Side.CLIENT ) -public class RenderTinyTNTPrimed extends Render -{ +@SideOnly(Side.CLIENT) +public class RenderTinyTNTPrimed extends Render { - public RenderTinyTNTPrimed( final RenderManager p_i46134_1_ ) - { - super( p_i46134_1_ ); - this.shadowSize = 0.5F; - } + public RenderTinyTNTPrimed(final RenderManager p_i46134_1_) { + super(p_i46134_1_); + this.shadowSize = 0.5F; + } - @Override - public void doRender( final EntityTinyTNTPrimed tnt, final double x, final double y, final double z, final float unused, final float life ) - { - final BlockRendererDispatcher blockrendererdispatcher = Minecraft.getMinecraft().getBlockRendererDispatcher(); - GlStateManager.pushMatrix(); - GlStateManager.translate( (float) x, (float) y + 0.25F, (float) z ); - float f2; + @Override + public void doRender(final EntityTinyTNTPrimed tnt, final double x, final double y, final double z, final float unused, final float life) { + final BlockRendererDispatcher blockrendererdispatcher = Minecraft.getMinecraft().getBlockRendererDispatcher(); + GlStateManager.pushMatrix(); + GlStateManager.translate((float) x, (float) y + 0.25F, (float) z); + float f2; - if( tnt.getFuse() - life + 1.0F < 10.0F ) - { - f2 = 1.0F - ( tnt.getFuse() - life + 1.0F ) / 10.0F; + if (tnt.getFuse() - life + 1.0F < 10.0F) { + f2 = 1.0F - (tnt.getFuse() - life + 1.0F) / 10.0F; - if( f2 < 0.0F ) - { - f2 = 0.0F; - } + if (f2 < 0.0F) { + f2 = 0.0F; + } - if( f2 > 1.0F ) - { - f2 = 1.0F; - } + if (f2 > 1.0F) { + f2 = 1.0F; + } - f2 *= f2; - f2 *= f2; - final float f3 = 1.0F + f2 * 0.3F; - GlStateManager.scale( f3, f3, f3 ); - } + f2 *= f2; + f2 *= f2; + final float f3 = 1.0F + f2 * 0.3F; + GlStateManager.scale(f3, f3, f3); + } - GlStateManager.scale( 0.5f, 0.5f, 0.5f ); - f2 = ( 1.0F - ( tnt.getFuse() - life + 1.0F ) / 100.0F ) * 0.8F; - this.bindEntityTexture( tnt ); - GlStateManager.translate( -0.5F, -0.5F, 0.5F ); - blockrendererdispatcher.renderBlockBrightness( Blocks.TNT.getDefaultState(), tnt.getBrightness() ); - GlStateManager.translate( 0.0F, 0.0F, 1.0F ); + GlStateManager.scale(0.5f, 0.5f, 0.5f); + f2 = (1.0F - (tnt.getFuse() - life + 1.0F) / 100.0F) * 0.8F; + this.bindEntityTexture(tnt); + GlStateManager.translate(-0.5F, -0.5F, 0.5F); + blockrendererdispatcher.renderBlockBrightness(Blocks.TNT.getDefaultState(), tnt.getBrightness()); + GlStateManager.translate(0.0F, 0.0F, 1.0F); - if( tnt.getFuse() / 5 % 2 == 0 ) - { - GlStateManager.disableTexture2D(); - GlStateManager.disableLighting(); - GlStateManager.enableBlend(); - GlStateManager.blendFunc( 770, 772 ); - GlStateManager.color( 1.0F, 1.0F, 1.0F, f2 ); - GlStateManager.doPolygonOffset( -3.0F, -3.0F ); - GlStateManager.enablePolygonOffset(); - blockrendererdispatcher.renderBlockBrightness( Blocks.TNT.getDefaultState(), 1.0F ); - GlStateManager.doPolygonOffset( 0.0F, 0.0F ); - GlStateManager.disablePolygonOffset(); - GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); - GlStateManager.disableBlend(); - GlStateManager.enableLighting(); - GlStateManager.enableTexture2D(); - } + if (tnt.getFuse() / 5 % 2 == 0) { + GlStateManager.disableTexture2D(); + GlStateManager.disableLighting(); + GlStateManager.enableBlend(); + GlStateManager.blendFunc(770, 772); + GlStateManager.color(1.0F, 1.0F, 1.0F, f2); + GlStateManager.doPolygonOffset(-3.0F, -3.0F); + GlStateManager.enablePolygonOffset(); + blockrendererdispatcher.renderBlockBrightness(Blocks.TNT.getDefaultState(), 1.0F); + GlStateManager.doPolygonOffset(0.0F, 0.0F); + GlStateManager.disablePolygonOffset(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.disableBlend(); + GlStateManager.enableLighting(); + GlStateManager.enableTexture2D(); + } - GlStateManager.popMatrix(); - super.doRender( tnt, x, y, z, unused, life ); - } + GlStateManager.popMatrix(); + super.doRender(tnt, x, y, z, unused, life); + } - @Override - protected ResourceLocation getEntityTexture( final EntityTinyTNTPrimed entity ) - { - return TextureMap.LOCATION_BLOCKS_TEXTURE; - } + @Override + protected ResourceLocation getEntityTexture(final EntityTinyTNTPrimed entity) { + return TextureMap.LOCATION_BLOCKS_TEXTURE; + } } diff --git a/src/main/java/appeng/facade/FacadeContainer.java b/src/main/java/appeng/facade/FacadeContainer.java index 0c7631a12..02c958bdb 100644 --- a/src/main/java/appeng/facade/FacadeContainer.java +++ b/src/main/java/appeng/facade/FacadeContainer.java @@ -19,15 +19,6 @@ package appeng.facade; -import java.io.IOException; -import java.util.Optional; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import appeng.api.AEApi; import appeng.api.parts.IFacadeContainer; import appeng.api.parts.IFacadePart; @@ -35,185 +26,158 @@ import appeng.api.parts.IPartHost; import appeng.api.util.AEPartLocation; import appeng.items.parts.ItemFacade; import appeng.parts.CableBusStorage; +import io.netty.buffer.ByteBuf; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +import java.io.IOException; +import java.util.Optional; -public class FacadeContainer implements IFacadeContainer -{ +public class FacadeContainer implements IFacadeContainer { - private final int facades = 6; - private final CableBusStorage storage; + private final int facades = 6; + private final CableBusStorage storage; - public FacadeContainer( final CableBusStorage cbs ) - { - this.storage = cbs; - } + public FacadeContainer(final CableBusStorage cbs) { + this.storage = cbs; + } - @Override - public boolean addFacade( final IFacadePart a ) - { - if( this.getFacade( a.getSide() ) == null ) - { - this.storage.setFacade( a.getSide().ordinal(), a ); - return true; - } - return false; - } + @Override + public boolean addFacade(final IFacadePart a) { + if (this.getFacade(a.getSide()) == null) { + this.storage.setFacade(a.getSide().ordinal(), a); + return true; + } + return false; + } - @Override - public void removeFacade( final IPartHost host, final AEPartLocation side ) - { - if( side != null && side != AEPartLocation.INTERNAL ) - { - if( this.storage.getFacade( side.ordinal() ) != null ) - { - this.storage.setFacade( side.ordinal(), null ); - if( host != null ) - { - host.markForUpdate(); - } - } - } - } + @Override + public void removeFacade(final IPartHost host, final AEPartLocation side) { + if (side != null && side != AEPartLocation.INTERNAL) { + if (this.storage.getFacade(side.ordinal()) != null) { + this.storage.setFacade(side.ordinal(), null); + if (host != null) { + host.markForUpdate(); + } + } + } + } - @Override - public IFacadePart getFacade( final AEPartLocation s ) - { - return this.storage.getFacade( s.ordinal() ); - } + @Override + public IFacadePart getFacade(final AEPartLocation s) { + return this.storage.getFacade(s.ordinal()); + } - @Override - public void rotateLeft() - { - final IFacadePart[] newFacades = new FacadePart[6]; + @Override + public void rotateLeft() { + final IFacadePart[] newFacades = new FacadePart[6]; - newFacades[AEPartLocation.UP.ordinal()] = this.storage.getFacade( AEPartLocation.UP.ordinal() ); - newFacades[AEPartLocation.DOWN.ordinal()] = this.storage.getFacade( AEPartLocation.DOWN.ordinal() ); + newFacades[AEPartLocation.UP.ordinal()] = this.storage.getFacade(AEPartLocation.UP.ordinal()); + newFacades[AEPartLocation.DOWN.ordinal()] = this.storage.getFacade(AEPartLocation.DOWN.ordinal()); - newFacades[AEPartLocation.EAST.ordinal()] = this.storage.getFacade( AEPartLocation.NORTH.ordinal() ); - newFacades[AEPartLocation.SOUTH.ordinal()] = this.storage.getFacade( AEPartLocation.EAST.ordinal() ); + newFacades[AEPartLocation.EAST.ordinal()] = this.storage.getFacade(AEPartLocation.NORTH.ordinal()); + newFacades[AEPartLocation.SOUTH.ordinal()] = this.storage.getFacade(AEPartLocation.EAST.ordinal()); - newFacades[AEPartLocation.WEST.ordinal()] = this.storage.getFacade( AEPartLocation.SOUTH.ordinal() ); - newFacades[AEPartLocation.NORTH.ordinal()] = this.storage.getFacade( AEPartLocation.WEST.ordinal() ); + newFacades[AEPartLocation.WEST.ordinal()] = this.storage.getFacade(AEPartLocation.SOUTH.ordinal()); + newFacades[AEPartLocation.NORTH.ordinal()] = this.storage.getFacade(AEPartLocation.WEST.ordinal()); - for( int x = 0; x < this.facades; x++ ) - { - this.storage.setFacade( x, newFacades[x] ); - } - } + for (int x = 0; x < this.facades; x++) { + this.storage.setFacade(x, newFacades[x]); + } + } - @Override - public void writeToNBT( final NBTTagCompound c ) - { - for( int x = 0; x < this.facades; x++ ) - { - if( this.storage.getFacade( x ) != null ) - { - final NBTTagCompound data = new NBTTagCompound(); - this.storage.getFacade( x ).getItemStack().writeToNBT( data ); - c.setTag( "facade:" + x, data ); - } - } - } + @Override + public void writeToNBT(final NBTTagCompound c) { + for (int x = 0; x < this.facades; x++) { + if (this.storage.getFacade(x) != null) { + final NBTTagCompound data = new NBTTagCompound(); + this.storage.getFacade(x).getItemStack().writeToNBT(data); + c.setTag("facade:" + x, data); + } + } + } - @Override - public boolean readFromStream( final ByteBuf out ) throws IOException - { - final int facadeSides = out.readByte(); + @Override + public boolean readFromStream(final ByteBuf out) throws IOException { + final int facadeSides = out.readByte(); - boolean changed = false; + boolean changed = false; - final int[] ids = new int[2]; - for( int x = 0; x < this.facades; x++ ) - { - final AEPartLocation side = AEPartLocation.fromOrdinal( x ); - final int ix = ( 1 << x ); - if( ( facadeSides & ix ) == ix ) - { - ids[0] = out.readInt(); - ids[1] = out.readInt(); - ids[0] = Math.abs( ids[0] ); + final int[] ids = new int[2]; + for (int x = 0; x < this.facades; x++) { + final AEPartLocation side = AEPartLocation.fromOrdinal(x); + final int ix = (1 << x); + if ((facadeSides & ix) == ix) { + ids[0] = out.readInt(); + ids[1] = out.readInt(); + ids[0] = Math.abs(ids[0]); - Optional maybeFacadeItem = AEApi.instance().definitions().items().facade().maybeItem(); - if( maybeFacadeItem.isPresent() ) - { - final ItemFacade ifa = (ItemFacade) maybeFacadeItem.get(); - final ItemStack facade = ifa.createFromIDs( ids ); - if( facade != null ) - { - changed = changed || this.storage.getFacade( x ) == null; - this.storage.setFacade( x, ifa.createPartFromItemStack( facade, side ) ); - } - } - } - else - { - changed = changed || this.storage.getFacade( x ) != null; - this.storage.setFacade( x, null ); - } - } + Optional maybeFacadeItem = AEApi.instance().definitions().items().facade().maybeItem(); + if (maybeFacadeItem.isPresent()) { + final ItemFacade ifa = (ItemFacade) maybeFacadeItem.get(); + final ItemStack facade = ifa.createFromIDs(ids); + if (facade != null) { + changed = changed || this.storage.getFacade(x) == null; + this.storage.setFacade(x, ifa.createPartFromItemStack(facade, side)); + } + } + } else { + changed = changed || this.storage.getFacade(x) != null; + this.storage.setFacade(x, null); + } + } - return changed; - } + return changed; + } - @Override - public void readFromNBT( final NBTTagCompound c ) - { - for( int x = 0; x < this.facades; x++ ) - { - this.storage.setFacade( x, null ); + @Override + public void readFromNBT(final NBTTagCompound c) { + for (int x = 0; x < this.facades; x++) { + this.storage.setFacade(x, null); - final NBTTagCompound t = c.getCompoundTag( "facade:" + x ); - if( t != null ) - { - final ItemStack is = new ItemStack( t ); - if( !is.isEmpty() ) - { - final Item i = is.getItem(); - if( i instanceof IFacadeItem ) - { - this.storage.setFacade( x, ( (IFacadeItem) i ).createPartFromItemStack( is, AEPartLocation.fromOrdinal( x ) ) ); - } - } - } - } - } + final NBTTagCompound t = c.getCompoundTag("facade:" + x); + if (t != null) { + final ItemStack is = new ItemStack(t); + if (!is.isEmpty()) { + final Item i = is.getItem(); + if (i instanceof IFacadeItem) { + this.storage.setFacade(x, ((IFacadeItem) i).createPartFromItemStack(is, AEPartLocation.fromOrdinal(x))); + } + } + } + } + } - @Override - public void writeToStream( final ByteBuf out ) throws IOException - { - int facadeSides = 0; - for( int x = 0; x < this.facades; x++ ) - { - if( this.getFacade( AEPartLocation.fromOrdinal( x ) ) != null ) - { - facadeSides |= ( 1 << x ); - } - } - out.writeByte( (byte) facadeSides ); + @Override + public void writeToStream(final ByteBuf out) throws IOException { + int facadeSides = 0; + for (int x = 0; x < this.facades; x++) { + if (this.getFacade(AEPartLocation.fromOrdinal(x)) != null) { + facadeSides |= (1 << x); + } + } + out.writeByte((byte) facadeSides); - for( int x = 0; x < this.facades; x++ ) - { - final IFacadePart part = this.getFacade( AEPartLocation.fromOrdinal( x ) ); - if( part != null ) - { - final int itemID = Item.getIdFromItem( part.getItem() ); - final int dmgValue = part.getItemDamage(); - out.writeInt( itemID * ( part.notAEFacade() ? -1 : 1 ) ); - out.writeInt( dmgValue ); - } - } - } + for (int x = 0; x < this.facades; x++) { + final IFacadePart part = this.getFacade(AEPartLocation.fromOrdinal(x)); + if (part != null) { + final int itemID = Item.getIdFromItem(part.getItem()); + final int dmgValue = part.getItemDamage(); + out.writeInt(itemID * (part.notAEFacade() ? -1 : 1)); + out.writeInt(dmgValue); + } + } + } - @Override - public boolean isEmpty() - { - for( int x = 0; x < this.facades; x++ ) - { - if( this.storage.getFacade( x ) != null ) - { - return false; - } - } - return true; - } + @Override + public boolean isEmpty() { + for (int x = 0; x < this.facades; x++) { + if (this.storage.getFacade(x) != null) { + return false; + } + } + return true; + } } diff --git a/src/main/java/appeng/facade/FacadePart.java b/src/main/java/appeng/facade/FacadePart.java index ea2080a36..6acdd2494 100644 --- a/src/main/java/appeng/facade/FacadePart.java +++ b/src/main/java/appeng/facade/FacadePart.java @@ -19,6 +19,11 @@ package appeng.facade; +import appeng.api.AEApi; +import appeng.api.parts.IBoxProvider; +import appeng.api.parts.IFacadePart; +import appeng.api.parts.IPartCollisionHelper; +import appeng.api.util.AEPartLocation; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -27,136 +32,108 @@ import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import appeng.api.AEApi; -import appeng.api.parts.IBoxProvider; -import appeng.api.parts.IFacadePart; -import appeng.api.parts.IPartCollisionHelper; -import appeng.api.util.AEPartLocation; +public class FacadePart implements IFacadePart, IBoxProvider { -public class FacadePart implements IFacadePart, IBoxProvider -{ + private final ItemStack facade; + private final AEPartLocation side; - private final ItemStack facade; - private final AEPartLocation side; + public FacadePart(final ItemStack facade, final AEPartLocation side) { + if (facade == null) { + throw new IllegalArgumentException("Facade Part constructed on null item."); + } + this.facade = facade.copy(); + this.facade.setCount(1); + this.side = side; + } - public FacadePart( final ItemStack facade, final AEPartLocation side ) - { - if( facade == null ) - { - throw new IllegalArgumentException( "Facade Part constructed on null item." ); - } - this.facade = facade.copy(); - this.facade.setCount( 1 ); - this.side = side; - } + public static boolean isFacade(final ItemStack is) { + return is.getItem() instanceof IFacadeItem; + } - public static boolean isFacade( final ItemStack is ) - { - return is.getItem() instanceof IFacadeItem; - } + @Override + public ItemStack getItemStack() { + return this.facade; + } - @Override - public ItemStack getItemStack() - { - return this.facade; - } + @Override + public void getBoxes(final IPartCollisionHelper ch, final Entity e) { + if (e instanceof EntityLivingBase) { + // prevent weird snag behavior + ch.addBox(0.0, 0.0, 14, 16.0, 16.0, 16.0); + } else { + // the box is 15.9 for transition planes to pick up collision events. + ch.addBox(0.0, 0.0, 14, 16.0, 16.0, 15.9); + } + } - @Override - public void getBoxes( final IPartCollisionHelper ch, final Entity e ) - { - if( e instanceof EntityLivingBase ) - { - // prevent weird snag behavior - ch.addBox( 0.0, 0.0, 14, 16.0, 16.0, 16.0 ); - } - else - { - // the box is 15.9 for transition planes to pick up collision events. - ch.addBox( 0.0, 0.0, 14, 16.0, 16.0, 15.9 ); - } - } + @Override + public AEPartLocation getSide() { + return this.side; + } - @Override - public AEPartLocation getSide() - { - return this.side; - } + @Override + public Item getItem() { + final ItemStack is = this.getTextureItem(); + if (is.isEmpty()) { + return Items.AIR; + } + return is.getItem(); + } - @Override - public Item getItem() - { - final ItemStack is = this.getTextureItem(); - if( is.isEmpty() ) - { - return Items.AIR; - } - return is.getItem(); - } + @Override + public int getItemDamage() { + final ItemStack is = this.getTextureItem(); + if (is.isEmpty()) { + return 0; + } + return is.getItemDamage(); + } - @Override - public int getItemDamage() - { - final ItemStack is = this.getTextureItem(); - if( is.isEmpty() ) - { - return 0; - } - return is.getItemDamage(); - } + @Override + public boolean notAEFacade() { + return !(this.facade.getItem() instanceof IFacadeItem); + } - @Override - public boolean notAEFacade() - { - return !( this.facade.getItem() instanceof IFacadeItem ); - } + @Override + public boolean isTransparent() { + if (AEApi.instance().partHelper().getCableRenderMode().transparentFacades) { + return true; + } - @Override - public boolean isTransparent() - { - if( AEApi.instance().partHelper().getCableRenderMode().transparentFacades ) - { - return true; - } + return this.getBlockState().isOpaqueCube(); + } - return this.getBlockState().isOpaqueCube(); - } + @Override + public ItemStack getTextureItem() { + final Item maybeFacade = this.facade.getItem(); - @Override - public ItemStack getTextureItem() - { - final Item maybeFacade = this.facade.getItem(); + // AE Facade + if (maybeFacade instanceof IFacadeItem) { + final IFacadeItem facade = (IFacadeItem) maybeFacade; - // AE Facade - if( maybeFacade instanceof IFacadeItem ) - { - final IFacadeItem facade = (IFacadeItem) maybeFacade; + return facade.getTextureItem(this.facade); + } - return facade.getTextureItem( this.facade ); - } + return ItemStack.EMPTY; + } - return ItemStack.EMPTY; - } + @Override + public IBlockState getBlockState() { + final Item maybeFacade = this.facade.getItem(); - @Override - public IBlockState getBlockState() - { - final Item maybeFacade = this.facade.getItem(); + // AE Facade + if (maybeFacade instanceof IFacadeItem) { + final IFacadeItem facade = (IFacadeItem) maybeFacade; - // AE Facade - if( maybeFacade instanceof IFacadeItem ) - { - final IFacadeItem facade = (IFacadeItem) maybeFacade; + return facade.getTextureBlockState(this.facade); + } - return facade.getTextureBlockState( this.facade ); - } + return Blocks.GLASS.getDefaultState(); + } - return Blocks.GLASS.getDefaultState(); - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - this.getBoxes( bch, null ); - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + this.getBoxes(bch, null); + } } diff --git a/src/main/java/appeng/facade/IFacadeItem.java b/src/main/java/appeng/facade/IFacadeItem.java index fd10484ff..b93d56964 100644 --- a/src/main/java/appeng/facade/IFacadeItem.java +++ b/src/main/java/appeng/facade/IFacadeItem.java @@ -19,19 +19,17 @@ package appeng.facade; +import appeng.api.util.AEPartLocation; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; -import appeng.api.util.AEPartLocation; +public interface IFacadeItem { -public interface IFacadeItem -{ + FacadePart createPartFromItemStack(ItemStack is, AEPartLocation side); - FacadePart createPartFromItemStack( ItemStack is, AEPartLocation side ); + ItemStack getTextureItem(ItemStack is); - ItemStack getTextureItem( ItemStack is ); - - IBlockState getTextureBlockState( ItemStack is ); + IBlockState getTextureBlockState(ItemStack is); } diff --git a/src/main/java/appeng/fluids/block/BlockFluidInterface.java b/src/main/java/appeng/fluids/block/BlockFluidInterface.java index 4eabf1efd..b369727ba 100644 --- a/src/main/java/appeng/fluids/block/BlockFluidInterface.java +++ b/src/main/java/appeng/fluids/block/BlockFluidInterface.java @@ -19,8 +19,11 @@ package appeng.fluids.block; -import javax.annotation.Nullable; - +import appeng.api.util.AEPartLocation; +import appeng.block.AEBaseTileBlock; +import appeng.core.sync.GuiBridge; +import appeng.fluids.tile.TileFluidInterface; +import appeng.util.Platform; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -30,37 +33,27 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.api.util.AEPartLocation; -import appeng.block.AEBaseTileBlock; -import appeng.core.sync.GuiBridge; -import appeng.fluids.tile.TileFluidInterface; -import appeng.util.Platform; +import javax.annotation.Nullable; -public class BlockFluidInterface extends AEBaseTileBlock -{ - public BlockFluidInterface() - { - super( Material.IRON ); - } +public class BlockFluidInterface extends AEBaseTileBlock { + public BlockFluidInterface() { + super(Material.IRON); + } - @Override - public boolean onActivated( final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated(final World w, final BlockPos pos, final EntityPlayer p, final EnumHand hand, final @Nullable ItemStack heldItem, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileEntity tg = this.getTileEntity( w, pos ); - if( tg instanceof TileFluidInterface ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, AEPartLocation.fromFacing( side ), GuiBridge.GUI_FLUID_INTERFACE ); - } - return true; - } - return false; - } + final TileEntity tg = this.getTileEntity(w, pos); + if (tg instanceof TileFluidInterface) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, AEPartLocation.fromFacing(side), GuiBridge.GUI_FLUID_INTERFACE); + } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/fluids/client/gui/GuiFluidFormationPlane.java b/src/main/java/appeng/fluids/client/gui/GuiFluidFormationPlane.java index 6be00d3d6..acf3f16c5 100644 --- a/src/main/java/appeng/fluids/client/gui/GuiFluidFormationPlane.java +++ b/src/main/java/appeng/fluids/client/gui/GuiFluidFormationPlane.java @@ -1,12 +1,6 @@ - package appeng.fluids.client.gui; -import java.io.IOException; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.client.gui.implementations.GuiUpgradeable; import appeng.client.gui.widgets.GuiTabButton; import appeng.core.localization.GuiText; @@ -18,73 +12,64 @@ import appeng.fluids.client.gui.widgets.GuiOptionalFluidSlot; import appeng.fluids.container.ContainerFluidFormationPlane; import appeng.fluids.parts.PartFluidFormationPlane; import appeng.fluids.util.IAEFluidTank; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; + +import java.io.IOException; -public class GuiFluidFormationPlane extends GuiUpgradeable -{ - private final PartFluidFormationPlane plane; - private GuiTabButton priority; +public class GuiFluidFormationPlane extends GuiUpgradeable { + private final PartFluidFormationPlane plane; + private GuiTabButton priority; - public GuiFluidFormationPlane( InventoryPlayer inventoryPlayer, PartFluidFormationPlane te ) - { - super( new ContainerFluidFormationPlane( inventoryPlayer, te ) ); - this.ySize = 251; - this.plane = te; - } + public GuiFluidFormationPlane(InventoryPlayer inventoryPlayer, PartFluidFormationPlane te) { + super(new ContainerFluidFormationPlane(inventoryPlayer, te)); + this.ySize = 251; + this.plane = te; + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - final int xo = 8; - final int yo = 23 + 6; + final int xo = 8; + final int yo = 23 + 6; - final IAEFluidTank config = this.plane.getConfig(); - final ContainerFluidFormationPlane container = (ContainerFluidFormationPlane) this.inventorySlots; + final IAEFluidTank config = this.plane.getConfig(); + final ContainerFluidFormationPlane container = (ContainerFluidFormationPlane) this.inventorySlots; - for( int y = 0; y < 7; y++ ) - { - for( int x = 0; x < 9; x++ ) - { - final int idx = y * 9 + x; - if( y < 2 ) - { - this.guiSlots.add( new GuiFluidSlot( config, idx, idx, xo + x * 18, yo + y * 18 ) ); - } - else - { - this.guiSlots.add( new GuiOptionalFluidSlot( config, container, idx, idx, y - 2, xo, yo, x, y ) ); - } - } - } - } + for (int y = 0; y < 7; y++) { + for (int x = 0; x < 9; x++) { + final int idx = y * 9 + x; + if (y < 2) { + this.guiSlots.add(new GuiFluidSlot(config, idx, idx, xo + x * 18, yo + y * 18)); + } else { + this.guiSlots.add(new GuiOptionalFluidSlot(config, container, idx, idx, y - 2, xo, yo, x, y)); + } + } + } + } - @Override - protected void addButtons() - { - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender ) ); - } + @Override + protected void addButtons() { + this.buttonList.add(this.priority = new GuiTabButton(this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender)); + } - @Override - protected String getBackground() - { - return "guis/storagebus.png"; - } + @Override + protected String getBackground() { + return "guis/storagebus.png"; + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); - if( btn == this.priority ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - } + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); + if (btn == this.priority) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } + } - @Override - protected GuiText getName() - { - return GuiText.FluidFormationPlane; - } + @Override + protected GuiText getName() { + return GuiText.FluidFormationPlane; + } } diff --git a/src/main/java/appeng/fluids/client/gui/GuiFluidIO.java b/src/main/java/appeng/fluids/client/gui/GuiFluidIO.java index 20ccdfd48..dde7c0285 100644 --- a/src/main/java/appeng/fluids/client/gui/GuiFluidIO.java +++ b/src/main/java/appeng/fluids/client/gui/GuiFluidIO.java @@ -19,8 +19,6 @@ package appeng.fluids.client.gui; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.client.gui.implementations.GuiUpgradeable; import appeng.core.localization.GuiText; import appeng.fluids.client.gui.widgets.GuiFluidSlot; @@ -29,6 +27,7 @@ import appeng.fluids.container.ContainerFluidIO; import appeng.fluids.parts.PartFluidImportBus; import appeng.fluids.parts.PartSharedFluidBus; import appeng.fluids.util.IAEFluidTank; +import net.minecraft.entity.player.InventoryPlayer; /** @@ -36,41 +35,37 @@ import appeng.fluids.util.IAEFluidTank; * @version rv5 - 1/05/2018 * @since rv5 1/05/2018 */ -public class GuiFluidIO extends GuiUpgradeable -{ - private final PartSharedFluidBus bus; +public class GuiFluidIO extends GuiUpgradeable { + private final PartSharedFluidBus bus; - public GuiFluidIO( InventoryPlayer inventoryPlayer, PartSharedFluidBus te ) - { - super( new ContainerFluidIO( inventoryPlayer, te ) ); - this.bus = te; - } + public GuiFluidIO(InventoryPlayer inventoryPlayer, PartSharedFluidBus te) { + super(new ContainerFluidIO(inventoryPlayer, te)); + this.bus = te; + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - final ContainerFluidIO container = (ContainerFluidIO) this.inventorySlots; - final IAEFluidTank inv = this.bus.getConfig(); - final int y = 40; - final int x = 80; + final ContainerFluidIO container = (ContainerFluidIO) this.inventorySlots; + final IAEFluidTank inv = this.bus.getConfig(); + final int y = 40; + final int x = 80; - this.guiSlots.add( new GuiFluidSlot( inv, 0, 0, x, y ) ); - this.guiSlots.add( new GuiOptionalFluidSlot( inv, container, 1, 1, 1, x, y, -1, 0 ) ); - this.guiSlots.add( new GuiOptionalFluidSlot( inv, container, 2, 2, 1, x, y, 1, 0 ) ); - this.guiSlots.add( new GuiOptionalFluidSlot( inv, container, 3, 3, 1, x, y, 0, -1 ) ); - this.guiSlots.add( new GuiOptionalFluidSlot( inv, container, 4, 4, 1, x, y, 0, 1 ) ); + this.guiSlots.add(new GuiFluidSlot(inv, 0, 0, x, y)); + this.guiSlots.add(new GuiOptionalFluidSlot(inv, container, 1, 1, 1, x, y, -1, 0)); + this.guiSlots.add(new GuiOptionalFluidSlot(inv, container, 2, 2, 1, x, y, 1, 0)); + this.guiSlots.add(new GuiOptionalFluidSlot(inv, container, 3, 3, 1, x, y, 0, -1)); + this.guiSlots.add(new GuiOptionalFluidSlot(inv, container, 4, 4, 1, x, y, 0, 1)); - this.guiSlots.add( new GuiOptionalFluidSlot( inv, container, 5, 5, 2, x, y, -1, -1 ) ); - this.guiSlots.add( new GuiOptionalFluidSlot( inv, container, 6, 6, 2, x, y, 1, -1 ) ); - this.guiSlots.add( new GuiOptionalFluidSlot( inv, container, 7, 7, 2, x, y, -1, 1 ) ); - this.guiSlots.add( new GuiOptionalFluidSlot( inv, container, 8, 8, 2, x, y, 1, 1 ) ); - } + this.guiSlots.add(new GuiOptionalFluidSlot(inv, container, 5, 5, 2, x, y, -1, -1)); + this.guiSlots.add(new GuiOptionalFluidSlot(inv, container, 6, 6, 2, x, y, 1, -1)); + this.guiSlots.add(new GuiOptionalFluidSlot(inv, container, 7, 7, 2, x, y, -1, 1)); + this.guiSlots.add(new GuiOptionalFluidSlot(inv, container, 8, 8, 2, x, y, 1, 1)); + } - @Override - protected GuiText getName() - { - return this.bc instanceof PartFluidImportBus ? GuiText.ImportBusFluids : GuiText.ExportBusFluids; - } + @Override + protected GuiText getName() { + return this.bc instanceof PartFluidImportBus ? GuiText.ImportBusFluids : GuiText.ExportBusFluids; + } } diff --git a/src/main/java/appeng/fluids/client/gui/GuiFluidInterface.java b/src/main/java/appeng/fluids/client/gui/GuiFluidInterface.java index 01d90017b..0fef98912 100644 --- a/src/main/java/appeng/fluids/client/gui/GuiFluidInterface.java +++ b/src/main/java/appeng/fluids/client/gui/GuiFluidInterface.java @@ -19,15 +19,9 @@ package appeng.fluids.client.gui; -import java.io.IOException; - import appeng.api.util.IConfigManager; -import appeng.client.gui.widgets.GuiCustomSlot; -import appeng.util.IConfigManagerHost; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.client.gui.implementations.GuiUpgradeable; +import appeng.client.gui.widgets.GuiCustomSlot; import appeng.client.gui.widgets.GuiTabButton; import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; @@ -39,102 +33,92 @@ import appeng.fluids.container.ContainerFluidInterface; import appeng.fluids.helper.DualityFluidInterface; import appeng.fluids.helper.IFluidInterfaceHost; import appeng.fluids.util.IAEFluidTank; +import appeng.util.IConfigManagerHost; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; + +import java.io.IOException; -public class GuiFluidInterface extends GuiUpgradeable implements IConfigManagerHost -{ - public final static int ID_BUTTON_TANK = 222; +public class GuiFluidInterface extends GuiUpgradeable implements IConfigManagerHost { + public final static int ID_BUTTON_TANK = 222; - private final IFluidInterfaceHost host; - private final ContainerFluidInterface container; - private GuiTabButton priority; + private final IFluidInterfaceHost host; + private final ContainerFluidInterface container; + private GuiTabButton priority; - public GuiFluidInterface( final InventoryPlayer ip, final IFluidInterfaceHost te ) - { - super( new ContainerFluidInterface( ip, te ) ); - this.ySize = 231; - this.host = te; - ( this.container = (ContainerFluidInterface) this.inventorySlots ).setGui( this ); + public GuiFluidInterface(final InventoryPlayer ip, final IFluidInterfaceHost te) { + super(new ContainerFluidInterface(ip, te)); + this.ySize = 231; + this.host = te; + (this.container = (ContainerFluidInterface) this.inventorySlots).setGui(this); - } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - final IAEFluidTank configFluids = this.host.getDualityFluidInterface().getConfig(); - final IAEFluidTank fluidTank = this.host.getDualityFluidInterface().getTanks(); + final IAEFluidTank configFluids = this.host.getDualityFluidInterface().getConfig(); + final IAEFluidTank fluidTank = this.host.getDualityFluidInterface().getTanks(); - for( int i = 0; i < DualityFluidInterface.NUMBER_OF_TANKS; ++i ) - { - this.guiSlots.add( new GuiFluidTank( fluidTank, i, DualityFluidInterface.NUMBER_OF_TANKS + i, 36 + 18 * i, 57, 16, 64 ) ); - this.guiSlots.add( new GuiFluidSlot( configFluids, i, i, 35 + 18 * i, 35 ) ); - } + for (int i = 0; i < DualityFluidInterface.NUMBER_OF_TANKS; ++i) { + this.guiSlots.add(new GuiFluidTank(fluidTank, i, DualityFluidInterface.NUMBER_OF_TANKS + i, 36 + 18 * i, 57, 16, 64)); + this.guiSlots.add(new GuiFluidSlot(configFluids, i, i, 35 + 18 * i, 35)); + } - this.priority = new GuiTabButton( this.getGuiLeft() + 154, this.getGuiTop(), 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender ); - this.buttonList.add( this.priority ); - } + this.priority = new GuiTabButton(this.getGuiLeft() + 154, this.getGuiTop(), 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender); + this.buttonList.add(this.priority); + } - @Override - protected void addButtons() - { - } + @Override + protected void addButtons() { + } - @Override - public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.FluidInterface.getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.Config.getLocal(), 35, 6 + 11 + 7, 4210752 ); - this.fontRenderer.drawString( GuiText.StoredFluids.getLocal(), 35, 6 + 112 + 7, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - } + @Override + public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(GuiText.FluidInterface.getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.Config.getLocal(), 35, 6 + 11 + 7, 4210752); + this.fontRenderer.drawString(GuiText.StoredFluids.getLocal(), 35, 6 + 112 + 7, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); + } - @Override - public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - this.bindTexture( "guis/interfacefluid.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) { + this.bindTexture("guis/interfacefluid.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - if( btn == this.priority ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - } + if (btn == this.priority) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } + } - @Override - protected void mouseClicked( int xCoord, int yCoord, int btn ) throws IOException - { - for( GuiCustomSlot slot : this.guiSlots ) - { - if( slot instanceof GuiFluidTank ) - { - if( this.isPointInRegion( slot.xPos(), slot.yPos(), slot.getWidth(), slot.getHeight(), xCoord, yCoord ) && slot.canClick( this.mc.player ) ) - { - this.container.setTargetStack( ( (GuiFluidTank) slot ).getFluidStack() ); - slot.slotClicked( this.mc.player.inventory.getItemStack(), btn ); - return; - } - } - } - super.mouseClicked( xCoord, yCoord, btn ); - } + @Override + protected void mouseClicked(int xCoord, int yCoord, int btn) throws IOException { + for (GuiCustomSlot slot : this.guiSlots) { + if (slot instanceof GuiFluidTank) { + if (this.isPointInRegion(slot.xPos(), slot.yPos(), slot.getWidth(), slot.getHeight(), xCoord, yCoord) && slot.canClick(this.mc.player)) { + this.container.setTargetStack(((GuiFluidTank) slot).getFluidStack()); + slot.slotClicked(this.mc.player.inventory.getItemStack(), btn); + return; + } + } + } + super.mouseClicked(xCoord, yCoord, btn); + } - @Override - protected boolean drawUpgrades() - { - return false; - } + @Override + protected boolean drawUpgrades() { + return false; + } - @Override - public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) - { + @Override + public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) { - } + } } diff --git a/src/main/java/appeng/fluids/client/gui/GuiFluidLevelEmitter.java b/src/main/java/appeng/fluids/client/gui/GuiFluidLevelEmitter.java index 7ac0812de..402595e20 100644 --- a/src/main/java/appeng/fluids/client/gui/GuiFluidLevelEmitter.java +++ b/src/main/java/appeng/fluids/client/gui/GuiFluidLevelEmitter.java @@ -1,12 +1,6 @@ - package appeng.fluids.client.gui; -import java.io.IOException; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.api.config.RedstoneMode; import appeng.api.config.Settings; import appeng.client.gui.implementations.GuiUpgradeable; @@ -20,204 +14,176 @@ import appeng.core.sync.packets.PacketValueConfig; import appeng.fluids.client.gui.widgets.GuiFluidSlot; import appeng.fluids.container.ContainerFluidLevelEmitter; import appeng.fluids.parts.PartFluidLevelEmitter; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; + +import java.io.IOException; -public class GuiFluidLevelEmitter extends GuiUpgradeable -{ - private final PartFluidLevelEmitter levelEmitter; - private GuiNumberBox level; +public class GuiFluidLevelEmitter extends GuiUpgradeable { + private final PartFluidLevelEmitter levelEmitter; + private GuiNumberBox level; - private GuiButton plus1; - private GuiButton plus10; - private GuiButton plus100; - private GuiButton plus1000; - private GuiButton minus1; - private GuiButton minus10; - private GuiButton minus100; - private GuiButton minus1000; + private GuiButton plus1; + private GuiButton plus10; + private GuiButton plus100; + private GuiButton plus1000; + private GuiButton minus1; + private GuiButton minus10; + private GuiButton minus100; + private GuiButton minus1000; - public GuiFluidLevelEmitter( final InventoryPlayer inventoryPlayer, final PartFluidLevelEmitter te ) - { - super( new ContainerFluidLevelEmitter( inventoryPlayer, te ) ); - this.levelEmitter = te; - } + public GuiFluidLevelEmitter(final InventoryPlayer inventoryPlayer, final PartFluidLevelEmitter te) { + super(new ContainerFluidLevelEmitter(inventoryPlayer, te)); + this.levelEmitter = te; + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.level = new GuiNumberBox( this.fontRenderer, this.guiLeft + 24, this.guiTop + 43, 79, this.fontRenderer.FONT_HEIGHT, Long.class ); - this.level.setEnableBackgroundDrawing( false ); - this.level.setMaxStringLength( 16 ); - this.level.setTextColor( 0xFFFFFF ); - this.level.setVisible( true ); - this.level.setFocused( true ); - ( (ContainerFluidLevelEmitter) this.inventorySlots ).setTextField( this.level ); + this.level = new GuiNumberBox(this.fontRenderer, this.guiLeft + 24, this.guiTop + 43, 79, this.fontRenderer.FONT_HEIGHT, Long.class); + this.level.setEnableBackgroundDrawing(false); + this.level.setMaxStringLength(16); + this.level.setTextColor(0xFFFFFF); + this.level.setVisible(true); + this.level.setFocused(true); + ((ContainerFluidLevelEmitter) this.inventorySlots).setTextField(this.level); - final int y = 40; - final int x = 80 + 44; - this.guiSlots.add( new GuiFluidSlot( this.levelEmitter.getConfig(), 0, 0, x, y ) ); - } + final int y = 40; + final int x = 80 + 44; + this.guiSlots.add(new GuiFluidSlot(this.levelEmitter.getConfig(), 0, 0, x, y)); + } - @Override - protected void addButtons() - { - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.REDSTONE_EMITTER, RedstoneMode.LOW_SIGNAL ); + @Override + protected void addButtons() { + this.redstoneMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.REDSTONE_EMITTER, RedstoneMode.LOW_SIGNAL); - final int a = AEConfig.instance().levelByMillyBuckets( 0 ); - final int b = AEConfig.instance().levelByMillyBuckets( 1 ); - final int c = AEConfig.instance().levelByMillyBuckets( 2 ); - final int d = AEConfig.instance().levelByMillyBuckets( 3 ); + final int a = AEConfig.instance().levelByMillyBuckets(0); + final int b = AEConfig.instance().levelByMillyBuckets(1); + final int c = AEConfig.instance().levelByMillyBuckets(2); + final int d = AEConfig.instance().levelByMillyBuckets(3); - this.buttonList.add( this.plus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 17, 22, 20, "+" + a ) ); - this.buttonList.add( this.plus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 17, 28, 20, "+" + b ) ); - this.buttonList.add( this.plus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 17, 32, 20, "+" + c ) ); - this.buttonList.add( this.plus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 17, 38, 20, "+" + d ) ); + this.buttonList.add(this.plus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 17, 22, 20, "+" + a)); + this.buttonList.add(this.plus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 17, 28, 20, "+" + b)); + this.buttonList.add(this.plus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 17, 32, 20, "+" + c)); + this.buttonList.add(this.plus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 17, 38, 20, "+" + d)); - this.buttonList.add( this.minus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 59, 22, 20, "-" + a ) ); - this.buttonList.add( this.minus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 59, 28, 20, "-" + b ) ); - this.buttonList.add( this.minus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 59, 32, 20, "-" + c ) ); - this.buttonList.add( this.minus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 59, 38, 20, "-" + d ) ); + this.buttonList.add(this.minus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 59, 22, 20, "-" + a)); + this.buttonList.add(this.minus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 59, 28, 20, "-" + b)); + this.buttonList.add(this.minus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 59, 32, 20, "-" + c)); + this.buttonList.add(this.minus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 59, 38, 20, "-" + d)); - this.buttonList.add( this.redstoneMode ); - } + this.buttonList.add(this.redstoneMode); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawBG( offsetX, offsetY, mouseX, mouseY ); - this.level.drawTextBox(); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawBG(offsetX, offsetY, mouseX, mouseY); + this.level.drawTextBox(); + } - @Override - public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - if( isPointInRegion( 24, 43,89,this.fontRenderer.FONT_HEIGHT,mouseX,mouseY ) ) drawTooltip( mouseX - guiLeft - 7, mouseY - guiTop + 25, "Amount in millibuckets" ); - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - } + @Override + public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) { + if (isPointInRegion(24, 43, 89, this.fontRenderer.FONT_HEIGHT, mouseX, mouseY)) + drawTooltip(mouseX - guiLeft - 7, mouseY - guiTop + 25, "Amount in millibuckets"); + super.drawFG(offsetX, offsetY, mouseX, mouseY); + } - @Override - protected boolean drawUpgrades() - { - return false; - } + @Override + protected boolean drawUpgrades() { + return false; + } - @Override - protected String getBackground() - { - return "guis/lvlemitter.png"; - } + @Override + protected String getBackground() { + return "guis/lvlemitter.png"; + } - @Override - protected GuiText getName() - { - return GuiText.FluidLevelEmitter; - } + @Override + protected GuiText getName() { + return GuiText.FluidLevelEmitter; + } - @Override - protected void handleButtonVisibility() - { - } + @Override + protected void handleButtonVisibility() { + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; - final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; + final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; - if( isPlus || isMinus ) - { - this.addQty( this.getQty( btn ) ); - } - } + if (isPlus || isMinus) { + this.addQty(this.getQty(btn)); + } + } - private void addQty( final long i ) - { - try - { - String Out = this.level.getText(); + private void addQty(final long i) { + try { + String Out = this.level.getText(); - boolean Fixed = false; - while( Out.startsWith( "0" ) && Out.length() > 1 ) - { - Out = Out.substring( 1 ); - Fixed = true; - } + boolean Fixed = false; + while (Out.startsWith("0") && Out.length() > 1) { + Out = Out.substring(1); + Fixed = true; + } - if( Fixed ) - { - this.level.setText( Out ); - } + if (Fixed) { + this.level.setText(Out); + } - if( Out.isEmpty() ) - { - Out = "0"; - } + if (Out.isEmpty()) { + Out = "0"; + } - long result = Long.parseLong( Out ); - result += i; - if( result < 0 ) - { - result = 0; - } + long result = Long.parseLong(Out); + result += i; + if (result < 0) { + result = 0; + } - this.level.setText( Out = Long.toString( result ) ); + this.level.setText(Out = Long.toString(result)); - NetworkHandler.instance().sendToServer( new PacketValueConfig( "FluidLevelEmitter.Value", Out ) ); - } - catch( final NumberFormatException e ) - { - // nope.. - this.level.setText( "0" ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + NetworkHandler.instance().sendToServer(new PacketValueConfig("FluidLevelEmitter.Value", Out)); + } catch (final NumberFormatException e) { + // nope.. + this.level.setText("0"); + } catch (final IOException e) { + AELog.debug(e); + } + } - @Override - protected void keyTyped( final char character, final int key ) throws IOException - { - if( !this.checkHotbarKeys( key ) ) - { - if( ( key == 211 || key == 205 || key == 203 || key == 14 || Character.isDigit( character ) ) && this.level.textboxKeyTyped( character, key ) ) - { - try - { - String Out = this.level.getText(); + @Override + protected void keyTyped(final char character, final int key) throws IOException { + if (!this.checkHotbarKeys(key)) { + if ((key == 211 || key == 205 || key == 203 || key == 14 || Character.isDigit(character)) && this.level.textboxKeyTyped(character, key)) { + try { + String Out = this.level.getText(); - boolean Fixed = false; - while( Out.startsWith( "0" ) && Out.length() > 1 ) - { - Out = Out.substring( 1 ); - Fixed = true; - } + boolean Fixed = false; + while (Out.startsWith("0") && Out.length() > 1) { + Out = Out.substring(1); + Fixed = true; + } - if( Fixed ) - { - this.level.setText( Out ); - } + if (Fixed) { + this.level.setText(Out); + } - if( Out.isEmpty() ) - { - Out = "0"; - } + if (Out.isEmpty()) { + Out = "0"; + } - NetworkHandler.instance().sendToServer( new PacketValueConfig( "FluidLevelEmitter.Value", Out ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - else - { - super.keyTyped( character, key ); - } - } - } + NetworkHandler.instance().sendToServer(new PacketValueConfig("FluidLevelEmitter.Value", Out)); + } catch (final IOException e) { + AELog.debug(e); + } + } else { + super.keyTyped(character, key); + } + } + } } diff --git a/src/main/java/appeng/fluids/client/gui/GuiFluidStorageBus.java b/src/main/java/appeng/fluids/client/gui/GuiFluidStorageBus.java index ef001df02..e85e6c743 100644 --- a/src/main/java/appeng/fluids/client/gui/GuiFluidStorageBus.java +++ b/src/main/java/appeng/fluids/client/gui/GuiFluidStorageBus.java @@ -19,18 +19,7 @@ package appeng.fluids.client.gui; -import java.io.IOException; - -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; - -import appeng.api.config.AccessRestriction; -import appeng.api.config.ActionItems; -import appeng.api.config.FuzzyMode; -import appeng.api.config.Settings; -import appeng.api.config.StorageFilter; +import appeng.api.config.*; import appeng.client.gui.implementations.GuiUpgradeable; import appeng.client.gui.widgets.GuiImgButton; import appeng.client.gui.widgets.GuiTabButton; @@ -46,6 +35,11 @@ import appeng.fluids.client.gui.widgets.GuiOptionalFluidSlot; import appeng.fluids.container.ContainerFluidStorageBus; import appeng.fluids.parts.PartFluidStorageBus; import appeng.fluids.util.IAEFluidTank; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import org.lwjgl.input.Mouse; + +import java.io.IOException; /** @@ -53,135 +47,107 @@ import appeng.fluids.util.IAEFluidTank; * @version rv6 - 22/05/2018 * @since rv6 22/05/2018 */ -public class GuiFluidStorageBus extends GuiUpgradeable -{ - private GuiImgButton rwMode; - private GuiImgButton storageFilter; - private GuiTabButton priority; - private GuiImgButton partition; - private GuiImgButton clear; - private final PartFluidStorageBus bus; +public class GuiFluidStorageBus extends GuiUpgradeable { + private GuiImgButton rwMode; + private GuiImgButton storageFilter; + private GuiTabButton priority; + private GuiImgButton partition; + private GuiImgButton clear; + private final PartFluidStorageBus bus; - public GuiFluidStorageBus( InventoryPlayer inventoryPlayer, PartFluidStorageBus te ) - { - super( new ContainerFluidStorageBus( inventoryPlayer, te ) ); - this.ySize = 251; - this.bus = te; - } + public GuiFluidStorageBus(InventoryPlayer inventoryPlayer, PartFluidStorageBus te) { + super(new ContainerFluidStorageBus(inventoryPlayer, te)); + this.ySize = 251; + this.bus = te; + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - final int xo = 8; - final int yo = 23 + 6; + final int xo = 8; + final int yo = 23 + 6; - final IAEFluidTank config = this.bus.getConfig(); - final ContainerFluidStorageBus container = (ContainerFluidStorageBus) this.inventorySlots; + final IAEFluidTank config = this.bus.getConfig(); + final ContainerFluidStorageBus container = (ContainerFluidStorageBus) this.inventorySlots; - for( int y = 0; y < 7; y++ ) - { - for( int x = 0; x < 9; x++ ) - { - final int idx = y * 9 + x; - if( y < 2 ) - { - this.guiSlots.add( new GuiFluidSlot( config, idx, idx, xo + x * 18, yo + y * 18 ) ); - } - else - { - this.guiSlots.add( new GuiOptionalFluidSlot( config, container, idx, idx, y - 2, xo, yo, x, y ) ); - } - } - } - } + for (int y = 0; y < 7; y++) { + for (int x = 0; x < 9; x++) { + final int idx = y * 9 + x; + if (y < 2) { + this.guiSlots.add(new GuiFluidSlot(config, idx, idx, xo + x * 18, yo + y * 18)); + } else { + this.guiSlots.add(new GuiOptionalFluidSlot(config, container, idx, idx, y - 2, xo, yo, x, y)); + } + } + } + } - @Override - protected void addButtons() - { - this.clear = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE ); - this.partition = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH ); - this.rwMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.ACCESS, AccessRestriction.READ_WRITE ); - this.storageFilter = new GuiImgButton( this.guiLeft - 18, this.guiTop + 68, Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 88, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); + @Override + protected void addButtons() { + this.clear = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE); + this.partition = new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH); + this.rwMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 48, Settings.ACCESS, AccessRestriction.READ_WRITE); + this.storageFilter = new GuiImgButton(this.guiLeft - 18, this.guiTop + 68, Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY); + this.fuzzyMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 88, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender ) ); + this.buttonList.add(this.priority = new GuiTabButton(this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), this.itemRender)); - this.buttonList.add( this.storageFilter ); - this.buttonList.add( this.fuzzyMode ); - this.buttonList.add( this.rwMode ); - this.buttonList.add( this.partition ); - this.buttonList.add( this.clear ); - } + this.buttonList.add(this.storageFilter); + this.buttonList.add(this.fuzzyMode); + this.buttonList.add(this.rwMode); + this.buttonList.add(this.partition); + this.buttonList.add(this.clear); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( this.getName().getLocal() ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName(this.getName().getLocal()), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); - if( this.fuzzyMode != null ) - { - this.fuzzyMode.set( this.cvb.getFuzzyMode() ); - } + if (this.fuzzyMode != null) { + this.fuzzyMode.set(this.cvb.getFuzzyMode()); + } - if( this.storageFilter != null ) - { - this.storageFilter.set( ( (ContainerFluidStorageBus) this.cvb ).getStorageFilter() ); - } + if (this.storageFilter != null) { + this.storageFilter.set(((ContainerFluidStorageBus) this.cvb).getStorageFilter()); + } - if( this.rwMode != null ) - { - this.rwMode.set( ( (ContainerFluidStorageBus) this.cvb ).getReadWriteMode() ); - } - } + if (this.rwMode != null) { + this.rwMode.set(((ContainerFluidStorageBus) this.cvb).getReadWriteMode()); + } + } - @Override - protected String getBackground() - { - return "guis/storagebus.png"; - } + @Override + protected String getBackground() { + return "guis/storagebus.png"; + } - @Override - protected void actionPerformed( final GuiButton btn ) throws IOException - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) throws IOException { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - try - { - if( btn == this.partition ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "StorageBus.Action", "Partition" ) ); - } - else if( btn == this.clear ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "StorageBus.Action", "Clear" ) ); - } - else if( btn == this.priority ) - { - NetworkHandler.instance().sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - else if( btn == this.rwMode ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.rwMode.getSetting(), backwards ) ); - } - else if( btn == this.storageFilter ) - { - NetworkHandler.instance().sendToServer( new PacketConfigButton( this.storageFilter.getSetting(), backwards ) ); - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + try { + if (btn == this.partition) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("StorageBus.Action", "Partition")); + } else if (btn == this.clear) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("StorageBus.Action", "Clear")); + } else if (btn == this.priority) { + NetworkHandler.instance().sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } else if (btn == this.rwMode) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.rwMode.getSetting(), backwards)); + } else if (btn == this.storageFilter) { + NetworkHandler.instance().sendToServer(new PacketConfigButton(this.storageFilter.getSetting(), backwards)); + } + } catch (final IOException e) { + AELog.debug(e); + } + } - @Override - protected GuiText getName() - { - return GuiText.StorageBusFluids; - } + @Override + protected GuiText getName() { + return GuiText.StorageBusFluids; + } } diff --git a/src/main/java/appeng/fluids/client/gui/GuiFluidTerminal.java b/src/main/java/appeng/fluids/client/gui/GuiFluidTerminal.java index 2df75ab4a..b9fc3e2df 100644 --- a/src/main/java/appeng/fluids/client/gui/GuiFluidTerminal.java +++ b/src/main/java/appeng/fluids/client/gui/GuiFluidTerminal.java @@ -19,22 +19,6 @@ package appeng.fluids.client.gui; -import java.io.IOException; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; - -import org.lwjgl.input.Mouse; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.ClickType; -import net.minecraft.inventory.Slot; -import net.minecraft.util.text.TextFormatting; -import net.minecraftforge.fml.common.Loader; - import appeng.api.config.Settings; import appeng.api.storage.ITerminalHost; import appeng.api.storage.data.IAEFluidStack; @@ -58,6 +42,20 @@ import appeng.fluids.container.slots.IMEFluidSlot; import appeng.helpers.InventoryAction; import appeng.util.IConfigManagerHost; import appeng.util.Platform; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.ClickType; +import net.minecraft.inventory.Slot; +import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.fml.common.Loader; +import org.lwjgl.input.Mouse; + +import java.io.IOException; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; /** @@ -65,302 +63,255 @@ import appeng.util.Platform; * @version rv6 - 12/05/2018 * @since rv6 12/05/2018 */ -public class GuiFluidTerminal extends AEBaseMEGui implements ISortSource, IConfigManagerHost -{ - private final List meFluidSlots = new LinkedList<>(); - private final FluidRepo repo; - private final IConfigManager configSrc; - private final ContainerFluidTerminal container; - private final int offsetX = 9; - private int rows = 6; - private int perRow = 9; +public class GuiFluidTerminal extends AEBaseMEGui implements ISortSource, IConfigManagerHost { + private final List meFluidSlots = new LinkedList<>(); + private final FluidRepo repo; + private final IConfigManager configSrc; + private final ContainerFluidTerminal container; + private final int offsetX = 9; + private final int rows = 6; + private final int perRow = 9; - protected ITerminalHost terminal; + protected ITerminalHost terminal; - private MEGuiTextField searchField; - private GuiImgButton sortByBox; - private GuiImgButton sortDirBox; + private MEGuiTextField searchField; + private GuiImgButton sortByBox; + private GuiImgButton sortDirBox; - public GuiFluidTerminal( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - this( inventoryPlayer, te, new ContainerFluidTerminal( inventoryPlayer, te ) ); - } + public GuiFluidTerminal(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + this(inventoryPlayer, te, new ContainerFluidTerminal(inventoryPlayer, te)); + } - public GuiFluidTerminal( InventoryPlayer inventoryPlayer, final ITerminalHost te, final ContainerFluidTerminal c ) - { - super( c ); - this.terminal = te; - this.xSize = 185; - this.ySize = 222; - final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - this.repo = new FluidRepo( scrollbar, this ); - this.configSrc = ( (IConfigurableObject) this.inventorySlots ).getConfigManager(); - ( this.container = (ContainerFluidTerminal) this.inventorySlots ).setGui( this ); - } + public GuiFluidTerminal(InventoryPlayer inventoryPlayer, final ITerminalHost te, final ContainerFluidTerminal c) { + super(c); + this.terminal = te; + this.xSize = 185; + this.ySize = 222; + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar(scrollbar); + this.repo = new FluidRepo(scrollbar, this); + this.configSrc = ((IConfigurableObject) this.inventorySlots).getConfigManager(); + (this.container = (ContainerFluidTerminal) this.inventorySlots).setGui(this); + } - @Override - public void initGui() - { - this.mc.player.openContainer = this.inventorySlots; - this.guiLeft = ( this.width - this.xSize ) / 2; - this.guiTop = ( this.height - this.ySize ) / 2; + @Override + public void initGui() { + this.mc.player.openContainer = this.inventorySlots; + this.guiLeft = (this.width - this.xSize) / 2; + this.guiTop = (this.height - this.ySize) / 2; - this.searchField = new MEGuiTextField( this.fontRenderer, this.guiLeft + Math.max( 80, this.offsetX ), this.guiTop + 4, 90, 12 ); - this.searchField.setEnableBackgroundDrawing( false ); - this.searchField.setMaxStringLength( 25 ); - this.searchField.setTextColor( 0xFFFFFF ); - this.searchField.setSelectionColor( 0xFF99FF99 ); - this.searchField.setVisible( true ); + this.searchField = new MEGuiTextField(this.fontRenderer, this.guiLeft + Math.max(80, this.offsetX), this.guiTop + 4, 90, 12); + this.searchField.setEnableBackgroundDrawing(false); + this.searchField.setMaxStringLength(25); + this.searchField.setTextColor(0xFFFFFF); + this.searchField.setSelectionColor(0xFF99FF99); + this.searchField.setVisible(true); - int offset = this.guiTop; + int offset = this.guiTop; - this.buttonList.add( this.sortByBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.SORT_BY, this.configSrc.getSetting( Settings.SORT_BY ) ) ); - offset += 20; + this.buttonList.add(this.sortByBox = new GuiImgButton(this.guiLeft - 18, offset, Settings.SORT_BY, this.configSrc.getSetting(Settings.SORT_BY))); + offset += 20; - this.buttonList.add( this.sortDirBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.SORT_DIRECTION, this.configSrc - .getSetting( Settings.SORT_DIRECTION ) ) ); + this.buttonList.add(this.sortDirBox = new GuiImgButton(this.guiLeft - 18, offset, Settings.SORT_DIRECTION, this.configSrc + .getSetting(Settings.SORT_DIRECTION))); - for( int y = 0; y < this.rows; y++ ) - { - for( int x = 0; x < this.perRow; x++ ) - { - SlotFluidME slot = new SlotFluidME( new InternalFluidSlotME( this.repo, x + y * this.perRow, this.offsetX + x * 18, 18 + y * 18 ) ); - this.getMeFluidSlots().add( slot ); - this.inventorySlots.inventorySlots.add( slot ); - } - } - this.setScrollBar(); - } + for (int y = 0; y < this.rows; y++) { + for (int x = 0; x < this.perRow; x++) { + SlotFluidME slot = new SlotFluidME(new InternalFluidSlotME(this.repo, x + y * this.perRow, this.offsetX + x * 18, 18 + y * 18)); + this.getMeFluidSlots().add(slot); + this.inventorySlots.inventorySlots.add(slot); + } + } + this.setScrollBar(); + } - @Override - public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - this.fontRenderer.drawString( this.getGuiDisplayName( "Fluid Terminal" ), 8, 6, 4210752 ); - this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - } + @Override + public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) { + this.fontRenderer.drawString(this.getGuiDisplayName("Fluid Terminal"), 8, 6, 4210752); + this.fontRenderer.drawString(GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752); + } - @Override - public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - this.bindTexture( this.getBackground() ); - final int x_width = 197; - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, x_width, 18 ); + @Override + public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) { + this.bindTexture(this.getBackground()); + final int x_width = 197; + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, x_width, 18); - for( int x = 0; x < 6; x++ ) - { - this.drawTexturedModalRect( offsetX, offsetY + 18 + x * 18, 0, 18, x_width, 18 ); - } + for (int x = 0; x < 6; x++) { + this.drawTexturedModalRect(offsetX, offsetY + 18 + x * 18, 0, 18, x_width, 18); + } - this.drawTexturedModalRect( offsetX, offsetY + 16 + 6 * 18, 0, 106 - 18 - 18, x_width, 99 + 77 ); + this.drawTexturedModalRect(offsetX, offsetY + 16 + 6 * 18, 0, 106 - 18 - 18, x_width, 99 + 77); - if( this.searchField != null ) - { - this.searchField.drawTextBox(); - } - } + if (this.searchField != null) { + this.searchField.drawTextBox(); + } + } - @Override - public void updateScreen() - { - this.repo.setPower( this.container.isPowered() ); - super.updateScreen(); - } + @Override + public void updateScreen() { + this.repo.setPower(this.container.isPowered()); + super.updateScreen(); + } - @Override - protected void renderHoveredToolTip( int mouseX, int mouseY ) - { - final Slot slot = this.getSlot( mouseX, mouseY ); + @Override + protected void renderHoveredToolTip(int mouseX, int mouseY) { + final Slot slot = this.getSlot(mouseX, mouseY); - if( slot != null && slot instanceof IMEFluidSlot && slot.isEnabled() ) - { - final IMEFluidSlot fluidSlot = (IMEFluidSlot) slot; + if (slot != null && slot instanceof IMEFluidSlot && slot.isEnabled()) { + final IMEFluidSlot fluidSlot = (IMEFluidSlot) slot; - if( fluidSlot.getAEFluidStack() != null && fluidSlot.shouldRenderAsFluid() ) - { - final IAEFluidStack fluidStack = fluidSlot.getAEFluidStack(); - final String formattedAmount = NumberFormat.getNumberInstance( Locale.US ).format( fluidStack.getStackSize() / 1000.0 ) + " B"; + if (fluidSlot.getAEFluidStack() != null && fluidSlot.shouldRenderAsFluid()) { + final IAEFluidStack fluidStack = fluidSlot.getAEFluidStack(); + final String formattedAmount = NumberFormat.getNumberInstance(Locale.US).format(fluidStack.getStackSize() / 1000.0) + " B"; - final String modName = "" + TextFormatting.BLUE + TextFormatting.ITALIC + Loader.instance() - .getIndexedModList() - .get( Platform.getModId( fluidStack ) ) - .getName(); + final String modName = "" + TextFormatting.BLUE + TextFormatting.ITALIC + Loader.instance() + .getIndexedModList() + .get(Platform.getModId(fluidStack)) + .getName(); - final List list = new ArrayList<>(); + final List list = new ArrayList<>(); - list.add( fluidStack.getFluidStack().getLocalizedName() ); - list.add( formattedAmount ); - list.add( modName ); + list.add(fluidStack.getFluidStack().getLocalizedName()); + list.add(formattedAmount); + list.add(modName); - this.drawHoveringText( list, mouseX, mouseY ); + this.drawHoveringText(list, mouseX, mouseY); - return; - } - } - super.renderHoveredToolTip( mouseX, mouseY ); - } + return; + } + } + super.renderHoveredToolTip(mouseX, mouseY); + } - @Override - protected void actionPerformed( GuiButton btn ) throws IOException - { - if( btn instanceof GuiImgButton ) - { - final boolean backwards = Mouse.isButtonDown( 1 ); - final GuiImgButton iBtn = (GuiImgButton) btn; + @Override + protected void actionPerformed(GuiButton btn) throws IOException { + if (btn instanceof GuiImgButton) { + final boolean backwards = Mouse.isButtonDown(1); + final GuiImgButton iBtn = (GuiImgButton) btn; - if( iBtn.getSetting() != Settings.ACTIONS ) - { - final Enum cv = iBtn.getCurrentValue(); - final Enum next = Platform.rotateEnum( cv, backwards, iBtn.getSetting().getPossibleValues() ); + if (iBtn.getSetting() != Settings.ACTIONS) { + final Enum cv = iBtn.getCurrentValue(); + final Enum next = Platform.rotateEnum(cv, backwards, iBtn.getSetting().getPossibleValues()); - try - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( iBtn.getSetting().name(), next.name() ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } + try { + NetworkHandler.instance().sendToServer(new PacketValueConfig(iBtn.getSetting().name(), next.name())); + } catch (final IOException e) { + AELog.debug(e); + } - iBtn.set( next ); - } - } - } + iBtn.set(next); + } + } + } - @Override - protected void handleMouseClick( Slot slot, int slotIdx, int mouseButton, ClickType clickType ) - { - if( slot instanceof SlotFluidME ) - { - final SlotFluidME meSlot = (SlotFluidME) slot; + @Override + protected void handleMouseClick(Slot slot, int slotIdx, int mouseButton, ClickType clickType) { + if (slot instanceof SlotFluidME) { + final SlotFluidME meSlot = (SlotFluidME) slot; - if( clickType == ClickType.PICKUP ) - { - // TODO: Allow more options - if( mouseButton == 0 && meSlot.getHasStack() ) - { - this.container.setTargetStack( meSlot.getAEFluidStack() ); - AELog.debug( "mouse0 GUI STACK SIZE %s", meSlot.getAEFluidStack().getStackSize() ); - NetworkHandler.instance().sendToServer( new PacketInventoryAction( InventoryAction.FILL_ITEM, slot.slotNumber, 0 ) ); - } - else - { - this.container.setTargetStack( meSlot.getAEFluidStack() ); - if( meSlot.getAEFluidStack() != null ) - { - AELog.debug( "mouse1 GUI STACK SIZE %s", meSlot.getAEFluidStack().getStackSize() ); - } - NetworkHandler.instance().sendToServer( new PacketInventoryAction( InventoryAction.EMPTY_ITEM, slot.slotNumber, 0 ) ); - } - } - return; - } - super.handleMouseClick( slot, slotIdx, mouseButton, clickType ); - } + if (clickType == ClickType.PICKUP) { + // TODO: Allow more options + if (mouseButton == 0 && meSlot.getHasStack()) { + this.container.setTargetStack(meSlot.getAEFluidStack()); + AELog.debug("mouse0 GUI STACK SIZE %s", meSlot.getAEFluidStack().getStackSize()); + NetworkHandler.instance().sendToServer(new PacketInventoryAction(InventoryAction.FILL_ITEM, slot.slotNumber, 0)); + } else { + this.container.setTargetStack(meSlot.getAEFluidStack()); + if (meSlot.getAEFluidStack() != null) { + AELog.debug("mouse1 GUI STACK SIZE %s", meSlot.getAEFluidStack().getStackSize()); + } + NetworkHandler.instance().sendToServer(new PacketInventoryAction(InventoryAction.EMPTY_ITEM, slot.slotNumber, 0)); + } + } + return; + } + super.handleMouseClick(slot, slotIdx, mouseButton, clickType); + } - @Override - protected void keyTyped( final char character, final int key ) throws IOException - { - if( !this.checkHotbarKeys( key ) ) - { - if( character == ' ' && this.searchField.getText().isEmpty() ) - { - return; - } + @Override + protected void keyTyped(final char character, final int key) throws IOException { + if (!this.checkHotbarKeys(key)) { + if (character == ' ' && this.searchField.getText().isEmpty()) { + return; + } - if( this.searchField.textboxKeyTyped( character, key ) ) - { - this.repo.setSearchString( this.searchField.getText() ); - this.repo.updateView(); - this.setScrollBar(); - } - else - { - super.keyTyped( character, key ); - } - } - } + if (this.searchField.textboxKeyTyped(character, key)) { + this.repo.setSearchString(this.searchField.getText()); + this.repo.updateView(); + this.setScrollBar(); + } else { + super.keyTyped(character, key); + } + } + } - @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) throws IOException - { - this.searchField.mouseClicked( xCoord, yCoord, btn ); + @Override + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) throws IOException { + this.searchField.mouseClicked(xCoord, yCoord, btn); - if( btn == 1 && this.searchField.isMouseIn( xCoord, yCoord ) ) - { - this.searchField.setText( "" ); - this.repo.setSearchString( "" ); - this.repo.updateView(); - this.setScrollBar(); - } + if (btn == 1 && this.searchField.isMouseIn(xCoord, yCoord)) { + this.searchField.setText(""); + this.repo.setSearchString(""); + this.repo.updateView(); + this.setScrollBar(); + } - super.mouseClicked( xCoord, yCoord, btn ); - } + super.mouseClicked(xCoord, yCoord, btn); + } - public void postUpdate( final List list ) - { - for( final IAEFluidStack is : list ) - { - this.repo.postUpdate( is ); - } + public void postUpdate(final List list) { + for (final IAEFluidStack is : list) { + this.repo.postUpdate(is); + } - this.repo.updateView(); - this.setScrollBar(); - } + this.repo.updateView(); + this.setScrollBar(); + } - private void setScrollBar() - { - this.getScrollBar().setTop( 18 ).setLeft( 175 ).setHeight( this.rows * 18 - 2 ); - this.getScrollBar().setRange( 0, ( this.repo.size() + this.perRow - 1 ) / this.perRow - this.rows, Math.max( 1, this.rows / 6 ) ); - } + private void setScrollBar() { + this.getScrollBar().setTop(18).setLeft(175).setHeight(this.rows * 18 - 2); + this.getScrollBar().setRange(0, (this.repo.size() + this.perRow - 1) / this.perRow - this.rows, Math.max(1, this.rows / 6)); + } - @Override - public Enum getSortBy() - { - return this.configSrc.getSetting( Settings.SORT_BY ); - } + @Override + public Enum getSortBy() { + return this.configSrc.getSetting(Settings.SORT_BY); + } - @Override - public Enum getSortDir() - { - return this.configSrc.getSetting( Settings.SORT_DIRECTION ); - } + @Override + public Enum getSortDir() { + return this.configSrc.getSetting(Settings.SORT_DIRECTION); + } - @Override - public Enum getSortDisplay() - { - return this.configSrc.getSetting( Settings.VIEW_MODE ); - } + @Override + public Enum getSortDisplay() { + return this.configSrc.getSetting(Settings.VIEW_MODE); + } - @Override - public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) - { - if( this.sortByBox != null ) - { - this.sortByBox.set( this.configSrc.getSetting( Settings.SORT_BY ) ); - } + @Override + public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) { + if (this.sortByBox != null) { + this.sortByBox.set(this.configSrc.getSetting(Settings.SORT_BY)); + } - if( this.sortDirBox != null ) - { - this.sortDirBox.set( this.configSrc.getSetting( Settings.SORT_DIRECTION ) ); - } + if (this.sortDirBox != null) { + this.sortDirBox.set(this.configSrc.getSetting(Settings.SORT_DIRECTION)); + } - this.repo.updateView(); - } + this.repo.updateView(); + } - protected List getMeFluidSlots() - { - return this.meFluidSlots; - } + protected List getMeFluidSlots() { + return this.meFluidSlots; + } - @Override - protected boolean isPowered() - { - return this.repo.hasPower(); - } + @Override + protected boolean isPowered() { + return this.repo.hasPower(); + } - protected String getBackground() - { - return "guis/terminal.png"; - } + protected String getBackground() { + return "guis/terminal.png"; + } } diff --git a/src/main/java/appeng/fluids/client/gui/widgets/GuiFluidSlot.java b/src/main/java/appeng/fluids/client/gui/widgets/GuiFluidSlot.java index d0e432a08..85f91b3d7 100644 --- a/src/main/java/appeng/fluids/client/gui/widgets/GuiFluidSlot.java +++ b/src/main/java/appeng/fluids/client/gui/widgets/GuiFluidSlot.java @@ -1,10 +1,13 @@ - package appeng.fluids.client.gui.widgets; -import java.util.Collections; - +import appeng.api.storage.data.IAEFluidStack; +import appeng.client.gui.widgets.GuiCustomSlot; import appeng.container.slot.IJEITargetSlot; +import appeng.core.sync.network.NetworkHandler; +import appeng.core.sync.packets.PacketFluidSlot; +import appeng.fluids.util.AEFluidStack; +import appeng.fluids.util.IAEFluidTank; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -16,98 +19,78 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; -import appeng.api.storage.data.IAEFluidStack; -import appeng.client.gui.widgets.GuiCustomSlot; -import appeng.core.sync.network.NetworkHandler; -import appeng.core.sync.packets.PacketFluidSlot; -import appeng.fluids.util.AEFluidStack; -import appeng.fluids.util.IAEFluidTank; +import java.util.Collections; -public class GuiFluidSlot extends GuiCustomSlot implements IJEITargetSlot -{ - private final IAEFluidTank fluids; - private final int slot; +public class GuiFluidSlot extends GuiCustomSlot implements IJEITargetSlot { + private final IAEFluidTank fluids; + private final int slot; - public GuiFluidSlot( final IAEFluidTank fluids, final int slot, final int id, final int x, final int y ) - { - super( id, x, y ); - this.fluids = fluids; - this.slot = slot; - } + public GuiFluidSlot(final IAEFluidTank fluids, final int slot, final int id, final int x, final int y) { + super(id, x, y); + this.fluids = fluids; + this.slot = slot; + } - @Override - public void drawContent( final Minecraft mc, final int mouseX, final int mouseY, final float partialTicks ) - { - final IAEFluidStack fs = this.getFluidStack(); - if( fs != null ) - { - GlStateManager.disableLighting(); - GlStateManager.disableBlend(); - final Fluid fluid = fs.getFluid(); - mc.getTextureManager().bindTexture( TextureMap.LOCATION_BLOCKS_TEXTURE ); - final TextureAtlasSprite sprite = mc.getTextureMapBlocks().getAtlasSprite( fluid.getStill().toString() ); + @Override + public void drawContent(final Minecraft mc, final int mouseX, final int mouseY, final float partialTicks) { + final IAEFluidStack fs = this.getFluidStack(); + if (fs != null) { + GlStateManager.disableLighting(); + GlStateManager.disableBlend(); + final Fluid fluid = fs.getFluid(); + mc.getTextureManager().bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); + final TextureAtlasSprite sprite = mc.getTextureMapBlocks().getAtlasSprite(fluid.getStill().toString()); - // Set color for dynamic fluids - // Convert int color to RGB - final float red = ( fluid.getColor() >> 16 & 255 ) / 255.0F; - final float green = ( fluid.getColor() >> 8 & 255 ) / 255.0F; - final float blue = ( fluid.getColor() & 255 ) / 255.0F; - GlStateManager.color( red, green, blue ); + // Set color for dynamic fluids + // Convert int color to RGB + final float red = (fluid.getColor() >> 16 & 255) / 255.0F; + final float green = (fluid.getColor() >> 8 & 255) / 255.0F; + final float blue = (fluid.getColor() & 255) / 255.0F; + GlStateManager.color(red, green, blue); - this.drawTexturedModalRect( this.xPos(), this.yPos(), sprite, this.getWidth(), this.getHeight() ); - } - } + this.drawTexturedModalRect(this.xPos(), this.yPos(), sprite, this.getWidth(), this.getHeight()); + } + } - @Override - public boolean canClick( final EntityPlayer player ) - { - final ItemStack mouseStack = player.inventory.getItemStack(); - return mouseStack.isEmpty() || mouseStack.hasCapability( CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null ); - } + @Override + public boolean canClick(final EntityPlayer player) { + final ItemStack mouseStack = player.inventory.getItemStack(); + return mouseStack.isEmpty() || mouseStack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null); + } - @Override - public void slotClicked( final ItemStack clickStack, int mouseButton ) - { - if( clickStack.isEmpty() || mouseButton == 1 ) - { - this.setFluidStack( null ); - } - else if( mouseButton == 0 ) - { - final FluidStack fluid = FluidUtil.getFluidContained( clickStack ); - if( fluid != null ) - { - this.setFluidStack( AEFluidStack.fromFluidStack( fluid ) ); - } - } - } + @Override + public void slotClicked(final ItemStack clickStack, int mouseButton) { + if (clickStack.isEmpty() || mouseButton == 1) { + this.setFluidStack(null); + } else if (mouseButton == 0) { + final FluidStack fluid = FluidUtil.getFluidContained(clickStack); + if (fluid != null) { + this.setFluidStack(AEFluidStack.fromFluidStack(fluid)); + } + } + } - @Override - public String getMessage() - { - final IAEFluidStack fluid = this.getFluidStack(); - if( fluid != null ) - { - return fluid.getFluidStack().getLocalizedName(); - } - return null; - } + @Override + public String getMessage() { + final IAEFluidStack fluid = this.getFluidStack(); + if (fluid != null) { + return fluid.getFluidStack().getLocalizedName(); + } + return null; + } - @Override - public boolean isVisible() - { - return true; - } + @Override + public boolean isVisible() { + return true; + } - public IAEFluidStack getFluidStack() - { - return this.fluids.getFluidInSlot( this.slot ); - } + public IAEFluidStack getFluidStack() { + return this.fluids.getFluidInSlot(this.slot); + } - public void setFluidStack( final IAEFluidStack stack ) - { - this.fluids.setFluidInSlot( this.slot, stack ); - NetworkHandler.instance().sendToServer( new PacketFluidSlot( Collections.singletonMap( this.getId(), this.getFluidStack() ) ) ); - } + public void setFluidStack(final IAEFluidStack stack) { + this.fluids.setFluidInSlot(this.slot, stack); + NetworkHandler.instance().sendToServer(new PacketFluidSlot(Collections.singletonMap(this.getId(), this.getFluidStack()))); + } } diff --git a/src/main/java/appeng/fluids/client/gui/widgets/GuiFluidTank.java b/src/main/java/appeng/fluids/client/gui/widgets/GuiFluidTank.java index a357de568..6590babc8 100644 --- a/src/main/java/appeng/fluids/client/gui/widgets/GuiFluidTank.java +++ b/src/main/java/appeng/fluids/client/gui/widgets/GuiFluidTank.java @@ -19,9 +19,12 @@ package appeng.fluids.client.gui.widgets; +import appeng.api.storage.data.IAEFluidStack; import appeng.client.gui.widgets.GuiCustomSlot; +import appeng.client.gui.widgets.ITooltip; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketInventoryAction; +import appeng.fluids.util.IAEFluidTank; import appeng.helpers.InventoryAction; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; @@ -31,127 +34,104 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.storage.data.IAEFluidStack; -import appeng.client.gui.widgets.ITooltip; -import appeng.fluids.util.IAEFluidTank; +@SideOnly(Side.CLIENT) +public class GuiFluidTank extends GuiCustomSlot implements ITooltip { + private final IAEFluidTank tank; + private final int slot; + private final int width; + private final int height; -@SideOnly( Side.CLIENT ) -public class GuiFluidTank extends GuiCustomSlot implements ITooltip -{ - private final IAEFluidTank tank; - private final int slot; - private final int width; - private final int height; + public GuiFluidTank(IAEFluidTank tank, int slot, int id, int x, int y, int w, int h) { + super(id, x, y); + this.tank = tank; + this.slot = slot; + this.width = w; + this.height = h; + } - public GuiFluidTank( IAEFluidTank tank, int slot, int id, int x, int y, int w, int h ) - { - super( id, x, y ); - this.tank = tank; - this.slot = slot; - this.width = w; - this.height = h; - } + @Override + public void drawContent(Minecraft mc, int mouseX, int mouseY, float partialTicks) { + final IAEFluidStack fs = this.getFluidStack(); + if (fs != null) { + GlStateManager.disableBlend(); + GlStateManager.disableLighting(); - @Override - public void drawContent( Minecraft mc, int mouseX, int mouseY, float partialTicks ) - { - final IAEFluidStack fs = this.getFluidStack(); - if( fs != null ) - { - GlStateManager.disableBlend(); - GlStateManager.disableLighting(); + //drawRect( this.x, this.y, this.x + this.width, this.y + this.height, AEColor.GRAY.blackVariant | 0xFF000000 ); - //drawRect( this.x, this.y, this.x + this.width, this.y + this.height, AEColor.GRAY.blackVariant | 0xFF000000 ); + final IAEFluidStack fluid = this.tank.getFluidInSlot(this.slot); + if (fluid != null && fluid.getStackSize() > 0) { + mc.getTextureManager().bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); - final IAEFluidStack fluid = this.tank.getFluidInSlot( this.slot ); - if( fluid != null && fluid.getStackSize() > 0 ) - { - mc.getTextureManager().bindTexture( TextureMap.LOCATION_BLOCKS_TEXTURE ); + float red = (fluid.getFluid().getColor() >> 16 & 255) / 255.0F; + float green = (fluid.getFluid().getColor() >> 8 & 255) / 255.0F; + float blue = (fluid.getFluid().getColor() & 255) / 255.0F; + GlStateManager.color(red, green, blue); - float red = ( fluid.getFluid().getColor() >> 16 & 255 ) / 255.0F; - float green = ( fluid.getFluid().getColor() >> 8 & 255 ) / 255.0F; - float blue = ( fluid.getFluid().getColor() & 255 ) / 255.0F; - GlStateManager.color( red, green, blue ); + TextureAtlasSprite sprite = mc.getTextureMapBlocks().getAtlasSprite(fluid.getFluid().getStill().toString()); + final int scaledHeight = (int) (this.height * ((float) fluid.getStackSize() / this.tank.getTankProperties()[this.slot].getCapacity())); - TextureAtlasSprite sprite = mc.getTextureMapBlocks().getAtlasSprite( fluid.getFluid().getStill().toString() ); - final int scaledHeight = (int) ( this.height * ( (float) fluid.getStackSize() / this.tank.getTankProperties()[this.slot].getCapacity() ) ); + int iconHeightRemainder = scaledHeight % 16; + if (iconHeightRemainder > 0) { + this.drawTexturedModalRect(this.xPos(), this.yPos() + this.getHeight() - iconHeightRemainder, sprite, 16, iconHeightRemainder); + } + for (int i = 0; i < scaledHeight / 16; i++) { + this.drawTexturedModalRect(this.xPos(), this.yPos() + this.getHeight() - iconHeightRemainder - (i + 1) * 16, sprite, 16, 16); + } + } + } + } - int iconHeightRemainder = scaledHeight % 16; - if( iconHeightRemainder > 0 ) - { - this.drawTexturedModalRect( this.xPos(), this.yPos() + this.getHeight() - iconHeightRemainder, sprite, 16, iconHeightRemainder ); - } - for( int i = 0; i < scaledHeight / 16; i++ ) - { - this.drawTexturedModalRect( this.xPos(), this.yPos() + this.getHeight() - iconHeightRemainder - ( i + 1 ) * 16, sprite, 16, 16 ); - } - } - } - } + @Override + public String getMessage() { + final IAEFluidStack fluid = this.tank.getFluidInSlot(this.slot); + if (fluid != null && fluid.getStackSize() > 0) { + String desc = fluid.getFluid().getLocalizedName(fluid.getFluidStack()); + String amountToText = fluid.getStackSize() + "mB"; - @Override - public String getMessage() - { - final IAEFluidStack fluid = this.tank.getFluidInSlot( this.slot ); - if( fluid != null && fluid.getStackSize() > 0 ) - { - String desc = fluid.getFluid().getLocalizedName( fluid.getFluidStack() ); - String amountToText = fluid.getStackSize() + "mB"; + return desc + "\n" + amountToText; + } + return null; + } - return desc + "\n" + amountToText; - } - return null; - } + @Override + public int xPos() { + return this.x - 1; + } - @Override - public int xPos() - { - return this.x - 1; - } + @Override + public int yPos() { + return this.y - 4; + } - @Override - public int yPos() - { - return this.y - 4; - } + @Override + public int getWidth() { + return this.width; + } - @Override - public int getWidth() - { - return this.width; - } + @Override + public int getHeight() { + return this.height + 4; + } - @Override - public int getHeight() - { - return this.height + 4; - } + @Override + public boolean isVisible() { + return true; + } - @Override - public boolean isVisible() - { - return true; - } + public IAEFluidStack getFluidStack() { + return this.tank.getFluidInSlot(this.slot); + } - public IAEFluidStack getFluidStack() - { - return this.tank.getFluidInSlot( this.slot ); - } + @Override + public void slotClicked(ItemStack clickStack, final int mouseButton) { - @Override - public void slotClicked( ItemStack clickStack, final int mouseButton ) - { + if (getFluidStack() != null) { + NetworkHandler.instance().sendToServer(new PacketInventoryAction(InventoryAction.FILL_ITEM, slot, 0)); + } else { + NetworkHandler.instance().sendToServer(new PacketInventoryAction(InventoryAction.EMPTY_ITEM, slot, 0)); + } - if( getFluidStack() != null ) - { - NetworkHandler.instance().sendToServer( new PacketInventoryAction( InventoryAction.FILL_ITEM, slot, 0 ) ); - } - else - { - NetworkHandler.instance().sendToServer( new PacketInventoryAction( InventoryAction.EMPTY_ITEM, slot, 0 ) ); - } - - } + } } diff --git a/src/main/java/appeng/fluids/client/gui/widgets/GuiOptionalFluidSlot.java b/src/main/java/appeng/fluids/client/gui/widgets/GuiOptionalFluidSlot.java index e8670d3d8..75dcaafbc 100644 --- a/src/main/java/appeng/fluids/client/gui/widgets/GuiOptionalFluidSlot.java +++ b/src/main/java/appeng/fluids/client/gui/widgets/GuiOptionalFluidSlot.java @@ -1,63 +1,51 @@ - package appeng.fluids.client.gui.widgets; -import net.minecraft.client.renderer.GlStateManager; - import appeng.api.storage.data.IAEFluidStack; import appeng.container.slot.IOptionalSlotHost; import appeng.fluids.util.IAEFluidTank; +import net.minecraft.client.renderer.GlStateManager; -public class GuiOptionalFluidSlot extends GuiFluidSlot -{ - private final IOptionalSlotHost containerBus; - private final int groupNum; - private final int srcX; - private final int srcY; +public class GuiOptionalFluidSlot extends GuiFluidSlot { + private final IOptionalSlotHost containerBus; + private final int groupNum; + private final int srcX; + private final int srcY; - public GuiOptionalFluidSlot( IAEFluidTank fluids, final IOptionalSlotHost containerBus, int slot, int id, int groupNum, int x, int y, int xoffs, int yoffs ) - { - super( fluids, slot, id, x + xoffs * 18, y + yoffs * 18 ); - this.containerBus = containerBus; - this.groupNum = groupNum; - this.srcX = x; - this.srcY = y; - } + public GuiOptionalFluidSlot(IAEFluidTank fluids, final IOptionalSlotHost containerBus, int slot, int id, int groupNum, int x, int y, int xoffs, int yoffs) { + super(fluids, slot, id, x + xoffs * 18, y + yoffs * 18); + this.containerBus = containerBus; + this.groupNum = groupNum; + this.srcX = x; + this.srcY = y; + } - @Override - public boolean isSlotEnabled() - { - if( this.containerBus == null ) - { - return false; - } - return this.containerBus.isSlotEnabled( this.groupNum ); - } + @Override + public boolean isSlotEnabled() { + if (this.containerBus == null) { + return false; + } + return this.containerBus.isSlotEnabled(this.groupNum); + } - @Override - public IAEFluidStack getFluidStack() - { - if( !this.isSlotEnabled() && super.getFluidStack() != null ) - { - this.setFluidStack( null ); - } - return super.getFluidStack(); - } + @Override + public IAEFluidStack getFluidStack() { + if (!this.isSlotEnabled() && super.getFluidStack() != null) { + this.setFluidStack(null); + } + return super.getFluidStack(); + } - @Override - public void drawBackground( int guileft, int guitop ) - { - GlStateManager.enableBlend(); - if( this.isSlotEnabled() ) - { - GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); - } - else - { - GlStateManager.color( 1.0F, 1.0F, 1.0F, 0.4F ); - } - this.drawTexturedModalRect( guileft + this.xPos() - 1, guitop + this.yPos() - 1, this.srcX - 1, this.srcY - 1, this.getWidth() + 2, - this.getHeight() + 2 ); - } + @Override + public void drawBackground(int guileft, int guitop) { + GlStateManager.enableBlend(); + if (this.isSlotEnabled()) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + } else { + GlStateManager.color(1.0F, 1.0F, 1.0F, 0.4F); + } + this.drawTexturedModalRect(guileft + this.xPos() - 1, guitop + this.yPos() - 1, this.srcX - 1, this.srcY - 1, this.getWidth() + 2, + this.getHeight() + 2); + } } diff --git a/src/main/java/appeng/fluids/client/render/FluidStackSizeRenderer.java b/src/main/java/appeng/fluids/client/render/FluidStackSizeRenderer.java index 6149bc89d..3c61e9100 100644 --- a/src/main/java/appeng/fluids/client/render/FluidStackSizeRenderer.java +++ b/src/main/java/appeng/fluids/client/render/FluidStackSizeRenderer.java @@ -19,18 +19,17 @@ package appeng.fluids.client.render; -import java.math.RoundingMode; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; - -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.GlStateManager; - import appeng.api.storage.data.IAEFluidStack; import appeng.core.AEConfig; import appeng.util.ISlimReadableNumberConverter; import appeng.util.IWideReadableNumberConverter; import appeng.util.ReadableNumberConverter; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.renderer.GlStateManager; + +import java.math.RoundingMode; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; /** @@ -40,95 +39,81 @@ import appeng.util.ReadableNumberConverter; * @version rv6 * @since rv6 */ -public class FluidStackSizeRenderer -{ +public class FluidStackSizeRenderer { - private static final String[] NUMBER_FORMATS = new String[] { "#.000", "#.00", "#.0", "#" }; + private static final String[] NUMBER_FORMATS = new String[]{"#.000", "#.00", "#.0", "#"}; - private static final ISlimReadableNumberConverter SLIM_CONVERTER = ReadableNumberConverter.INSTANCE; - private static final IWideReadableNumberConverter WIDE_CONVERTER = ReadableNumberConverter.INSTANCE; + private static final ISlimReadableNumberConverter SLIM_CONVERTER = ReadableNumberConverter.INSTANCE; + private static final IWideReadableNumberConverter WIDE_CONVERTER = ReadableNumberConverter.INSTANCE; - public void renderStackSize( FontRenderer fontRenderer, IAEFluidStack aeStack, int xPos, int yPos ) - { - if( aeStack != null ) - { - final float scaleFactor = AEConfig.instance().useTerminalUseLargeFont() ? 0.85f : 0.5f; - final float inverseScaleFactor = 1.0f / scaleFactor; - final int offset = AEConfig.instance().useTerminalUseLargeFont() ? 0 : -1; + public void renderStackSize(FontRenderer fontRenderer, IAEFluidStack aeStack, int xPos, int yPos) { + if (aeStack != null) { + final float scaleFactor = AEConfig.instance().useTerminalUseLargeFont() ? 0.85f : 0.5f; + final float inverseScaleFactor = 1.0f / scaleFactor; + final int offset = AEConfig.instance().useTerminalUseLargeFont() ? 0 : -1; - final boolean unicodeFlag = fontRenderer.getUnicodeFlag(); - fontRenderer.setUnicodeFlag( false ); + final boolean unicodeFlag = fontRenderer.getUnicodeFlag(); + fontRenderer.setUnicodeFlag(false); - if( aeStack.getStackSize() > 0 ) - { - final String stackSize = this.getToBeRenderedStackSize( aeStack.getStackSize() ); + if (aeStack.getStackSize() > 0) { + final String stackSize = this.getToBeRenderedStackSize(aeStack.getStackSize()); - GlStateManager.disableLighting(); - GlStateManager.disableDepth(); - GlStateManager.disableBlend(); - GlStateManager.pushMatrix(); - GlStateManager.scale( scaleFactor, scaleFactor, scaleFactor ); - final int X = (int) ( ( (float) xPos + offset + 16.0f - fontRenderer.getStringWidth( stackSize ) * scaleFactor ) * inverseScaleFactor ); - final int Y = (int) ( ( (float) yPos + offset + 16.0f - 7.0f * scaleFactor ) * inverseScaleFactor ); - fontRenderer.drawStringWithShadow( stackSize, X, Y, 16777215 ); - GlStateManager.popMatrix(); - GlStateManager.enableLighting(); - GlStateManager.enableDepth(); - GlStateManager.enableBlend(); - } + GlStateManager.disableLighting(); + GlStateManager.disableDepth(); + GlStateManager.disableBlend(); + GlStateManager.pushMatrix(); + GlStateManager.scale(scaleFactor, scaleFactor, scaleFactor); + final int X = (int) (((float) xPos + offset + 16.0f - fontRenderer.getStringWidth(stackSize) * scaleFactor) * inverseScaleFactor); + final int Y = (int) (((float) yPos + offset + 16.0f - 7.0f * scaleFactor) * inverseScaleFactor); + fontRenderer.drawStringWithShadow(stackSize, X, Y, 16777215); + GlStateManager.popMatrix(); + GlStateManager.enableLighting(); + GlStateManager.enableDepth(); + GlStateManager.enableBlend(); + } - fontRenderer.setUnicodeFlag( unicodeFlag ); - } - } + fontRenderer.setUnicodeFlag(unicodeFlag); + } + } - private String getToBeRenderedStackSize( final long originalSize ) - { - // Handle any value below 100 (large font) or 1000 (small font) Buckets with a custom formatter, - // otherwise pass it to the normal number converter - if( originalSize < 1000 * 100 && AEConfig.instance().useTerminalUseLargeFont() ) - { - return this.getSlimRenderedStacksize( originalSize ); - } - else if( originalSize < 1000 * 1000 && !AEConfig.instance().useTerminalUseLargeFont() ) - { - return this.getWideRenderedStacksize( originalSize ); - } + private String getToBeRenderedStackSize(final long originalSize) { + // Handle any value below 100 (large font) or 1000 (small font) Buckets with a custom formatter, + // otherwise pass it to the normal number converter + if (originalSize < 1000 * 100 && AEConfig.instance().useTerminalUseLargeFont()) { + return this.getSlimRenderedStacksize(originalSize); + } else if (originalSize < 1000 * 1000 && !AEConfig.instance().useTerminalUseLargeFont()) { + return this.getWideRenderedStacksize(originalSize); + } - if( AEConfig.instance().useTerminalUseLargeFont() ) - { - return SLIM_CONVERTER.toSlimReadableForm( originalSize / 1000 ); - } - else - { - return WIDE_CONVERTER.toWideReadableForm( originalSize / 1000 ); - } - } + if (AEConfig.instance().useTerminalUseLargeFont()) { + return SLIM_CONVERTER.toSlimReadableForm(originalSize / 1000); + } else { + return WIDE_CONVERTER.toWideReadableForm(originalSize / 1000); + } + } - private String getSlimRenderedStacksize( final long originalSize ) - { - final int log = 1 + (int) Math.floor( Math.log10( originalSize ) ) / 2; + private String getSlimRenderedStacksize(final long originalSize) { + final int log = 1 + (int) Math.floor(Math.log10(originalSize)) / 2; - return this.getRenderedFluidStackSize( originalSize, log ); - } + return this.getRenderedFluidStackSize(originalSize, log); + } - private String getWideRenderedStacksize( final long originalSize ) - { - final int log = (int) Math.floor( Math.log10( originalSize ) ) / 2; + private String getWideRenderedStacksize(final long originalSize) { + final int log = (int) Math.floor(Math.log10(originalSize)) / 2; - return this.getRenderedFluidStackSize( originalSize, log ); - } + return this.getRenderedFluidStackSize(originalSize, log); + } - private String getRenderedFluidStackSize( final long originalSize, final int log ) - { - final int index = Math.max( 0, Math.min( 3, log ) ); + private String getRenderedFluidStackSize(final long originalSize, final int log) { + final int index = Math.max(0, Math.min(3, log)); - final DecimalFormatSymbols symbols = new DecimalFormatSymbols(); - symbols.setDecimalSeparator( '.' ); - final DecimalFormat format = new DecimalFormat( NUMBER_FORMATS[index] ); - format.setDecimalFormatSymbols( symbols ); - format.setRoundingMode( RoundingMode.DOWN ); + final DecimalFormatSymbols symbols = new DecimalFormatSymbols(); + symbols.setDecimalSeparator('.'); + final DecimalFormat format = new DecimalFormat(NUMBER_FORMATS[index]); + format.setDecimalFormatSymbols(symbols); + format.setRoundingMode(RoundingMode.DOWN); - return format.format( originalSize / 1000d ); - } + return format.format(originalSize / 1000d); + } } diff --git a/src/main/java/appeng/fluids/container/ContainerFluidConfigurable.java b/src/main/java/appeng/fluids/container/ContainerFluidConfigurable.java index aa09acc9c..3675092eb 100644 --- a/src/main/java/appeng/fluids/container/ContainerFluidConfigurable.java +++ b/src/main/java/appeng/fluids/container/ContainerFluidConfigurable.java @@ -1,16 +1,6 @@ - package appeng.fluids.container; -import java.util.Collections; -import java.util.Map; - -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IContainerListener; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; - import appeng.api.config.Upgrades; import appeng.api.implementations.IUpgradeableHost; import appeng.api.storage.data.IAEFluidStack; @@ -19,99 +9,87 @@ import appeng.fluids.helper.FluidSyncHelper; import appeng.fluids.util.AEFluidStack; import appeng.fluids.util.IAEFluidTank; import appeng.util.Platform; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IContainerListener; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; + +import java.util.Collections; +import java.util.Map; -public abstract class ContainerFluidConfigurable extends ContainerUpgradeable implements IFluidSyncContainer -{ - private FluidSyncHelper sync = null; +public abstract class ContainerFluidConfigurable extends ContainerUpgradeable implements IFluidSyncContainer { + private FluidSyncHelper sync = null; - public ContainerFluidConfigurable( InventoryPlayer ip, IUpgradeableHost te ) - { - super( ip, te ); - } + public ContainerFluidConfigurable(InventoryPlayer ip, IUpgradeableHost te) { + super(ip, te); + } - public abstract IAEFluidTank getFluidConfigInventory(); + public abstract IAEFluidTank getFluidConfigInventory(); - private FluidSyncHelper getSynchHelper() - { - if( this.sync == null ) - { - this.sync = new FluidSyncHelper( this.getFluidConfigInventory(), 0 ); - } - return this.sync; - } + private FluidSyncHelper getSynchHelper() { + if (this.sync == null) { + this.sync = new FluidSyncHelper(this.getFluidConfigInventory(), 0); + } + return this.sync; + } - @Override - protected ItemStack transferStackToContainer( ItemStack input ) - { - FluidStack fs = FluidUtil.getFluidContained( input ); - if( fs != null ) - { - final IAEFluidTank t = this.getFluidConfigInventory(); - final IAEFluidStack stack = AEFluidStack.fromFluidStack( fs ); - for( int i = 0; i < t.getSlots(); ++i ) - { - if( t.getFluidInSlot( i ) == null && this.isValidForConfig( i, stack ) ) - { - t.setFluidInSlot( i, stack ); - break; - } - } - } - return input; - } + @Override + protected ItemStack transferStackToContainer(ItemStack input) { + FluidStack fs = FluidUtil.getFluidContained(input); + if (fs != null) { + final IAEFluidTank t = this.getFluidConfigInventory(); + final IAEFluidStack stack = AEFluidStack.fromFluidStack(fs); + for (int i = 0; i < t.getSlots(); ++i) { + if (t.getFluidInSlot(i) == null && this.isValidForConfig(i, stack)) { + t.setFluidInSlot(i, stack); + break; + } + } + } + return input; + } - protected boolean isValidForConfig( int slot, IAEFluidStack fs ) - { - if( this.supportCapacity() ) - { - // assumes 4 slots per upgrade - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); + protected boolean isValidForConfig(int slot, IAEFluidStack fs) { + if (this.supportCapacity()) { + // assumes 4 slots per upgrade + final int upgrades = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); - if( slot > 0 && upgrades < 1 ) - { - return false; - } - if( slot > 4 && upgrades < 2 ) - { - return false; - } - } + if (slot > 0 && upgrades < 1) { + return false; + } + return slot <= 4 || upgrades >= 2; + } - return true; - } + return true; + } - @Override - protected void standardDetectAndSendChanges() - { - if( Platform.isServer() ) - { - this.getSynchHelper().sendDiff( this.listeners ); + @Override + protected void standardDetectAndSendChanges() { + if (Platform.isServer()) { + this.getSynchHelper().sendDiff(this.listeners); - // clear out config items that are no longer valid (eg capacity upgrade removed) - final IAEFluidTank t = this.getFluidConfigInventory(); - for( int i = 0; i < t.getSlots(); ++i ) - { - if( t.getFluidInSlot( i ) != null && !this.isValidForConfig( i, t.getFluidInSlot( i ) ) ) - { - t.setFluidInSlot( i, null ); - } - } - } - super.standardDetectAndSendChanges(); - } + // clear out config items that are no longer valid (eg capacity upgrade removed) + final IAEFluidTank t = this.getFluidConfigInventory(); + for (int i = 0; i < t.getSlots(); ++i) { + if (t.getFluidInSlot(i) != null && !this.isValidForConfig(i, t.getFluidInSlot(i))) { + t.setFluidInSlot(i, null); + } + } + } + super.standardDetectAndSendChanges(); + } - @Override - public void addListener( IContainerListener listener ) - { - super.addListener( listener ); - this.getSynchHelper().sendFull( Collections.singleton( listener ) ); - } + @Override + public void addListener(IContainerListener listener) { + super.addListener(listener); + this.getSynchHelper().sendFull(Collections.singleton(listener)); + } - @Override - public void receiveFluidSlots( Map fluids ) - { - this.getSynchHelper().readPacket( fluids ); - } + @Override + public void receiveFluidSlots(Map fluids) { + this.getSynchHelper().readPacket(fluids); + } } diff --git a/src/main/java/appeng/fluids/container/ContainerFluidFormationPlane.java b/src/main/java/appeng/fluids/container/ContainerFluidFormationPlane.java index 8705cc641..6f593dc73 100644 --- a/src/main/java/appeng/fluids/container/ContainerFluidFormationPlane.java +++ b/src/main/java/appeng/fluids/container/ContainerFluidFormationPlane.java @@ -1,103 +1,87 @@ - package appeng.fluids.container; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.SecurityPermissions; import appeng.api.config.Upgrades; import appeng.api.storage.data.IAEFluidStack; import appeng.container.slot.SlotRestrictedInput; import appeng.fluids.parts.PartFluidFormationPlane; import appeng.fluids.util.IAEFluidTank; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraftforge.items.IItemHandler; -public class ContainerFluidFormationPlane extends ContainerFluidConfigurable -{ - private final PartFluidFormationPlane plane; +public class ContainerFluidFormationPlane extends ContainerFluidConfigurable { + private final PartFluidFormationPlane plane; - public ContainerFluidFormationPlane( final InventoryPlayer ip, final PartFluidFormationPlane te ) - { - super( ip, te ); - this.plane = te; - } + public ContainerFluidFormationPlane(final InventoryPlayer ip, final PartFluidFormationPlane te) { + super(ip, te); + this.plane = te; + } - @Override - protected int getHeight() - { - return 251; - } + @Override + protected int getHeight() { + return 251; + } - @Override - public IAEFluidTank getFluidConfigInventory() - { - return this.plane.getConfig(); - } + @Override + public IAEFluidTank getFluidConfigInventory() { + return this.plane.getConfig(); + } - @Override - protected void setupConfig() - { - final IItemHandler upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } + @Override + protected void setupConfig() { + final IItemHandler upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer())) + .setNotDraggable()); + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); - this.checkToolbox(); - this.standardDetectAndSendChanges(); - } + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); + this.checkToolbox(); + this.standardDetectAndSendChanges(); + } - @Override - protected boolean isValidForConfig( int slot, IAEFluidStack fs ) - { - if( this.supportCapacity() ) - { - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); + @Override + protected boolean isValidForConfig(int slot, IAEFluidStack fs) { + if (this.supportCapacity()) { + final int upgrades = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); - final int y = slot / 9; + final int y = slot / 9; - if( y >= upgrades + 2 ) - { - return false; - } - } + return y < upgrades + 2; + } - return true; - } + return true; + } - @Override - public boolean isSlotEnabled( final int idx ) - { - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); + @Override + public boolean isSlotEnabled(final int idx) { + final int upgrades = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); - return upgrades > idx; - } + return upgrades > idx; + } - @Override - protected boolean supportCapacity() - { - return true; - } + @Override + protected boolean supportCapacity() { + return true; + } - @Override - public int availableUpgrades() - { - return 5; - } + @Override + public int availableUpgrades() { + return 5; + } } diff --git a/src/main/java/appeng/fluids/container/ContainerFluidIO.java b/src/main/java/appeng/fluids/container/ContainerFluidIO.java index 0147bb2e1..65f23ecb8 100644 --- a/src/main/java/appeng/fluids/container/ContainerFluidIO.java +++ b/src/main/java/appeng/fluids/container/ContainerFluidIO.java @@ -19,10 +19,9 @@ package appeng.fluids.container; -import net.minecraft.entity.player.InventoryPlayer; - import appeng.fluids.parts.PartSharedFluidBus; import appeng.fluids.util.IAEFluidTank; +import net.minecraft.entity.player.InventoryPlayer; /** @@ -30,25 +29,21 @@ import appeng.fluids.util.IAEFluidTank; * @version rv5 - 1/05/2018 * @since rv5 1/05/2018 */ -public class ContainerFluidIO extends ContainerFluidConfigurable -{ - private final PartSharedFluidBus bus; +public class ContainerFluidIO extends ContainerFluidConfigurable { + private final PartSharedFluidBus bus; - public ContainerFluidIO( InventoryPlayer ip, PartSharedFluidBus te ) - { - super( ip, te ); - this.bus = te; - } + public ContainerFluidIO(InventoryPlayer ip, PartSharedFluidBus te) { + super(ip, te); + this.bus = te; + } - @Override - public IAEFluidTank getFluidConfigInventory() - { - return this.bus.getConfig(); - } + @Override + public IAEFluidTank getFluidConfigInventory() { + return this.bus.getConfig(); + } - @Override - protected void setupConfig() - { - this.setupUpgrades(); - } + @Override + protected void setupConfig() { + this.setupUpgrades(); + } } diff --git a/src/main/java/appeng/fluids/container/ContainerFluidInterface.java b/src/main/java/appeng/fluids/container/ContainerFluidInterface.java index 36073d25f..a30cc4f22 100644 --- a/src/main/java/appeng/fluids/container/ContainerFluidInterface.java +++ b/src/main/java/appeng/fluids/container/ContainerFluidInterface.java @@ -19,243 +19,201 @@ package appeng.fluids.container; -import javax.annotation.Nonnull; - -import java.util.Collections; -import java.util.Map; - -import appeng.core.sync.network.NetworkHandler; -import appeng.core.sync.packets.PacketTargetFluidStack; -import appeng.fluids.util.AEFluidStack; -import appeng.helpers.InventoryAction; -import appeng.util.IConfigManagerHost; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IContainerListener; - import appeng.api.config.SecurityPermissions; import appeng.api.storage.data.IAEFluidStack; import appeng.api.util.IConfigManager; +import appeng.core.sync.network.NetworkHandler; +import appeng.core.sync.packets.PacketTargetFluidStack; import appeng.fluids.helper.DualityFluidInterface; import appeng.fluids.helper.FluidSyncHelper; import appeng.fluids.helper.IFluidInterfaceHost; +import appeng.fluids.util.AEFluidStack; import appeng.fluids.util.IAEFluidTank; +import appeng.helpers.InventoryAction; +import appeng.util.IConfigManagerHost; import appeng.util.Platform; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IContainerListener; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fluids.capability.IFluidHandlerItem; +import javax.annotation.Nonnull; +import java.util.Collections; +import java.util.Map; -public class ContainerFluidInterface extends ContainerFluidConfigurable implements IConfigManagerHost -{ - private final DualityFluidInterface myDuality; - private final FluidSyncHelper tankSync; - private IConfigManagerHost gui; - // Holds the fluid the client wishes to extract, or null for insert - private IAEFluidStack clientRequestedTargetFluid = null; - public ContainerFluidInterface( final InventoryPlayer ip, final IFluidInterfaceHost te ) - { - super( ip, te.getDualityFluidInterface().getHost() ); +public class ContainerFluidInterface extends ContainerFluidConfigurable implements IConfigManagerHost { + private final DualityFluidInterface myDuality; + private final FluidSyncHelper tankSync; + private IConfigManagerHost gui; + // Holds the fluid the client wishes to extract, or null for insert + private IAEFluidStack clientRequestedTargetFluid = null; - this.myDuality = te.getDualityFluidInterface(); - this.tankSync = new FluidSyncHelper( this.myDuality.getTanks(), DualityFluidInterface.NUMBER_OF_TANKS ); - } + public ContainerFluidInterface(final InventoryPlayer ip, final IFluidInterfaceHost te) { + super(ip, te.getDualityFluidInterface().getHost()); - @Override - protected int getHeight() - { - return 231; - } + this.myDuality = te.getDualityFluidInterface(); + this.tankSync = new FluidSyncHelper(this.myDuality.getTanks(), DualityFluidInterface.NUMBER_OF_TANKS); + } - @Override - public IAEFluidTank getFluidConfigInventory() - { - return this.myDuality.getConfig(); - } + @Override + protected int getHeight() { + return 231; + } - @Override - public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) - { - if( this.getGui() != null ) - { - this.getGui().updateSetting( manager, settingName, newValue ); - } - } + @Override + public IAEFluidTank getFluidConfigInventory() { + return this.myDuality.getConfig(); + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + @Override + public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) { + if (this.getGui() != null) { + this.getGui().updateSetting(manager, settingName, newValue); + } + } - if( Platform.isServer() ) - { - this.tankSync.sendDiff( this.listeners ); - } + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - super.detectAndSendChanges(); - } + if (Platform.isServer()) { + this.tankSync.sendDiff(this.listeners); + } - @Override - protected void setupConfig() - { - } + super.detectAndSendChanges(); + } - @Override - protected void loadSettingsFromHost( final IConfigManager cm ) - { - } + @Override + protected void setupConfig() { + } - @Override - public void addListener( IContainerListener listener ) - { - super.addListener( listener ); - this.tankSync.sendFull( Collections.singleton( listener ) ); - } + @Override + protected void loadSettingsFromHost(final IConfigManager cm) { + } - @Override - public void receiveFluidSlots( Map fluids ) - { - super.receiveFluidSlots( fluids ); - this.tankSync.readPacket( fluids ); - } + @Override + public void addListener(IContainerListener listener) { + super.addListener(listener); + this.tankSync.sendFull(Collections.singleton(listener)); + } - private IConfigManagerHost getGui() - { - return this.gui; - } + @Override + public void receiveFluidSlots(Map fluids) { + super.receiveFluidSlots(fluids); + this.tankSync.readPacket(fluids); + } - public void setGui( @Nonnull final IConfigManagerHost gui ) - { - this.gui = gui; - } + private IConfigManagerHost getGui() { + return this.gui; + } - public void doAction( EntityPlayerMP player, InventoryAction action, int slot, long id ) - { - if( action != InventoryAction.FILL_ITEM && action != InventoryAction.EMPTY_ITEM ) - { - super.doAction( player, action, slot, id ); - return; - } + public void setGui(@Nonnull final IConfigManagerHost gui) { + this.gui = gui; + } - final ItemStack held = player.inventory.getItemStack(); - ItemStack heldCopy = held.copy(); - heldCopy.setCount( 1 ); - IFluidHandlerItem fh = FluidUtil.getFluidHandler( heldCopy ); - if( fh == null ) - { - // only fluid handlers items - return; - } + public void doAction(EntityPlayerMP player, InventoryAction action, int slot, long id) { + if (action != InventoryAction.FILL_ITEM && action != InventoryAction.EMPTY_ITEM) { + super.doAction(player, action, slot, id); + return; + } - if( action == InventoryAction.FILL_ITEM && this.clientRequestedTargetFluid != null ) - { - final IAEFluidStack stack = this.clientRequestedTargetFluid.copy(); + final ItemStack held = player.inventory.getItemStack(); + ItemStack heldCopy = held.copy(); + heldCopy.setCount(1); + IFluidHandlerItem fh = FluidUtil.getFluidHandler(heldCopy); + if (fh == null) { + // only fluid handlers items + return; + } - // Check how much we can store in the item - stack.setStackSize( Integer.MAX_VALUE ); - int amountAllowed = fh.fill( stack.getFluidStack(), false ); - int heldAmount = held.getCount(); - for( int i = 0; i < heldAmount; i++ ) - { - ItemStack copiedFluidContainer = held.copy(); - copiedFluidContainer.setCount( 1 ); - fh = FluidUtil.getFluidHandler( copiedFluidContainer ); + if (action == InventoryAction.FILL_ITEM && this.clientRequestedTargetFluid != null) { + final IAEFluidStack stack = this.clientRequestedTargetFluid.copy(); - FluidStack extractableFluid = this.myDuality.getTanks().drain( stack.setStackSize( amountAllowed ).getFluidStack(), false ); - if( extractableFluid == null || extractableFluid.amount == 0 ) - { - break; - } + // Check how much we can store in the item + stack.setStackSize(Integer.MAX_VALUE); + int amountAllowed = fh.fill(stack.getFluidStack(), false); + int heldAmount = held.getCount(); + for (int i = 0; i < heldAmount; i++) { + ItemStack copiedFluidContainer = held.copy(); + copiedFluidContainer.setCount(1); + fh = FluidUtil.getFluidHandler(copiedFluidContainer); - int fillableAmount = fh.fill( extractableFluid, false ); - if( fillableAmount > 0 ) - { - FluidStack extractedFluid = this.myDuality.getTanks().drain( extractableFluid, true ); - fh.fill( extractedFluid, true ); - } + FluidStack extractableFluid = this.myDuality.getTanks().drain(stack.setStackSize(amountAllowed).getFluidStack(), false); + if (extractableFluid == null || extractableFluid.amount == 0) { + break; + } - if( held.getCount() == 1 ) - { - player.inventory.setItemStack( fh.getContainer() ); - } - else - { - player.inventory.getItemStack().shrink( 1 ); - if( !player.inventory.addItemStackToInventory( fh.getContainer() ) ) - { - player.dropItem( fh.getContainer(), false ); - } - } - } - } - else if( action == InventoryAction.EMPTY_ITEM ) - { - int heldAmount = held.getCount(); - for( int i = 0; i < heldAmount; i++ ) - { - ItemStack copiedFluidContainer = held.copy(); - copiedFluidContainer.setCount( 1 ); - fh = FluidUtil.getFluidHandler( copiedFluidContainer ); + int fillableAmount = fh.fill(extractableFluid, false); + if (fillableAmount > 0) { + FluidStack extractedFluid = this.myDuality.getTanks().drain(extractableFluid, true); + fh.fill(extractedFluid, true); + } - FluidStack drainable = fh.drain( this.myDuality.getTanks().getTankProperties()[slot].getCapacity(), false ); - if( drainable != null ) - { - fh.drain( drainable, true ); - this.myDuality.getTanks().fill( drainable, true ); - } + if (held.getCount() == 1) { + player.inventory.setItemStack(fh.getContainer()); + } else { + player.inventory.getItemStack().shrink(1); + if (!player.inventory.addItemStackToInventory(fh.getContainer())) { + player.dropItem(fh.getContainer(), false); + } + } + } + } else if (action == InventoryAction.EMPTY_ITEM) { + int heldAmount = held.getCount(); + for (int i = 0; i < heldAmount; i++) { + ItemStack copiedFluidContainer = held.copy(); + copiedFluidContainer.setCount(1); + fh = FluidUtil.getFluidHandler(copiedFluidContainer); - if( held.getCount() == 1 ) - { - player.inventory.setItemStack( fh.getContainer() ); - } - else - { - player.inventory.getItemStack().shrink( 1 ); - if( !player.inventory.addItemStackToInventory( fh.getContainer() ) ) - { - player.dropItem( fh.getContainer(), false ); - } - } - } - } - this.updateHeld( player ); - } + FluidStack drainable = fh.drain(this.myDuality.getTanks().getTankProperties()[slot].getCapacity(), false); + if (drainable != null) { + fh.drain(drainable, true); + this.myDuality.getTanks().fill(drainable, true); + } - public void setTargetStack( final IAEFluidStack stack ) - { - if( Platform.isClient() ) - { - if( stack == null && this.clientRequestedTargetFluid == null ) - { - return; - } - if( stack != null && this.clientRequestedTargetFluid != null && stack.getFluidStack().isFluidEqual( this.clientRequestedTargetFluid.getFluidStack() ) ) - { - return; - } - NetworkHandler.instance().sendToServer( new PacketTargetFluidStack( (AEFluidStack) stack ) ); - } + if (held.getCount() == 1) { + player.inventory.setItemStack(fh.getContainer()); + } else { + player.inventory.getItemStack().shrink(1); + if (!player.inventory.addItemStackToInventory(fh.getContainer())) { + player.dropItem(fh.getContainer(), false); + } + } + } + } + this.updateHeld(player); + } - this.clientRequestedTargetFluid = stack == null ? null : stack.copy(); - } + public void setTargetStack(final IAEFluidStack stack) { + if (Platform.isClient()) { + if (stack == null && this.clientRequestedTargetFluid == null) { + return; + } + if (stack != null && this.clientRequestedTargetFluid != null && stack.getFluidStack().isFluidEqual(this.clientRequestedTargetFluid.getFluidStack())) { + return; + } + NetworkHandler.instance().sendToServer(new PacketTargetFluidStack((AEFluidStack) stack)); + } - @Override - protected boolean supportCapacity() - { - return false; - } + this.clientRequestedTargetFluid = stack == null ? null : stack.copy(); + } - @Override - public int availableUpgrades() - { - return 0; - } + @Override + protected boolean supportCapacity() { + return false; + } - @Override - public boolean hasToolbox() - { - return false; - } + @Override + public int availableUpgrades() { + return 0; + } + + @Override + public boolean hasToolbox() { + return false; + } } diff --git a/src/main/java/appeng/fluids/container/ContainerFluidLevelEmitter.java b/src/main/java/appeng/fluids/container/ContainerFluidLevelEmitter.java index 8eb730591..99e4f4166 100644 --- a/src/main/java/appeng/fluids/container/ContainerFluidLevelEmitter.java +++ b/src/main/java/appeng/fluids/container/ContainerFluidLevelEmitter.java @@ -1,13 +1,6 @@ - package appeng.fluids.container; -import net.minecraft.client.gui.GuiTextField; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.config.RedstoneMode; import appeng.api.config.SecurityPermissions; import appeng.api.config.Settings; @@ -15,83 +8,75 @@ import appeng.container.guisync.GuiSync; import appeng.fluids.parts.PartFluidLevelEmitter; import appeng.fluids.util.IAEFluidTank; import appeng.util.Platform; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class ContainerFluidLevelEmitter extends ContainerFluidConfigurable -{ - private final PartFluidLevelEmitter lvlEmitter; +public class ContainerFluidLevelEmitter extends ContainerFluidConfigurable { + private final PartFluidLevelEmitter lvlEmitter; - @SideOnly( Side.CLIENT ) - private GuiTextField textField; - @GuiSync( 3 ) - public long EmitterValue = -1; + @SideOnly(Side.CLIENT) + private GuiTextField textField; + @GuiSync(3) + public long EmitterValue = -1; - public ContainerFluidLevelEmitter( final InventoryPlayer ip, final PartFluidLevelEmitter te ) - { - super( ip, te ); - this.lvlEmitter = te; - } + public ContainerFluidLevelEmitter(final InventoryPlayer ip, final PartFluidLevelEmitter te) { + super(ip, te); + this.lvlEmitter = te; + } - @SideOnly( Side.CLIENT ) - public void setTextField( final GuiTextField level ) - { - this.textField = level; - this.textField.setText( String.valueOf( this.EmitterValue ) ); - } + @SideOnly(Side.CLIENT) + public void setTextField(final GuiTextField level) { + this.textField = level; + this.textField.setText(String.valueOf(this.EmitterValue)); + } - public void setLevel( final long l, final EntityPlayer player ) - { - this.lvlEmitter.setReportingValue( l ); - this.EmitterValue = l; - } + public void setLevel(final long l, final EntityPlayer player) { + this.lvlEmitter.setReportingValue(l); + this.EmitterValue = l; + } - @Override - protected void setupConfig() - { - } + @Override + protected void setupConfig() { + } - @Override - protected boolean supportCapacity() - { - return false; - } + @Override + protected boolean supportCapacity() { + return false; + } - @Override - public int availableUpgrades() - { + @Override + public int availableUpgrades() { - return 0; - } + return 0; + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - if( Platform.isServer() ) - { - this.EmitterValue = this.lvlEmitter.getReportingValue(); - this.setRedStoneMode( (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting( Settings.REDSTONE_EMITTER ) ); - } + if (Platform.isServer()) { + this.EmitterValue = this.lvlEmitter.getReportingValue(); + this.setRedStoneMode((RedstoneMode) this.getUpgradeable().getConfigManager().getSetting(Settings.REDSTONE_EMITTER)); + } - this.standardDetectAndSendChanges(); - } + this.standardDetectAndSendChanges(); + } - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if( field.equals( "EmitterValue" ) ) - { - if( this.textField != null ) - { - this.textField.setText( String.valueOf( this.EmitterValue ) ); - } - } - } + @Override + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("EmitterValue")) { + if (this.textField != null) { + this.textField.setText(String.valueOf(this.EmitterValue)); + } + } + } - @Override - public IAEFluidTank getFluidConfigInventory() - { - return this.lvlEmitter.getConfig(); - } + @Override + public IAEFluidTank getFluidConfigInventory() { + return this.lvlEmitter.getConfig(); + } } diff --git a/src/main/java/appeng/fluids/container/ContainerFluidStorageBus.java b/src/main/java/appeng/fluids/container/ContainerFluidStorageBus.java index bdcdbfaa5..7fb6c0f7c 100644 --- a/src/main/java/appeng/fluids/container/ContainerFluidStorageBus.java +++ b/src/main/java/appeng/fluids/container/ContainerFluidStorageBus.java @@ -19,18 +19,8 @@ package appeng.fluids.container; -import java.util.Iterator; - -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; -import appeng.api.config.AccessRestriction; -import appeng.api.config.FuzzyMode; -import appeng.api.config.SecurityPermissions; -import appeng.api.config.Settings; -import appeng.api.config.StorageFilter; -import appeng.api.config.Upgrades; +import appeng.api.config.*; import appeng.api.storage.IMEInventory; import appeng.api.storage.channels.IFluidStorageChannel; import appeng.api.storage.data.IAEFluidStack; @@ -41,6 +31,10 @@ import appeng.fluids.parts.PartFluidStorageBus; import appeng.fluids.util.IAEFluidTank; import appeng.util.Platform; import appeng.util.iterators.NullIterator; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraftforge.items.IItemHandler; + +import java.util.Iterator; /** @@ -48,163 +42,136 @@ import appeng.util.iterators.NullIterator; * @version rv6 - 22/05/2018 * @since rv6 22/05/2018 */ -public class ContainerFluidStorageBus extends ContainerFluidConfigurable -{ +public class ContainerFluidStorageBus extends ContainerFluidConfigurable { - private final PartFluidStorageBus storageBus; + private final PartFluidStorageBus storageBus; - @GuiSync( 3 ) - public AccessRestriction rwMode = AccessRestriction.READ_WRITE; + @GuiSync(3) + public AccessRestriction rwMode = AccessRestriction.READ_WRITE; - @GuiSync( 4 ) - public StorageFilter storageFilter = StorageFilter.EXTRACTABLE_ONLY; + @GuiSync(4) + public StorageFilter storageFilter = StorageFilter.EXTRACTABLE_ONLY; - public ContainerFluidStorageBus( InventoryPlayer ip, PartFluidStorageBus te ) - { - super( ip, te ); - this.storageBus = te; - } + public ContainerFluidStorageBus(InventoryPlayer ip, PartFluidStorageBus te) { + super(ip, te); + this.storageBus = te; + } - @Override - protected int getHeight() - { - return 251; - } + @Override + protected int getHeight() { + return 251; + } - @Override - protected void setupConfig() - { - final IItemHandler upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - this.addSlotToContainer( - ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer() ) ) - .setNotDraggable() ); - } + @Override + protected void setupConfig() { + final IItemHandler upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer( + (new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer())) + .setNotDraggable()); + } - @Override - protected boolean isValidForConfig( int slot, IAEFluidStack fs ) - { - if( this.supportCapacity() ) - { - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); + @Override + protected boolean isValidForConfig(int slot, IAEFluidStack fs) { + if (this.supportCapacity()) { + final int upgrades = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); - final int y = slot / 9; + final int y = slot / 9; - if( y >= upgrades + 2 ) - { - return false; - } - } + return y < upgrades + 2; + } - return true; - } + return true; + } - @Override - protected boolean supportCapacity() - { - return true; - } + @Override + protected boolean supportCapacity() { + return true; + } - @Override - public int availableUpgrades() - { - return 5; - } + @Override + public int availableUpgrades() { + return 5; + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - if( Platform.isServer() ) - { - this.setFuzzyMode( (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting( Settings.FUZZY_MODE ) ); - this.setReadWriteMode( (AccessRestriction) this.getUpgradeable().getConfigManager().getSetting( Settings.ACCESS ) ); - this.setStorageFilter( (StorageFilter) this.getUpgradeable().getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); - } + if (Platform.isServer()) { + this.setFuzzyMode((FuzzyMode) this.getUpgradeable().getConfigManager().getSetting(Settings.FUZZY_MODE)); + this.setReadWriteMode((AccessRestriction) this.getUpgradeable().getConfigManager().getSetting(Settings.ACCESS)); + this.setStorageFilter((StorageFilter) this.getUpgradeable().getConfigManager().getSetting(Settings.STORAGE_FILTER)); + } - this.standardDetectAndSendChanges(); - } + this.standardDetectAndSendChanges(); + } - @Override - public boolean isSlotEnabled( final int idx ) - { - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); + @Override + public boolean isSlotEnabled(final int idx) { + final int upgrades = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); - return upgrades > idx; - } + return upgrades > idx; + } - public void clear() - { - IAEFluidTank h = this.storageBus.getConfig(); - for( int i = 0; i < h.getSlots(); ++i ) - { - h.setFluidInSlot( i, null ); - } - this.detectAndSendChanges(); - } + public void clear() { + IAEFluidTank h = this.storageBus.getConfig(); + for (int i = 0; i < h.getSlots(); ++i) { + h.setFluidInSlot(i, null); + } + this.detectAndSendChanges(); + } - public void partition() - { - IAEFluidTank h = this.storageBus.getConfig(); + public void partition() { + IAEFluidTank h = this.storageBus.getConfig(); - final IMEInventory cellInv = this.storageBus.getInternalHandler(); + final IMEInventory cellInv = this.storageBus.getInternalHandler(); - Iterator i = new NullIterator<>(); - if( cellInv != null ) - { - final IItemList list = cellInv - .getAvailableItems( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList() ); - i = list.iterator(); - } + Iterator i = new NullIterator<>(); + if (cellInv != null) { + final IItemList list = cellInv + .getAvailableItems(AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class).createList()); + i = list.iterator(); + } - for( int x = 0; x < h.getSlots(); x++ ) - { - if( i.hasNext() && this.isSlotEnabled( ( x / 9 ) - 2 ) ) - { - h.setFluidInSlot( x, i.next() ); - } - else - { - h.setFluidInSlot( x, null ); - } - } - this.detectAndSendChanges(); - } + for (int x = 0; x < h.getSlots(); x++) { + if (i.hasNext() && this.isSlotEnabled((x / 9) - 2)) { + h.setFluidInSlot(x, i.next()); + } else { + h.setFluidInSlot(x, null); + } + } + this.detectAndSendChanges(); + } - public AccessRestriction getReadWriteMode() - { - return this.rwMode; - } + public AccessRestriction getReadWriteMode() { + return this.rwMode; + } - private void setReadWriteMode( final AccessRestriction rwMode ) - { - this.rwMode = rwMode; - } + private void setReadWriteMode(final AccessRestriction rwMode) { + this.rwMode = rwMode; + } - public StorageFilter getStorageFilter() - { - return this.storageFilter; - } + public StorageFilter getStorageFilter() { + return this.storageFilter; + } - private void setStorageFilter( final StorageFilter storageFilter ) - { - this.storageFilter = storageFilter; - } + private void setStorageFilter(final StorageFilter storageFilter) { + this.storageFilter = storageFilter; + } - @Override - public IAEFluidTank getFluidConfigInventory() - { - return this.storageBus.getConfig(); - } + @Override + public IAEFluidTank getFluidConfigInventory() { + return this.storageBus.getConfig(); + } } diff --git a/src/main/java/appeng/fluids/container/ContainerFluidTerminal.java b/src/main/java/appeng/fluids/container/ContainerFluidTerminal.java index a803fecba..80d61e922 100644 --- a/src/main/java/appeng/fluids/container/ContainerFluidTerminal.java +++ b/src/main/java/appeng/fluids/container/ContainerFluidTerminal.java @@ -19,30 +19,8 @@ package appeng.fluids.container; -import java.io.IOException; -import java.nio.BufferOverflowException; - -import javax.annotation.Nonnull; - -import appeng.container.slot.AppEngSlot; -import appeng.container.slot.SlotPlayerHotBar; -import appeng.container.slot.SlotPlayerInv; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IContainerListener; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fluids.capability.IFluidHandlerItem; - import appeng.api.AEApi; -import appeng.api.config.Actionable; -import appeng.api.config.PowerMultiplier; -import appeng.api.config.Settings; -import appeng.api.config.SortDir; -import appeng.api.config.SortOrder; -import appeng.api.config.ViewItems; +import appeng.api.config.*; import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -62,6 +40,9 @@ import appeng.api.util.IConfigManager; import appeng.api.util.IConfigurableObject; import appeng.container.AEBaseContainer; import appeng.container.guisync.GuiSync; +import appeng.container.slot.AppEngSlot; +import appeng.container.slot.SlotPlayerHotBar; +import appeng.container.slot.SlotPlayerInv; import appeng.core.AELog; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketMEFluidInventoryUpdate; @@ -73,7 +54,18 @@ import appeng.me.helpers.ChannelPowerSrc; import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; import appeng.util.Platform; -import net.minecraftforge.items.IItemHandler; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IContainerListener; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; +import net.minecraftforge.fluids.capability.IFluidHandlerItem; + +import javax.annotation.Nonnull; +import java.io.IOException; +import java.nio.BufferOverflowException; /** @@ -81,540 +73,424 @@ import net.minecraftforge.items.IItemHandler; * @version rv6 - 12/05/2018 * @since rv6 12/05/2018 */ -public class ContainerFluidTerminal extends AEBaseContainer implements IConfigManagerHost, IConfigurableObject, IMEMonitorHandlerReceiver -{ - private final IConfigManager clientCM; - private final IMEMonitor monitor; - private final IItemList fluids = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList(); - @GuiSync( 99 ) - public boolean hasPower = false; - private ITerminalHost terminal; - private IConfigManager serverCM; - private IConfigManagerHost gui; - private IGridNode networkNode; - // Holds the fluid the client wishes to extract, or null for insert - private IAEFluidStack clientRequestedTargetFluid = null; +public class ContainerFluidTerminal extends AEBaseContainer implements IConfigManagerHost, IConfigurableObject, IMEMonitorHandlerReceiver { + private final IConfigManager clientCM; + private final IMEMonitor monitor; + private final IItemList fluids = AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class).createList(); + @GuiSync(99) + public boolean hasPower = false; + private final ITerminalHost terminal; + private IConfigManager serverCM; + private IConfigManagerHost gui; + private IGridNode networkNode; + // Holds the fluid the client wishes to extract, or null for insert + private IAEFluidStack clientRequestedTargetFluid = null; - public ContainerFluidTerminal( InventoryPlayer ip, ITerminalHost terminal ) - { - super( ip, terminal ); - this.terminal = terminal; - this.clientCM = new ConfigManager( this ); + public ContainerFluidTerminal(InventoryPlayer ip, ITerminalHost terminal) { + super(ip, terminal); + this.terminal = terminal; + this.clientCM = new ConfigManager(this); - this.clientCM.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - this.clientCM.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - this.clientCM.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - if( Platform.isServer() ) - { - this.serverCM = terminal.getConfigManager(); - this.monitor = terminal.getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ); + this.clientCM.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.clientCM.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + this.clientCM.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + if (Platform.isServer()) { + this.serverCM = terminal.getConfigManager(); + this.monitor = terminal.getInventory(AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)); - if( this.monitor != null ) - { - this.monitor.addListener( this, null ); + if (this.monitor != null) { + this.monitor.addListener(this, null); - if( terminal instanceof IEnergySource ) - { - this.setPowerSource( (IEnergySource) terminal ); - } - else if( terminal instanceof IGridHost || terminal instanceof IActionHost ) - { - final IGridNode node; - if( terminal instanceof IGridHost ) - { - node = ( (IGridHost) terminal ).getGridNode( AEPartLocation.INTERNAL ); - } - else if( terminal instanceof IActionHost ) - { - node = ( (IActionHost) terminal ).getActionableNode(); - } - else - { - node = null; - } + if (terminal instanceof IEnergySource) { + this.setPowerSource((IEnergySource) terminal); + } else if (terminal instanceof IGridHost || terminal instanceof IActionHost) { + final IGridNode node; + if (terminal instanceof IGridHost) { + node = ((IGridHost) terminal).getGridNode(AEPartLocation.INTERNAL); + } else if (terminal instanceof IActionHost) { + node = ((IActionHost) terminal).getActionableNode(); + } else { + node = null; + } - if( node != null ) - { - this.networkNode = node; - final IGrid g = node.getGrid(); - if( g != null ) - { - this.setPowerSource( new ChannelPowerSrc( this.networkNode, (IEnergySource) g.getCache( IEnergyGrid.class ) ) ); - } - } - } - } - } - else - { - this.monitor = null; - } - this.bindPlayerInventory( ip, 0, 222 - 82 ); - } + if (node != null) { + this.networkNode = node; + final IGrid g = node.getGrid(); + if (g != null) { + this.setPowerSource(new ChannelPowerSrc(this.networkNode, g.getCache(IEnergyGrid.class))); + } + } + } + } + } else { + this.monitor = null; + } + this.bindPlayerInventory(ip, 0, 222 - 82); + } - @Override - public boolean isValid( Object verificationToken ) - { - return true; - } + @Override + public boolean isValid(Object verificationToken) { + return true; + } - @Override - public void postChange( IBaseMonitor monitor, Iterable change, IActionSource actionSource ) - { - for( final IAEFluidStack is : change ) - { - this.fluids.add( is ); - } - } + @Override + public void postChange(IBaseMonitor monitor, Iterable change, IActionSource actionSource) { + for (final IAEFluidStack is : change) { + this.fluids.add(is); + } + } - @Override - public void onListUpdate() - { - for( final IContainerListener c : this.listeners ) - { - this.queueInventory( c ); - } - } + @Override + public void onListUpdate() { + for (final IContainerListener c : this.listeners) { + this.queueInventory(c); + } + } - @Override - public void addListener( IContainerListener listener ) - { - super.addListener( listener ); + @Override + public void addListener(IContainerListener listener) { + super.addListener(listener); - this.queueInventory( listener ); - } + this.queueInventory(listener); + } - @Override - public void onContainerClosed( final EntityPlayer player ) - { - super.onContainerClosed( player ); - if( this.monitor != null ) - { - this.monitor.removeListener( this ); - } - } + @Override + public void onContainerClosed(final EntityPlayer player) { + super.onContainerClosed(player); + if (this.monitor != null) { + this.monitor.removeListener(this); + } + } - private void queueInventory( final IContainerListener c ) - { - if( Platform.isServer() && c instanceof EntityPlayer && this.monitor != null ) - { - try - { - PacketMEFluidInventoryUpdate piu = new PacketMEFluidInventoryUpdate(); - final IItemList monitorCache = this.monitor.getStorageList(); + private void queueInventory(final IContainerListener c) { + if (Platform.isServer() && c instanceof EntityPlayer && this.monitor != null) { + try { + PacketMEFluidInventoryUpdate piu = new PacketMEFluidInventoryUpdate(); + final IItemList monitorCache = this.monitor.getStorageList(); - for( final IAEFluidStack send : monitorCache ) - { - try - { - piu.appendFluid( send ); - } - catch( final BufferOverflowException boe ) - { - NetworkHandler.instance().sendTo( piu, (EntityPlayerMP) c ); + for (final IAEFluidStack send : monitorCache) { + try { + piu.appendFluid(send); + } catch (final BufferOverflowException boe) { + NetworkHandler.instance().sendTo(piu, (EntityPlayerMP) c); - piu = new PacketMEFluidInventoryUpdate(); - piu.appendFluid( send ); - } - } + piu = new PacketMEFluidInventoryUpdate(); + piu.appendFluid(send); + } + } - NetworkHandler.instance().sendTo( piu, (EntityPlayerMP) c ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } + NetworkHandler.instance().sendTo(piu, (EntityPlayerMP) c); + } catch (final IOException e) { + AELog.debug(e); + } + } + } - @Override - public IConfigManager getConfigManager() - { - if( Platform.isServer() ) - { - return this.serverCM; - } - return this.clientCM; - } + @Override + public IConfigManager getConfigManager() { + if (Platform.isServer()) { + return this.serverCM; + } + return this.clientCM; + } - public void setTargetStack( final IAEFluidStack stack ) - { - if( Platform.isClient() ) - { - if( stack == null && this.clientRequestedTargetFluid == null ) - { - return; - } - if( stack != null && this.clientRequestedTargetFluid != null && stack.getFluidStack() - .isFluidEqual( this.clientRequestedTargetFluid.getFluidStack() ) ) - { - return; - } - NetworkHandler.instance().sendToServer( new PacketTargetFluidStack( (AEFluidStack) stack ) ); - } + public void setTargetStack(final IAEFluidStack stack) { + if (Platform.isClient()) { + if (stack == null && this.clientRequestedTargetFluid == null) { + return; + } + if (stack != null && this.clientRequestedTargetFluid != null && stack.getFluidStack() + .isFluidEqual(this.clientRequestedTargetFluid.getFluidStack())) { + return; + } + NetworkHandler.instance().sendToServer(new PacketTargetFluidStack((AEFluidStack) stack)); + } - this.clientRequestedTargetFluid = stack == null ? null : stack.copy(); - } + this.clientRequestedTargetFluid = stack == null ? null : stack.copy(); + } - @Override - public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) - { - if( this.getGui() != null ) - { - this.getGui().updateSetting( manager, settingName, newValue ); - } - } + @Override + public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) { + if (this.getGui() != null) { + this.getGui().updateSetting(manager, settingName, newValue); + } + } - @Override - public void detectAndSendChanges() - { - if( Platform.isServer() ) - { - if( this.monitor != this.terminal.getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) ) - { - this.setValidContainer( false ); - } + @Override + public void detectAndSendChanges() { + if (Platform.isServer()) { + if (this.monitor != this.terminal.getInventory(AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class))) { + this.setValidContainer(false); + } - for( final Settings set : this.serverCM.getSettings() ) - { - final Enum sideLocal = this.serverCM.getSetting( set ); - final Enum sideRemote = this.clientCM.getSetting( set ); + for (final Settings set : this.serverCM.getSettings()) { + final Enum sideLocal = this.serverCM.getSetting(set); + final Enum sideRemote = this.clientCM.getSetting(set); - if( sideLocal != sideRemote ) - { - this.clientCM.putSetting( set, sideLocal ); - for( final IContainerListener crafter : this.listeners ) - { - if( crafter instanceof EntityPlayerMP ) - { - try - { - NetworkHandler.instance().sendTo( new PacketValueConfig( set.name(), sideLocal.name() ), (EntityPlayerMP) crafter ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } - } + if (sideLocal != sideRemote) { + this.clientCM.putSetting(set, sideLocal); + for (final IContainerListener crafter : this.listeners) { + if (crafter instanceof EntityPlayerMP) { + try { + NetworkHandler.instance().sendTo(new PacketValueConfig(set.name(), sideLocal.name()), (EntityPlayerMP) crafter); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } + } - if( !this.fluids.isEmpty() ) - { - try - { - final IItemList monitorCache = this.monitor.getStorageList(); + if (!this.fluids.isEmpty()) { + try { + final IItemList monitorCache = this.monitor.getStorageList(); - final PacketMEFluidInventoryUpdate piu = new PacketMEFluidInventoryUpdate(); + final PacketMEFluidInventoryUpdate piu = new PacketMEFluidInventoryUpdate(); - for( final IAEFluidStack is : this.fluids ) - { - final IAEFluidStack send = monitorCache.findPrecise( is ); - if( send == null ) - { - is.setStackSize( 0 ); - piu.appendFluid( is ); - } - else - { - piu.appendFluid( send ); - } - } + for (final IAEFluidStack is : this.fluids) { + final IAEFluidStack send = monitorCache.findPrecise(is); + if (send == null) { + is.setStackSize(0); + piu.appendFluid(is); + } else { + piu.appendFluid(send); + } + } - if( !piu.isEmpty() ) - { - this.fluids.resetStatus(); + if (!piu.isEmpty()) { + this.fluids.resetStatus(); - for( final Object c : this.listeners ) - { - if( c instanceof EntityPlayer ) - { - NetworkHandler.instance().sendTo( piu, (EntityPlayerMP) c ); - } - } - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - this.updatePowerStatus(); + for (final Object c : this.listeners) { + if (c instanceof EntityPlayer) { + NetworkHandler.instance().sendTo(piu, (EntityPlayerMP) c); + } + } + } + } catch (final IOException e) { + AELog.debug(e); + } + } + this.updatePowerStatus(); - super.detectAndSendChanges(); - } - } + super.detectAndSendChanges(); + } + } - @Override - public ItemStack transferStackInSlot( final EntityPlayer p, final int idx ) - { - if( Platform.isClient() ) - { - return ItemStack.EMPTY; - } - EntityPlayerMP player = (EntityPlayerMP) p; - if( this.inventorySlots.get( idx ) instanceof SlotPlayerInv || this.inventorySlots.get( idx ) instanceof SlotPlayerHotBar ) - { - final AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get( idx ); // require AE SLots! - ItemStack itemStack = clickSlot.getStack(); + @Override + public ItemStack transferStackInSlot(final EntityPlayer p, final int idx) { + if (Platform.isClient()) { + return ItemStack.EMPTY; + } + EntityPlayerMP player = (EntityPlayerMP) p; + if (this.inventorySlots.get(idx) instanceof SlotPlayerInv || this.inventorySlots.get(idx) instanceof SlotPlayerHotBar) { + final AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get(idx); // require AE SLots! + ItemStack itemStack = clickSlot.getStack(); - ItemStack copy = itemStack.copy(); - copy.setCount( 1 ); - IFluidHandlerItem fh = FluidUtil.getFluidHandler( copy ); - if( fh == null ) - { - // only fluid handlers items - return ItemStack.EMPTY; - } + ItemStack copy = itemStack.copy(); + copy.setCount(1); + IFluidHandlerItem fh = FluidUtil.getFluidHandler(copy); + if (fh == null) { + // only fluid handlers items + return ItemStack.EMPTY; + } - int heldAmount = itemStack.getCount(); - for( int i = 0; i < heldAmount; i++ ) - { - copy = itemStack.copy(); - copy.setCount( 1 ); - fh = FluidUtil.getFluidHandler( copy ); + int heldAmount = itemStack.getCount(); + for (int i = 0; i < heldAmount; i++) { + copy = itemStack.copy(); + copy.setCount(1); + fh = FluidUtil.getFluidHandler(copy); - final FluidStack extract = fh.drain( Integer.MAX_VALUE, false ); - if( extract == null || extract.amount < 1 ) - { - return ItemStack.EMPTY; - } + final FluidStack extract = fh.drain(Integer.MAX_VALUE, false); + if (extract == null || extract.amount < 1) { + return ItemStack.EMPTY; + } - // Check if we can push into the system - final IAEFluidStack notStorable = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ), this.getActionSource(), Actionable.SIMULATE ); + // Check if we can push into the system + final IAEFluidStack notStorable = Platform.poweredInsert(this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack(extract), this.getActionSource(), Actionable.SIMULATE); - if( notStorable != null && notStorable.getStackSize() > 0 ) - { - final int toStore = (int) ( extract.amount - notStorable.getStackSize() ); - final FluidStack storable = fh.drain( toStore, false ); + if (notStorable != null && notStorable.getStackSize() > 0) { + final int toStore = (int) (extract.amount - notStorable.getStackSize()); + final FluidStack storable = fh.drain(toStore, false); - if( storable == null || storable.amount == 0 ) - { - return ItemStack.EMPTY; - } - else - { - extract.amount = storable.amount; - } - } + if (storable == null || storable.amount == 0) { + return ItemStack.EMPTY; + } else { + extract.amount = storable.amount; + } + } - // Actually drain - final FluidStack drained = fh.drain( extract, true ); - extract.amount = drained.amount; + // Actually drain + final FluidStack drained = fh.drain(extract, true); + extract.amount = drained.amount; - final IAEFluidStack notInserted = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ), this.getActionSource() ); + final IAEFluidStack notInserted = Platform.poweredInsert(this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack(extract), this.getActionSource()); - if( notInserted != null && notInserted.getStackSize() > 0 ) - { - IAEFluidStack spill = this.monitor.injectItems( notInserted, Actionable.MODULATE, this.getActionSource() ); - if( spill != null && spill.getStackSize() > 0 ) - { - fh.fill( spill.getFluidStack(), true ); - } - } + if (notInserted != null && notInserted.getStackSize() > 0) { + IAEFluidStack spill = this.monitor.injectItems(notInserted, Actionable.MODULATE, this.getActionSource()); + if (spill != null && spill.getStackSize() > 0) { + fh.fill(spill.getFluidStack(), true); + } + } - if( notInserted == null || notInserted.getStackSize() == 0 ) - { - if( !player.inventory.addItemStackToInventory( fh.getContainer() ) ) - { - player.dropItem( fh.getContainer(), false ); - } - clickSlot.decrStackSize( 1 ); - } - } - this.detectAndSendChanges(); - return ItemStack.EMPTY; - } - return super.transferStackInSlot( p, idx ); - } + if (notInserted == null || notInserted.getStackSize() == 0) { + if (!player.inventory.addItemStackToInventory(fh.getContainer())) { + player.dropItem(fh.getContainer(), false); + } + clickSlot.decrStackSize(1); + } + } + this.detectAndSendChanges(); + return ItemStack.EMPTY; + } + return super.transferStackInSlot(p, idx); + } - @Override - public void doAction( EntityPlayerMP player, InventoryAction action, int slot, long id ) - { - if( action != InventoryAction.FILL_ITEM && action != InventoryAction.EMPTY_ITEM ) - { - super.doAction( player, action, slot, id ); - return; - } + @Override + public void doAction(EntityPlayerMP player, InventoryAction action, int slot, long id) { + if (action != InventoryAction.FILL_ITEM && action != InventoryAction.EMPTY_ITEM) { + super.doAction(player, action, slot, id); + return; + } - final ItemStack held = player.inventory.getItemStack(); - ItemStack heldCopy = held.copy(); - heldCopy.setCount( 1 ); - IFluidHandlerItem fh = FluidUtil.getFluidHandler( heldCopy ); - if( fh == null ) - { - // only fluid handlers items - return; - } + final ItemStack held = player.inventory.getItemStack(); + ItemStack heldCopy = held.copy(); + heldCopy.setCount(1); + IFluidHandlerItem fh = FluidUtil.getFluidHandler(heldCopy); + if (fh == null) { + // only fluid handlers items + return; + } - if( action == InventoryAction.FILL_ITEM && this.clientRequestedTargetFluid != null ) - { - final IAEFluidStack stack = this.clientRequestedTargetFluid.copy(); + if (action == InventoryAction.FILL_ITEM && this.clientRequestedTargetFluid != null) { + final IAEFluidStack stack = this.clientRequestedTargetFluid.copy(); - // Check how much we can store in the item - stack.setStackSize( Integer.MAX_VALUE ); - int amountAllowed = fh.fill( stack.getFluidStack(), false ); - int heldAmount = held.getCount(); - for( int i = 0; i < heldAmount; i++ ) - { - ItemStack copiedFluidContainer = held.copy(); - copiedFluidContainer.setCount( 1 ); - fh = FluidUtil.getFluidHandler( copiedFluidContainer ); + // Check how much we can store in the item + stack.setStackSize(Integer.MAX_VALUE); + int amountAllowed = fh.fill(stack.getFluidStack(), false); + int heldAmount = held.getCount(); + for (int i = 0; i < heldAmount; i++) { + ItemStack copiedFluidContainer = held.copy(); + copiedFluidContainer.setCount(1); + fh = FluidUtil.getFluidHandler(copiedFluidContainer); - // Check if we can pull out of the system - final IAEFluidStack canPull = Platform.poweredExtraction( this.getPowerSource(), this.monitor, stack.setStackSize( amountAllowed ), this.getActionSource(), Actionable.SIMULATE ); - if( canPull == null || canPull.getStackSize() < 1 ) - { - return; - } + // Check if we can pull out of the system + final IAEFluidStack canPull = Platform.poweredExtraction(this.getPowerSource(), this.monitor, stack.setStackSize(amountAllowed), this.getActionSource(), Actionable.SIMULATE); + if (canPull == null || canPull.getStackSize() < 1) { + return; + } - // How much could fit into the container - final int canFill = fh.fill( canPull.getFluidStack(), false ); - if( canFill == 0 ) - { - return; - } + // How much could fit into the container + final int canFill = fh.fill(canPull.getFluidStack(), false); + if (canFill == 0) { + return; + } - // Now actually pull out of the system - final IAEFluidStack pulled = Platform.poweredExtraction( this.getPowerSource(), this.monitor, stack.setStackSize( canFill ), this.getActionSource() ); - if( pulled == null || pulled.getStackSize() < 1 ) - { - // Something went wrong - AELog.error( "Unable to pull fluid out of the ME system even though the simulation said yes " ); - return; - } + // Now actually pull out of the system + final IAEFluidStack pulled = Platform.poweredExtraction(this.getPowerSource(), this.monitor, stack.setStackSize(canFill), this.getActionSource()); + if (pulled == null || pulled.getStackSize() < 1) { + // Something went wrong + AELog.error("Unable to pull fluid out of the ME system even though the simulation said yes "); + return; + } - // Actually fill - final int used = fh.fill( pulled.getFluidStack(), true ); + // Actually fill + final int used = fh.fill(pulled.getFluidStack(), true); - if( used != canFill ) - { - AELog.error( "Fluid item [%s] reported a different possible amount than it actually accepted.", held.getDisplayName() ); - } + if (used != canFill) { + AELog.error("Fluid item [%s] reported a different possible amount than it actually accepted.", held.getDisplayName()); + } - if( held.getCount() == 1 ) - { - player.inventory.setItemStack( fh.getContainer() ); - } - else - { - player.inventory.getItemStack().shrink( 1 ); - if( !player.inventory.addItemStackToInventory( fh.getContainer() ) ) - { - player.dropItem( fh.getContainer(), false ); - } - } - } - this.updateHeld( player ); + if (held.getCount() == 1) { + player.inventory.setItemStack(fh.getContainer()); + } else { + player.inventory.getItemStack().shrink(1); + if (!player.inventory.addItemStackToInventory(fh.getContainer())) { + player.dropItem(fh.getContainer(), false); + } + } + } + this.updateHeld(player); - } - else if( action == InventoryAction.EMPTY_ITEM ) - { - int heldAmount = held.getCount(); - for( int i = 0; i < heldAmount; i++ ) - { - ItemStack copiedFluidContainer = held.copy(); - copiedFluidContainer.setCount( 1 ); - fh = FluidUtil.getFluidHandler( copiedFluidContainer ); + } else if (action == InventoryAction.EMPTY_ITEM) { + int heldAmount = held.getCount(); + for (int i = 0; i < heldAmount; i++) { + ItemStack copiedFluidContainer = held.copy(); + copiedFluidContainer.setCount(1); + fh = FluidUtil.getFluidHandler(copiedFluidContainer); - // See how much we can drain from the item - final FluidStack extract = fh.drain( Integer.MAX_VALUE, false ); - if( extract == null || extract.amount < 1 ) - { - return; - } + // See how much we can drain from the item + final FluidStack extract = fh.drain(Integer.MAX_VALUE, false); + if (extract == null || extract.amount < 1) { + return; + } - // Check if we can push into the system - final IAEFluidStack notStorable = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ), this.getActionSource(), Actionable.SIMULATE ); + // Check if we can push into the system + final IAEFluidStack notStorable = Platform.poweredInsert(this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack(extract), this.getActionSource(), Actionable.SIMULATE); - if( notStorable != null && notStorable.getStackSize() > 0 ) - { - final int toStore = (int) ( extract.amount - notStorable.getStackSize() ); - final FluidStack storable = fh.drain( toStore, false ); + if (notStorable != null && notStorable.getStackSize() > 0) { + final int toStore = (int) (extract.amount - notStorable.getStackSize()); + final FluidStack storable = fh.drain(toStore, false); - if( storable == null || storable.amount == 0 ) - { - return; - } - else - { - extract.amount = storable.amount; - } - } + if (storable == null || storable.amount == 0) { + return; + } else { + extract.amount = storable.amount; + } + } - // Actually drain - final FluidStack drained = fh.drain( extract, true ); - extract.amount = drained.amount; + // Actually drain + final FluidStack drained = fh.drain(extract, true); + extract.amount = drained.amount; - final IAEFluidStack notInserted = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ), this.getActionSource() ); + final IAEFluidStack notInserted = Platform.poweredInsert(this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack(extract), this.getActionSource()); - if( notInserted != null && notInserted.getStackSize() > 0 ) - { - IAEFluidStack spill = this.monitor.injectItems( notInserted, Actionable.MODULATE, this.getActionSource() ); - if( spill != null && spill.getStackSize() > 0 ) - { - fh.fill( spill.getFluidStack(), true ); - } - } + if (notInserted != null && notInserted.getStackSize() > 0) { + IAEFluidStack spill = this.monitor.injectItems(notInserted, Actionable.MODULATE, this.getActionSource()); + if (spill != null && spill.getStackSize() > 0) { + fh.fill(spill.getFluidStack(), true); + } + } - if( held.getCount() == 1 ) - { - player.inventory.setItemStack( fh.getContainer() ); - } - else - { - player.inventory.getItemStack().shrink( 1 ); - if( !player.inventory.addItemStackToInventory( fh.getContainer() ) ) - { - player.dropItem( fh.getContainer(), false ); - } - } - } - this.updateHeld( player ); - } - } + if (held.getCount() == 1) { + player.inventory.setItemStack(fh.getContainer()); + } else { + player.inventory.getItemStack().shrink(1); + if (!player.inventory.addItemStackToInventory(fh.getContainer())) { + player.dropItem(fh.getContainer(), false); + } + } + } + this.updateHeld(player); + } + } - protected void updatePowerStatus() - { - try - { - if( this.networkNode != null ) - { - this.setPowered( this.networkNode.isActive() ); - } - else if( this.getPowerSource() instanceof IEnergyGrid ) - { - this.setPowered( ( (IEnergyGrid) this.getPowerSource() ).isNetworkPowered() ); - } - else - { - this.setPowered( this.getPowerSource().extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.8 ); - } - } - catch( final Exception ignore ) - { - // :P - } - } + protected void updatePowerStatus() { + try { + if (this.networkNode != null) { + this.setPowered(this.networkNode.isActive()); + } else if (this.getPowerSource() instanceof IEnergyGrid) { + this.setPowered(((IEnergyGrid) this.getPowerSource()).isNetworkPowered()); + } else { + this.setPowered(this.getPowerSource().extractAEPower(1, Actionable.SIMULATE, PowerMultiplier.CONFIG) > 0.8); + } + } catch (final Exception ignore) { + // :P + } + } - private IConfigManagerHost getGui() - { - return this.gui; - } + private IConfigManagerHost getGui() { + return this.gui; + } - public void setGui( @Nonnull final IConfigManagerHost gui ) - { - this.gui = gui; - } + public void setGui(@Nonnull final IConfigManagerHost gui) { + this.gui = gui; + } - public boolean isPowered() - { - return this.hasPower; - } + public boolean isPowered() { + return this.hasPower; + } - private void setPowered( final boolean isPowered ) - { - this.hasPower = isPowered; - } + private void setPowered(final boolean isPowered) { + this.hasPower = isPowered; + } } diff --git a/src/main/java/appeng/fluids/container/IFluidSyncContainer.java b/src/main/java/appeng/fluids/container/IFluidSyncContainer.java index ef3307bf4..a2e6f1f2b 100644 --- a/src/main/java/appeng/fluids/container/IFluidSyncContainer.java +++ b/src/main/java/appeng/fluids/container/IFluidSyncContainer.java @@ -1,13 +1,11 @@ - package appeng.fluids.container; -import java.util.Map; - import appeng.api.storage.data.IAEFluidStack; +import java.util.Map; -public interface IFluidSyncContainer -{ - void receiveFluidSlots( final Map fluids ); + +public interface IFluidSyncContainer { + void receiveFluidSlots(final Map fluids); } diff --git a/src/main/java/appeng/fluids/container/slots/IMEFluidSlot.java b/src/main/java/appeng/fluids/container/slots/IMEFluidSlot.java index b8addaf30..e21f2145a 100644 --- a/src/main/java/appeng/fluids/container/slots/IMEFluidSlot.java +++ b/src/main/java/appeng/fluids/container/slots/IMEFluidSlot.java @@ -27,12 +27,10 @@ import appeng.api.storage.data.IAEFluidStack; * @version rv6 * @since rv6 */ -public interface IMEFluidSlot -{ - IAEFluidStack getAEFluidStack(); +public interface IMEFluidSlot { + IAEFluidStack getAEFluidStack(); - default boolean shouldRenderAsFluid() - { - return true; - } + default boolean shouldRenderAsFluid() { + return true; + } } diff --git a/src/main/java/appeng/fluids/helper/DualityFluidInterface.java b/src/main/java/appeng/fluids/helper/DualityFluidInterface.java index 37f9bf812..8ca574498 100644 --- a/src/main/java/appeng/fluids/helper/DualityFluidInterface.java +++ b/src/main/java/appeng/fluids/helper/DualityFluidInterface.java @@ -19,18 +19,6 @@ package appeng.fluids.helper; -import java.util.Optional; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.Upgrades; @@ -43,11 +31,7 @@ import appeng.api.networking.security.IActionSource; import appeng.api.networking.ticking.IGridTickable; import appeng.api.networking.ticking.TickRateModulation; import appeng.api.networking.ticking.TickingRequest; -import appeng.api.storage.IMEInventory; -import appeng.api.storage.IMEMonitor; -import appeng.api.storage.IStorageChannel; -import appeng.api.storage.IStorageMonitorable; -import appeng.api.storage.IStorageMonitorableAccessor; +import appeng.api.storage.*; import appeng.api.storage.channels.IFluidStorageChannel; import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEFluidStack; @@ -71,561 +55,459 @@ import appeng.me.storage.NullInventory; import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; import appeng.util.Platform; - - -public class DualityFluidInterface implements IGridTickable, IStorageMonitorable, IAEFluidInventory, IUpgradeableHost, IConfigManagerHost, IConfigurableFluidInventory -{ - public static final int NUMBER_OF_TANKS = 6; - public static final int TANK_CAPACITY = Fluid.BUCKET_VOLUME * 4; - - private final ConfigManager cm = new ConfigManager( this ); - private final AENetworkProxy gridProxy; - private final IFluidInterfaceHost iHost; - private final IActionSource mySource; - private final IActionSource interfaceRequestSource; - private boolean hasConfig = false; - private final IStorageMonitorableAccessor accessor = this::getMonitorable; - private final AEFluidInventory tanks = new AEFluidInventory( this, NUMBER_OF_TANKS, TANK_CAPACITY ); - private final AEFluidInventory config = new AEFluidInventory( this, NUMBER_OF_TANKS ); - private final IAEFluidStack[] requireWork; - private int isWorking = -1; - private int priority; - - private final MEMonitorPassThrough items = new MEMonitorPassThrough<>( new NullInventory(), AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - private final MEMonitorPassThrough fluids = new MEMonitorPassThrough<>( new NullInventory(), AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ); - private boolean resetConfigCache = true; - private IMEMonitor configCachedHandler; - - public DualityFluidInterface( final AENetworkProxy networkProxy, final IFluidInterfaceHost ih ) - { - this.gridProxy = networkProxy; - this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL ); - this.iHost = ih; - - this.mySource = new MachineSource( this.iHost ); - this.interfaceRequestSource = new InterfaceRequestSource( this.iHost ); - - this.fluids.setChangeSource( this.mySource ); - this.items.setChangeSource( this.mySource ); - - this.requireWork = new IAEFluidStack[NUMBER_OF_TANKS]; - for( int i = 0; i < NUMBER_OF_TANKS; ++i ) - { - this.requireWork[i] = null; - } - } - - public IUpgradeableHost getHost() - { - return this.iHost; - } - - @Override - public > IMEMonitor getInventory( IStorageChannel channel ) - { - if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - if( this.hasConfig() ) - { - return null; - } - - return (IMEMonitor) this.items; - } - else if( channel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) - { - if( this.hasConfig() ) - { - if( resetConfigCache ) - { - resetConfigCache = false; - configCachedHandler = new InterfaceInventory( this ); - } - return (IMEMonitor) configCachedHandler; - } - - return (IMEMonitor) this.fluids; - } - - return null; - } - - public IStorageMonitorable getMonitorable( final IActionSource src ) - { - if( Platform.canAccess( this.gridProxy, src ) ) - { - return this; - } - - return null; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.Interface.getMin(), TickRates.Interface.getMax(), !this.hasWorkToDo(), true ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( !this.gridProxy.isActive() ) - { - return TickRateModulation.SLEEP; - } - - final boolean couldDoWork = this.updateStorage(); - return this.hasWorkToDo() ? ( couldDoWork ? TickRateModulation.URGENT : TickRateModulation.SLOWER ) : TickRateModulation.SLEEP; - } - - public void notifyNeighbors() - { - if( this.gridProxy.isActive() ) - { - try - { - this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - final TileEntity te = this.iHost.getTileEntity(); - if( te != null && te.getWorld() != null ) - { - Platform.notifyBlocksOfNeighbors( te.getWorld(), te.getPos() ); - } - } - - public void gridChanged() - { - try - { - this.items.setInternal( this.gridProxy.getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) ); - this.fluids.setInternal( this.gridProxy.getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) ); - } - catch( final GridAccessException gae ) - { - this.items.setInternal( new NullInventory() ); - this.fluids.setInternal( new NullInventory() ); - } - - this.notifyNeighbors(); - } - - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.SMART; - } - - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this.iHost.getTileEntity() ); - } - - public boolean hasCapability( Capability capabilityClass, EnumFacing facing ) - { - return capabilityClass == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || capabilityClass == Capabilities.STORAGE_MONITORABLE_ACCESSOR; - } - - @SuppressWarnings( "unchecked" ) - public T getCapability( Capability capabilityClass, EnumFacing facing ) - { - if( capabilityClass == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY ) - { - return (T) this.tanks; - } - else if( capabilityClass == Capabilities.STORAGE_MONITORABLE_ACCESSOR ) - { - return (T) this.accessor; - } - return null; - } - - private boolean hasConfig() - { - return this.hasConfig; - } - - private void readConfig() - { - this.hasConfig = false; - - for( int i = 0; i < this.config.getSlots(); i++ ) - { - if( this.config.getFluidInSlot( i ) != null ) - { - this.hasConfig = true; - break; - } - } - - final boolean had = this.hasWorkToDo(); - - for( int x = 0; x < NUMBER_OF_TANKS; x++ ) - { - this.updatePlan( x ); - } - - final boolean has = this.hasWorkToDo(); - - if( had != has ) - { - try - { - if( has ) - { - this.gridProxy.getTick().alertDevice( this.gridProxy.getNode() ); - } - else - { - this.gridProxy.getTick().sleepDevice( this.gridProxy.getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - - this.notifyNeighbors(); - } - - private boolean updateStorage() - { - boolean didSomething = false; - for( int x = 0; x < NUMBER_OF_TANKS; x++ ) - { - if( this.requireWork[x] != null ) - { - didSomething = this.usePlan( x ) || didSomething; - } - } - return didSomething; - } - - private boolean hasWorkToDo() - { - for( final IAEFluidStack requiredWork : this.requireWork ) - { - if( requiredWork != null ) - { - return true; - } - } - - return false; - } - - private void updatePlan( final int slot ) - { - final IAEFluidStack req = this.config.getFluidInSlot( slot ); - final IAEFluidStack stored = this.tanks.getFluidInSlot( slot ); - - if( req == null && ( stored != null && stored.getStackSize() > 0 ) ) - { - final IAEFluidStack work = stored.copy(); - this.requireWork[slot] = work.setStackSize( -work.getStackSize() ); - return; - } - else if( req != null ) - { - if( stored == null || stored.getStackSize() == 0 ) // need to add stuff! - { - this.requireWork[slot] = req.copy(); - this.requireWork[slot].setStackSize( TANK_CAPACITY ); - return; - } - else if( req.equals( stored ) ) // same type ( qty different? )! - { - if( stored.getStackSize() < TANK_CAPACITY ) - { - this.requireWork[slot] = req.copy(); - this.requireWork[slot].setStackSize( TANK_CAPACITY - stored.getStackSize() ); - return; - } - } - else - // Stored != null; dispose! - { - final IAEFluidStack work = stored.copy(); - this.requireWork[slot] = work.setStackSize( -work.getStackSize() ); - return; - } - } - - this.requireWork[slot] = null; - } - - private boolean usePlan( final int slot ) - { - IAEFluidStack work = this.requireWork[slot]; - this.isWorking = slot; - - boolean changed = false; - try - { - final IMEInventory dest = this.gridProxy.getStorage() - .getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ); - final IEnergySource src = this.gridProxy.getEnergy(); - - if( work.getStackSize() > 0 ) - { - // make sure strange things didn't happen... - if( this.tanks.fill( slot, work.getFluidStack(), false ) != work.getStackSize() ) - { - changed = true; - } - else if( this.gridProxy.getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ).getStorageList().findPrecise( work ) != null ) - { - final IAEFluidStack acquired = Platform.poweredExtraction( src, dest, work, this.interfaceRequestSource ); - if( acquired != null ) - { - changed = true; - final int filled = this.tanks.fill( slot, acquired.getFluidStack(), true ); - if( filled != acquired.getStackSize() ) - { - throw new IllegalStateException( "bad attempt at managing tanks. ( fill )" ); - } - } - } - } - else if( work.getStackSize() < 0 ) - { - IAEFluidStack toStore = work.copy(); - toStore.setStackSize( -toStore.getStackSize() ); - - // make sure strange things didn't happen... - final FluidStack canExtract = this.tanks.drain( slot, toStore.getFluidStack(), false ); - if( canExtract == null || canExtract.amount != toStore.getStackSize() ) - { - changed = true; - } - else - { - IAEFluidStack notStored = Platform.poweredInsert( src, dest, toStore, this.interfaceRequestSource ); - toStore.setStackSize( toStore.getStackSize() - ( notStored == null ? 0 : notStored.getStackSize() ) ); - - if( toStore.getStackSize() > 0 ) - { - // extract items! - changed = true; - final FluidStack removed = this.tanks.drain( slot, toStore.getFluidStack(), true ); - if( removed == null || toStore.getStackSize() != removed.amount ) - { - throw new IllegalStateException( "bad attempt at managing tanks. ( drain )" ); - } - } - } - } - } - catch( final GridAccessException e ) - { - // :P - } - - if( changed ) - { - this.updatePlan( slot ); - } - - this.isWorking = -1; - return changed; - } - - @Override - public void onFluidInventoryChanged( final IAEFluidTank inventory, final int slot ) - { - if( this.isWorking == slot ) - { - return; - } - - if( inventory == this.config ) - { - boolean cfg = hasConfig(); - this.readConfig(); - if( cfg != hasConfig ) - { - resetConfigCache = true; - this.notifyNeighbors(); - } - } - else if( inventory == this.tanks ) - { - this.saveChanges(); - - final boolean had = this.hasWorkToDo(); - - this.updatePlan( slot ); - - final boolean now = this.hasWorkToDo(); - - if( had != now ) - { - try - { - if( now ) - { - this.gridProxy.getTick().alertDevice( this.gridProxy.getNode() ); - } - else - { - this.gridProxy.getTick().sleepDevice( this.gridProxy.getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - } - } - - public int getPriority() - { - return this.priority; - } - - public void setPriority( final int newValue ) - { - this.priority = newValue; - } - - public void writeToNBT( final NBTTagCompound data ) - { - data.setInteger( "priority", this.priority ); - this.tanks.writeToNBT( data, "storage" ); - this.config.writeToNBT( data, "config" ); - } - - public void readFromNBT( final NBTTagCompound data ) - { - this.config.readFromNBT( data, "config" ); - this.tanks.readFromNBT( data, "storage" ); - this.priority = data.getInteger( "priority" ); - this.readConfig(); - } - - public IAEFluidTank getConfig() - { - return this.config; - } - - public IAEFluidTank getTanks() - { - return this.tanks; - } - - private class InterfaceRequestSource extends MachineSource - { - private final InterfaceRequestContext context; - - InterfaceRequestSource( IActionHost v ) - { - super( v ); - this.context = new InterfaceRequestContext(); - } - - @Override - public Optional context( Class key ) - { - if( key == InterfaceRequestContext.class ) - { - return (Optional) Optional.of( this.context ); - } - - return super.context( key ); - } - } - - private class InterfaceRequestContext implements Comparable - { - @Override - public int compareTo( Integer o ) - { - return Integer.compare( DualityFluidInterface.this.priority, o ); - } - } - - private class InterfaceInventory extends MEMonitorIFluidHandler - { - - InterfaceInventory( final DualityFluidInterface tileInterface ) - { - super( tileInterface.tanks ); - } - - @Override - public IAEFluidStack injectItems( final IAEFluidStack input, final Actionable type, final IActionSource src ) - { - final Optional context = src.context( InterfaceRequestContext.class ); - final boolean isInterface = context.isPresent(); - - if( isInterface ) - { - return input; - } - - return super.injectItems( input, type, src ); - } - - @Override - public IAEFluidStack extractItems( final IAEFluidStack request, final Actionable type, final IActionSource src ) - { - final Optional context = src.context( InterfaceRequestContext.class ); - final boolean hasLowerOrEqualPriority = context.map( c -> c.compareTo( DualityFluidInterface.this.priority ) <= 0 ).orElse( false ); - - if( hasLowerOrEqualPriority ) - { - return null; - } - - return super.extractItems( request, type, src ); - } - } - - public void saveChanges() - { - this.iHost.saveChanges(); - } - - @Override - public IConfigManager getConfigManager() - { - return this.cm; - } - - @Override - public IItemHandler getInventoryByName( String name ) - { - return null; - } - - @Override - public IFluidHandler getFluidInventoryByName( final String name) { - if (name.equals("config")) { - return this.config; - } - return null; - } - - @Override - public int getInstalledUpgrades( Upgrades u ) - { - return 0; - } - - @Override - public TileEntity getTile() - { - return (TileEntity) ( this.iHost instanceof TileEntity ? this.iHost : null ); - } - - @Override - public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) - { - } +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; +import net.minecraftforge.fluids.capability.IFluidHandler; +import net.minecraftforge.items.IItemHandler; + +import java.util.Optional; + + +public class DualityFluidInterface implements IGridTickable, IStorageMonitorable, IAEFluidInventory, IUpgradeableHost, IConfigManagerHost, IConfigurableFluidInventory { + public static final int NUMBER_OF_TANKS = 6; + public static final int TANK_CAPACITY = Fluid.BUCKET_VOLUME * 4; + + private final ConfigManager cm = new ConfigManager(this); + private final AENetworkProxy gridProxy; + private final IFluidInterfaceHost iHost; + private final IActionSource mySource; + private final IActionSource interfaceRequestSource; + private boolean hasConfig = false; + private final IStorageMonitorableAccessor accessor = this::getMonitorable; + private final AEFluidInventory tanks = new AEFluidInventory(this, NUMBER_OF_TANKS, TANK_CAPACITY); + private final AEFluidInventory config = new AEFluidInventory(this, NUMBER_OF_TANKS); + private final IAEFluidStack[] requireWork; + private int isWorking = -1; + private int priority; + + private final MEMonitorPassThrough items = new MEMonitorPassThrough<>(new NullInventory(), AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + private final MEMonitorPassThrough fluids = new MEMonitorPassThrough<>(new NullInventory(), AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)); + private boolean resetConfigCache = true; + private IMEMonitor configCachedHandler; + + public DualityFluidInterface(final AENetworkProxy networkProxy, final IFluidInterfaceHost ih) { + this.gridProxy = networkProxy; + this.gridProxy.setFlags(GridFlags.REQUIRE_CHANNEL); + this.iHost = ih; + + this.mySource = new MachineSource(this.iHost); + this.interfaceRequestSource = new InterfaceRequestSource(this.iHost); + + this.fluids.setChangeSource(this.mySource); + this.items.setChangeSource(this.mySource); + + this.requireWork = new IAEFluidStack[NUMBER_OF_TANKS]; + for (int i = 0; i < NUMBER_OF_TANKS; ++i) { + this.requireWork[i] = null; + } + } + + public IUpgradeableHost getHost() { + return this.iHost; + } + + @Override + public > IMEMonitor getInventory(IStorageChannel channel) { + if (channel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + if (this.hasConfig()) { + return null; + } + + return (IMEMonitor) this.items; + } else if (channel == AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)) { + if (this.hasConfig()) { + if (resetConfigCache) { + resetConfigCache = false; + configCachedHandler = new InterfaceInventory(this); + } + return (IMEMonitor) configCachedHandler; + } + + return (IMEMonitor) this.fluids; + } + + return null; + } + + public IStorageMonitorable getMonitorable(final IActionSource src) { + if (Platform.canAccess(this.gridProxy, src)) { + return this; + } + + return null; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.Interface.getMin(), TickRates.Interface.getMax(), !this.hasWorkToDo(), true); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (!this.gridProxy.isActive()) { + return TickRateModulation.SLEEP; + } + + final boolean couldDoWork = this.updateStorage(); + return this.hasWorkToDo() ? (couldDoWork ? TickRateModulation.URGENT : TickRateModulation.SLOWER) : TickRateModulation.SLEEP; + } + + public void notifyNeighbors() { + if (this.gridProxy.isActive()) { + try { + this.gridProxy.getTick().wakeDevice(this.gridProxy.getNode()); + } catch (final GridAccessException e) { + // :P + } + } + + final TileEntity te = this.iHost.getTileEntity(); + if (te != null && te.getWorld() != null) { + Platform.notifyBlocksOfNeighbors(te.getWorld(), te.getPos()); + } + } + + public void gridChanged() { + try { + this.items.setInternal(this.gridProxy.getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class))); + this.fluids.setInternal(this.gridProxy.getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class))); + } catch (final GridAccessException gae) { + this.items.setInternal(new NullInventory()); + this.fluids.setInternal(new NullInventory()); + } + + this.notifyNeighbors(); + } + + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.SMART; + } + + public DimensionalCoord getLocation() { + return new DimensionalCoord(this.iHost.getTileEntity()); + } + + public boolean hasCapability(Capability capabilityClass, EnumFacing facing) { + return capabilityClass == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || capabilityClass == Capabilities.STORAGE_MONITORABLE_ACCESSOR; + } + + @SuppressWarnings("unchecked") + public T getCapability(Capability capabilityClass, EnumFacing facing) { + if (capabilityClass == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { + return (T) this.tanks; + } else if (capabilityClass == Capabilities.STORAGE_MONITORABLE_ACCESSOR) { + return (T) this.accessor; + } + return null; + } + + private boolean hasConfig() { + return this.hasConfig; + } + + private void readConfig() { + this.hasConfig = false; + + for (int i = 0; i < this.config.getSlots(); i++) { + if (this.config.getFluidInSlot(i) != null) { + this.hasConfig = true; + break; + } + } + + final boolean had = this.hasWorkToDo(); + + for (int x = 0; x < NUMBER_OF_TANKS; x++) { + this.updatePlan(x); + } + + final boolean has = this.hasWorkToDo(); + + if (had != has) { + try { + if (has) { + this.gridProxy.getTick().alertDevice(this.gridProxy.getNode()); + } else { + this.gridProxy.getTick().sleepDevice(this.gridProxy.getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + + this.notifyNeighbors(); + } + + private boolean updateStorage() { + boolean didSomething = false; + for (int x = 0; x < NUMBER_OF_TANKS; x++) { + if (this.requireWork[x] != null) { + didSomething = this.usePlan(x) || didSomething; + } + } + return didSomething; + } + + private boolean hasWorkToDo() { + for (final IAEFluidStack requiredWork : this.requireWork) { + if (requiredWork != null) { + return true; + } + } + + return false; + } + + private void updatePlan(final int slot) { + final IAEFluidStack req = this.config.getFluidInSlot(slot); + final IAEFluidStack stored = this.tanks.getFluidInSlot(slot); + + if (req == null && (stored != null && stored.getStackSize() > 0)) { + final IAEFluidStack work = stored.copy(); + this.requireWork[slot] = work.setStackSize(-work.getStackSize()); + return; + } else if (req != null) { + if (stored == null || stored.getStackSize() == 0) // need to add stuff! + { + this.requireWork[slot] = req.copy(); + this.requireWork[slot].setStackSize(TANK_CAPACITY); + return; + } else if (req.equals(stored)) // same type ( qty different? )! + { + if (stored.getStackSize() < TANK_CAPACITY) { + this.requireWork[slot] = req.copy(); + this.requireWork[slot].setStackSize(TANK_CAPACITY - stored.getStackSize()); + return; + } + } else + // Stored != null; dispose! + { + final IAEFluidStack work = stored.copy(); + this.requireWork[slot] = work.setStackSize(-work.getStackSize()); + return; + } + } + + this.requireWork[slot] = null; + } + + private boolean usePlan(final int slot) { + IAEFluidStack work = this.requireWork[slot]; + this.isWorking = slot; + + boolean changed = false; + try { + final IMEInventory dest = this.gridProxy.getStorage() + .getInventory(AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)); + final IEnergySource src = this.gridProxy.getEnergy(); + + if (work.getStackSize() > 0) { + // make sure strange things didn't happen... + if (this.tanks.fill(slot, work.getFluidStack(), false) != work.getStackSize()) { + changed = true; + } else if (this.gridProxy.getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)).getStorageList().findPrecise(work) != null) { + final IAEFluidStack acquired = Platform.poweredExtraction(src, dest, work, this.interfaceRequestSource); + if (acquired != null) { + changed = true; + final int filled = this.tanks.fill(slot, acquired.getFluidStack(), true); + if (filled != acquired.getStackSize()) { + throw new IllegalStateException("bad attempt at managing tanks. ( fill )"); + } + } + } + } else if (work.getStackSize() < 0) { + IAEFluidStack toStore = work.copy(); + toStore.setStackSize(-toStore.getStackSize()); + + // make sure strange things didn't happen... + final FluidStack canExtract = this.tanks.drain(slot, toStore.getFluidStack(), false); + if (canExtract == null || canExtract.amount != toStore.getStackSize()) { + changed = true; + } else { + IAEFluidStack notStored = Platform.poweredInsert(src, dest, toStore, this.interfaceRequestSource); + toStore.setStackSize(toStore.getStackSize() - (notStored == null ? 0 : notStored.getStackSize())); + + if (toStore.getStackSize() > 0) { + // extract items! + changed = true; + final FluidStack removed = this.tanks.drain(slot, toStore.getFluidStack(), true); + if (removed == null || toStore.getStackSize() != removed.amount) { + throw new IllegalStateException("bad attempt at managing tanks. ( drain )"); + } + } + } + } + } catch (final GridAccessException e) { + // :P + } + + if (changed) { + this.updatePlan(slot); + } + + this.isWorking = -1; + return changed; + } + + @Override + public void onFluidInventoryChanged(final IAEFluidTank inventory, final int slot) { + if (this.isWorking == slot) { + return; + } + + if (inventory == this.config) { + boolean cfg = hasConfig(); + this.readConfig(); + if (cfg != hasConfig) { + resetConfigCache = true; + this.notifyNeighbors(); + } + } else if (inventory == this.tanks) { + this.saveChanges(); + + final boolean had = this.hasWorkToDo(); + + this.updatePlan(slot); + + final boolean now = this.hasWorkToDo(); + + if (had != now) { + try { + if (now) { + this.gridProxy.getTick().alertDevice(this.gridProxy.getNode()); + } else { + this.gridProxy.getTick().sleepDevice(this.gridProxy.getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + } + } + + public int getPriority() { + return this.priority; + } + + public void setPriority(final int newValue) { + this.priority = newValue; + } + + public void writeToNBT(final NBTTagCompound data) { + data.setInteger("priority", this.priority); + this.tanks.writeToNBT(data, "storage"); + this.config.writeToNBT(data, "config"); + } + + public void readFromNBT(final NBTTagCompound data) { + this.config.readFromNBT(data, "config"); + this.tanks.readFromNBT(data, "storage"); + this.priority = data.getInteger("priority"); + this.readConfig(); + } + + public IAEFluidTank getConfig() { + return this.config; + } + + public IAEFluidTank getTanks() { + return this.tanks; + } + + private class InterfaceRequestSource extends MachineSource { + private final InterfaceRequestContext context; + + InterfaceRequestSource(IActionHost v) { + super(v); + this.context = new InterfaceRequestContext(); + } + + @Override + public Optional context(Class key) { + if (key == InterfaceRequestContext.class) { + return (Optional) Optional.of(this.context); + } + + return super.context(key); + } + } + + private class InterfaceRequestContext implements Comparable { + @Override + public int compareTo(Integer o) { + return Integer.compare(DualityFluidInterface.this.priority, o); + } + } + + private class InterfaceInventory extends MEMonitorIFluidHandler { + + InterfaceInventory(final DualityFluidInterface tileInterface) { + super(tileInterface.tanks); + } + + @Override + public IAEFluidStack injectItems(final IAEFluidStack input, final Actionable type, final IActionSource src) { + final Optional context = src.context(InterfaceRequestContext.class); + final boolean isInterface = context.isPresent(); + + if (isInterface) { + return input; + } + + return super.injectItems(input, type, src); + } + + @Override + public IAEFluidStack extractItems(final IAEFluidStack request, final Actionable type, final IActionSource src) { + final Optional context = src.context(InterfaceRequestContext.class); + final boolean hasLowerOrEqualPriority = context.map(c -> c.compareTo(DualityFluidInterface.this.priority) <= 0).orElse(false); + + if (hasLowerOrEqualPriority) { + return null; + } + + return super.extractItems(request, type, src); + } + } + + public void saveChanges() { + this.iHost.saveChanges(); + } + + @Override + public IConfigManager getConfigManager() { + return this.cm; + } + + @Override + public IItemHandler getInventoryByName(String name) { + return null; + } + + @Override + public IFluidHandler getFluidInventoryByName(final String name) { + if (name.equals("config")) { + return this.config; + } + return null; + } + + @Override + public int getInstalledUpgrades(Upgrades u) { + return 0; + } + + @Override + public TileEntity getTile() { + return (TileEntity) (this.iHost instanceof TileEntity ? this.iHost : null); + } + + @Override + public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) { + } } diff --git a/src/main/java/appeng/fluids/helper/FluidCellConfig.java b/src/main/java/appeng/fluids/helper/FluidCellConfig.java index ba13de7b5..681382fdd 100644 --- a/src/main/java/appeng/fluids/helper/FluidCellConfig.java +++ b/src/main/java/appeng/fluids/helper/FluidCellConfig.java @@ -19,16 +19,15 @@ package appeng.fluids.helper; -import javax.annotation.Nonnull; - +import appeng.core.Api; +import appeng.fluids.items.FluidDummyItem; +import appeng.items.contents.CellConfig; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; -import appeng.core.Api; -import appeng.fluids.items.FluidDummyItem; -import appeng.items.contents.CellConfig; +import javax.annotation.Nonnull; /** @@ -36,71 +35,60 @@ import appeng.items.contents.CellConfig; * @version rv6 - 2018-01-22 * @since rv6 2018-01-22 */ -public class FluidCellConfig extends CellConfig -{ - public FluidCellConfig( ItemStack is ) - { - super( is ); - } +public class FluidCellConfig extends CellConfig { + public FluidCellConfig(ItemStack is) { + super(is); + } - @Override - @Nonnull - public ItemStack insertItem( int slot, @Nonnull ItemStack stack, boolean simulate ) - { - if( stack.isEmpty() || stack.getItem() instanceof FluidDummyItem ) - { - super.insertItem( slot, stack, simulate ); - } - FluidStack fluid = FluidUtil.getFluidContained( stack ); - if( fluid == null || !Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack( 1 ).isPresent() ) - { - return stack; - } + @Override + @Nonnull + public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) { + if (stack.isEmpty() || stack.getItem() instanceof FluidDummyItem) { + super.insertItem(slot, stack, simulate); + } + FluidStack fluid = FluidUtil.getFluidContained(stack); + if (fluid == null || !Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack(1).isPresent()) { + return stack; + } - fluid.amount = Fluid.BUCKET_VOLUME; - ItemStack is = Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack( 1 ).get(); - FluidDummyItem item = (FluidDummyItem) is.getItem(); - item.setFluidStack( is, fluid ); - return super.insertItem( slot, is, simulate ); - } + fluid.amount = Fluid.BUCKET_VOLUME; + ItemStack is = Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack(1).get(); + FluidDummyItem item = (FluidDummyItem) is.getItem(); + item.setFluidStack(is, fluid); + return super.insertItem(slot, is, simulate); + } - @Override - public void setStackInSlot( int slot, @Nonnull ItemStack stack ) - { - if( stack.isEmpty() || stack.getItem() instanceof FluidDummyItem ) - { - super.setStackInSlot( slot, stack ); - } - FluidStack fluid = FluidUtil.getFluidContained( stack ); - if( fluid == null || !Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack( 1 ).isPresent() ) - { - return; - } + @Override + public void setStackInSlot(int slot, @Nonnull ItemStack stack) { + if (stack.isEmpty() || stack.getItem() instanceof FluidDummyItem) { + super.setStackInSlot(slot, stack); + } + FluidStack fluid = FluidUtil.getFluidContained(stack); + if (fluid == null || !Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack(1).isPresent()) { + return; + } - fluid.amount = Fluid.BUCKET_VOLUME; - ItemStack is = Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack( 1 ).get(); - FluidDummyItem item = (FluidDummyItem) is.getItem(); - item.setFluidStack( is, fluid ); - super.setStackInSlot( slot, is ); - } + fluid.amount = Fluid.BUCKET_VOLUME; + ItemStack is = Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack(1).get(); + FluidDummyItem item = (FluidDummyItem) is.getItem(); + item.setFluidStack(is, fluid); + super.setStackInSlot(slot, is); + } - @Override - public boolean isItemValid( int slot, ItemStack stack ) - { - if( stack.isEmpty() || stack.getItem() instanceof FluidDummyItem ) - { - super.isItemValid( slot, stack ); - } - FluidStack fluid = FluidUtil.getFluidContained( stack ); - if( fluid == null || !Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack( 1 ).isPresent() ) - { - return false; - } - fluid.amount = Fluid.BUCKET_VOLUME; - ItemStack is = Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack( 1 ).get(); - FluidDummyItem item = (FluidDummyItem) is.getItem(); - item.setFluidStack( is, fluid ); - return super.isItemValid( slot, is ); - } + @Override + public boolean isItemValid(int slot, ItemStack stack) { + if (stack.isEmpty() || stack.getItem() instanceof FluidDummyItem) { + super.isItemValid(slot, stack); + } + FluidStack fluid = FluidUtil.getFluidContained(stack); + if (fluid == null || !Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack(1).isPresent()) { + return false; + } + fluid.amount = Fluid.BUCKET_VOLUME; + ItemStack is = Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack(1).get(); + FluidDummyItem item = (FluidDummyItem) is.getItem(); + item.setFluidStack(is, fluid); + return super.isItemValid(slot, is); + } } diff --git a/src/main/java/appeng/fluids/helper/FluidSyncHelper.java b/src/main/java/appeng/fluids/helper/FluidSyncHelper.java index 8a3eb8173..c3bf54e5b 100644 --- a/src/main/java/appeng/fluids/helper/FluidSyncHelper.java +++ b/src/main/java/appeng/fluids/helper/FluidSyncHelper.java @@ -1,98 +1,79 @@ - package appeng.fluids.helper; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.inventory.IContainerListener; - import appeng.api.storage.data.IAEFluidStack; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketFluidSlot; import appeng.fluids.util.AEFluidInventory; import appeng.fluids.util.IAEFluidTank; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.IContainerListener; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; -public class FluidSyncHelper -{ - private final IAEFluidTank inv; - private final IAEFluidTank cache; - private final int idOffset; +public class FluidSyncHelper { + private final IAEFluidTank inv; + private final IAEFluidTank cache; + private final int idOffset; - public FluidSyncHelper( final IAEFluidTank inv, final int idOffset ) - { - this.inv = inv; - this.cache = new AEFluidInventory( null, inv.getSlots() ); - this.idOffset = idOffset; - } + public FluidSyncHelper(final IAEFluidTank inv, final int idOffset) { + this.inv = inv; + this.cache = new AEFluidInventory(null, inv.getSlots()); + this.idOffset = idOffset; + } - public void sendFull( final Iterable listeners ) - { - this.sendDiffMap( this.createDiffMap( true ), listeners ); - } + public void sendFull(final Iterable listeners) { + this.sendDiffMap(this.createDiffMap(true), listeners); + } - public void sendDiff( final Iterable listeners ) - { - this.sendDiffMap( this.createDiffMap( false ), listeners ); - } + public void sendDiff(final Iterable listeners) { + this.sendDiffMap(this.createDiffMap(false), listeners); + } - public void readPacket( final Map data ) - { - for( int i = 0; i < this.inv.getSlots(); ++i ) - { - if( data.containsKey( i + this.idOffset ) ) - { - this.inv.setFluidInSlot( i, data.get( i + this.idOffset ) ); - } - } - } + public void readPacket(final Map data) { + for (int i = 0; i < this.inv.getSlots(); ++i) { + if (data.containsKey(i + this.idOffset)) { + this.inv.setFluidInSlot(i, data.get(i + this.idOffset)); + } + } + } - private void sendDiffMap( final Map data, final Iterable listeners ) - { - if( data.isEmpty() ) - { - return; - } + private void sendDiffMap(final Map data, final Iterable listeners) { + if (data.isEmpty()) { + return; + } - for( final IContainerListener l : listeners ) - { - if( l instanceof EntityPlayerMP ) - { - NetworkHandler.instance().sendTo( new PacketFluidSlot( data ), (EntityPlayerMP) l ); - } - } - } + for (final IContainerListener l : listeners) { + if (l instanceof EntityPlayerMP) { + NetworkHandler.instance().sendTo(new PacketFluidSlot(data), (EntityPlayerMP) l); + } + } + } - private final Map createDiffMap( final boolean full ) - { - final Map ret = new HashMap<>(); - for( int i = 0; i < this.inv.getSlots(); ++i ) - { - if( full || !this.equalsSlot( i ) ) - { - ret.put( i + this.idOffset, this.inv.getFluidInSlot( i ) ); - } - if( !full ) - { - this.cache.setFluidInSlot( i, this.inv.getFluidInSlot( i ) ); - } - } - return ret; - } + private final Map createDiffMap(final boolean full) { + final Map ret = new HashMap<>(); + for (int i = 0; i < this.inv.getSlots(); ++i) { + if (full || !this.equalsSlot(i)) { + ret.put(i + this.idOffset, this.inv.getFluidInSlot(i)); + } + if (!full) { + this.cache.setFluidInSlot(i, this.inv.getFluidInSlot(i)); + } + } + return ret; + } - private final boolean equalsSlot( int slot ) - { - final IAEFluidStack stackA = this.inv.getFluidInSlot( slot ); - final IAEFluidStack stackB = this.cache.getFluidInSlot( slot ); + private final boolean equalsSlot(int slot) { + final IAEFluidStack stackA = this.inv.getFluidInSlot(slot); + final IAEFluidStack stackB = this.cache.getFluidInSlot(slot); - if( !Objects.equals( stackA, stackB ) ) - { - return false; - } + if (!Objects.equals(stackA, stackB)) { + return false; + } - return stackA == null || stackA.getStackSize() == stackB.getStackSize(); - } + return stackA == null || stackA.getStackSize() == stackB.getStackSize(); + } } diff --git a/src/main/java/appeng/fluids/helper/IConfigurableFluidInventory.java b/src/main/java/appeng/fluids/helper/IConfigurableFluidInventory.java index c073cd444..6726718ec 100644 --- a/src/main/java/appeng/fluids/helper/IConfigurableFluidInventory.java +++ b/src/main/java/appeng/fluids/helper/IConfigurableFluidInventory.java @@ -2,10 +2,8 @@ package appeng.fluids.helper; import net.minecraftforge.fluids.capability.IFluidHandler; -public interface IConfigurableFluidInventory -{ - default IFluidHandler getFluidInventoryByName( String name ) - { +public interface IConfigurableFluidInventory { + default IFluidHandler getFluidInventoryByName(String name) { return null; } } diff --git a/src/main/java/appeng/fluids/helper/IFluidInterfaceHost.java b/src/main/java/appeng/fluids/helper/IFluidInterfaceHost.java index c17d8a720..1f4ae59f6 100644 --- a/src/main/java/appeng/fluids/helper/IFluidInterfaceHost.java +++ b/src/main/java/appeng/fluids/helper/IFluidInterfaceHost.java @@ -19,23 +19,21 @@ package appeng.fluids.helper; -import java.util.EnumSet; - -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; - import appeng.api.implementations.IUpgradeableHost; import appeng.api.networking.security.IActionHost; import appeng.me.helpers.IGridProxyable; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; + +import java.util.EnumSet; -public interface IFluidInterfaceHost extends IActionHost, IGridProxyable, IUpgradeableHost -{ - DualityFluidInterface getDualityFluidInterface(); +public interface IFluidInterfaceHost extends IActionHost, IGridProxyable, IUpgradeableHost { + DualityFluidInterface getDualityFluidInterface(); - EnumSet getTargets(); + EnumSet getTargets(); - TileEntity getTileEntity(); + TileEntity getTileEntity(); - void saveChanges(); + void saveChanges(); } diff --git a/src/main/java/appeng/fluids/items/BasicFluidStorageCell.java b/src/main/java/appeng/fluids/items/BasicFluidStorageCell.java index 2b7444284..488932471 100644 --- a/src/main/java/appeng/fluids/items/BasicFluidStorageCell.java +++ b/src/main/java/appeng/fluids/items/BasicFluidStorageCell.java @@ -19,10 +19,6 @@ package appeng.fluids.items; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.storage.IStorageChannel; import appeng.api.storage.channels.IFluidStorageChannel; @@ -31,6 +27,9 @@ import appeng.fluids.helper.FluidCellConfig; import appeng.items.materials.MaterialType; import appeng.items.storage.AbstractStorageCell; import appeng.util.InventoryAdaptor; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraftforge.items.IItemHandler; /** @@ -38,80 +37,70 @@ import appeng.util.InventoryAdaptor; * @version rv6 - 2018-01-17 * @since rv6 2018-01-17 */ -public final class BasicFluidStorageCell extends AbstractStorageCell -{ +public final class BasicFluidStorageCell extends AbstractStorageCell { - private final int perType; - private final double idleDrain; + private final int perType; + private final double idleDrain; - public BasicFluidStorageCell( final MaterialType whichCell, final int kilobytes ) - { - super( whichCell, kilobytes ); - switch( whichCell ) - { - case FLUID_CELL1K_PART: - this.idleDrain = 0.5; - this.perType = 8; - break; - case FLUID_CELL4K_PART: - this.idleDrain = 1.0; - this.perType = 32; - break; - case FLUID_CELL16K_PART: - this.idleDrain = 1.5; - this.perType = 128; - break; - case FLUID_CELL64K_PART: - this.idleDrain = 2.0; - this.perType = 512; - break; - default: - this.idleDrain = 0.0; - this.perType = 8; - } + public BasicFluidStorageCell(final MaterialType whichCell, final int kilobytes) { + super(whichCell, kilobytes); + switch (whichCell) { + case FLUID_CELL1K_PART: + this.idleDrain = 0.5; + this.perType = 8; + break; + case FLUID_CELL4K_PART: + this.idleDrain = 1.0; + this.perType = 32; + break; + case FLUID_CELL16K_PART: + this.idleDrain = 1.5; + this.perType = 128; + break; + case FLUID_CELL64K_PART: + this.idleDrain = 2.0; + this.perType = 512; + break; + default: + this.idleDrain = 0.0; + this.perType = 8; + } - } + } - @Override - public int getBytesPerType( ItemStack cellItem ) - { - return this.perType; - } + @Override + public int getBytesPerType(ItemStack cellItem) { + return this.perType; + } - @Override - public double getIdleDrain() - { - return this.idleDrain; - } + @Override + public double getIdleDrain() { + return this.idleDrain; + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class); + } - @Override - public int getTotalTypes( final ItemStack cellItem ) - { - return 5; - } + @Override + public int getTotalTypes(final ItemStack cellItem) { + return 5; + } - @Override - public IItemHandler getConfigInventory( final ItemStack is ) - { - return new FluidCellConfig( is ); - } + @Override + public IItemHandler getConfigInventory(final ItemStack is) { + return new FluidCellConfig(is); + } - @Override - protected void dropEmptyStorageCellCase( final InventoryAdaptor ia, final EntityPlayer player ) - { - AEApi.instance().definitions().materials().emptyStorageCell().maybeStack( 1 ).ifPresent( is -> - { - final ItemStack extraA = ia.addItems( is ); - if( !extraA.isEmpty() ) - { - player.dropItem( extraA, false ); - } - } ); - } + @Override + protected void dropEmptyStorageCellCase(final InventoryAdaptor ia, final EntityPlayer player) { + AEApi.instance().definitions().materials().emptyStorageCell().maybeStack(1).ifPresent(is -> + { + final ItemStack extraA = ia.addItems(is); + if (!extraA.isEmpty()) { + player.dropItem(extraA, false); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/appeng/fluids/items/FluidDummyItem.java b/src/main/java/appeng/fluids/items/FluidDummyItem.java index 134583aeb..2d3d4942b 100644 --- a/src/main/java/appeng/fluids/items/FluidDummyItem.java +++ b/src/main/java/appeng/fluids/items/FluidDummyItem.java @@ -19,6 +19,7 @@ package appeng.fluids.items; +import appeng.items.AEBaseItem; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -27,8 +28,6 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; -import appeng.items.AEBaseItem; - /** * Dummy item to display the fluid Icon @@ -37,47 +36,37 @@ import appeng.items.AEBaseItem; * @version rv6 - 2018-01-22 * @since rv6 2018-01-22 */ -public class FluidDummyItem extends AEBaseItem -{ - @Override - public String getItemStackDisplayName( ItemStack stack ) - { +public class FluidDummyItem extends AEBaseItem { + @Override + public String getItemStackDisplayName(ItemStack stack) { - FluidStack fluidStack = this.getFluidStack( stack ); - if( fluidStack == null ) - { - fluidStack = new FluidStack( FluidRegistry.WATER, Fluid.BUCKET_VOLUME ); - } - return fluidStack.getLocalizedName(); - } + FluidStack fluidStack = this.getFluidStack(stack); + if (fluidStack == null) { + fluidStack = new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME); + } + return fluidStack.getLocalizedName(); + } - public FluidStack getFluidStack( ItemStack is ) - { - if( is.hasTagCompound() ) - { - NBTTagCompound tag = is.getTagCompound(); - return FluidStack.loadFluidStackFromNBT( tag ); - } - return null; - } + public FluidStack getFluidStack(ItemStack is) { + if (is.hasTagCompound()) { + NBTTagCompound tag = is.getTagCompound(); + return FluidStack.loadFluidStackFromNBT(tag); + } + return null; + } - public void setFluidStack( ItemStack is, FluidStack fs ) - { - if( fs == null ) - { - is.setTagCompound( null ); - } - else - { - NBTTagCompound tag = new NBTTagCompound(); - fs.writeToNBT( tag ); - is.setTagCompound( tag ); - } - } + public void setFluidStack(ItemStack is, FluidStack fs) { + if (fs == null) { + is.setTagCompound(null); + } else { + NBTTagCompound tag = new NBTTagCompound(); + fs.writeToNBT(tag); + is.setTagCompound(tag); + } + } - @Override - protected void getCheckedSubItems( final CreativeTabs creativeTab, final NonNullList itemStacks ) - { - // Don't show this item in CreativeTabs - } + @Override + protected void getCheckedSubItems(final CreativeTabs creativeTab, final NonNullList itemStacks) { + // Don't show this item in CreativeTabs + } } diff --git a/src/main/java/appeng/fluids/items/FluidDummyItemRendering.java b/src/main/java/appeng/fluids/items/FluidDummyItemRendering.java index 897b9a485..7871e6eaf 100644 --- a/src/main/java/appeng/fluids/items/FluidDummyItemRendering.java +++ b/src/main/java/appeng/fluids/items/FluidDummyItemRendering.java @@ -29,11 +29,9 @@ import appeng.client.render.DummyFluidItemModel; * @version rv6 - 2018-01-22 * @since rv6 2018-01-22 */ -public class FluidDummyItemRendering extends ItemRenderingCustomizer -{ - @Override - public void customize( IItemRendering rendering ) - { - rendering.builtInModel( "models/item/dummy_fluid_item", new DummyFluidItemModel() ); - } +public class FluidDummyItemRendering extends ItemRenderingCustomizer { + @Override + public void customize(IItemRendering rendering) { + rendering.builtInModel("models/item/dummy_fluid_item", new DummyFluidItemModel()); + } } diff --git a/src/main/java/appeng/fluids/parts/FluidHandlerAdapter.java b/src/main/java/appeng/fluids/parts/FluidHandlerAdapter.java index 88c3d87fa..a5f688296 100644 --- a/src/main/java/appeng/fluids/parts/FluidHandlerAdapter.java +++ b/src/main/java/appeng/fluids/parts/FluidHandlerAdapter.java @@ -19,21 +19,11 @@ package appeng.fluids.parts; -import java.util.*; - +import appeng.api.AEApi; import appeng.api.config.AccessRestriction; +import appeng.api.config.Actionable; import appeng.api.config.Settings; import appeng.api.config.StorageFilter; -import appeng.api.storage.data.IAEItemStack; -import appeng.me.GridAccessException; -import appeng.util.inv.ItemSlot; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidTankProperties; - -import appeng.api.AEApi; -import appeng.api.config.Actionable; import appeng.api.networking.security.IActionSource; import appeng.api.networking.storage.IBaseMonitor; import appeng.api.networking.ticking.TickRateModulation; @@ -44,8 +34,14 @@ import appeng.api.storage.channels.IFluidStorageChannel; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; import appeng.fluids.util.AEFluidStack; +import appeng.me.GridAccessException; import appeng.me.helpers.IGridProxyable; import appeng.me.storage.ITickingMonitor; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.capability.IFluidHandler; +import net.minecraftforge.fluids.capability.IFluidTankProperties; + +import java.util.*; /** @@ -55,218 +51,178 @@ import appeng.me.storage.ITickingMonitor; * @version rv6 - 22/05/2018 * @since rv6 22/05/2018 */ -public class FluidHandlerAdapter implements IMEInventory, IBaseMonitor, ITickingMonitor -{ - private final Map, Object> listeners = new HashMap<>(); - private IActionSource source; - private final IFluidHandler fluidHandler; - private final IGridProxyable proxyable; - private final FluidHandlerAdapter.InventoryCache cache; - private StorageFilter mode; - private AccessRestriction access; +public class FluidHandlerAdapter implements IMEInventory, IBaseMonitor, ITickingMonitor { + private final Map, Object> listeners = new HashMap<>(); + private IActionSource source; + private final IFluidHandler fluidHandler; + private final IGridProxyable proxyable; + private final FluidHandlerAdapter.InventoryCache cache; + private StorageFilter mode; + private AccessRestriction access; - FluidHandlerAdapter( IFluidHandler fluidHandler, IGridProxyable proxy ) - { - this.fluidHandler = fluidHandler; - this.proxyable = proxy; - if( this.proxyable instanceof PartFluidStorageBus ) - { - PartFluidStorageBus partFluidStorageBus = (PartFluidStorageBus) this.proxyable; - this.mode = ( (StorageFilter) partFluidStorageBus.getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); - this.access = ( (AccessRestriction) partFluidStorageBus.getConfigManager().getSetting( Settings.ACCESS ) ); - } - this.cache = new FluidHandlerAdapter.InventoryCache( this.fluidHandler, this.mode ); - this.cache.update(); - } + FluidHandlerAdapter(IFluidHandler fluidHandler, IGridProxyable proxy) { + this.fluidHandler = fluidHandler; + this.proxyable = proxy; + if (this.proxyable instanceof PartFluidStorageBus) { + PartFluidStorageBus partFluidStorageBus = (PartFluidStorageBus) this.proxyable; + this.mode = ((StorageFilter) partFluidStorageBus.getConfigManager().getSetting(Settings.STORAGE_FILTER)); + this.access = ((AccessRestriction) partFluidStorageBus.getConfigManager().getSetting(Settings.ACCESS)); + } + this.cache = new FluidHandlerAdapter.InventoryCache(this.fluidHandler, this.mode); + this.cache.update(); + } - @Override - public IAEFluidStack injectItems( IAEFluidStack input, Actionable type, IActionSource src ) - { - FluidStack fluidStack = input.getFluidStack(); + @Override + public IAEFluidStack injectItems(IAEFluidStack input, Actionable type, IActionSource src) { + FluidStack fluidStack = input.getFluidStack(); - // Insert - int wasFillled = this.fluidHandler.fill( fluidStack, type != Actionable.SIMULATE ); - int remaining = fluidStack.amount - wasFillled; - if( fluidStack.amount == remaining ) - { - // The stack was unmodified, target tank is full - return input; - } + // Insert + int wasFillled = this.fluidHandler.fill(fluidStack, type != Actionable.SIMULATE); + int remaining = fluidStack.amount - wasFillled; + if (fluidStack.amount == remaining) { + // The stack was unmodified, target tank is full + return input; + } - if( type == Actionable.MODULATE ) - { - IAEFluidStack added = input.copy().setStackSize( input.getStackSize() - remaining ); - this.cache.currentlyCached.add( added ); - this.postDifference( Collections.singletonList( added ) ); - try - { - this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() ); - } - catch( GridAccessException ex ) - { - // meh - } - } + if (type == Actionable.MODULATE) { + IAEFluidStack added = input.copy().setStackSize(input.getStackSize() - remaining); + this.cache.currentlyCached.add(added); + this.postDifference(Collections.singletonList(added)); + try { + this.proxyable.getProxy().getTick().alertDevice(this.proxyable.getProxy().getNode()); + } catch (GridAccessException ex) { + // meh + } + } - fluidStack.amount = remaining; + fluidStack.amount = remaining; - return AEFluidStack.fromFluidStack( fluidStack ); - } + return AEFluidStack.fromFluidStack(fluidStack); + } - @Override - public IAEFluidStack extractItems( IAEFluidStack request, Actionable mode, IActionSource src ) - { - FluidStack requestedFluidStack = request.getFluidStack(); - final boolean doDrain = ( mode == Actionable.MODULATE ); + @Override + public IAEFluidStack extractItems(IAEFluidStack request, Actionable mode, IActionSource src) { + FluidStack requestedFluidStack = request.getFluidStack(); + final boolean doDrain = (mode == Actionable.MODULATE); - // Drain the fluid from the tank - FluidStack gathered = this.fluidHandler.drain( requestedFluidStack, doDrain ); - if( gathered == null ) - { - // If nothing was pulled from the tank, return null - return null; - } + // Drain the fluid from the tank + FluidStack gathered = this.fluidHandler.drain(requestedFluidStack, doDrain); + if (gathered == null) { + // If nothing was pulled from the tank, return null + return null; + } - IAEFluidStack gatheredAEFluidstack = AEFluidStack.fromFluidStack( gathered ); - if( mode == Actionable.MODULATE ) - { - IAEFluidStack cachedStack = this.cache.currentlyCached.findPrecise( request ); - if( cachedStack != null ) - { - cachedStack.decStackSize( gatheredAEFluidstack.getStackSize() ); - this.postDifference( Collections.singletonList( gatheredAEFluidstack.copy().setStackSize( -gatheredAEFluidstack.getStackSize() ) ) ); - } - try - { - this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() ); - } - catch( GridAccessException ex ) - { - // meh - } - } - return gatheredAEFluidstack; - } + IAEFluidStack gatheredAEFluidstack = AEFluidStack.fromFluidStack(gathered); + if (mode == Actionable.MODULATE) { + IAEFluidStack cachedStack = this.cache.currentlyCached.findPrecise(request); + if (cachedStack != null) { + cachedStack.decStackSize(gatheredAEFluidstack.getStackSize()); + this.postDifference(Collections.singletonList(gatheredAEFluidstack.copy().setStackSize(-gatheredAEFluidstack.getStackSize()))); + } + try { + this.proxyable.getProxy().getTick().alertDevice(this.proxyable.getProxy().getNode()); + } catch (GridAccessException ex) { + // meh + } + } + return gatheredAEFluidstack; + } - @Override - public TickRateModulation onTick() - { - List changes = this.cache.update(); - if( !changes.isEmpty() && access.hasPermission( AccessRestriction.READ ) ) - { - this.postDifference( changes ); - return TickRateModulation.URGENT; - } - else - { - return TickRateModulation.SLOWER; - } - } + @Override + public TickRateModulation onTick() { + List changes = this.cache.update(); + if (!changes.isEmpty() && access.hasPermission(AccessRestriction.READ)) { + this.postDifference(changes); + return TickRateModulation.URGENT; + } else { + return TickRateModulation.SLOWER; + } + } - @Override - public IItemList getAvailableItems( IItemList out ) - { - return this.cache.getAvailableItems( out ); - } + @Override + public IItemList getAvailableItems(IItemList out) { + return this.cache.getAvailableItems(out); + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class); + } - @Override - public void setActionSource( IActionSource source ) - { - this.source = source; - } + @Override + public void setActionSource(IActionSource source) { + this.source = source; + } - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } - private void postDifference( Iterable a ) - { - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while( i.hasNext() ) - { - final Map.Entry, Object> l = i.next(); - final IMEMonitorHandlerReceiver key = l.getKey(); - if( key.isValid( l.getValue() ) ) - { - key.postChange( this, a, this.source ); - } - else - { - i.remove(); - } - } - } + private void postDifference(Iterable a) { + final Iterator, Object>> i = this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Map.Entry, Object> l = i.next(); + final IMEMonitorHandlerReceiver key = l.getKey(); + if (key.isValid(l.getValue())) { + key.postChange(this, a, this.source); + } else { + i.remove(); + } + } + } - private static class InventoryCache - { - private final IFluidHandler fluidHandler; - private final StorageFilter mode; - IItemList currentlyCached = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList(); + private static class InventoryCache { + private final IFluidHandler fluidHandler; + private final StorageFilter mode; + IItemList currentlyCached = AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class).createList(); - public InventoryCache( IFluidHandler fluidHandler, StorageFilter mode ) - { - this.mode = mode; - this.fluidHandler = fluidHandler; - } + public InventoryCache(IFluidHandler fluidHandler, StorageFilter mode) { + this.mode = mode; + this.fluidHandler = fluidHandler; + } - public List update() - { - final List changes = new ArrayList<>(); - final IFluidTankProperties[] tankProperties = this.fluidHandler.getTankProperties(); + public List update() { + final List changes = new ArrayList<>(); + final IFluidTankProperties[] tankProperties = this.fluidHandler.getTankProperties(); - IItemList currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList(); + IItemList currentlyOnStorage = AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class).createList(); - for( IFluidTankProperties tankProperty : tankProperties ) - { - if( this.mode == StorageFilter.EXTRACTABLE_ONLY && this.fluidHandler.drain( 1, false ) == null ) - { - continue; - } - currentlyOnStorage.add( AEFluidStack.fromFluidStack( tankProperty.getContents() ) ); - } + for (IFluidTankProperties tankProperty : tankProperties) { + if (this.mode == StorageFilter.EXTRACTABLE_ONLY && this.fluidHandler.drain(1, false) == null) { + continue; + } + currentlyOnStorage.add(AEFluidStack.fromFluidStack(tankProperty.getContents())); + } - for ( final IAEFluidStack is : currentlyCached ) - { - is.setStackSize( -is.getStackSize() ); - } + for (final IAEFluidStack is : currentlyCached) { + is.setStackSize(-is.getStackSize()); + } - for ( final IAEFluidStack is : currentlyOnStorage ) - { - currentlyCached.add( is ); - } + for (final IAEFluidStack is : currentlyOnStorage) { + currentlyCached.add(is); + } - for ( final IAEFluidStack is : currentlyCached ) - { - if( is.getStackSize() != 0 ) - { - changes.add( is ); - } - } + for (final IAEFluidStack is : currentlyCached) { + if (is.getStackSize() != 0) { + changes.add(is); + } + } - currentlyCached = currentlyOnStorage; + currentlyCached = currentlyOnStorage; - return changes; - } + return changes; + } - public IItemList getAvailableItems( IItemList out ) - { - currentlyCached.iterator().forEachRemaining( out::add ); - return out; - } + public IItemList getAvailableItems(IItemList out) { + currentlyCached.iterator().forEachRemaining(out::add); + return out; + } - } + } } diff --git a/src/main/java/appeng/fluids/parts/PartFluidAnnihilationPlane.java b/src/main/java/appeng/fluids/parts/PartFluidAnnihilationPlane.java index 1058e9c2a..20b6ea8b1 100644 --- a/src/main/java/appeng/fluids/parts/PartFluidAnnihilationPlane.java +++ b/src/main/java/appeng/fluids/parts/PartFluidAnnihilationPlane.java @@ -1,22 +1,6 @@ - package appeng.fluids.parts; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockLiquid; -import net.minecraft.block.state.IBlockState; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; -import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fluids.IFluidBlock; -import net.minecraftforge.fluids.capability.IFluidHandler; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -50,274 +34,245 @@ import appeng.parts.PartBasicState; import appeng.parts.automation.PlaneConnections; import appeng.parts.automation.PlaneModels; import appeng.util.Platform; +import net.minecraft.block.Block; +import net.minecraft.block.BlockLiquid; +import net.minecraft.block.state.IBlockState; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.fluids.FluidUtil; +import net.minecraftforge.fluids.IFluidBlock; +import net.minecraftforge.fluids.capability.IFluidHandler; + +import java.util.List; -public class PartFluidAnnihilationPlane extends PartBasicState implements IGridTickable -{ - private static final PlaneModels MODELS = new PlaneModels( "part/fluid_annihilation_plane_", "part/fluid_annihilation_plane_on_" ); +public class PartFluidAnnihilationPlane extends PartBasicState implements IGridTickable { + private static final PlaneModels MODELS = new PlaneModels("part/fluid_annihilation_plane_", "part/fluid_annihilation_plane_on_"); - @PartModels - public static List getModels() - { - return MODELS.getModels(); - } + @PartModels + public static List getModels() { + return MODELS.getModels(); + } - private final IActionSource mySrc = new MachineSource( this ); + private final IActionSource mySrc = new MachineSource(this); - public PartFluidAnnihilationPlane( final ItemStack is ) - { - super( is ); - } + public PartFluidAnnihilationPlane(final ItemStack is) { + super(is); + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - int minX = 1; - int minY = 1; - int maxX = 15; - int maxY = 15; + @Override + public void getBoxes(final IPartCollisionHelper bch) { + int minX = 1; + int minY = 1; + int maxX = 15; + int maxY = 15; - final IPartHost host = this.getHost(); - if( host != null ) - { - final TileEntity te = host.getTile(); + final IPartHost host = this.getHost(); + if (host != null) { + final TileEntity te = host.getTile(); - final BlockPos pos = te.getPos(); + final BlockPos pos = te.getPos(); - final EnumFacing e = bch.getWorldX(); - final EnumFacing u = bch.getWorldY(); + final EnumFacing e = bch.getWorldX(); + final EnumFacing u = bch.getWorldY(); - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( e.getOpposite() ) ), this.getSide() ) ) - { - minX = 0; - } + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(e.getOpposite())), this.getSide())) { + minX = 0; + } - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( e ) ), this.getSide() ) ) - { - maxX = 16; - } + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(e)), this.getSide())) { + maxX = 16; + } - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( u.getOpposite() ) ), this.getSide() ) ) - { - minY = 0; - } + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(u.getOpposite())), this.getSide())) { + minY = 0; + } - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( e ) ), this.getSide() ) ) - { - maxY = 16; - } - } + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(e)), this.getSide())) { + maxY = 16; + } + } - bch.addBox( 5, 5, 14, 11, 11, 15 ); - bch.addBox( minX, minY, 15, maxX, maxY, 16 ); - } + bch.addBox(5, 5, 14, 11, 11, 15); + bch.addBox(minX, minY, 15, maxX, maxY, 16); + } - public PlaneConnections getConnections() - { + public PlaneConnections getConnections() { - final EnumFacing facingRight, facingUp; - AEPartLocation location = this.getSide(); - switch( location ) - { - case UP: - facingRight = EnumFacing.EAST; - facingUp = EnumFacing.NORTH; - break; - case DOWN: - facingRight = EnumFacing.WEST; - facingUp = EnumFacing.NORTH; - break; - case NORTH: - facingRight = EnumFacing.WEST; - facingUp = EnumFacing.UP; - break; - case SOUTH: - facingRight = EnumFacing.EAST; - facingUp = EnumFacing.UP; - break; - case WEST: - facingRight = EnumFacing.SOUTH; - facingUp = EnumFacing.UP; - break; - case EAST: - facingRight = EnumFacing.NORTH; - facingUp = EnumFacing.UP; - break; - default: - case INTERNAL: - return PlaneConnections.of( false, false, false, false ); - } + final EnumFacing facingRight, facingUp; + AEPartLocation location = this.getSide(); + switch (location) { + case UP: + facingRight = EnumFacing.EAST; + facingUp = EnumFacing.NORTH; + break; + case DOWN: + facingRight = EnumFacing.WEST; + facingUp = EnumFacing.NORTH; + break; + case NORTH: + facingRight = EnumFacing.WEST; + facingUp = EnumFacing.UP; + break; + case SOUTH: + facingRight = EnumFacing.EAST; + facingUp = EnumFacing.UP; + break; + case WEST: + facingRight = EnumFacing.SOUTH; + facingUp = EnumFacing.UP; + break; + case EAST: + facingRight = EnumFacing.NORTH; + facingUp = EnumFacing.UP; + break; + default: + case INTERNAL: + return PlaneConnections.of(false, false, false, false); + } - boolean left = false, right = false, down = false, up = false; + boolean left = false, right = false, down = false, up = false; - final IPartHost host = this.getHost(); - if( host != null ) - { - final TileEntity te = host.getTile(); + final IPartHost host = this.getHost(); + if (host != null) { + final TileEntity te = host.getTile(); - final BlockPos pos = te.getPos(); + final BlockPos pos = te.getPos(); - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( facingRight.getOpposite() ) ), this.getSide() ) ) - { - left = true; - } + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(facingRight.getOpposite())), this.getSide())) { + left = true; + } - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( facingRight ) ), this.getSide() ) ) - { - right = true; - } + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(facingRight)), this.getSide())) { + right = true; + } - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( facingUp.getOpposite() ) ), this.getSide() ) ) - { - down = true; - } + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(facingUp.getOpposite())), this.getSide())) { + down = true; + } - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( facingUp ) ), this.getSide() ) ) - { - up = true; - } - } + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(facingUp)), this.getSide())) { + up = true; + } + } - return PlaneConnections.of( up, right, down, left ); - } + return PlaneConnections.of(up, right, down, left); + } - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - if( pos.offset( this.getSide().getFacing() ).equals( neighbor ) ) - { - this.refresh(); - } - } + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + if (pos.offset(this.getSide().getFacing()).equals(neighbor)) { + this.refresh(); + } + } - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 1; - } + @Override + public float getCableConnectionLength(AECableType cable) { + return 1; + } - private boolean isAnnihilationPlane( final TileEntity blockTileEntity, final AEPartLocation side ) - { - if( blockTileEntity instanceof IPartHost ) - { - final IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); - return p != null && p.getClass() == this.getClass(); - } - return false; - } + private boolean isAnnihilationPlane(final TileEntity blockTileEntity, final AEPartLocation side) { + if (blockTileEntity instanceof IPartHost) { + final IPart p = ((IPartHost) blockTileEntity).getPart(side); + return p != null && p.getClass() == this.getClass(); + } + return false; + } - private void refresh() - { - try - { - this.getProxy().getTick().alertDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } + private void refresh() { + try { + this.getProxy().getTick().alertDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // :P + } + } - @Override - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - this.refresh(); - this.getHost().markForUpdate(); - } + @Override + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + this.refresh(); + this.getHost().markForUpdate(); + } - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.refresh(); - this.getHost().markForUpdate(); - } + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.refresh(); + this.getHost().markForUpdate(); + } - private TickRateModulation pickupFluid() - { - if( !this.getProxy().isActive() ) - { - return TickRateModulation.SLEEP; - } + private TickRateModulation pickupFluid() { + if (!this.getProxy().isActive()) { + return TickRateModulation.SLEEP; + } - final TileEntity te = this.getTile(); - final World w = te.getWorld(); - final BlockPos pos = te.getPos().offset( this.getSide().getFacing() ); - final IBlockState state = w.getBlockState( pos ); - final Block block = state.getBlock(); + final TileEntity te = this.getTile(); + final World w = te.getWorld(); + final BlockPos pos = te.getPos().offset(this.getSide().getFacing()); + final IBlockState state = w.getBlockState(pos); + final Block block = state.getBlock(); - if( block instanceof IFluidBlock || block instanceof BlockLiquid ) - { - final IFluidHandler fh = FluidUtil.getFluidHandler( w, pos, null ); - final IAEFluidStack blockFluid = AEFluidStack.fromFluidStack( fh.drain( Integer.MAX_VALUE, false ) ); + if (block instanceof IFluidBlock || block instanceof BlockLiquid) { + final IFluidHandler fh = FluidUtil.getFluidHandler(w, pos, null); + final IAEFluidStack blockFluid = AEFluidStack.fromFluidStack(fh.drain(Integer.MAX_VALUE, false)); - if( blockFluid != null ) - { - if( this.storeFluid( blockFluid, false ) ) - { - this.storeFluid( AEFluidStack.fromFluidStack( fh.drain( Integer.MAX_VALUE, true ) ), true ); + if (blockFluid != null) { + if (this.storeFluid(blockFluid, false)) { + this.storeFluid(AEFluidStack.fromFluidStack(fh.drain(Integer.MAX_VALUE, true)), true); - AppEng.proxy.sendToAllNearExcept( null, pos.getX(), pos.getY(), pos.getZ(), 64, w, - new PacketTransitionEffect( pos.getX(), pos.getY(), pos.getZ(), this.getSide(), true ) ); + AppEng.proxy.sendToAllNearExcept(null, pos.getX(), pos.getY(), pos.getZ(), 64, w, + new PacketTransitionEffect(pos.getX(), pos.getY(), pos.getZ(), this.getSide(), true)); - return TickRateModulation.URGENT; - } - return TickRateModulation.IDLE; - } - } + return TickRateModulation.URGENT; + } + return TickRateModulation.IDLE; + } + } - // nothing to do here :) - return TickRateModulation.SLEEP; - } + // nothing to do here :) + return TickRateModulation.SLEEP; + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.AnnihilationPlane.getMin(), TickRates.AnnihilationPlane.getMax(), false, true ); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.AnnihilationPlane.getMin(), TickRates.AnnihilationPlane.getMax(), false, true); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.pickupFluid(); - } + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.pickupFluid(); + } - private boolean storeFluid( IAEFluidStack stack, boolean modulate ) - { - try - { - final IStorageGrid storage = this.getProxy().getStorage(); - final IMEInventory inv = storage.getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ); + private boolean storeFluid(IAEFluidStack stack, boolean modulate) { + try { + final IStorageGrid storage = this.getProxy().getStorage(); + final IMEInventory inv = storage.getInventory(AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)); - if( modulate ) - { - final IEnergyGrid energy = this.getProxy().getEnergy(); - return Platform.poweredInsert( energy, inv, stack, this.mySrc ) == null; - } - else - { - final float requiredPower = stack.getStackSize() / Math.min( 1.0f, stack.getChannel().transferFactor() ); - final IEnergyGrid energy = this.getProxy().getEnergy(); + if (modulate) { + final IEnergyGrid energy = this.getProxy().getEnergy(); + return Platform.poweredInsert(energy, inv, stack, this.mySrc) == null; + } else { + final float requiredPower = stack.getStackSize() / Math.min(1.0f, stack.getChannel().transferFactor()); + final IEnergyGrid energy = this.getProxy().getEnergy(); - if( energy.extractAEPower( requiredPower, Actionable.SIMULATE, PowerMultiplier.CONFIG ) < requiredPower ) - { - return false; - } - final IAEFluidStack leftOver = inv.injectItems( stack, Actionable.SIMULATE, this.mySrc ); - return leftOver == null || leftOver.getStackSize() == 0; - } - } - catch( final GridAccessException e ) - { - // :P - } - return false; - } + if (energy.extractAEPower(requiredPower, Actionable.SIMULATE, PowerMultiplier.CONFIG) < requiredPower) { + return false; + } + final IAEFluidStack leftOver = inv.injectItems(stack, Actionable.SIMULATE, this.mySrc); + return leftOver == null || leftOver.getStackSize() == 0; + } + } catch (final GridAccessException e) { + // :P + } + return false; + } - @Override - public IPartModel getStaticModels() - { - return MODELS.getModel( this.getConnections(), this.isPowered(), this.isActive() ); - } + @Override + public IPartModel getStaticModels() { + return MODELS.getModel(this.getConnections(), this.isPowered(), this.isActive()); + } } diff --git a/src/main/java/appeng/fluids/parts/PartFluidExportBus.java b/src/main/java/appeng/fluids/parts/PartFluidExportBus.java index b09159b81..5d2d8e520 100644 --- a/src/main/java/appeng/fluids/parts/PartFluidExportBus.java +++ b/src/main/java/appeng/fluids/parts/PartFluidExportBus.java @@ -19,20 +19,7 @@ package appeng.fluids.parts; -import javax.annotation.Nonnull; - -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandler; - -import appeng.api.config.Actionable; -import appeng.api.config.FuzzyMode; -import appeng.api.config.RedstoneMode; -import appeng.api.config.SchedulingMode; -import appeng.api.config.Settings; -import appeng.api.config.YesNo; +import appeng.api.config.*; import appeng.api.networking.IGridNode; import appeng.api.networking.security.IActionSource; import appeng.api.networking.ticking.TickRateModulation; @@ -47,6 +34,13 @@ import appeng.items.parts.PartModels; import appeng.me.GridAccessException; import appeng.me.helpers.MachineSource; import appeng.parts.PartModel; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; +import net.minecraftforge.fluids.capability.IFluidHandler; + +import javax.annotation.Nonnull; /** @@ -54,133 +48,109 @@ import appeng.parts.PartModel; * @version rv6 - 30/04/2018 * @since rv6 30/04/2018 */ -public class PartFluidExportBus extends PartSharedFluidBus -{ - public static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "part/fluid_export_bus_base" ); - @PartModels - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/fluid_export_bus_off" ) ); - @PartModels - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/fluid_export_bus_on" ) ); - @PartModels - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/fluid_export_bus_has_channel" ) ); +public class PartFluidExportBus extends PartSharedFluidBus { + public static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "part/fluid_export_bus_base"); + @PartModels + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/fluid_export_bus_off")); + @PartModels + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/fluid_export_bus_on")); + @PartModels + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/fluid_export_bus_has_channel")); - private final IActionSource source; + private final IActionSource source; - public PartFluidExportBus( ItemStack is ) - { - super( is ); - this.getConfigManager().registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.CRAFT_ONLY, YesNo.NO ); - this.getConfigManager().registerSetting( Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT ); - this.source = new MachineSource( this ); - } + public PartFluidExportBus(ItemStack is) { + super(is); + this.getConfigManager().registerSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.getConfigManager().registerSetting(Settings.CRAFT_ONLY, YesNo.NO); + this.getConfigManager().registerSetting(Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT); + this.source = new MachineSource(this); + } - @Override - public TickingRequest getTickingRequest( IGridNode node ) - { - return new TickingRequest( TickRates.FluidExportBus.getMin(), TickRates.FluidExportBus.getMax(), this.isSleeping(), false ); - } + @Override + public TickingRequest getTickingRequest(IGridNode node) { + return new TickingRequest(TickRates.FluidExportBus.getMin(), TickRates.FluidExportBus.getMax(), this.isSleeping(), false); + } - @Override - public TickRateModulation tickingRequest( IGridNode node, int ticksSinceLastCall ) - { - return this.canDoBusWork() ? this.doBusWork() : TickRateModulation.IDLE; - } + @Override + public TickRateModulation tickingRequest(IGridNode node, int ticksSinceLastCall) { + return this.canDoBusWork() ? this.doBusWork() : TickRateModulation.IDLE; + } - @Override - protected boolean canDoBusWork() - { - return this.getProxy().isActive(); - } + @Override + protected boolean canDoBusWork() { + return this.getProxy().isActive(); + } - @Override - protected TickRateModulation doBusWork() - { - if( !this.canDoBusWork() ) - { - return TickRateModulation.IDLE; - } + @Override + protected TickRateModulation doBusWork() { + if (!this.canDoBusWork()) { + return TickRateModulation.IDLE; + } - final TileEntity te = this.getConnectedTE(); + final TileEntity te = this.getConnectedTE(); - if( te != null && te.hasCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing().getOpposite() ) ) - { - try - { - final IFluidHandler fh = te.getCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing().getOpposite() ); - final IMEMonitor inv = this.getProxy().getStorage().getInventory( this.getChannel() ); + if (te != null && te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing().getOpposite())) { + try { + final IFluidHandler fh = te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing().getOpposite()); + final IMEMonitor inv = this.getProxy().getStorage().getInventory(this.getChannel()); - if( fh != null ) - { - for( int i = 0; i < this.getConfig().getSlots(); i++ ) - { - IAEFluidStack fluid = this.getConfig().getFluidInSlot( i ); - if( fluid != null ) - { - final IAEFluidStack toExtract = fluid.copy(); + if (fh != null) { + for (int i = 0; i < this.getConfig().getSlots(); i++) { + IAEFluidStack fluid = this.getConfig().getFluidInSlot(i); + if (fluid != null) { + final IAEFluidStack toExtract = fluid.copy(); - toExtract.setStackSize( this.calculateAmountToSend() ); + toExtract.setStackSize(this.calculateAmountToSend()); - final IAEFluidStack out = inv.extractItems( toExtract, Actionable.SIMULATE, this.source ); + final IAEFluidStack out = inv.extractItems(toExtract, Actionable.SIMULATE, this.source); - if( out != null ) - { - int wasInserted = fh.fill( out.getFluidStack(), true ); + if (out != null) { + int wasInserted = fh.fill(out.getFluidStack(), true); - if( wasInserted > 0 ) - { - toExtract.setStackSize( wasInserted ); - inv.extractItems( toExtract, Actionable.MODULATE, this.source ); + if (wasInserted > 0) { + toExtract.setStackSize(wasInserted); + inv.extractItems(toExtract, Actionable.MODULATE, this.source); - return TickRateModulation.FASTER; - } - } - } - } + return TickRateModulation.FASTER; + } + } + } + } - return TickRateModulation.SLOWER; - } - } - catch( GridAccessException e ) - { - // Ignore - } - } + return TickRateModulation.SLOWER; + } + } catch (GridAccessException e) { + // Ignore + } + } - return TickRateModulation.SLEEP; - } + return TickRateModulation.SLEEP; + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 4, 4, 12, 12, 12, 14 ); - bch.addBox( 5, 5, 14, 11, 11, 15 ); - bch.addBox( 6, 6, 15, 10, 10, 16 ); - bch.addBox( 6, 6, 11, 10, 10, 12 ); - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(4, 4, 12, 12, 12, 14); + bch.addBox(5, 5, 14, 11, 11, 15); + bch.addBox(6, 6, 15, 10, 10, 16); + bch.addBox(6, 6, 11, 10, 10, 12); + } - @Override - public RedstoneMode getRSMode() - { - return (RedstoneMode) this.getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ); - } + @Override + public RedstoneMode getRSMode() { + return (RedstoneMode) this.getConfigManager().getSetting(Settings.REDSTONE_CONTROLLED); + } - @Nonnull - @Override - public IPartModel getStaticModels() - { - if( this.isActive() && this.isPowered() ) - { - return MODELS_HAS_CHANNEL; - } - else if( this.isPowered() ) - { - return MODELS_ON; - } - else - { - return MODELS_OFF; - } - } + @Nonnull + @Override + public IPartModel getStaticModels() { + if (this.isActive() && this.isPowered()) { + return MODELS_HAS_CHANNEL; + } else if (this.isPowered()) { + return MODELS_ON; + } else { + return MODELS_OFF; + } + } } diff --git a/src/main/java/appeng/fluids/parts/PartFluidFormationPlane.java b/src/main/java/appeng/fluids/parts/PartFluidFormationPlane.java index 963b3c2e1..ce4283333 100644 --- a/src/main/java/appeng/fluids/parts/PartFluidFormationPlane.java +++ b/src/main/java/appeng/fluids/parts/PartFluidFormationPlane.java @@ -1,29 +1,6 @@ - package appeng.fluids.parts; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import appeng.fluids.helper.IConfigurableFluidInventory; -import net.minecraft.block.Block; -import net.minecraft.block.BlockLiquid; -import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTank; -import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fluids.IFluidBlock; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -42,6 +19,7 @@ import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; import appeng.api.util.AEPartLocation; import appeng.core.sync.GuiBridge; +import appeng.fluids.helper.IConfigurableFluidInventory; import appeng.fluids.util.AEFluidInventory; import appeng.fluids.util.IAEFluidInventory; import appeng.fluids.util.IAEFluidTank; @@ -52,196 +30,182 @@ import appeng.parts.automation.PartAbstractFormationPlane; import appeng.parts.automation.PlaneModels; import appeng.util.Platform; import appeng.util.prioritylist.PrecisePriorityList; +import net.minecraft.block.Block; +import net.minecraft.block.BlockLiquid; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; +import net.minecraft.world.World; +import net.minecraftforge.fluids.*; import net.minecraftforge.fluids.capability.IFluidHandler; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; -public class PartFluidFormationPlane extends PartAbstractFormationPlane implements IAEFluidInventory, IConfigurableFluidInventory -{ - private static final PlaneModels MODELS = new PlaneModels( "part/fluid_formation_plane_", "part/fluid_formation_plane_on_" ); - @PartModels - public static List getModels() - { - return MODELS.getModels(); - } +public class PartFluidFormationPlane extends PartAbstractFormationPlane implements IAEFluidInventory, IConfigurableFluidInventory { + private static final PlaneModels MODELS = new PlaneModels("part/fluid_formation_plane_", "part/fluid_formation_plane_on_"); - private final MEInventoryHandler myHandler = new MEInventoryHandler<>( this, AEApi.instance() - .storage() - .getStorageChannel( IFluidStorageChannel.class ) ); - private final AEFluidInventory config = new AEFluidInventory( this, 63 ); + @PartModels + public static List getModels() { + return MODELS.getModels(); + } - public PartFluidFormationPlane( final ItemStack is ) - { - super( is ); - this.updateHandler(); - } + private final MEInventoryHandler myHandler = new MEInventoryHandler<>(this, AEApi.instance() + .storage() + .getStorageChannel(IFluidStorageChannel.class)); + private final AEFluidInventory config = new AEFluidInventory(this, 63); - @Override - protected void updateHandler() - { - this.myHandler.setBaseAccess( AccessRestriction.WRITE ); - this.myHandler.setWhitelist( this.getInstalledUpgrades( Upgrades.INVERTER ) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST ); - this.myHandler.setPriority( this.getPriority() ); + public PartFluidFormationPlane(final ItemStack is) { + super(is); + this.updateHandler(); + } - final IItemList priorityList = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList(); + @Override + protected void updateHandler() { + this.myHandler.setBaseAccess(AccessRestriction.WRITE); + this.myHandler.setWhitelist(this.getInstalledUpgrades(Upgrades.INVERTER) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST); + this.myHandler.setPriority(this.getPriority()); - final int slotsToUse = 18 + this.getInstalledUpgrades( Upgrades.CAPACITY ) * 9; - for( int x = 0; x < this.config.getSlots() && x < slotsToUse; x++ ) - { - final IAEFluidStack is = this.config.getFluidInSlot( x ); - if( is != null ) - { - priorityList.add( is ); - } - } - this.myHandler.setPartitionList( new PrecisePriorityList( priorityList ) ); + final IItemList priorityList = AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class).createList(); - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } + final int slotsToUse = 18 + this.getInstalledUpgrades(Upgrades.CAPACITY) * 9; + for (int x = 0; x < this.config.getSlots() && x < slotsToUse; x++) { + final IAEFluidStack is = this.config.getFluidInSlot(x); + if (is != null) { + priorityList.add(is); + } + } + this.myHandler.setPartitionList(new PrecisePriorityList(priorityList)); - @Override - public IAEFluidStack injectItems( IAEFluidStack input, Actionable type, IActionSource src ) - { - if( this.blocked || input == null || input.getStackSize() < Fluid.BUCKET_VOLUME ) - { - // need a full bucket - return input; - } + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } - final TileEntity te = this.getHost().getTile(); - final World w = te.getWorld(); - final AEPartLocation side = this.getSide(); - final BlockPos pos = te.getPos().offset( side.getFacing() ); - final IBlockState state = w.getBlockState( pos ); + @Override + public IAEFluidStack injectItems(IAEFluidStack input, Actionable type, IActionSource src) { + if (this.blocked || input == null || input.getStackSize() < Fluid.BUCKET_VOLUME) { + // need a full bucket + return input; + } - if( this.canReplace( w, state, state.getBlock(), pos ) ) - { - if( type == Actionable.MODULATE ) - { - final FluidStack fs = input.getFluidStack(); - fs.amount = Fluid.BUCKET_VOLUME; + final TileEntity te = this.getHost().getTile(); + final World w = te.getWorld(); + final AEPartLocation side = this.getSide(); + final BlockPos pos = te.getPos().offset(side.getFacing()); + final IBlockState state = w.getBlockState(pos); - final FluidTank tank = new FluidTank( fs, Fluid.BUCKET_VOLUME ); - if( !FluidUtil.tryPlaceFluid( null, w, pos, tank, fs ) ) - { - return input; - } - } - final IAEFluidStack ret = input.copy(); - ret.setStackSize( input.getStackSize() - Fluid.BUCKET_VOLUME ); - return ret.getStackSize() == 0 ? null : ret; - } - this.blocked = true; - return input; - } + if (this.canReplace(w, state, state.getBlock(), pos)) { + if (type == Actionable.MODULATE) { + final FluidStack fs = input.getFluidStack(); + fs.amount = Fluid.BUCKET_VOLUME; - private boolean canReplace( World w, IBlockState state, Block block, BlockPos pos ) - { - return block.isReplaceable( w, pos ) && !( block instanceof IFluidBlock ) && !( block instanceof BlockLiquid ) && !state.getMaterial().isLiquid(); - } + final FluidTank tank = new FluidTank(fs, Fluid.BUCKET_VOLUME); + if (!FluidUtil.tryPlaceFluid(null, w, pos, tank, fs)) { + return input; + } + } + final IAEFluidStack ret = input.copy(); + ret.setStackSize(input.getStackSize() - Fluid.BUCKET_VOLUME); + return ret.getStackSize() == 0 ? null : ret; + } + this.blocked = true; + return input; + } - @Override - public void onFluidInventoryChanged( IAEFluidTank inv, int slot ) - { - if( inv == this.config ) - { - this.updateHandler(); - } - } + private boolean canReplace(World w, IBlockState state, Block block, BlockPos pos) { + return block.isReplaceable(w, pos) && !(block instanceof IFluidBlock) && !(block instanceof BlockLiquid) && !state.getMaterial().isLiquid(); + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.config.readFromNBT( data, "config" ); - this.updateHandler(); - } + @Override + public void onFluidInventoryChanged(IAEFluidTank inv, int slot) { + if (inv == this.config) { + this.updateHandler(); + } + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.config.writeToNBT( data, "config" ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.config.readFromNBT(data, "config"); + this.updateHandler(); + } - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.stateChanged(); - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.config.writeToNBT(data, "config"); + } - @Override - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged changedChannels ) - { - this.stateChanged(); - } + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.stateChanged(); + } - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_FLUID_FORMATION_PLANE ); - } + @Override + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged changedChannels) { + this.stateChanged(); + } - return true; - } + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_FLUID_FORMATION_PLANE); + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ); - } + return true; + } - @Override - public List getCellArray( final IStorageChannel channel ) - { - if( channel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) - { - final List handler = new ArrayList<>( 1 ); - handler.add( this.myHandler ); - return handler; - } - return Collections.emptyList(); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class); + } - @Override - public IPartModel getStaticModels() - { - return MODELS.getModel( this.getConnections(), this.isPowered(), this.isActive() ); - } + @Override + public List getCellArray(final IStorageChannel channel) { + if (channel == AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)) { + final List handler = new ArrayList<>(1); + handler.add(this.myHandler); + return handler; + } + return Collections.emptyList(); + } - public IAEFluidTank getConfig() - { - return this.config; - } + @Override + public IPartModel getStaticModels() { + return MODELS.getModel(this.getConnections(), this.isPowered(), this.isActive()); + } - @Override - public IFluidHandler getFluidInventoryByName( final String name) { - if (name.equals("config")) { - return this.config; - } - return null; - } + public IAEFluidTank getConfig() { + return this.config; + } - @Override - public ItemStack getItemStackRepresentation() - { - return AEApi.instance().definitions().parts().fluidFormationnPlane().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - } + @Override + public IFluidHandler getFluidInventoryByName(final String name) { + if (name.equals("config")) { + return this.config; + } + return null; + } - @Override - public GuiBridge getGuiBridge() - { - return GuiBridge.GUI_FLUID_FORMATION_PLANE; - } + @Override + public ItemStack getItemStackRepresentation() { + return AEApi.instance().definitions().parts().fluidFormationnPlane().maybeStack(1).orElse(ItemStack.EMPTY); + } + + @Override + public GuiBridge getGuiBridge() { + return GuiBridge.GUI_FLUID_FORMATION_PLANE; + } } diff --git a/src/main/java/appeng/fluids/parts/PartFluidImportBus.java b/src/main/java/appeng/fluids/parts/PartFluidImportBus.java index 4c2e5f7aa..2f60fdafd 100644 --- a/src/main/java/appeng/fluids/parts/PartFluidImportBus.java +++ b/src/main/java/appeng/fluids/parts/PartFluidImportBus.java @@ -19,21 +19,7 @@ package appeng.fluids.parts; -import javax.annotation.Nonnull; - -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandler; - -import appeng.api.config.Actionable; -import appeng.api.config.FuzzyMode; -import appeng.api.config.RedstoneMode; -import appeng.api.config.SchedulingMode; -import appeng.api.config.Settings; -import appeng.api.config.YesNo; +import appeng.api.config.*; import appeng.api.networking.IGridNode; import appeng.api.networking.security.IActionSource; import appeng.api.networking.ticking.TickRateModulation; @@ -48,6 +34,14 @@ import appeng.items.parts.PartModels; import appeng.me.GridAccessException; import appeng.me.helpers.MachineSource; import appeng.parts.PartModel; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; +import net.minecraftforge.fluids.capability.IFluidHandler; + +import javax.annotation.Nonnull; /** @@ -55,147 +49,119 @@ import appeng.parts.PartModel; * @version rv6 - 30/04/2018 * @since rv6 30/04/2018 */ -public class PartFluidImportBus extends PartSharedFluidBus -{ - public static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "part/fluid_import_bus_base" ); - @PartModels - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/fluid_import_bus_off" ) ); - @PartModels - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/fluid_import_bus_on" ) ); - @PartModels - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/fluid_import_bus_has_channel" ) ); +public class PartFluidImportBus extends PartSharedFluidBus { + public static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "part/fluid_import_bus_base"); + @PartModels + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/fluid_import_bus_off")); + @PartModels + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/fluid_import_bus_on")); + @PartModels + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/fluid_import_bus_has_channel")); - private final IActionSource source; + private final IActionSource source; - public PartFluidImportBus( ItemStack is ) - { - super( is ); - this.getConfigManager().registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.CRAFT_ONLY, YesNo.NO ); - this.getConfigManager().registerSetting( Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT ); - this.source = new MachineSource( this ); - } + public PartFluidImportBus(ItemStack is) { + super(is); + this.getConfigManager().registerSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.getConfigManager().registerSetting(Settings.CRAFT_ONLY, YesNo.NO); + this.getConfigManager().registerSetting(Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT); + this.source = new MachineSource(this); + } - @Override - public TickingRequest getTickingRequest( IGridNode node ) - { - return new TickingRequest( TickRates.FluidImportBus.getMin(), TickRates.FluidImportBus.getMax(), this.isSleeping(), false ); - } + @Override + public TickingRequest getTickingRequest(IGridNode node) { + return new TickingRequest(TickRates.FluidImportBus.getMin(), TickRates.FluidImportBus.getMax(), this.isSleeping(), false); + } - @Override - public TickRateModulation tickingRequest( IGridNode node, int ticksSinceLastCall ) - { - return this.canDoBusWork() ? this.doBusWork() : TickRateModulation.IDLE; - } + @Override + public TickRateModulation tickingRequest(IGridNode node, int ticksSinceLastCall) { + return this.canDoBusWork() ? this.doBusWork() : TickRateModulation.IDLE; + } - @Override - protected TickRateModulation doBusWork() - { - if( !this.canDoBusWork() ) - { - return TickRateModulation.IDLE; - } + @Override + protected TickRateModulation doBusWork() { + if (!this.canDoBusWork()) { + return TickRateModulation.IDLE; + } - final TileEntity te = this.getConnectedTE(); + final TileEntity te = this.getConnectedTE(); - if( te != null && te.hasCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing().getOpposite() ) ) - { - try - { - final IFluidHandler fh = te.getCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing().getOpposite() ); - final IMEMonitor inv = this.getProxy().getStorage().getInventory( this.getChannel() ); + if (te != null && te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing().getOpposite())) { + try { + final IFluidHandler fh = te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing().getOpposite()); + final IMEMonitor inv = this.getProxy().getStorage().getInventory(this.getChannel()); - if( fh != null ) - { - final FluidStack fluidStack = fh.drain( this.calculateAmountToSend(), false ); + if (fh != null) { + final FluidStack fluidStack = fh.drain(this.calculateAmountToSend(), false); - if( this.filterEnabled() && !this.isInFilter( fluidStack ) ) - { - return TickRateModulation.SLOWER; - } + if (this.filterEnabled() && !this.isInFilter(fluidStack)) { + return TickRateModulation.SLOWER; + } - final AEFluidStack aeFluidStack = AEFluidStack.fromFluidStack( fluidStack ); + final AEFluidStack aeFluidStack = AEFluidStack.fromFluidStack(fluidStack); - if( aeFluidStack != null ) - { - final IAEFluidStack notInserted = inv.injectItems( aeFluidStack, Actionable.MODULATE, this.source ); + if (aeFluidStack != null) { + final IAEFluidStack notInserted = inv.injectItems(aeFluidStack, Actionable.MODULATE, this.source); - if( notInserted != null && notInserted.getStackSize() > 0 ) - { - aeFluidStack.decStackSize( notInserted.getStackSize() ); - } + if (notInserted != null && notInserted.getStackSize() > 0) { + aeFluidStack.decStackSize(notInserted.getStackSize()); + } - fh.drain( aeFluidStack.getFluidStack(), true ); + fh.drain(aeFluidStack.getFluidStack(), true); - return TickRateModulation.FASTER; - } + return TickRateModulation.FASTER; + } - return TickRateModulation.IDLE; - } - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - } + return TickRateModulation.IDLE; + } + } catch (GridAccessException e) { + e.printStackTrace(); + } + } - return TickRateModulation.SLEEP; - } + return TickRateModulation.SLEEP; + } - @Override - protected boolean canDoBusWork() - { - return this.getProxy().isActive(); - } + @Override + protected boolean canDoBusWork() { + return this.getProxy().isActive(); + } - private boolean isInFilter( FluidStack fluid ) - { - for( int i = 0; i < this.getConfig().getSlots(); i++ ) - { - final IAEFluidStack stack = this.getConfig().getFluidInSlot( i ); - if( stack != null && stack.equals( fluid ) ) - { - return true; - } - } - return false; - } + private boolean isInFilter(FluidStack fluid) { + for (int i = 0; i < this.getConfig().getSlots(); i++) { + final IAEFluidStack stack = this.getConfig().getFluidInSlot(i); + if (stack != null && stack.equals(fluid)) { + return true; + } + } + return false; + } - private boolean filterEnabled() - { - for( int i = 0; i < this.getConfig().getSlots(); i++ ) - { - final IAEFluidStack stack = this.getConfig().getFluidInSlot( i ); - if( stack != null ) - { - return true; - } - } - return false; - } + private boolean filterEnabled() { + for (int i = 0; i < this.getConfig().getSlots(); i++) { + final IAEFluidStack stack = this.getConfig().getFluidInSlot(i); + if (stack != null) { + return true; + } + } + return false; + } - @Override - public RedstoneMode getRSMode() - { - return (RedstoneMode) this.getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ); - } + @Override + public RedstoneMode getRSMode() { + return (RedstoneMode) this.getConfigManager().getSetting(Settings.REDSTONE_CONTROLLED); + } - @Nonnull - @Override - public IPartModel getStaticModels() - { - if( this.isActive() && this.isPowered() ) - { - return MODELS_HAS_CHANNEL; - } - else if( this.isPowered() ) - { - return MODELS_ON; - } - else - { - return MODELS_OFF; - } - } + @Nonnull + @Override + public IPartModel getStaticModels() { + if (this.isActive() && this.isPowered()) { + return MODELS_HAS_CHANNEL; + } else if (this.isPowered()) { + return MODELS_ON; + } else { + return MODELS_OFF; + } + } } diff --git a/src/main/java/appeng/fluids/parts/PartFluidInterface.java b/src/main/java/appeng/fluids/parts/PartFluidInterface.java index 0e778eec6..be7519d86 100644 --- a/src/main/java/appeng/fluids/parts/PartFluidInterface.java +++ b/src/main/java/appeng/fluids/parts/PartFluidInterface.java @@ -19,21 +19,6 @@ package appeng.fluids.parts; -import java.util.EnumSet; - -import appeng.fluids.helper.IConfigurableFluidInventory; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.Vec3d; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.Upgrades; import appeng.api.networking.IGridNode; @@ -54,6 +39,7 @@ import appeng.api.util.IConfigManager; import appeng.core.AppEng; import appeng.core.sync.GuiBridge; import appeng.fluids.helper.DualityFluidInterface; +import appeng.fluids.helper.IConfigurableFluidInventory; import appeng.fluids.helper.IFluidInterfaceHost; import appeng.helpers.IPriorityHost; import appeng.helpers.Reflected; @@ -61,196 +47,177 @@ import appeng.items.parts.PartModels; import appeng.parts.PartBasicState; import appeng.parts.PartModel; import appeng.util.Platform; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.Vec3d; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.capability.IFluidHandler; +import net.minecraftforge.items.IItemHandler; + +import java.util.EnumSet; -public class PartFluidInterface extends PartBasicState implements IGridTickable, IStorageMonitorable, IFluidInterfaceHost, IPriorityHost, IConfigurableFluidInventory -{ - public static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "part/fluid_interface_base" ); +public class PartFluidInterface extends PartBasicState implements IGridTickable, IStorageMonitorable, IFluidInterfaceHost, IPriorityHost, IConfigurableFluidInventory { + public static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "part/fluid_interface_base"); - @PartModels - public static final PartModel MODELS_OFF = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/fluid_interface_off" ) ); + @PartModels + public static final PartModel MODELS_OFF = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/fluid_interface_off")); - @PartModels - public static final PartModel MODELS_ON = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/fluid_interface_on" ) ); + @PartModels + public static final PartModel MODELS_ON = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/fluid_interface_on")); - @PartModels - public static final PartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/fluid_interface_has_channel" ) ); + @PartModels + public static final PartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/fluid_interface_has_channel")); - private final DualityFluidInterface duality = new DualityFluidInterface( this.getProxy(), this ); + private final DualityFluidInterface duality = new DualityFluidInterface(this.getProxy(), this); - @Reflected - public PartFluidInterface( final ItemStack is ) - { - super( is ); - } + @Reflected + public PartFluidInterface(final ItemStack is) { + super(is); + } - @Override - public DualityFluidInterface getDualityFluidInterface() - { - return this.duality; - } + @Override + public DualityFluidInterface getDualityFluidInterface() { + return this.duality; + } - @Override - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - this.duality.notifyNeighbors(); - } + @Override + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + this.duality.notifyNeighbors(); + } - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.duality.notifyNeighbors(); - } + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.duality.notifyNeighbors(); + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 2, 2, 14, 14, 14, 16 ); - bch.addBox( 5, 5, 12, 11, 11, 14 ); - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + bch.addBox(5, 5, 12, 11, 11, 14); + } - @Override - public void gridChanged() - { - this.duality.gridChanged(); - } + @Override + public void gridChanged() { + this.duality.gridChanged(); + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.duality.readFromNBT( data ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.duality.readFromNBT(data); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.duality.writeToNBT( data ); - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.duality.writeToNBT(data); + } - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 4; - } + @Override + public float getCableConnectionLength(AECableType cable) { + return 4; + } - @Override - public boolean onPartActivate( final EntityPlayer p, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, this.getTileEntity(), this.getSide(), GuiBridge.GUI_FLUID_INTERFACE ); - } + @Override + public boolean onPartActivate(final EntityPlayer p, final EnumHand hand, final Vec3d pos) { + if (Platform.isServer()) { + Platform.openGUI(p, this.getTileEntity(), this.getSide(), GuiBridge.GUI_FLUID_INTERFACE); + } - return true; - } + return true; + } - @Override - public > IMEMonitor getInventory( IStorageChannel channel ) - { - return this.duality.getInventory( channel ); - } + @Override + public > IMEMonitor getInventory(IStorageChannel channel) { + return this.duality.getInventory(channel); + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return this.duality.getTickingRequest( node ); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return this.duality.getTickingRequest(node); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.duality.tickingRequest( node, ticksSinceLastCall ); - } + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.duality.tickingRequest(node, ticksSinceLastCall); + } - @Override - public EnumSet getTargets() - { - return EnumSet.of( this.getSide().getFacing() ); - } + @Override + public EnumSet getTargets() { + return EnumSet.of(this.getSide().getFacing()); + } - @Override - public TileEntity getTileEntity() - { - return super.getHost().getTile(); - } + @Override + public TileEntity getTileEntity() { + return super.getHost().getTile(); + } - @Override - public IPartModel getStaticModels() - { - if( this.isActive() && this.isPowered() ) - { - return MODELS_HAS_CHANNEL; - } - else if( this.isPowered() ) - { - return MODELS_ON; - } - else - { - return MODELS_OFF; - } - } + @Override + public IPartModel getStaticModels() { + if (this.isActive() && this.isPowered()) { + return MODELS_HAS_CHANNEL; + } else if (this.isPowered()) { + return MODELS_ON; + } else { + return MODELS_OFF; + } + } - @Override - public int getPriority() - { - return this.duality.getPriority(); - } + @Override + public int getPriority() { + return this.duality.getPriority(); + } - @Override - public void setPriority( final int newValue ) - { - this.duality.setPriority( newValue ); - } + @Override + public void setPriority(final int newValue) { + this.duality.setPriority(newValue); + } - @Override - public boolean hasCapability( Capability capabilityClass ) - { - return this.duality.hasCapability( capabilityClass, this.getSide().getFacing() ); - } + @Override + public boolean hasCapability(Capability capabilityClass) { + return this.duality.hasCapability(capabilityClass, this.getSide().getFacing()); + } - @Override - public T getCapability( Capability capabilityClass ) - { - return this.duality.getCapability( capabilityClass, this.getSide().getFacing() ); - } + @Override + public T getCapability(Capability capabilityClass) { + return this.duality.getCapability(capabilityClass, this.getSide().getFacing()); + } - @Override - public int getInstalledUpgrades( Upgrades u ) - { - return this.duality.getInstalledUpgrades( u ); - } + @Override + public int getInstalledUpgrades(Upgrades u) { + return this.duality.getInstalledUpgrades(u); + } - @Override - public IConfigManager getConfigManager() - { - return this.duality.getConfigManager(); - } + @Override + public IConfigManager getConfigManager() { + return this.duality.getConfigManager(); + } - @Override - public IItemHandler getInventoryByName( String name ) - { - return this.duality.getInventoryByName( name ); - } + @Override + public IItemHandler getInventoryByName(String name) { + return this.duality.getInventoryByName(name); + } - @Override - public IFluidHandler getFluidInventoryByName( final String name) { - return this.duality.getFluidInventoryByName(name); - } + @Override + public IFluidHandler getFluidInventoryByName(final String name) { + return this.duality.getFluidInventoryByName(name); + } - @Override - public ItemStack getItemStackRepresentation() - { - return AEApi.instance().definitions().parts().fluidIface().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - } + @Override + public ItemStack getItemStackRepresentation() { + return AEApi.instance().definitions().parts().fluidIface().maybeStack(1).orElse(ItemStack.EMPTY); + } - @Override - public GuiBridge getGuiBridge() - { - return GuiBridge.GUI_FLUID_INTERFACE; - } + @Override + public GuiBridge getGuiBridge() { + return GuiBridge.GUI_FLUID_INTERFACE; + } } diff --git a/src/main/java/appeng/fluids/parts/PartFluidLevelEmitter.java b/src/main/java/appeng/fluids/parts/PartFluidLevelEmitter.java index efbf862c4..d1bf51ad7 100644 --- a/src/main/java/appeng/fluids/parts/PartFluidLevelEmitter.java +++ b/src/main/java/appeng/fluids/parts/PartFluidLevelEmitter.java @@ -1,23 +1,6 @@ - package appeng.fluids.parts; -import java.util.Random; - -import appeng.api.storage.data.IItemList; -import appeng.fluids.helper.IConfigurableFluidInventory; -import appeng.me.cache.NetworkMonitor; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumHand; -import net.minecraft.util.EnumParticleTypes; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; - import appeng.api.AEApi; import appeng.api.config.RedstoneMode; import appeng.api.config.Settings; @@ -36,362 +19,314 @@ import appeng.api.storage.IStorageChannel; import appeng.api.storage.channels.IFluidStorageChannel; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEStack; +import appeng.api.storage.data.IItemList; import appeng.api.util.AECableType; import appeng.api.util.AEPartLocation; import appeng.api.util.IConfigManager; import appeng.core.AppEng; import appeng.core.sync.GuiBridge; +import appeng.fluids.helper.IConfigurableFluidInventory; import appeng.fluids.util.AEFluidInventory; import appeng.fluids.util.IAEFluidInventory; import appeng.fluids.util.IAEFluidTank; import appeng.items.parts.PartModels; import appeng.me.GridAccessException; +import appeng.me.cache.NetworkMonitor; import appeng.parts.PartModel; import appeng.parts.automation.PartUpgradeable; import appeng.util.IConfigManagerHost; import appeng.util.Platform; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumHand; +import net.minecraft.util.EnumParticleTypes; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; +import net.minecraft.world.World; import net.minecraftforge.fluids.capability.IFluidHandler; +import java.util.Random; -public class PartFluidLevelEmitter extends PartUpgradeable implements IStackWatcherHost, IConfigManagerHost, IAEFluidInventory, IMEMonitorHandlerReceiver, IConfigurableFluidInventory -{ - @PartModels - public static final ResourceLocation MODEL_BASE_OFF = new ResourceLocation( AppEng.MOD_ID, "part/level_emitter_base_off" ); - @PartModels - public static final ResourceLocation MODEL_BASE_ON = new ResourceLocation( AppEng.MOD_ID, "part/level_emitter_base_on" ); - @PartModels - public static final ResourceLocation MODEL_STATUS_OFF = new ResourceLocation( AppEng.MOD_ID, "part/level_emitter_status_off" ); - @PartModels - public static final ResourceLocation MODEL_STATUS_ON = new ResourceLocation( AppEng.MOD_ID, "part/level_emitter_status_on" ); - @PartModels - public static final ResourceLocation MODEL_STATUS_HAS_CHANNEL = new ResourceLocation( AppEng.MOD_ID, "part/level_emitter_status_has_channel" ); - public static final PartModel MODEL_OFF_OFF = new PartModel( MODEL_BASE_OFF, MODEL_STATUS_OFF ); - public static final PartModel MODEL_OFF_ON = new PartModel( MODEL_BASE_OFF, MODEL_STATUS_ON ); - public static final PartModel MODEL_OFF_HAS_CHANNEL = new PartModel( MODEL_BASE_OFF, MODEL_STATUS_HAS_CHANNEL ); - public static final PartModel MODEL_ON_OFF = new PartModel( MODEL_BASE_ON, MODEL_STATUS_OFF ); - public static final PartModel MODEL_ON_ON = new PartModel( MODEL_BASE_ON, MODEL_STATUS_ON ); - public static final PartModel MODEL_ON_HAS_CHANNEL = new PartModel( MODEL_BASE_ON, MODEL_STATUS_HAS_CHANNEL ); +public class PartFluidLevelEmitter extends PartUpgradeable implements IStackWatcherHost, IConfigManagerHost, IAEFluidInventory, IMEMonitorHandlerReceiver, IConfigurableFluidInventory { + @PartModels + public static final ResourceLocation MODEL_BASE_OFF = new ResourceLocation(AppEng.MOD_ID, "part/level_emitter_base_off"); + @PartModels + public static final ResourceLocation MODEL_BASE_ON = new ResourceLocation(AppEng.MOD_ID, "part/level_emitter_base_on"); + @PartModels + public static final ResourceLocation MODEL_STATUS_OFF = new ResourceLocation(AppEng.MOD_ID, "part/level_emitter_status_off"); + @PartModels + public static final ResourceLocation MODEL_STATUS_ON = new ResourceLocation(AppEng.MOD_ID, "part/level_emitter_status_on"); + @PartModels + public static final ResourceLocation MODEL_STATUS_HAS_CHANNEL = new ResourceLocation(AppEng.MOD_ID, "part/level_emitter_status_has_channel"); - private static final int FLAG_ON = 4; + public static final PartModel MODEL_OFF_OFF = new PartModel(MODEL_BASE_OFF, MODEL_STATUS_OFF); + public static final PartModel MODEL_OFF_ON = new PartModel(MODEL_BASE_OFF, MODEL_STATUS_ON); + public static final PartModel MODEL_OFF_HAS_CHANNEL = new PartModel(MODEL_BASE_OFF, MODEL_STATUS_HAS_CHANNEL); + public static final PartModel MODEL_ON_OFF = new PartModel(MODEL_BASE_ON, MODEL_STATUS_OFF); + public static final PartModel MODEL_ON_ON = new PartModel(MODEL_BASE_ON, MODEL_STATUS_ON); + public static final PartModel MODEL_ON_HAS_CHANNEL = new PartModel(MODEL_BASE_ON, MODEL_STATUS_HAS_CHANNEL); - private boolean prevState = false; - private long lastReportedValue = 0; - private long reportingValue = 0; - private IStackWatcher stackWatcher = null; - private final AEFluidInventory config = new AEFluidInventory( this, 1 ); + private static final int FLAG_ON = 4; - public PartFluidLevelEmitter( ItemStack is ) - { - super( is ); + private boolean prevState = false; + private long lastReportedValue = 0; + private long reportingValue = 0; + private IStackWatcher stackWatcher = null; + private final AEFluidInventory config = new AEFluidInventory(this, 1); - this.getConfigManager().registerSetting( Settings.REDSTONE_EMITTER, RedstoneMode.HIGH_SIGNAL ); - } + public PartFluidLevelEmitter(ItemStack is) { + super(is); - public long getReportingValue() - { - return this.reportingValue; - } + this.getConfigManager().registerSetting(Settings.REDSTONE_EMITTER, RedstoneMode.HIGH_SIGNAL); + } - public void setReportingValue( final long v ) - { - this.reportingValue = v; - this.updateState(); - } + public long getReportingValue() { + return this.reportingValue; + } - @Override - public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) - { - this.configureWatchers(); - } + public void setReportingValue(final long v) { + this.reportingValue = v; + this.updateState(); + } - @Override - public void updateWatcher( IStackWatcher newWatcher ) - { - this.stackWatcher = newWatcher; - this.configureWatchers(); - } + @Override + public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) { + this.configureWatchers(); + } - @Override - public void onStackChange( IItemList o, IAEStack fullStack, IAEStack diffStack, IActionSource src, IStorageChannel chan ) - { - if( chan == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) && fullStack.equals( this.config.getFluidInSlot( 0 ) ) ) - { - this.lastReportedValue = fullStack.getStackSize(); - this.updateState(); - } - } + @Override + public void updateWatcher(IStackWatcher newWatcher) { + this.stackWatcher = newWatcher; + this.configureWatchers(); + } - @Override - public void onFluidInventoryChanged( IAEFluidTank inv, int slot ) - { - this.configureWatchers(); - } + @Override + public void onStackChange(IItemList o, IAEStack fullStack, IAEStack diffStack, IActionSource src, IStorageChannel chan) { + if (chan == AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class) && fullStack.equals(this.config.getFluidInSlot(0))) { + this.lastReportedValue = fullStack.getStackSize(); + this.updateState(); + } + } - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange powerEvent ) - { - if (this.getProxy().isActive()) - { - onListUpdate(); - } - this.updateState(); - } + @Override + public void onFluidInventoryChanged(IAEFluidTank inv, int slot) { + this.configureWatchers(); + } - @Override - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - if (this.getProxy().isActive()) - { - onListUpdate(); - } - this.updateState(); - } + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange powerEvent) { + if (this.getProxy().isActive()) { + onListUpdate(); + } + this.updateState(); + } - @Override - public int isProvidingStrongPower() - { - return this.prevState ? 15 : 0; - } + @Override + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + if (this.getProxy().isActive()) { + onListUpdate(); + } + this.updateState(); + } - @Override - public int isProvidingWeakPower() - { - return this.prevState ? 15 : 0; - } + @Override + public int isProvidingStrongPower() { + return this.prevState ? 15 : 0; + } - @Override - protected int populateFlags( final int cf ) - { - return cf | ( this.prevState ? FLAG_ON : 0 ); - } + @Override + public int isProvidingWeakPower() { + return this.prevState ? 15 : 0; + } - @Override - public boolean isValid( final Object effectiveGrid ) - { - try - { - return this.getProxy().getGrid() == effectiveGrid; - } - catch( final GridAccessException e ) - { - return false; - } - } + @Override + protected int populateFlags(final int cf) { + return cf | (this.prevState ? FLAG_ON : 0); + } - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final IActionSource actionSource ) - { - this.updateReportingValue( (IMEMonitor) monitor ); - } + @Override + public boolean isValid(final Object effectiveGrid) { + try { + return this.getProxy().getGrid() == effectiveGrid; + } catch (final GridAccessException e) { + return false; + } + } - @Override - public void onListUpdate() - { - try - { - final IStorageChannel channel = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ); - final IMEMonitor inventory = this.getProxy().getStorage().getInventory( channel ); + @Override + public void postChange(final IBaseMonitor monitor, final Iterable change, final IActionSource actionSource) { + this.updateReportingValue((IMEMonitor) monitor); + } - this.updateReportingValue( inventory ); - } - catch( final GridAccessException e ) - { - // ;P - } - } + @Override + public void onListUpdate() { + try { + final IStorageChannel channel = AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class); + final IMEMonitor inventory = this.getProxy().getStorage().getInventory(channel); - private void updateState() - { - final boolean isOn = this.isLevelEmitterOn(); - if( this.prevState != isOn ) - { - this.getHost().markForUpdate(); - final TileEntity te = this.getHost().getTile(); - this.prevState = isOn; - Platform.notifyBlocksOfNeighbors( te.getWorld(), te.getPos() ); - Platform.notifyBlocksOfNeighbors( te.getWorld(), te.getPos().offset( this.getSide().getFacing() ) ); - } - } + this.updateReportingValue(inventory); + } catch (final GridAccessException e) { + // ;P + } + } - private void configureWatchers() - { - final IFluidStorageChannel channel = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ); + private void updateState() { + final boolean isOn = this.isLevelEmitterOn(); + if (this.prevState != isOn) { + this.getHost().markForUpdate(); + final TileEntity te = this.getHost().getTile(); + this.prevState = isOn; + Platform.notifyBlocksOfNeighbors(te.getWorld(), te.getPos()); + Platform.notifyBlocksOfNeighbors(te.getWorld(), te.getPos().offset(this.getSide().getFacing())); + } + } - if( this.stackWatcher != null ) - { - this.stackWatcher.reset(); + private void configureWatchers() { + final IFluidStorageChannel channel = AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class); - final IAEFluidStack myStack = this.config.getFluidInSlot( 0 ); + if (this.stackWatcher != null) { + this.stackWatcher.reset(); - try - { - if( myStack != null ) - { - this.getProxy().getStorage().getInventory( channel ).removeListener( this ); - this.stackWatcher.add( myStack ); - } - else - { - this.getProxy() - .getStorage() - .getInventory( channel ) - .addListener( this, this.getProxy().getGrid() ); - } + final IAEFluidStack myStack = this.config.getFluidInSlot(0); - final IMEMonitor inventory = this.getProxy().getStorage().getInventory( channel ); + try { + if (myStack != null) { + this.getProxy().getStorage().getInventory(channel).removeListener(this); + this.stackWatcher.add(myStack); + } else { + this.getProxy() + .getStorage() + .getInventory(channel) + .addListener(this, this.getProxy().getGrid()); + } - this.updateReportingValue( inventory ); - } - catch( GridAccessException e ) - { - // NOP - } - } - } + final IMEMonitor inventory = this.getProxy().getStorage().getInventory(channel); - private void updateReportingValue( final IMEMonitor monitor ) - { - final IAEFluidStack myStack = this.config.getFluidInSlot( 0 ); + this.updateReportingValue(inventory); + } catch (GridAccessException e) { + // NOP + } + } + } - if( myStack == null ) - { - if( monitor instanceof NetworkMonitor ) - { - this.lastReportedValue = ( (NetworkMonitor) monitor ).getGridCurrentCount(); - } - } - else - { - final IAEFluidStack r = monitor.getStorageList().findPrecise( myStack ); - if( r == null ) - { - this.lastReportedValue = 0; - } - else - { - this.lastReportedValue = r.getStackSize(); - } - } - this.updateState(); - } + private void updateReportingValue(final IMEMonitor monitor) { + final IAEFluidStack myStack = this.config.getFluidInSlot(0); - private boolean isLevelEmitterOn() - { - if( Platform.isClient() ) - { - return ( this.getClientFlags() & FLAG_ON ) == FLAG_ON; - } + if (myStack == null) { + if (monitor instanceof NetworkMonitor) { + this.lastReportedValue = ((NetworkMonitor) monitor).getGridCurrentCount(); + } + } else { + final IAEFluidStack r = monitor.getStorageList().findPrecise(myStack); + if (r == null) { + this.lastReportedValue = 0; + } else { + this.lastReportedValue = r.getStackSize(); + } + } + this.updateState(); + } - if( !this.getProxy().isActive() ) - { - return false; - } + private boolean isLevelEmitterOn() { + if (Platform.isClient()) { + return (this.getClientFlags() & FLAG_ON) == FLAG_ON; + } - final boolean flipState = this.getConfigManager().getSetting( Settings.REDSTONE_EMITTER ) == RedstoneMode.LOW_SIGNAL; - return flipState ? this.reportingValue > this.lastReportedValue : this.reportingValue <= this.lastReportedValue; - } + if (!this.getProxy().isActive()) { + return false; + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.SMART; - } + final boolean flipState = this.getConfigManager().getSetting(Settings.REDSTONE_EMITTER) == RedstoneMode.LOW_SIGNAL; + return flipState == (this.reportingValue > this.lastReportedValue); + } - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 16; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.SMART; + } - @Override - public boolean canConnectRedstone() - { - return true; - } + @Override + public float getCableConnectionLength(AECableType cable) { + return 16; + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 7, 7, 11, 9, 9, 16 ); - } + @Override + public boolean canConnectRedstone() { + return true; + } - @Override - public void randomDisplayTick( final World world, final BlockPos pos, final Random r ) - { - if( this.isLevelEmitterOn() ) - { - final AEPartLocation d = this.getSide(); + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(7, 7, 11, 9, 9, 16); + } - final double d0 = d.xOffset * 0.45F + ( r.nextFloat() - 0.5F ) * 0.2D; - final double d1 = d.yOffset * 0.45F + ( r.nextFloat() - 0.5F ) * 0.2D; - final double d2 = d.zOffset * 0.45F + ( r.nextFloat() - 0.5F ) * 0.2D; + @Override + public void randomDisplayTick(final World world, final BlockPos pos, final Random r) { + if (this.isLevelEmitterOn()) { + final AEPartLocation d = this.getSide(); - world.spawnParticle( EnumParticleTypes.REDSTONE, 0.5 + pos.getX() + d0, 0.5 + pos.getY() + d1, 0.5 + pos.getZ() + d2, 0.0D, 0.0D, 0.0D, - new int[0] ); - } - } + final double d0 = d.xOffset * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; + final double d1 = d.yOffset * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; + final double d2 = d.zOffset * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_FLUID_LEVEL_EMITTER ); - } - return true; - } + world.spawnParticle(EnumParticleTypes.REDSTONE, 0.5 + pos.getX() + d0, 0.5 + pos.getY() + d1, 0.5 + pos.getZ() + d2, 0.0D, 0.0D, 0.0D + ); + } + } - @Override - public IPartModel getStaticModels() - { - if( this.isActive() && this.isPowered() ) - { - return this.isLevelEmitterOn() ? MODEL_ON_HAS_CHANNEL : MODEL_OFF_HAS_CHANNEL; - } - else if( this.isPowered() ) - { - return this.isLevelEmitterOn() ? MODEL_ON_ON : MODEL_OFF_ON; - } - else - { - return this.isLevelEmitterOn() ? MODEL_ON_OFF : MODEL_OFF_OFF; - } - } + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_FLUID_LEVEL_EMITTER); + } + return true; + } - public IAEFluidTank getConfig() - { - return this.config; - } + @Override + public IPartModel getStaticModels() { + if (this.isActive() && this.isPowered()) { + return this.isLevelEmitterOn() ? MODEL_ON_HAS_CHANNEL : MODEL_OFF_HAS_CHANNEL; + } else if (this.isPowered()) { + return this.isLevelEmitterOn() ? MODEL_ON_ON : MODEL_OFF_ON; + } else { + return this.isLevelEmitterOn() ? MODEL_ON_OFF : MODEL_OFF_OFF; + } + } - @Override - public IFluidHandler getFluidInventoryByName( final String name) { - if (name.equals("config")) { - return this.config; - } - return null; - } + public IAEFluidTank getConfig() { + return this.config; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.lastReportedValue = data.getLong( "lastReportedValue" ); - this.reportingValue = data.getLong( "reportingValue" ); - this.prevState = data.getBoolean( "prevState" ); - this.config.readFromNBT( data, "config" ); - } + @Override + public IFluidHandler getFluidInventoryByName(final String name) { + if (name.equals("config")) { + return this.config; + } + return null; + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setLong( "lastReportedValue", this.lastReportedValue ); - data.setLong( "reportingValue", this.reportingValue ); - data.setBoolean( "prevState", this.prevState ); - this.config.writeToNBT( data, "config" ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.lastReportedValue = data.getLong("lastReportedValue"); + this.reportingValue = data.getLong("reportingValue"); + this.prevState = data.getBoolean("prevState"); + this.config.readFromNBT(data, "config"); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setLong("lastReportedValue", this.lastReportedValue); + data.setLong("reportingValue", this.reportingValue); + data.setBoolean("prevState", this.prevState); + this.config.writeToNBT(data, "config"); + } } diff --git a/src/main/java/appeng/fluids/parts/PartFluidStorageBus.java b/src/main/java/appeng/fluids/parts/PartFluidStorageBus.java index effa3abf4..3c5b54403 100644 --- a/src/main/java/appeng/fluids/parts/PartFluidStorageBus.java +++ b/src/main/java/appeng/fluids/parts/PartFluidStorageBus.java @@ -19,8 +19,6 @@ package appeng.fluids.parts; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.networking.IGridNode; @@ -80,6 +78,8 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.fluids.capability.IFluidHandler; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -90,18 +90,17 @@ import java.util.Objects; * @version rv6 - 22/05/2018 * @since rv6 22/05/2018 */ -public class PartFluidStorageBus extends PartUpgradeable implements IGridTickable, ICellContainer, IMEMonitorHandlerReceiver, IAEFluidInventory, IConfigurableFluidInventory, IPriorityHost -{ - public static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "part/fluid_storage_bus_base" ); +public class PartFluidStorageBus extends PartUpgradeable implements IGridTickable, ICellContainer, IMEMonitorHandlerReceiver, IAEFluidInventory, IConfigurableFluidInventory, IPriorityHost { + public static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "part/fluid_storage_bus_base"); @PartModels - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/fluid_storage_bus_off" ) ); + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/fluid_storage_bus_off")); @PartModels - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/fluid_storage_bus_on" ) ); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/fluid_storage_bus_on")); @PartModels - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/fluid_storage_bus_has_channel" ) ); + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/fluid_storage_bus_has_channel")); private final IActionSource source; - private final AEFluidInventory config = new AEFluidInventory( this, 63 ); + private final AEFluidInventory config = new AEFluidInventory(this, 63); private int priority = 0; private boolean cached = false; private ITickingMonitor monitor = null; @@ -112,35 +111,28 @@ public class PartFluidStorageBus extends PartUpgradeable implements IGridTickabl private boolean accessChanged; private boolean readOncePass; - public PartFluidStorageBus( ItemStack is ) - { - super( is ); - this.getConfigManager().registerSetting( Settings.ACCESS, AccessRestriction.READ_WRITE ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY ); - this.source = new MachineSource( this ); + public PartFluidStorageBus(ItemStack is) { + super(is); + this.getConfigManager().registerSetting(Settings.ACCESS, AccessRestriction.READ_WRITE); + this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.getConfigManager().registerSetting(Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY); + this.source = new MachineSource(this); } @Override @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { + public void powerRender(final MENetworkPowerStatusChange c) { this.updateStatus(); } - protected void updateStatus() - { + protected void updateStatus() { final boolean currentActive = this.getProxy().isActive(); - if( this.wasActive != currentActive ) - { + if (this.wasActive != currentActive) { this.wasActive = currentActive; - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); this.getHost().markForUpdate(); - } - catch( final GridAccessException e ) - { + } catch (final GridAccessException e) { // :P } } @@ -148,277 +140,218 @@ public class PartFluidStorageBus extends PartUpgradeable implements IGridTickabl @Override @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged changedChannels ) - { + public void chanRender(final MENetworkChannelsChanged changedChannels) { this.updateStatus(); } @Override - protected int getUpgradeSlots() - { + protected int getUpgradeSlots() { return 5; } @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - if( settingName.name().equals( "ACCESS" ) ) - { + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + if (settingName.name().equals("ACCESS")) { this.accessChanged = true; } - this.resetCache( true ); + this.resetCache(true); this.getHost().markForSave(); } @Override - public void onFluidInventoryChanged( IAEFluidTank inv, int slot ) - { - if( inv == this.config ) - { - this.resetCache( true ); + public void onFluidInventoryChanged(IAEFluidTank inv, int slot) { + if (inv == this.config) { + this.resetCache(true); } } @Override - public void upgradesChanged() - { + public void upgradesChanged() { super.upgradesChanged(); - this.resetCache( true ); + this.resetCache(true); } @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.config.readFromNBT( data, "config" ); - this.priority = data.getInteger( "priority" ); + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.config.readFromNBT(data, "config"); + this.priority = data.getInteger("priority"); this.accessChanged = false; } @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.config.writeToNBT( data, "config" ); - data.setInteger( "priority", this.priority ); + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.config.writeToNBT(data, "config"); + data.setInteger("priority", this.priority); } @Override - public IFluidHandler getFluidInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { + public IFluidHandler getFluidInventoryByName(final String name) { + if (name.equals("config")) { return this.config; } return null; } - protected void resetCache( final boolean fullReset ) - { - if( this.getHost() == null || this.getHost().getTile() == null || this.getHost().getTile().getWorld() == null || this.getHost().getTile().getWorld().isRemote ) - { + protected void resetCache(final boolean fullReset) { + if (this.getHost() == null || this.getHost().getTile() == null || this.getHost().getTile().getWorld() == null || this.getHost().getTile().getWorld().isRemote) { return; } - if( fullReset ) - { + if (fullReset) { this.resetCacheLogic = 2; - } - else if( this.resetCacheLogic < 2 ) - { + } else if (this.resetCacheLogic < 2) { this.resetCacheLogic = 1; } - try - { - this.getProxy().getTick().alertDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { + try { + this.getProxy().getTick().alertDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { // :P } } @Override - public boolean isValid( final Object verificationToken ) - { + public boolean isValid(final Object verificationToken) { return this.handler == verificationToken; } @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final IActionSource source ) - { - if( this.getProxy().isActive() ) - { - AccessRestriction currentAccess = (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getSetting( Settings.ACCESS ); - if( readOncePass ) - { + public void postChange(final IBaseMonitor monitor, final Iterable change, final IActionSource source) { + if (this.getProxy().isActive()) { + AccessRestriction currentAccess = (AccessRestriction) ((ConfigManager) this.getConfigManager()).getSetting(Settings.ACCESS); + if (readOncePass) { readOncePass = false; - try - { - this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ), change, this.source ); - } - catch( final GridAccessException e ) - { + try { + this.getProxy().getStorage().postAlterationOfStoredItems(AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class), change, this.source); + } catch (final GridAccessException e) { // :( } return; } - if( !currentAccess.hasPermission( AccessRestriction.READ ) ) - { + if (!currentAccess.hasPermission(AccessRestriction.READ)) { return; } - try - { - this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ), change, source ); - } - catch( final GridAccessException e ) - { + try { + this.getProxy().getStorage().postAlterationOfStoredItems(AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class), change, source); + } catch (final GridAccessException e) { // :( } } } @Override - public void onListUpdate() - { + public void onListUpdate() { // not used here. } @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 3, 3, 15, 13, 13, 16 ); - bch.addBox( 2, 2, 14, 14, 14, 15 ); - bch.addBox( 5, 5, 12, 11, 11, 14 ); + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(3, 3, 15, 13, 13, 16); + bch.addBox(2, 2, 14, 14, 14, 15); + bch.addBox(5, 5, 12, 11, 11, 14); } @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - if( pos.offset( this.getSide().getFacing() ).equals( neighbor ) ) - { + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + if (pos.offset(this.getSide().getFacing()).equals(neighbor)) { - final TileEntity te = w.getTileEntity( neighbor ); + final TileEntity te = w.getTileEntity(neighbor); // In case the TE was destroyed, we have to do a full reset immediately. - if( te instanceof TileCableBus ) - { - IPart iPart = ( (TileCableBus) te ).getPart( this.getSide().getOpposite() ); - if( iPart == null || iPart instanceof PartFluidInterface ) - { - this.resetCache( true ); + if (te instanceof TileCableBus) { + IPart iPart = ((TileCableBus) te).getPart(this.getSide().getOpposite()); + if (iPart == null || iPart instanceof PartFluidInterface) { + this.resetCache(true); this.resetCache(); } - } - else if( te == null || te instanceof TileFluidInterface ) - { - this.resetCache( true ); + } else if (te == null || te instanceof TileFluidInterface) { + this.resetCache(true); this.resetCache(); - } - else - { - this.resetCache( false ); + } else { + this.resetCache(false); } } } @Override - public float getCableConnectionLength( AECableType cable ) - { + public float getCableConnectionLength(AECableType cable) { return 4; } @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_STORAGEBUS_FLUID ); + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_STORAGEBUS_FLUID); } return true; } @Override - public TickingRequest getTickingRequest( IGridNode node ) - { - return new TickingRequest( TickRates.FluidStorageBus.getMin(), TickRates.FluidStorageBus.getMax(), monitor == null, true ); + public TickingRequest getTickingRequest(IGridNode node) { + return new TickingRequest(TickRates.FluidStorageBus.getMin(), TickRates.FluidStorageBus.getMax(), monitor == null, true); } @Override - public TickRateModulation tickingRequest( IGridNode node, int ticksSinceLastCall ) - { - if( this.resetCacheLogic != 0 ) - { + public TickRateModulation tickingRequest(IGridNode node, int ticksSinceLastCall) { + if (this.resetCacheLogic != 0) { this.resetCache(); } - if( this.monitor != null ) - { + if (this.monitor != null) { return this.monitor.onTick(); } return TickRateModulation.SLEEP; } - protected void resetCache() - { + protected void resetCache() { final boolean fullReset = this.resetCacheLogic == 2; this.resetCacheLogic = 0; final MEInventoryHandler in = this.getInternalHandler(); - IItemList before = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList(); - if( in != null ) - { - if( accessChanged ) - { - AccessRestriction currentAccess = (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getSetting( Settings.ACCESS ); - AccessRestriction oldAccess = (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getOldSetting( Settings.ACCESS ); - if( oldAccess.hasPermission( AccessRestriction.READ ) && !currentAccess.hasPermission( AccessRestriction.READ ) ) - { + IItemList before = AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class).createList(); + if (in != null) { + if (accessChanged) { + AccessRestriction currentAccess = (AccessRestriction) ((ConfigManager) this.getConfigManager()).getSetting(Settings.ACCESS); + AccessRestriction oldAccess = (AccessRestriction) ((ConfigManager) this.getConfigManager()).getOldSetting(Settings.ACCESS); + if (oldAccess.hasPermission(AccessRestriction.READ) && !currentAccess.hasPermission(AccessRestriction.READ)) { readOncePass = true; } - in.setBaseAccess( oldAccess ); - before = in.getAvailableItems( before ); - in.setBaseAccess( currentAccess ); + in.setBaseAccess(oldAccess); + before = in.getAvailableItems(before); + in.setBaseAccess(currentAccess); accessChanged = false; - } - else - { - before = in.getAvailableItems( before ); + } else { + before = in.getAvailableItems(before); } } this.cached = false; - if( fullReset ) - { + if (fullReset) { this.handlerHash = 0; } final MEInventoryHandler out = this.getInternalHandler(); - IItemList after = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList(); + IItemList after = AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class).createList(); - if( in != out ) - { - if( out != null ) - { - after = out.getAvailableItems( after ); + if (in != out) { + if (out != null) { + after = out.getAvailableItems(after); } - Platform.postListChanges( before, after, this, this.source ); + Platform.postListChanges(before, after, this, this.source); } } - private IMEInventory getInventoryWrapper( TileEntity target ) - { + private IMEInventory getInventoryWrapper(TileEntity target) { EnumFacing targetSide = this.getSide().getFacing().getOpposite(); // Prioritize a handler to directly link to another ME network - IStorageMonitorableAccessor accessor = target.getCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide ); - if( accessor != null ) - { - IStorageMonitorable inventory = accessor.getInventory( this.source ); - if( inventory != null ) - { - return inventory.getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ); + IStorageMonitorableAccessor accessor = target.getCapability(Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide); + if (accessor != null) { + IStorageMonitorable inventory = accessor.getInventory(this.source); + if (inventory != null) { + return inventory.getInventory(AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)); } // So this could / can be a design decision. If the tile does support our custom capability, @@ -429,43 +362,36 @@ public class PartFluidStorageBus extends PartUpgradeable implements IGridTickabl } // Check via cap for IItemHandler - IFluidHandler handlerExt = target.getCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, targetSide ); - if( handlerExt != null ) - { - return new FluidHandlerAdapter( handlerExt, this ); + IFluidHandler handlerExt = target.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, targetSide); + if (handlerExt != null) { + return new FluidHandlerAdapter(handlerExt, this); } return null; } - private int createHandlerHash( TileEntity target ) - { - if( target == null ) - { + private int createHandlerHash(TileEntity target) { + if (target == null) { return 0; } final EnumFacing targetSide = this.getSide().getFacing().getOpposite(); - if( target.hasCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide ) ) - { - return Objects.hash( target, target.getCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide ) ); + if (target.hasCapability(Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide)) { + return Objects.hash(target, target.getCapability(Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide)); } - final IFluidHandler fluidHandler = target.getCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, targetSide ); + final IFluidHandler fluidHandler = target.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, targetSide); - if( fluidHandler != null ) - { - return Objects.hash( target, fluidHandler, fluidHandler.getTankProperties().length ); + if (fluidHandler != null) { + return Objects.hash(target, fluidHandler, fluidHandler.getTankProperties().length); } return 0; } - public MEInventoryHandler getInternalHandler() - { - if( this.cached ) - { + public MEInventoryHandler getInternalHandler() { + if (this.cached) { return this.handler; } @@ -473,98 +399,76 @@ public class PartFluidStorageBus extends PartUpgradeable implements IGridTickabl this.cached = true; final TileEntity self = this.getHost().getTile(); - final TileEntity target = self.getWorld().getTileEntity( self.getPos().offset( this.getSide().getFacing() ) ); - final int newHandlerHash = this.createHandlerHash( target ); + final TileEntity target = self.getWorld().getTileEntity(self.getPos().offset(this.getSide().getFacing())); + final int newHandlerHash = this.createHandlerHash(target); - if( newHandlerHash != 0 && newHandlerHash == this.handlerHash ) - { + if (newHandlerHash != 0 && newHandlerHash == this.handlerHash) { return this.handler; } this.handlerHash = newHandlerHash; this.handler = null; - if( this.monitor != null ) - { - ( (IBaseMonitor) monitor ).removeListener( this ); + if (this.monitor != null) { + ((IBaseMonitor) monitor).removeListener(this); } this.monitor = null; - if( target != null ) - { - IMEInventory inv = this.getInventoryWrapper( target ); - if( inv instanceof ITickingMonitor ) - { + if (target != null) { + IMEInventory inv = this.getInventoryWrapper(target); + if (inv instanceof ITickingMonitor) { this.monitor = (ITickingMonitor) inv; - this.monitor.setActionSource( this.source ); - this.monitor.setMode( (StorageFilter) this.getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); + this.monitor.setActionSource(this.source); + this.monitor.setMode((StorageFilter) this.getConfigManager().getSetting(Settings.STORAGE_FILTER)); } - if( inv != null ) - { - this.handler = new MEInventoryHandler<>( inv, AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ); + if (inv != null) { + this.handler = new MEInventoryHandler<>(inv, AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)); - this.handler.setBaseAccess( (AccessRestriction) this.getConfigManager().getSetting( Settings.ACCESS ) ); - this.handler.setWhitelist( this.getInstalledUpgrades( Upgrades.INVERTER ) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST ); - this.handler.setPriority( this.getPriority() ); + this.handler.setBaseAccess((AccessRestriction) this.getConfigManager().getSetting(Settings.ACCESS)); + this.handler.setWhitelist(this.getInstalledUpgrades(Upgrades.INVERTER) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST); + this.handler.setPriority(this.getPriority()); - final IItemList priorityList = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList(); + final IItemList priorityList = AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class).createList(); - final int slotsToUse = 18 + this.getInstalledUpgrades( Upgrades.CAPACITY ) * 9; - for( int x = 0; x < this.config.getSlots() && x < slotsToUse; x++ ) - { - final IAEFluidStack is = this.config.getFluidInSlot( x ); - if( is != null ) - { - priorityList.add( is ); + final int slotsToUse = 18 + this.getInstalledUpgrades(Upgrades.CAPACITY) * 9; + for (int x = 0; x < this.config.getSlots() && x < slotsToUse; x++) { + final IAEFluidStack is = this.config.getFluidInSlot(x); + if (is != null) { + priorityList.add(is); } } - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - this.handler.setPartitionList( new FuzzyPriorityList( priorityList, (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ) ) ); - } - else - { - this.handler.setPartitionList( new PrecisePriorityList( priorityList ) ); + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + this.handler.setPartitionList(new FuzzyPriorityList(priorityList, (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE))); + } else { + this.handler.setPartitionList(new PrecisePriorityList(priorityList)); } - if( inv instanceof IBaseMonitor ) - { - if( ( (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getSetting( Settings.ACCESS ) ).hasPermission( AccessRestriction.READ ) ) - { - ( (IBaseMonitor) inv ).addListener( this, this.handler ); + if (inv instanceof IBaseMonitor) { + if (((AccessRestriction) ((ConfigManager) this.getConfigManager()).getSetting(Settings.ACCESS)).hasPermission(AccessRestriction.READ)) { + ((IBaseMonitor) inv).addListener(this, this.handler); } } } } // update sleep state... - if( wasSleeping != ( this.monitor == null ) ) - { - try - { + if (wasSleeping != (this.monitor == null)) { + try { final ITickManager tm = this.getProxy().getTick(); - if( this.monitor == null ) - { - tm.sleepDevice( this.getProxy().getNode() ); + if (this.monitor == null) { + tm.sleepDevice(this.getProxy().getNode()); + } else { + tm.wakeDevice(this.getProxy().getNode()); } - else - { - tm.wakeDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException ignore ) - { + } catch (final GridAccessException ignore) { // :( } } - try - { + try { // force grid to update handlers... - ( (GridStorageCache) this.getProxy().getGrid().getCache( IStorageGrid.class ) ).cellUpdate( null ); - } - catch( final GridAccessException e ) - { + ((GridStorageCache) this.getProxy().getGrid().getCache(IStorageGrid.class)).cellUpdate(null); + } catch (final GridAccessException e) { // :3 } @@ -572,77 +476,61 @@ public class PartFluidStorageBus extends PartUpgradeable implements IGridTickabl } @Override - public List getCellArray( final IStorageChannel channel ) - { - if( channel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) - { + public List getCellArray(final IStorageChannel channel) { + if (channel == AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)) { final IMEInventoryHandler out = this.getInternalHandler(); - if( out != null ) - { - return Collections.singletonList( out ); + if (out != null) { + return Collections.singletonList(out); } } return Collections.emptyList(); } @Override - public int getPriority() - { + public int getPriority() { return this.priority; } @Override - public void setPriority( int newValue ) - { + public void setPriority(int newValue) { this.priority = newValue; this.getHost().markForSave(); - this.resetCache( true ); + this.resetCache(true); } @Override - public void blinkCell( int slot ) - { + public void blinkCell(int slot) { } @Override - public void saveChanges( @Nullable ICellInventory cellInventory ) - { + public void saveChanges(@Nullable ICellInventory cellInventory) { } - public IAEFluidTank getConfig() - { + public IAEFluidTank getConfig() { return this.config; } @Nonnull @Override - public IPartModel getStaticModels() - { - if( this.isActive() && this.isPowered() ) - { + public IPartModel getStaticModels() { + if (this.isActive() && this.isPowered()) { return MODELS_HAS_CHANNEL; - } - else if( this.isPowered() ) - { + } else if (this.isPowered()) { return MODELS_ON; - } - else - { + } else { return MODELS_OFF; } } @Override - public ItemStack getItemStackRepresentation() - { - return AEApi.instance().definitions().parts().fluidStorageBus().maybeStack( 1 ).orElse( ItemStack.EMPTY ); + public ItemStack getItemStackRepresentation() { + return AEApi.instance().definitions().parts().fluidStorageBus().maybeStack(1).orElse(ItemStack.EMPTY); } @Override - public GuiBridge getGuiBridge() - { + public GuiBridge getGuiBridge() { return GuiBridge.GUI_STORAGEBUS_FLUID; } } diff --git a/src/main/java/appeng/fluids/parts/PartFluidTerminal.java b/src/main/java/appeng/fluids/parts/PartFluidTerminal.java index 38c509026..5e59502ad 100644 --- a/src/main/java/appeng/fluids/parts/PartFluidTerminal.java +++ b/src/main/java/appeng/fluids/parts/PartFluidTerminal.java @@ -19,16 +19,15 @@ package appeng.fluids.parts; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - import appeng.api.parts.IPartModel; import appeng.core.AppEng; import appeng.core.sync.GuiBridge; import appeng.items.parts.PartModels; import appeng.parts.PartModel; import appeng.parts.reporting.AbstractPartTerminal; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; /** @@ -36,32 +35,28 @@ import appeng.parts.reporting.AbstractPartTerminal; * @version rv6 - 12/05/2018 * @since rv6 12/05/2018 */ -public class PartFluidTerminal extends AbstractPartTerminal -{ +public class PartFluidTerminal extends AbstractPartTerminal { - @PartModels - public static final ResourceLocation MODEL_OFF = new ResourceLocation( AppEng.MOD_ID, "part/fluid_terminal_off" ); - @PartModels - public static final ResourceLocation MODEL_ON = new ResourceLocation( AppEng.MOD_ID, "part/fluid_terminal_on" ); + @PartModels + public static final ResourceLocation MODEL_OFF = new ResourceLocation(AppEng.MOD_ID, "part/fluid_terminal_off"); + @PartModels + public static final ResourceLocation MODEL_ON = new ResourceLocation(AppEng.MOD_ID, "part/fluid_terminal_on"); - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF ); - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_ON ); - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL ); + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_ON); + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL); - public PartFluidTerminal( ItemStack is ) - { - super( is ); - } + public PartFluidTerminal(ItemStack is) { + super(is); + } - @Override - public GuiBridge getGui( EntityPlayer player ) - { - return GuiBridge.GUI_FLUID_TERMINAL; - } + @Override + public GuiBridge getGui(EntityPlayer player) { + return GuiBridge.GUI_FLUID_TERMINAL; + } - @Override - public IPartModel getStaticModels() - { - return this.selectModel( MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL ); - } + @Override + public IPartModel getStaticModels() { + return this.selectModel(MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL); + } } diff --git a/src/main/java/appeng/fluids/parts/PartSharedFluidBus.java b/src/main/java/appeng/fluids/parts/PartSharedFluidBus.java index 08f7dafb4..ec0d192ba 100644 --- a/src/main/java/appeng/fluids/parts/PartSharedFluidBus.java +++ b/src/main/java/appeng/fluids/parts/PartSharedFluidBus.java @@ -19,7 +19,21 @@ package appeng.fluids.parts; +import appeng.api.AEApi; +import appeng.api.config.RedstoneMode; +import appeng.api.config.Upgrades; +import appeng.api.networking.ticking.IGridTickable; +import appeng.api.networking.ticking.TickRateModulation; +import appeng.api.parts.IPartCollisionHelper; +import appeng.api.storage.channels.IFluidStorageChannel; +import appeng.api.util.AECableType; +import appeng.core.sync.GuiBridge; import appeng.fluids.helper.IConfigurableFluidInventory; +import appeng.fluids.util.AEFluidInventory; +import appeng.fluids.util.IAEFluidTank; +import appeng.me.GridAccessException; +import appeng.parts.automation.PartUpgradeable; +import appeng.util.Platform; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -30,21 +44,6 @@ import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - -import appeng.api.AEApi; -import appeng.api.config.RedstoneMode; -import appeng.api.config.Upgrades; -import appeng.api.networking.ticking.IGridTickable; -import appeng.api.networking.ticking.TickRateModulation; -import appeng.api.parts.IPartCollisionHelper; -import appeng.api.storage.channels.IFluidStorageChannel; -import appeng.api.util.AECableType; -import appeng.core.sync.GuiBridge; -import appeng.fluids.util.AEFluidInventory; -import appeng.fluids.util.IAEFluidTank; -import appeng.me.GridAccessException; -import appeng.parts.automation.PartUpgradeable; -import appeng.util.Platform; import net.minecraftforge.fluids.capability.IFluidHandler; @@ -53,151 +52,125 @@ import net.minecraftforge.fluids.capability.IFluidHandler; * @version rv6 - 30/04/2018 * @since rv6 30/04/2018 */ -public abstract class PartSharedFluidBus extends PartUpgradeable implements IGridTickable, IConfigurableFluidInventory -{ +public abstract class PartSharedFluidBus extends PartUpgradeable implements IGridTickable, IConfigurableFluidInventory { - private final AEFluidInventory config = new AEFluidInventory( null, 9 ); - private boolean lastRedstone; + private final AEFluidInventory config = new AEFluidInventory(null, 9); + private boolean lastRedstone; - public PartSharedFluidBus( ItemStack is ) - { - super( is ); - } + public PartSharedFluidBus(ItemStack is) { + super(is); + } - @Override - public void upgradesChanged() - { - this.updateState(); - } + @Override + public void upgradesChanged() { + this.updateState(); + } - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - this.updateState(); - if( this.lastRedstone != this.getHost().hasRedstone( this.getSide() ) ) - { - this.lastRedstone = !this.lastRedstone; - if( this.lastRedstone && this.getRSMode() == RedstoneMode.SIGNAL_PULSE ) - { - this.doBusWork(); - } - } - } + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + this.updateState(); + if (this.lastRedstone != this.getHost().hasRedstone(this.getSide())) { + this.lastRedstone = !this.lastRedstone; + if (this.lastRedstone && this.getRSMode() == RedstoneMode.SIGNAL_PULSE) { + this.doBusWork(); + } + } + } - private void updateState() - { - try - { - if( !this.isSleeping() ) - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - else - { - this.getProxy().getTick().sleepDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } + private void updateState() { + try { + if (!this.isSleeping()) { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } else { + this.getProxy().getTick().sleepDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS_FLUID ); - } + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS_FLUID); + } - return true; - } + return true; + } - @Override - public void getBoxes( IPartCollisionHelper bch ) - { - bch.addBox( 6, 6, 11, 10, 10, 13 ); - bch.addBox( 5, 5, 13, 11, 11, 14 ); - bch.addBox( 4, 4, 14, 12, 12, 16 ); - } + @Override + public void getBoxes(IPartCollisionHelper bch) { + bch.addBox(6, 6, 11, 10, 10, 13); + bch.addBox(5, 5, 13, 11, 11, 14); + bch.addBox(4, 4, 14, 12, 12, 16); + } - protected TileEntity getConnectedTE() - { - TileEntity self = this.getHost().getTile(); - return this.getTileEntity( self, self.getPos().offset( this.getSide().getFacing() ) ); - } + protected TileEntity getConnectedTE() { + TileEntity self = this.getHost().getTile(); + return this.getTileEntity(self, self.getPos().offset(this.getSide().getFacing())); + } - private TileEntity getTileEntity( final TileEntity self, final BlockPos pos ) - { - final World w = self.getWorld(); + private TileEntity getTileEntity(final TileEntity self, final BlockPos pos) { + final World w = self.getWorld(); - if( w.getChunkProvider().getLoadedChunk( pos.getX() >> 4, pos.getZ() >> 4 ) != null ) - { - return w.getTileEntity( pos ); - } + if (w.getChunkProvider().getLoadedChunk(pos.getX() >> 4, pos.getZ() >> 4) != null) { + return w.getTileEntity(pos); + } - return null; - } + return null; + } - protected int calculateAmountToSend() - { - double amount = this.getChannel().transferFactor(); - switch( this.getInstalledUpgrades( Upgrades.SPEED ) ) - { - case 4: - amount = amount * 1.5; - case 3: - amount = amount * 2; - case 2: - amount = amount * 4; - case 1: - amount = amount * 8; - case 0: - default: - return MathHelper.floor( amount ); - } - } + protected int calculateAmountToSend() { + double amount = this.getChannel().transferFactor(); + switch (this.getInstalledUpgrades(Upgrades.SPEED)) { + case 4: + amount = amount * 1.5; + case 3: + amount = amount * 2; + case 2: + amount = amount * 4; + case 1: + amount = amount * 8; + case 0: + default: + return MathHelper.floor(amount); + } + } - @Override - public void readFromNBT( NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.config.readFromNBT( extra, "config" ); - } + @Override + public void readFromNBT(NBTTagCompound extra) { + super.readFromNBT(extra); + this.config.readFromNBT(extra, "config"); + } - @Override - public void writeToNBT( NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.config.writeToNBT( extra, "config" ); - } + @Override + public void writeToNBT(NBTTagCompound extra) { + super.writeToNBT(extra); + this.config.writeToNBT(extra, "config"); + } - public IAEFluidTank getConfig() - { - return this.config; - } + public IAEFluidTank getConfig() { + return this.config; + } - @Override - public IFluidHandler getFluidInventoryByName( final String name) { - if (name.equals("config")) { - return this.config; - } - return null; - } + @Override + public IFluidHandler getFluidInventoryByName(final String name) { + if (name.equals("config")) { + return this.config; + } + return null; + } - protected IFluidStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ); - } + protected IFluidStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class); + } - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 5; - } + @Override + public float getCableConnectionLength(AECableType cable) { + return 5; + } - protected abstract TickRateModulation doBusWork(); + protected abstract TickRateModulation doBusWork(); - protected abstract boolean canDoBusWork(); + protected abstract boolean canDoBusWork(); } diff --git a/src/main/java/appeng/fluids/registries/BasicFluidCellGuiHandler.java b/src/main/java/appeng/fluids/registries/BasicFluidCellGuiHandler.java index d0148bf38..c7c731348 100644 --- a/src/main/java/appeng/fluids/registries/BasicFluidCellGuiHandler.java +++ b/src/main/java/appeng/fluids/registries/BasicFluidCellGuiHandler.java @@ -19,10 +19,6 @@ package appeng.fluids.registries; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - import appeng.api.AEApi; import appeng.api.implementations.tiles.IChestOrDrive; import appeng.api.storage.ICellGuiHandler; @@ -34,20 +30,20 @@ import appeng.api.storage.data.IAEStack; import appeng.api.util.AEPartLocation; import appeng.core.sync.GuiBridge; import appeng.util.Platform; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; -public class BasicFluidCellGuiHandler implements ICellGuiHandler -{ +public class BasicFluidCellGuiHandler implements ICellGuiHandler { - @Override - public > boolean isHandlerFor( final IStorageChannel channel ) - { - return channel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ); - } + @Override + public > boolean isHandlerFor(final IStorageChannel channel) { + return channel == AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class); + } - @Override - public void openChestGui( final EntityPlayer player, final IChestOrDrive chest, final ICellHandler cellHandler, final IMEInventoryHandler inv, final ItemStack is, final IStorageChannel chan ) - { - Platform.openGUI( player, (TileEntity) chest, AEPartLocation.fromFacing( chest.getUp() ), GuiBridge.GUI_FLUID_TERMINAL ); - } + @Override + public void openChestGui(final EntityPlayer player, final IChestOrDrive chest, final ICellHandler cellHandler, final IMEInventoryHandler inv, final ItemStack is, final IStorageChannel chan) { + Platform.openGUI(player, (TileEntity) chest, AEPartLocation.fromFacing(chest.getUp()), GuiBridge.GUI_FLUID_TERMINAL); + } } diff --git a/src/main/java/appeng/fluids/tile/TileFluidInterface.java b/src/main/java/appeng/fluids/tile/TileFluidInterface.java index 430e1deaa..eb730730e 100644 --- a/src/main/java/appeng/fluids/tile/TileFluidInterface.java +++ b/src/main/java/appeng/fluids/tile/TileFluidInterface.java @@ -19,19 +19,6 @@ package appeng.fluids.tile; -import java.util.EnumSet; - -import javax.annotation.Nullable; - -import appeng.fluids.helper.IConfigurableFluidInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.Upgrades; import appeng.api.networking.IGridNode; @@ -47,151 +34,139 @@ import appeng.api.util.DimensionalCoord; import appeng.api.util.IConfigManager; import appeng.core.sync.GuiBridge; import appeng.fluids.helper.DualityFluidInterface; +import appeng.fluids.helper.IConfigurableFluidInventory; import appeng.fluids.helper.IFluidInterfaceHost; import appeng.helpers.IPriorityHost; import appeng.tile.grid.AENetworkTile; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.capability.IFluidHandler; +import net.minecraftforge.items.IItemHandler; + +import javax.annotation.Nullable; +import java.util.EnumSet; -public class TileFluidInterface extends AENetworkTile implements IGridTickable, IFluidInterfaceHost, IPriorityHost, IConfigurableFluidInventory -{ - private final DualityFluidInterface duality = new DualityFluidInterface( this.getProxy(), this ); +public class TileFluidInterface extends AENetworkTile implements IGridTickable, IFluidInterfaceHost, IPriorityHost, IConfigurableFluidInventory { + private final DualityFluidInterface duality = new DualityFluidInterface(this.getProxy(), this); - @MENetworkEventSubscribe - public void stateChange( final MENetworkChannelsChanged c ) - { - this.duality.notifyNeighbors(); - } + @MENetworkEventSubscribe + public void stateChange(final MENetworkChannelsChanged c) { + this.duality.notifyNeighbors(); + } - @MENetworkEventSubscribe - public void stateChange( final MENetworkPowerStatusChange c ) - { - this.duality.notifyNeighbors(); - } + @MENetworkEventSubscribe + public void stateChange(final MENetworkPowerStatusChange c) { + this.duality.notifyNeighbors(); + } - @Override - public TickingRequest getTickingRequest( IGridNode node ) - { - return this.duality.getTickingRequest( node ); - } + @Override + public TickingRequest getTickingRequest(IGridNode node) { + return this.duality.getTickingRequest(node); + } - @Override - public TickRateModulation tickingRequest( IGridNode node, int ticksSinceLastCall ) - { - return this.duality.tickingRequest( node, ticksSinceLastCall ); - } + @Override + public TickRateModulation tickingRequest(IGridNode node, int ticksSinceLastCall) { + return this.duality.tickingRequest(node, ticksSinceLastCall); + } - @Override - public DualityFluidInterface getDualityFluidInterface() - { - return this.duality; - } + @Override + public DualityFluidInterface getDualityFluidInterface() { + return this.duality; + } - @Override - public TileEntity getTileEntity() - { - return this; - } + @Override + public TileEntity getTileEntity() { + return this; + } - @Override - public void gridChanged() - { - this.duality.gridChanged(); - } + @Override + public void gridChanged() { + this.duality.gridChanged(); + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.duality.writeToNBT( data ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.duality.writeToNBT(data); + return data; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.duality.readFromNBT( data ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.duality.readFromNBT(data); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return this.duality.getCableConnectionType( dir ); - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return this.duality.getCableConnectionType(dir); + } - @Override - public DimensionalCoord getLocation() - { - return this.duality.getLocation(); - } + @Override + public DimensionalCoord getLocation() { + return this.duality.getLocation(); + } - @Override - public EnumSet getTargets() - { - return EnumSet.allOf( EnumFacing.class ); - } + @Override + public EnumSet getTargets() { + return EnumSet.allOf(EnumFacing.class); + } - @Override - public int getPriority() - { - return this.duality.getPriority(); - } + @Override + public int getPriority() { + return this.duality.getPriority(); + } - @Override - public void setPriority( final int newValue ) - { - this.duality.setPriority( newValue ); - } + @Override + public void setPriority(final int newValue) { + this.duality.setPriority(newValue); + } - @Override - public boolean hasCapability( Capability capability, @Nullable EnumFacing facing ) - { - return this.duality.hasCapability( capability, facing ) || super.hasCapability( capability, facing ); - } + @Override + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { + return this.duality.hasCapability(capability, facing) || super.hasCapability(capability, facing); + } - @Override - public T getCapability( Capability capability, @Nullable EnumFacing facing ) - { - T result = this.duality.getCapability( capability, facing ); - if( result != null ) - { - return result; - } - return super.getCapability( capability, facing ); - } + @Override + public T getCapability(Capability capability, @Nullable EnumFacing facing) { + T result = this.duality.getCapability(capability, facing); + if (result != null) { + return result; + } + return super.getCapability(capability, facing); + } - @Override - public int getInstalledUpgrades( Upgrades u ) - { - return this.duality.getInstalledUpgrades( u ); - } + @Override + public int getInstalledUpgrades(Upgrades u) { + return this.duality.getInstalledUpgrades(u); + } - @Override - public IConfigManager getConfigManager() - { - return this.duality.getConfigManager(); - } + @Override + public IConfigManager getConfigManager() { + return this.duality.getConfigManager(); + } - @Override - public IItemHandler getInventoryByName( String name ) - { - return this.duality.getInventoryByName( name ); - } + @Override + public IItemHandler getInventoryByName(String name) { + return this.duality.getInventoryByName(name); + } - @Override - public IFluidHandler getFluidInventoryByName(final String name) { - return this.duality.getFluidInventoryByName(name); - } + @Override + public IFluidHandler getFluidInventoryByName(final String name) { + return this.duality.getFluidInventoryByName(name); + } - @Override - public ItemStack getItemStackRepresentation() - { - return AEApi.instance().definitions().blocks().fluidIface().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - } + @Override + public ItemStack getItemStackRepresentation() { + return AEApi.instance().definitions().blocks().fluidIface().maybeStack(1).orElse(ItemStack.EMPTY); + } - @Override - public GuiBridge getGuiBridge() - { - return GuiBridge.GUI_FLUID_INTERFACE; - } + @Override + public GuiBridge getGuiBridge() { + return GuiBridge.GUI_FLUID_INTERFACE; + } } diff --git a/src/main/java/appeng/fluids/util/AEFluidInventory.java b/src/main/java/appeng/fluids/util/AEFluidInventory.java index 09538e039..5944ad92f 100644 --- a/src/main/java/appeng/fluids/util/AEFluidInventory.java +++ b/src/main/java/appeng/fluids/util/AEFluidInventory.java @@ -1,382 +1,301 @@ - package appeng.fluids.util; -import java.util.Objects; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidTankProperties; - import appeng.api.storage.data.IAEFluidStack; import appeng.core.AELog; import appeng.util.Platform; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.capability.IFluidTankProperties; + +import java.util.Objects; -public class AEFluidInventory implements IAEFluidTank -{ - private final IAEFluidStack[] fluids; - private final IAEFluidInventory handler; - private final int capacity; - private IFluidTankProperties[] props = null; +public class AEFluidInventory implements IAEFluidTank { + private final IAEFluidStack[] fluids; + private final IAEFluidInventory handler; + private final int capacity; + private IFluidTankProperties[] props = null; - public AEFluidInventory( final IAEFluidInventory handler, final int slots, final int capcity ) - { - this.fluids = new IAEFluidStack[slots]; - this.handler = handler; - this.capacity = capcity; - } + public AEFluidInventory(final IAEFluidInventory handler, final int slots, final int capcity) { + this.fluids = new IAEFluidStack[slots]; + this.handler = handler; + this.capacity = capcity; + } - public AEFluidInventory( final IAEFluidInventory handler, final int slots ) - { - this( handler, slots, Integer.MAX_VALUE ); - } + public AEFluidInventory(final IAEFluidInventory handler, final int slots) { + this(handler, slots, Integer.MAX_VALUE); + } - @Override - public void setFluidInSlot( final int slot, final IAEFluidStack fluid ) - { - if( slot >= 0 && slot < this.getSlots() ) - { - if( Objects.equals( this.fluids[slot], fluid ) ) - { - if( fluid != null && fluid.getStackSize() != this.fluids[slot].getStackSize() ) - { - this.fluids[slot].setStackSize( Math.min( fluid.getStackSize(), this.capacity ) ); - this.onContentChanged( slot ); - } - } - else - { - if( fluid == null ) - { - this.fluids[slot] = null; - } - else - { - this.fluids[slot] = fluid.copy(); - this.fluids[slot].setStackSize( Math.min( fluid.getStackSize(), this.capacity ) ); - } + @Override + public void setFluidInSlot(final int slot, final IAEFluidStack fluid) { + if (slot >= 0 && slot < this.getSlots()) { + if (Objects.equals(this.fluids[slot], fluid)) { + if (fluid != null && fluid.getStackSize() != this.fluids[slot].getStackSize()) { + this.fluids[slot].setStackSize(Math.min(fluid.getStackSize(), this.capacity)); + this.onContentChanged(slot); + } + } else { + if (fluid == null) { + this.fluids[slot] = null; + } else { + this.fluids[slot] = fluid.copy(); + this.fluids[slot].setStackSize(Math.min(fluid.getStackSize(), this.capacity)); + } - this.onContentChanged( slot ); - } - } - } + this.onContentChanged(slot); + } + } + } - private void onContentChanged( final int slot ) - { - if( this.handler != null && Platform.isServer() ) - { - this.handler.onFluidInventoryChanged( this, slot ); - } - } + private void onContentChanged(final int slot) { + if (this.handler != null && Platform.isServer()) { + this.handler.onFluidInventoryChanged(this, slot); + } + } - @Override - public IAEFluidStack getFluidInSlot( final int slot ) - { - if( slot >= 0 && slot < this.getSlots() ) - { - return this.fluids[slot]; - } - return null; - } + @Override + public IAEFluidStack getFluidInSlot(final int slot) { + if (slot >= 0 && slot < this.getSlots()) { + return this.fluids[slot]; + } + return null; + } - @Override - public int getSlots() - { - return this.fluids.length; - } + @Override + public int getSlots() { + return this.fluids.length; + } - @Override - public IFluidTankProperties[] getTankProperties() - { - if( this.props == null ) - { - this.props = new IFluidTankProperties[this.getSlots()]; - for( int i = 0; i < this.getSlots(); ++i ) - { - this.props[i] = new FluidTankPropertiesWrapper( i ); - } + @Override + public IFluidTankProperties[] getTankProperties() { + if (this.props == null) { + this.props = new IFluidTankProperties[this.getSlots()]; + for (int i = 0; i < this.getSlots(); ++i) { + this.props[i] = new FluidTankPropertiesWrapper(i); + } - } - return this.props; - } + } + return this.props; + } - public int fill( final int slot, final FluidStack resource, final boolean doFill ) - { - if( resource == null || resource.amount <= 0 ) - { - return 0; - } + public int fill(final int slot, final FluidStack resource, final boolean doFill) { + if (resource == null || resource.amount <= 0) { + return 0; + } - final IAEFluidStack fluid = this.fluids[slot]; + final IAEFluidStack fluid = this.fluids[slot]; - if( fluid != null && !fluid.equals( resource ) ) - { - return 0; - } + if (fluid != null && !fluid.equals(resource)) { + return 0; + } - int amountToStore = this.capacity; + int amountToStore = this.capacity; - if( fluid != null ) - { - amountToStore -= fluid.getStackSize(); - } + if (fluid != null) { + amountToStore -= fluid.getStackSize(); + } - amountToStore = Math.min( amountToStore, resource.amount ); + amountToStore = Math.min(amountToStore, resource.amount); - if( doFill ) - { - if( fluid == null ) - { - this.setFluidInSlot( slot, AEFluidStack.fromFluidStack( resource ) ); - } - else - { - fluid.setStackSize( fluid.getStackSize() + amountToStore ); - this.onContentChanged( slot ); - } - } + if (doFill) { + if (fluid == null) { + this.setFluidInSlot(slot, AEFluidStack.fromFluidStack(resource)); + } else { + fluid.setStackSize(fluid.getStackSize() + amountToStore); + this.onContentChanged(slot); + } + } - return amountToStore; - } + return amountToStore; + } - public FluidStack drain( final int slot, final FluidStack resource, final boolean doDrain ) - { - final IAEFluidStack fluid = this.fluids[slot]; - if( resource == null || fluid == null || !fluid.equals( resource ) ) - { - return null; - } - return this.drain( slot, resource.amount, doDrain ); - } + public FluidStack drain(final int slot, final FluidStack resource, final boolean doDrain) { + final IAEFluidStack fluid = this.fluids[slot]; + if (resource == null || fluid == null || !fluid.equals(resource)) { + return null; + } + return this.drain(slot, resource.amount, doDrain); + } - public FluidStack drain( final int slot, final int maxDrain, boolean doDrain ) - { - final IAEFluidStack fluid = this.fluids[slot]; - if( fluid == null || maxDrain <= 0 ) - { - return null; - } + public FluidStack drain(final int slot, final int maxDrain, boolean doDrain) { + final IAEFluidStack fluid = this.fluids[slot]; + if (fluid == null || maxDrain <= 0) { + return null; + } - int drained = maxDrain; - if( fluid.getStackSize() < drained ) - { - drained = (int) fluid.getStackSize(); - } + int drained = maxDrain; + if (fluid.getStackSize() < drained) { + drained = (int) fluid.getStackSize(); + } - FluidStack stack = new FluidStack( fluid.getFluid(), drained ); - if( doDrain ) - { - fluid.setStackSize( fluid.getStackSize() - drained ); - if( fluid.getStackSize() <= 0 ) - { - this.fluids[slot] = null; - } - this.onContentChanged( slot ); - } - return stack; - } + FluidStack stack = new FluidStack(fluid.getFluid(), drained); + if (doDrain) { + fluid.setStackSize(fluid.getStackSize() - drained); + if (fluid.getStackSize() <= 0) { + this.fluids[slot] = null; + } + this.onContentChanged(slot); + } + return stack; + } - @Override - public int fill( final FluidStack fluid, final boolean doFill ) - { - if( fluid == null || fluid.amount <= 0 ) - { - return 0; - } + @Override + public int fill(final FluidStack fluid, final boolean doFill) { + if (fluid == null || fluid.amount <= 0) { + return 0; + } - final FluidStack insert = fluid.copy(); + final FluidStack insert = fluid.copy(); - int totalFillAmount = 0; - for( int slot = 0; slot < this.getSlots(); ++slot ) - { - int fillAmount = this.fill( slot, insert, doFill ); - totalFillAmount += fillAmount; - insert.amount -= fillAmount; - if( insert.amount <= 0 ) - { - break; - } - } - return totalFillAmount; - } + int totalFillAmount = 0; + for (int slot = 0; slot < this.getSlots(); ++slot) { + int fillAmount = this.fill(slot, insert, doFill); + totalFillAmount += fillAmount; + insert.amount -= fillAmount; + if (insert.amount <= 0) { + break; + } + } + return totalFillAmount; + } - @Override - public FluidStack drain( final FluidStack fluid, final boolean doDrain ) - { - if( fluid == null || fluid.amount <= 0 ) - { - return null; - } + @Override + public FluidStack drain(final FluidStack fluid, final boolean doDrain) { + if (fluid == null || fluid.amount <= 0) { + return null; + } - final FluidStack resource = fluid.copy(); + final FluidStack resource = fluid.copy(); - FluidStack totalDrained = null; - for( int slot = 0; slot < this.getSlots(); ++slot ) - { - FluidStack drain = this.drain( slot, resource, doDrain ); - if( drain != null ) - { - if( totalDrained == null ) - { - totalDrained = drain; - } - else - { - totalDrained.amount += drain.amount; - } + FluidStack totalDrained = null; + for (int slot = 0; slot < this.getSlots(); ++slot) { + FluidStack drain = this.drain(slot, resource, doDrain); + if (drain != null) { + if (totalDrained == null) { + totalDrained = drain; + } else { + totalDrained.amount += drain.amount; + } - resource.amount -= drain.amount; - if( resource.amount <= 0 ) - { - break; - } - } - } - return totalDrained; - } + resource.amount -= drain.amount; + if (resource.amount <= 0) { + break; + } + } + } + return totalDrained; + } - @Override - public FluidStack drain( final int maxDrain, final boolean doDrain ) - { - if( maxDrain == 0 ) - { - return null; - } + @Override + public FluidStack drain(final int maxDrain, final boolean doDrain) { + if (maxDrain == 0) { + return null; + } - FluidStack totalDrained = null; - int toDrain = maxDrain; + FluidStack totalDrained = null; + int toDrain = maxDrain; - for( int slot = 0; slot < this.getSlots(); ++slot ) - { - if( totalDrained == null ) - { - totalDrained = this.drain( slot, toDrain, doDrain ); - if( totalDrained != null ) - { - toDrain -= totalDrained.amount; - } - } - else - { - FluidStack copy = totalDrained.copy(); - copy.amount = toDrain; - FluidStack drain = this.drain( slot, copy, doDrain ); - if( drain != null ) - { - totalDrained.amount += drain.amount; - toDrain -= drain.amount; - } - } + for (int slot = 0; slot < this.getSlots(); ++slot) { + if (totalDrained == null) { + totalDrained = this.drain(slot, toDrain, doDrain); + if (totalDrained != null) { + toDrain -= totalDrained.amount; + } + } else { + FluidStack copy = totalDrained.copy(); + copy.amount = toDrain; + FluidStack drain = this.drain(slot, copy, doDrain); + if (drain != null) { + totalDrained.amount += drain.amount; + toDrain -= drain.amount; + } + } - if( toDrain <= 0 ) - { - break; - } - } - return totalDrained; - } + if (toDrain <= 0) { + break; + } + } + return totalDrained; + } - public void writeToNBT( final NBTTagCompound data, final String name ) - { - final NBTTagCompound c = new NBTTagCompound(); - this.writeToNBT( c ); - data.setTag( name, c ); - } + public void writeToNBT(final NBTTagCompound data, final String name) { + final NBTTagCompound c = new NBTTagCompound(); + this.writeToNBT(c); + data.setTag(name, c); + } - private void writeToNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.fluids.length; x++ ) - { - try - { - final NBTTagCompound c = new NBTTagCompound(); + private void writeToNBT(final NBTTagCompound target) { + for (int x = 0; x < this.fluids.length; x++) { + try { + final NBTTagCompound c = new NBTTagCompound(); - if( this.fluids[x] != null ) - { - this.fluids[x].writeToNBT( c ); - } + if (this.fluids[x] != null) { + this.fluids[x].writeToNBT(c); + } - target.setTag( "#" + x, c ); - } - catch( final Exception ignored ) - { - } - } - } + target.setTag("#" + x, c); + } catch (final Exception ignored) { + } + } + } - public void readFromNBT( final NBTTagCompound data, final String name ) - { - final NBTTagCompound c = data.getCompoundTag( name ); - if( c != null ) - { - this.readFromNBT( c ); - } - } + public void readFromNBT(final NBTTagCompound data, final String name) { + final NBTTagCompound c = data.getCompoundTag(name); + if (c != null) { + this.readFromNBT(c); + } + } - private void readFromNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.fluids.length; x++ ) - { - try - { - final NBTTagCompound c = target.getCompoundTag( "#" + x ); + private void readFromNBT(final NBTTagCompound target) { + for (int x = 0; x < this.fluids.length; x++) { + try { + final NBTTagCompound c = target.getCompoundTag("#" + x); - if( c != null ) - { - this.fluids[x] = AEFluidStack.fromNBT( c ); - } - } - catch( final Exception e ) - { - AELog.debug( e ); - } - } - } + if (c != null) { + this.fluids[x] = AEFluidStack.fromNBT(c); + } + } catch (final Exception e) { + AELog.debug(e); + } + } + } - private class FluidTankPropertiesWrapper implements IFluidTankProperties - { - private final int slot; + private class FluidTankPropertiesWrapper implements IFluidTankProperties { + private final int slot; - public FluidTankPropertiesWrapper( final int slot ) - { - this.slot = slot; - } + public FluidTankPropertiesWrapper(final int slot) { + this.slot = slot; + } - @Override - public FluidStack getContents() - { - return AEFluidInventory.this.fluids[this.slot] == null ? null : AEFluidInventory.this.fluids[this.slot].getFluidStack(); - } + @Override + public FluidStack getContents() { + return AEFluidInventory.this.fluids[this.slot] == null ? null : AEFluidInventory.this.fluids[this.slot].getFluidStack(); + } - @Override - public int getCapacity() - { - return Math.min( AEFluidInventory.this.capacity, Integer.MAX_VALUE ); - } + @Override + public int getCapacity() { + return Math.min(AEFluidInventory.this.capacity, Integer.MAX_VALUE); + } - @Override - public boolean canFill() - { - return true; - } + @Override + public boolean canFill() { + return true; + } - @Override - public boolean canDrain() - { - return true; - } + @Override + public boolean canDrain() { + return true; + } - @Override - public boolean canFillFluidType( FluidStack fluidStack ) - { - return true; - } + @Override + public boolean canFillFluidType(FluidStack fluidStack) { + return true; + } - @Override - public boolean canDrainFluidType( FluidStack fluidStack ) - { - return fluidStack != null; - } - } + @Override + public boolean canDrainFluidType(FluidStack fluidStack) { + return fluidStack != null; + } + } } diff --git a/src/main/java/appeng/fluids/util/AEFluidStack.java b/src/main/java/appeng/fluids/util/AEFluidStack.java index d04652bcb..7be7e439e 100644 --- a/src/main/java/appeng/fluids/util/AEFluidStack.java +++ b/src/main/java/appeng/fluids/util/AEFluidStack.java @@ -19,22 +19,6 @@ package appeng.fluids.util; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import javax.annotation.Nonnull; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; - import appeng.api.AEApi; import appeng.api.config.FuzzyMode; import appeng.api.storage.IStorageChannel; @@ -44,310 +28,277 @@ import appeng.core.Api; import appeng.fluids.items.FluidDummyItem; import appeng.util.Platform; import appeng.util.item.AEStack; +import io.netty.buffer.ByteBuf; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +import javax.annotation.Nonnull; +import java.io.*; +import java.nio.charset.StandardCharsets; -public final class AEFluidStack extends AEStack implements IAEFluidStack, Comparable -{ +public final class AEFluidStack extends AEStack implements IAEFluidStack, Comparable { - private final Fluid fluid; - private NBTTagCompound tagCompound; + private final Fluid fluid; + private NBTTagCompound tagCompound; - private AEFluidStack( final AEFluidStack fluidStack ) - { - this.fluid = fluidStack.fluid; - this.setStackSize( fluidStack.getStackSize() ); + private AEFluidStack(final AEFluidStack fluidStack) { + this.fluid = fluidStack.fluid; + this.setStackSize(fluidStack.getStackSize()); - // priority = is.priority; - this.setCraftable( fluidStack.isCraftable() ); - this.setCountRequestable( fluidStack.getCountRequestable() ); + // priority = is.priority; + this.setCraftable(fluidStack.isCraftable()); + this.setCountRequestable(fluidStack.getCountRequestable()); - if( fluidStack.hasTagCompound() ) - { - this.tagCompound = fluidStack.tagCompound.copy(); - } - } + if (fluidStack.hasTagCompound()) { + this.tagCompound = fluidStack.tagCompound.copy(); + } + } - private AEFluidStack( @Nonnull final FluidStack fluidStack ) - { - this.fluid = fluidStack.getFluid(); + private AEFluidStack(@Nonnull final FluidStack fluidStack) { + this.fluid = fluidStack.getFluid(); - if( this.fluid == null ) - { - throw new IllegalArgumentException( "Fluid is null." ); - } + if (this.fluid == null) { + throw new IllegalArgumentException("Fluid is null."); + } - this.setStackSize( fluidStack.amount ); - this.setCraftable( false ); - this.setCountRequestable( 0 ); + this.setStackSize(fluidStack.amount); + this.setCraftable(false); + this.setCountRequestable(0); - if( fluidStack.tag != null ) - { - this.tagCompound = fluidStack.tag.copy(); - } - } + if (fluidStack.tag != null) { + this.tagCompound = fluidStack.tag.copy(); + } + } - public static AEFluidStack fromFluidStack( final FluidStack input ) - { - if( input == null ) - { - return null; - } + public static AEFluidStack fromFluidStack(final FluidStack input) { + if (input == null) { + return null; + } - return new AEFluidStack( input ); - } + return new AEFluidStack(input); + } - public static IAEFluidStack fromNBT( final NBTTagCompound data ) - { - final FluidStack fluidStack = FluidStack.loadFluidStackFromNBT( data ); + public static IAEFluidStack fromNBT(final NBTTagCompound data) { + final FluidStack fluidStack = FluidStack.loadFluidStackFromNBT(data); - if( fluidStack == null ) - { - return null; - } + if (fluidStack == null) { + return null; + } - final AEFluidStack fluid = AEFluidStack.fromFluidStack( fluidStack ); - fluid.setStackSize( data.getLong( "Cnt" ) ); - fluid.setCountRequestable( data.getLong( "Req" ) ); - fluid.setCraftable( data.getBoolean( "Craft" ) ); + final AEFluidStack fluid = AEFluidStack.fromFluidStack(fluidStack); + fluid.setStackSize(data.getLong("Cnt")); + fluid.setCountRequestable(data.getLong("Req")); + fluid.setCraftable(data.getBoolean("Craft")); - if( fluid.hasTagCompound() ) - { - fluid.tagCompound = fluid.tagCompound.copy(); - } + if (fluid.hasTagCompound()) { + fluid.tagCompound = fluid.tagCompound.copy(); + } - return fluid; - } + return fluid; + } - public static IAEFluidStack fromPacket( final ByteBuf buffer ) throws IOException - { - final byte mask = buffer.readByte(); - final byte stackType = (byte) ( ( mask & 0x0C ) >> 2 ); - final byte countReqType = (byte) ( ( mask & 0x30 ) >> 4 ); - final boolean isCraftable = ( mask & 0x40 ) > 0; - final boolean hasTagCompound = ( mask & 0x80 ) > 0; + public static IAEFluidStack fromPacket(final ByteBuf buffer) throws IOException { + final byte mask = buffer.readByte(); + final byte stackType = (byte) ((mask & 0x0C) >> 2); + final byte countReqType = (byte) ((mask & 0x30) >> 4); + final boolean isCraftable = (mask & 0x40) > 0; + final boolean hasTagCompound = (mask & 0x80) > 0; - // don't send this... - final NBTTagCompound d = new NBTTagCompound(); + // don't send this... + final NBTTagCompound d = new NBTTagCompound(); - final byte len2 = buffer.readByte(); - final byte[] name = new byte[len2]; - buffer.readBytes( name, 0, len2 ); + final byte len2 = buffer.readByte(); + final byte[] name = new byte[len2]; + buffer.readBytes(name, 0, len2); - d.setString( "FluidName", new String( name, "UTF-8" ) ); - d.setByte( "Count", (byte) 0 ); + d.setString("FluidName", new String(name, StandardCharsets.UTF_8)); + d.setByte("Count", (byte) 0); - if( hasTagCompound ) - { - final int len = buffer.readInt(); + if (hasTagCompound) { + final int len = buffer.readInt(); - final byte[] bd = new byte[len]; - buffer.readBytes( bd ); + final byte[] bd = new byte[len]; + buffer.readBytes(bd); - final DataInputStream di = new DataInputStream( new ByteArrayInputStream( bd ) ); - d.setTag( "Tag", CompressedStreamTools.read( di ) ); - } + final DataInputStream di = new DataInputStream(new ByteArrayInputStream(bd)); + d.setTag("Tag", CompressedStreamTools.read(di)); + } - final long stackSize = getPacketValue( stackType, buffer ); - final long countRequestable = getPacketValue( countReqType, buffer ); + final long stackSize = getPacketValue(stackType, buffer); + final long countRequestable = getPacketValue(countReqType, buffer); - final FluidStack fluidStack = FluidStack.loadFluidStackFromNBT( d ); + final FluidStack fluidStack = FluidStack.loadFluidStackFromNBT(d); - if( fluidStack == null ) - { - return null; - } + if (fluidStack == null) { + return null; + } - final AEFluidStack fluid = AEFluidStack.fromFluidStack( fluidStack ); - // fluid.priority = (int) priority; - fluid.setStackSize( stackSize ); - fluid.setCountRequestable( countRequestable ); - fluid.setCraftable( isCraftable ); - return fluid; - } + final AEFluidStack fluid = AEFluidStack.fromFluidStack(fluidStack); + // fluid.priority = (int) priority; + fluid.setStackSize(stackSize); + fluid.setCountRequestable(countRequestable); + fluid.setCraftable(isCraftable); + return fluid; + } - @Override - public void add( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } - this.incStackSize( option.getStackSize() ); - this.setCountRequestable( this.getCountRequestable() + option.getCountRequestable() ); - this.setCraftable( this.isCraftable() || option.isCraftable() ); - } + @Override + public void add(final IAEFluidStack option) { + if (option == null) { + return; + } + this.incStackSize(option.getStackSize()); + this.setCountRequestable(this.getCountRequestable() + option.getCountRequestable()); + this.setCraftable(this.isCraftable() || option.isCraftable()); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - data.setString( "FluidName", this.fluid.getName() ); - data.setByte( "Count", (byte) 0 ); - data.setLong( "Cnt", this.getStackSize() ); - data.setLong( "Req", this.getCountRequestable() ); - data.setBoolean( "Craft", this.isCraftable() ); + @Override + public void writeToNBT(final NBTTagCompound data) { + data.setString("FluidName", this.fluid.getName()); + data.setByte("Count", (byte) 0); + data.setLong("Cnt", this.getStackSize()); + data.setLong("Req", this.getCountRequestable()); + data.setBoolean("Craft", this.isCraftable()); - if( this.hasTagCompound() ) - { - data.setTag( "Tag", this.tagCompound ); - } - else - { - data.removeTag( "Tag" ); - } - } + if (this.hasTagCompound()) { + data.setTag("Tag", this.tagCompound); + } else { + data.removeTag("Tag"); + } + } - @Override - public boolean fuzzyComparison( final IAEFluidStack other, final FuzzyMode mode ) - { - return this.fluid == other.getFluid(); - } + @Override + public boolean fuzzyComparison(final IAEFluidStack other, final FuzzyMode mode) { + return this.fluid == other.getFluid(); + } - @Override - public IAEFluidStack copy() - { - return new AEFluidStack( this ); - } + @Override + public IAEFluidStack copy() { + return new AEFluidStack(this); + } - @Override - public IAEFluidStack empty() - { - final IAEFluidStack dup = this.copy(); - dup.reset(); - return dup; - } + @Override + public IAEFluidStack empty() { + final IAEFluidStack dup = this.copy(); + dup.reset(); + return dup; + } - @Override - public boolean isItem() - { - return false; - } + @Override + public boolean isItem() { + return false; + } - @Override - public boolean isFluid() - { - return true; - } + @Override + public boolean isFluid() { + return true; + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class); + } - @Override - public int compareTo( final AEFluidStack other ) - { - if( this.fluid != other.fluid ) - { - return this.fluid.getName().compareTo( other.fluid.getName() ); - } + @Override + public int compareTo(final AEFluidStack other) { + if (this.fluid != other.fluid) { + return this.fluid.getName().compareTo(other.fluid.getName()); + } - if( Platform.itemComparisons().isNbtTagEqual( this.tagCompound, other.tagCompound ) ) - { - return 0; - } + if (Platform.itemComparisons().isNbtTagEqual(this.tagCompound, other.tagCompound)) { + return 0; + } - return this.tagCompound.hashCode() - other.tagCompound.hashCode(); - } + return this.tagCompound.hashCode() - other.tagCompound.hashCode(); + } - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ( ( this.fluid == null ) ? 0 : this.fluid.hashCode() ); - result = prime * result + ( ( this.tagCompound == null ) ? 0 : this.tagCompound.hashCode() ); + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.fluid == null) ? 0 : this.fluid.hashCode()); + result = prime * result + ((this.tagCompound == null) ? 0 : this.tagCompound.hashCode()); - return result; - } + return result; + } - @Override - public boolean equals( final Object other ) - { - if( other instanceof AEFluidStack ) - { - final AEFluidStack is = (AEFluidStack) other; - return is.fluid == this.fluid && Platform.itemComparisons().isNbtTagEqual( this.tagCompound, is.tagCompound ); - } - else if( other instanceof FluidStack ) - { - final FluidStack is = (FluidStack) other; - return is.getFluid() == this.fluid && Platform.itemComparisons().isNbtTagEqual( this.tagCompound, is.tag ); - } - return false; - } + @Override + public boolean equals(final Object other) { + if (other instanceof AEFluidStack) { + final AEFluidStack is = (AEFluidStack) other; + return is.fluid == this.fluid && Platform.itemComparisons().isNbtTagEqual(this.tagCompound, is.tagCompound); + } else if (other instanceof FluidStack) { + final FluidStack is = (FluidStack) other; + return is.getFluid() == this.fluid && Platform.itemComparisons().isNbtTagEqual(this.tagCompound, is.tag); + } + return false; + } - @Override - public String toString() - { - return this.getStackSize() + "x" + this.getFluidStack().getFluid().getName() + " " + this.tagCompound; - } + @Override + public String toString() { + return this.getStackSize() + "x" + this.getFluidStack().getFluid().getName() + " " + this.tagCompound; + } - @Override - public boolean hasTagCompound() - { - return this.tagCompound != null; - } + @Override + public boolean hasTagCompound() { + return this.tagCompound != null; + } - @Override - public FluidStack getFluidStack() - { - final int amount = (int) Math.min( Integer.MAX_VALUE, this.getStackSize() ); - final FluidStack is = new FluidStack( this.fluid, amount, this.tagCompound ); + @Override + public FluidStack getFluidStack() { + final int amount = (int) Math.min(Integer.MAX_VALUE, this.getStackSize()); + final FluidStack is = new FluidStack(this.fluid, amount, this.tagCompound); - return is; - } + return is; + } - @Override - public Fluid getFluid() - { - return this.fluid; - } + @Override + public Fluid getFluid() { + return this.fluid; + } - @Override - public ItemStack asItemStackRepresentation() - { - ItemStack is = Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - if( !is.isEmpty() ) - { - FluidDummyItem item = (FluidDummyItem) is.getItem(); - item.setFluidStack( is, this.getFluidStack() ); - return is; - } - return ItemStack.EMPTY; - } + @Override + public ItemStack asItemStackRepresentation() { + ItemStack is = Api.INSTANCE.definitions().items().dummyFluidItem().maybeStack(1).orElse(ItemStack.EMPTY); + if (!is.isEmpty()) { + FluidDummyItem item = (FluidDummyItem) is.getItem(); + item.setFluidStack(is, this.getFluidStack()); + return is; + } + return ItemStack.EMPTY; + } - @Override - public void writeToPacket( final ByteBuf buffer ) throws IOException - { - final byte mask = (byte) ( ( this.getType( this.getStackSize() ) << 2 ) | ( this - .getType( this.getCountRequestable() ) << 4 ) | ( (byte) ( this.isCraftable() ? 1 : 0 ) << 6 ) | ( this.hasTagCompound() ? 1 : 0 ) << 7 ); + @Override + public void writeToPacket(final ByteBuf buffer) throws IOException { + final byte mask = (byte) ((this.getType(this.getStackSize()) << 2) | (this + .getType(this.getCountRequestable()) << 4) | ((byte) (this.isCraftable() ? 1 : 0) << 6) | (this.hasTagCompound() ? 1 : 0) << 7); - buffer.writeByte( mask ); + buffer.writeByte(mask); - this.writeToStream( buffer ); + this.writeToStream(buffer); - this.putPacketValue( buffer, this.getStackSize() ); - this.putPacketValue( buffer, this.getCountRequestable() ); - } + this.putPacketValue(buffer, this.getStackSize()); + this.putPacketValue(buffer, this.getCountRequestable()); + } - private void writeToStream( final ByteBuf buffer ) throws IOException - { - final byte[] name = this.fluid.getName().getBytes( "UTF-8" ); - buffer.writeByte( (byte) name.length ); - buffer.writeBytes( name ); - if( this.hasTagCompound() ) - { - final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final DataOutputStream data = new DataOutputStream( bytes ); + private void writeToStream(final ByteBuf buffer) throws IOException { + final byte[] name = this.fluid.getName().getBytes(StandardCharsets.UTF_8); + buffer.writeByte((byte) name.length); + buffer.writeBytes(name); + if (this.hasTagCompound()) { + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + final DataOutputStream data = new DataOutputStream(bytes); - CompressedStreamTools.write( this.tagCompound, data ); + CompressedStreamTools.write(this.tagCompound, data); - final byte[] tagBytes = bytes.toByteArray(); - final int size = tagBytes.length; + final byte[] tagBytes = bytes.toByteArray(); + final int size = tagBytes.length; - buffer.writeInt( size ); - buffer.writeBytes( tagBytes ); - } - } + buffer.writeInt(size); + buffer.writeBytes(tagBytes); + } + } } diff --git a/src/main/java/appeng/fluids/util/AEFluidTank.java b/src/main/java/appeng/fluids/util/AEFluidTank.java index 27696204b..2ddb9fda9 100644 --- a/src/main/java/appeng/fluids/util/AEFluidTank.java +++ b/src/main/java/appeng/fluids/util/AEFluidTank.java @@ -19,61 +19,50 @@ package appeng.fluids.util; +import appeng.api.storage.data.IAEFluidStack; +import appeng.util.Platform; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.fluids.FluidTank; -import appeng.api.storage.data.IAEFluidStack; -import appeng.util.Platform; +public class AEFluidTank extends FluidTank implements IAEFluidTank { + private final IAEFluidInventory host; -public class AEFluidTank extends FluidTank implements IAEFluidTank -{ - private final IAEFluidInventory host; + public AEFluidTank(IAEFluidInventory host, int capacity) { + super(capacity); + this.host = host; + if (host instanceof TileEntity) { + this.setTileEntity((TileEntity) host); + } + } - public AEFluidTank( IAEFluidInventory host, int capacity ) - { - super( capacity ); - this.host = host; - if( host instanceof TileEntity ) - { - this.setTileEntity( (TileEntity) host ); - } - } + @Override + protected void onContentsChanged() { + if (this.host != null && Platform.isServer()) { + this.host.onFluidInventoryChanged(this, 0); + } + super.onContentsChanged(); + } - @Override - protected void onContentsChanged() - { - if( this.host != null && Platform.isServer() ) - { - this.host.onFluidInventoryChanged( this, 0 ); - } - super.onContentsChanged(); - } + @Override + public void setFluidInSlot(int slot, IAEFluidStack fluid) { + if (slot == 0) { + this.setFluid(fluid == null ? null : fluid.getFluidStack()); + this.onContentsChanged(); + } + } - @Override - public void setFluidInSlot( int slot, IAEFluidStack fluid ) - { - if( slot == 0 ) - { - this.setFluid( fluid == null ? null : fluid.getFluidStack() ); - this.onContentsChanged(); - } - } + @Override + public IAEFluidStack getFluidInSlot(int slot) { + if (slot == 0) { + return AEFluidStack.fromFluidStack(this.getFluid()); + } + return null; + } - @Override - public IAEFluidStack getFluidInSlot( int slot ) - { - if( slot == 0 ) - { - return AEFluidStack.fromFluidStack( this.getFluid() ); - } - return null; - } - - @Override - public int getSlots() - { - return 1; - } + @Override + public int getSlots() { + return 1; + } } diff --git a/src/main/java/appeng/fluids/util/FluidList.java b/src/main/java/appeng/fluids/util/FluidList.java index bc3ffaf3e..7a8e8485a 100644 --- a/src/main/java/appeng/fluids/util/FluidList.java +++ b/src/main/java/appeng/fluids/util/FluidList.java @@ -19,183 +19,153 @@ package appeng.fluids.util; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; +import java.util.*; -public final class FluidList implements IItemList -{ - private final Map records = new HashMap<>(); +public final class FluidList implements IItemList { - @Override - public void add( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } + private final Map records = new HashMap<>(); - final IAEFluidStack st = this.getFluidRecord( option ); + @Override + public void add(final IAEFluidStack option) { + if (option == null) { + return; + } - if( st != null ) - { - st.add( option ); - return; - } + final IAEFluidStack st = this.getFluidRecord(option); - final IAEFluidStack opt = option.copy(); + if (st != null) { + st.add(option); + return; + } - this.putFluidRecord( opt ); - } + final IAEFluidStack opt = option.copy(); - @Override - public IAEFluidStack findPrecise( final IAEFluidStack fluidStack ) - { - if( fluidStack == null ) - { - return null; - } + this.putFluidRecord(opt); + } - return this.getFluidRecord( fluidStack ); - } + @Override + public IAEFluidStack findPrecise(final IAEFluidStack fluidStack) { + if (fluidStack == null) { + return null; + } - @Override - public Collection findFuzzy( final IAEFluidStack filter, final FuzzyMode fuzzy ) - { - if( filter == null ) - { - return Collections.emptyList(); - } + return this.getFluidRecord(fluidStack); + } - return Collections.singletonList( this.findPrecise( filter ) ); - } + @Override + public Collection findFuzzy(final IAEFluidStack filter, final FuzzyMode fuzzy) { + if (filter == null) { + return Collections.emptyList(); + } - @Override - public boolean isEmpty() - { - return !this.iterator().hasNext(); - } + return Collections.singletonList(this.findPrecise(filter)); + } - @Override - public void addStorage( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } + @Override + public boolean isEmpty() { + return !this.iterator().hasNext(); + } - final IAEFluidStack st = this.getFluidRecord( option ); + @Override + public void addStorage(final IAEFluidStack option) { + if (option == null) { + return; + } - if( st != null ) - { - st.incStackSize( option.getStackSize() ); - return; - } + final IAEFluidStack st = this.getFluidRecord(option); - final IAEFluidStack opt = option.copy(); + if (st != null) { + st.incStackSize(option.getStackSize()); + return; + } - this.putFluidRecord( opt ); - } + final IAEFluidStack opt = option.copy(); - /* - * public synchronized void clean() { Iterator i = iterator(); while (i.hasNext()) { StackType AEI = - * i.next(); if ( !AEI.isMeaningful() ) i.remove(); } } - */ + this.putFluidRecord(opt); + } - @Override - public void addCrafting( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } + /* + * public synchronized void clean() { Iterator i = iterator(); while (i.hasNext()) { StackType AEI = + * i.next(); if ( !AEI.isMeaningful() ) i.remove(); } } + */ - final IAEFluidStack st = this.getFluidRecord( option ); + @Override + public void addCrafting(final IAEFluidStack option) { + if (option == null) { + return; + } - if( st != null ) - { - st.setCraftable( true ); - return; - } + final IAEFluidStack st = this.getFluidRecord(option); - final IAEFluidStack opt = option.copy(); - opt.setStackSize( 0 ); - opt.setCraftable( true ); + if (st != null) { + st.setCraftable(true); + return; + } - this.putFluidRecord( opt ); - } + final IAEFluidStack opt = option.copy(); + opt.setStackSize(0); + opt.setCraftable(true); - @Override - public void addRequestable( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } + this.putFluidRecord(opt); + } - final IAEFluidStack st = this.getFluidRecord( option ); + @Override + public void addRequestable(final IAEFluidStack option) { + if (option == null) { + return; + } - if( st != null ) - { - st.setCountRequestable( st.getCountRequestable() + option.getCountRequestable() ); - return; - } + final IAEFluidStack st = this.getFluidRecord(option); - final IAEFluidStack opt = option.copy(); - opt.setStackSize( 0 ); - opt.setCraftable( false ); - opt.setCountRequestable( option.getCountRequestable() ); + if (st != null) { + st.setCountRequestable(st.getCountRequestable() + option.getCountRequestable()); + return; + } - this.putFluidRecord( opt ); - } + final IAEFluidStack opt = option.copy(); + opt.setStackSize(0); + opt.setCraftable(false); + opt.setCountRequestable(option.getCountRequestable()); - @Override - public IAEFluidStack getFirstItem() - { - for( final IAEFluidStack stackType : this ) - { - return stackType; - } + this.putFluidRecord(opt); + } - return null; - } + @Override + public IAEFluidStack getFirstItem() { + for (final IAEFluidStack stackType : this) { + return stackType; + } - @Override - public int size() - { - return this.records.values().size(); - } + return null; + } - @Override - public Iterator iterator() - { - return new MeaningfulFluidIterator<>( this.records.values().iterator() ); - } + @Override + public int size() { + return this.records.values().size(); + } - @Override - public void resetStatus() - { - for( final IAEFluidStack i : this ) - { - i.reset(); - } - } + @Override + public Iterator iterator() { + return new MeaningfulFluidIterator<>(this.records.values().iterator()); + } - private IAEFluidStack getFluidRecord( final IAEFluidStack fluid ) - { - return this.records.get( fluid ); - } + @Override + public void resetStatus() { + for (final IAEFluidStack i : this) { + i.reset(); + } + } - private IAEFluidStack putFluidRecord( final IAEFluidStack fluid ) - { - return this.records.put( fluid, fluid ); - } + private IAEFluidStack getFluidRecord(final IAEFluidStack fluid) { + return this.records.get(fluid); + } + + private IAEFluidStack putFluidRecord(final IAEFluidStack fluid) { + return this.records.put(fluid, fluid); + } } diff --git a/src/main/java/appeng/fluids/util/FluidSorters.java b/src/main/java/appeng/fluids/util/FluidSorters.java index c1ec8a4a4..4eecefce1 100644 --- a/src/main/java/appeng/fluids/util/FluidSorters.java +++ b/src/main/java/appeng/fluids/util/FluidSorters.java @@ -19,74 +19,64 @@ package appeng.fluids.util; -import java.util.Comparator; - import appeng.api.config.SortDir; import appeng.api.storage.data.IAEFluidStack; import appeng.util.Platform; +import java.util.Comparator; + /** * @author BrockWS * @version rv6 - 22/05/2018 * @since rv6 22/05/2018 */ -public class FluidSorters -{ - private static SortDir Direction = SortDir.ASCENDING; +public class FluidSorters { + private static SortDir Direction = SortDir.ASCENDING; - public static final Comparator CONFIG_BASED_SORT_BY_NAME = ( o1, o2 ) -> - { - if( getDirection() == SortDir.ASCENDING ) - { - return Platform.getFluidDisplayName( o1 ).compareToIgnoreCase( Platform.getFluidDisplayName( o2 ) ); - } - return Platform.getFluidDisplayName( o2 ).compareToIgnoreCase( Platform.getFluidDisplayName( o1 ) ); - }; + public static final Comparator CONFIG_BASED_SORT_BY_NAME = (o1, o2) -> + { + if (getDirection() == SortDir.ASCENDING) { + return Platform.getFluidDisplayName(o1).compareToIgnoreCase(Platform.getFluidDisplayName(o2)); + } + return Platform.getFluidDisplayName(o2).compareToIgnoreCase(Platform.getFluidDisplayName(o1)); + }; - public static final Comparator CONFIG_BASED_SORT_BY_MOD = new Comparator() - { + public static final Comparator CONFIG_BASED_SORT_BY_MOD = new Comparator() { - @Override - public int compare( final IAEFluidStack o1, final IAEFluidStack o2 ) - { - final AEFluidStack op1 = (AEFluidStack) o1; - final AEFluidStack op2 = (AEFluidStack) o2; + @Override + public int compare(final IAEFluidStack o1, final IAEFluidStack o2) { + final AEFluidStack op1 = (AEFluidStack) o1; + final AEFluidStack op2 = (AEFluidStack) o2; - if( getDirection() == SortDir.ASCENDING ) - { - return this.secondarySort( Platform.getModId( op1 ).compareToIgnoreCase( Platform.getModId( op2 ) ), o2, o1 ); - } - return this.secondarySort( Platform.getModId( op2 ).compareToIgnoreCase( Platform.getModId( op1 ) ), o1, o2 ); - } + if (getDirection() == SortDir.ASCENDING) { + return this.secondarySort(Platform.getModId(op1).compareToIgnoreCase(Platform.getModId(op2)), o2, o1); + } + return this.secondarySort(Platform.getModId(op2).compareToIgnoreCase(Platform.getModId(op1)), o1, o2); + } - private int secondarySort( final int compareToIgnoreCase, final IAEFluidStack o1, final IAEFluidStack o2 ) - { - if( compareToIgnoreCase == 0 ) - { - return Platform.getFluidDisplayName( o2 ).compareToIgnoreCase( Platform.getFluidDisplayName( o1 ) ); - } + private int secondarySort(final int compareToIgnoreCase, final IAEFluidStack o1, final IAEFluidStack o2) { + if (compareToIgnoreCase == 0) { + return Platform.getFluidDisplayName(o2).compareToIgnoreCase(Platform.getFluidDisplayName(o1)); + } - return compareToIgnoreCase; - } - }; + return compareToIgnoreCase; + } + }; - public static final Comparator CONFIG_BASED_SORT_BY_SIZE = ( o1, o2 ) -> - { - if( getDirection() == SortDir.ASCENDING ) - { - return Long.compare( o2.getStackSize(), o1.getStackSize() ); - } - return Long.compare( o1.getStackSize(), o2.getStackSize() ); - }; + public static final Comparator CONFIG_BASED_SORT_BY_SIZE = (o1, o2) -> + { + if (getDirection() == SortDir.ASCENDING) { + return Long.compare(o2.getStackSize(), o1.getStackSize()); + } + return Long.compare(o1.getStackSize(), o2.getStackSize()); + }; - private static SortDir getDirection() - { - return Direction; - } + private static SortDir getDirection() { + return Direction; + } - public static void setDirection( final SortDir direction ) - { - Direction = direction; - } + public static void setDirection(final SortDir direction) { + Direction = direction; + } } diff --git a/src/main/java/appeng/fluids/util/IAEFluidInventory.java b/src/main/java/appeng/fluids/util/IAEFluidInventory.java index 08c9c7d1a..295f2c44b 100644 --- a/src/main/java/appeng/fluids/util/IAEFluidInventory.java +++ b/src/main/java/appeng/fluids/util/IAEFluidInventory.java @@ -20,7 +20,6 @@ package appeng.fluids.util; @FunctionalInterface -public interface IAEFluidInventory -{ - void onFluidInventoryChanged( final IAEFluidTank inv, final int slot ); +public interface IAEFluidInventory { + void onFluidInventoryChanged(final IAEFluidTank inv, final int slot); } diff --git a/src/main/java/appeng/fluids/util/IAEFluidTank.java b/src/main/java/appeng/fluids/util/IAEFluidTank.java index 8469d55c5..ad232470f 100644 --- a/src/main/java/appeng/fluids/util/IAEFluidTank.java +++ b/src/main/java/appeng/fluids/util/IAEFluidTank.java @@ -1,18 +1,15 @@ - package appeng.fluids.util; +import appeng.api.storage.data.IAEFluidStack; import net.minecraftforge.fluids.capability.IFluidHandler; -import appeng.api.storage.data.IAEFluidStack; +public interface IAEFluidTank extends IFluidHandler { + void setFluidInSlot(final int slot, final IAEFluidStack fluid); -public interface IAEFluidTank extends IFluidHandler -{ - void setFluidInSlot( final int slot, final IAEFluidStack fluid ); + IAEFluidStack getFluidInSlot(final int slot); - IAEFluidStack getFluidInSlot( final int slot ); - - int getSlots(); + int getSlots(); } diff --git a/src/main/java/appeng/fluids/util/MeaningfulFluidIterator.java b/src/main/java/appeng/fluids/util/MeaningfulFluidIterator.java index b92e7f6bc..540562d90 100644 --- a/src/main/java/appeng/fluids/util/MeaningfulFluidIterator.java +++ b/src/main/java/appeng/fluids/util/MeaningfulFluidIterator.java @@ -19,57 +19,47 @@ package appeng.fluids.util; +import appeng.api.storage.data.IAEStack; + import java.util.Iterator; import java.util.NoSuchElementException; -import appeng.api.storage.data.IAEStack; +public class MeaningfulFluidIterator implements Iterator { -public class MeaningfulFluidIterator implements Iterator -{ + private final Iterator parent; + private T next; - private final Iterator parent; - private T next; + public MeaningfulFluidIterator(final Iterator iterator) { + this.parent = iterator; + } - public MeaningfulFluidIterator( final Iterator iterator ) - { - this.parent = iterator; - } + @Override + public boolean hasNext() { + while (this.parent.hasNext()) { + this.next = this.parent.next(); + if (this.next.isMeaningful()) { + return true; + } else { + this.parent.remove(); // self cleaning :3 + } + } - @Override - public boolean hasNext() - { - while( this.parent.hasNext() ) - { - this.next = this.parent.next(); - if( this.next.isMeaningful() ) - { - return true; - } - else - { - this.parent.remove(); // self cleaning :3 - } - } + this.next = null; + return false; + } - this.next = null; - return false; - } + @Override + public T next() { + if (this.next == null) { + throw new NoSuchElementException(); + } - @Override - public T next() - { - if( this.next == null ) - { - throw new NoSuchElementException(); - } + return this.next; + } - return this.next; - } - - @Override - public void remove() - { - this.parent.remove(); - } + @Override + public void remove() { + this.parent.remove(); + } } diff --git a/src/main/java/appeng/helpers/AEGlassMaterial.java b/src/main/java/appeng/helpers/AEGlassMaterial.java index 7667ea789..46c643030 100644 --- a/src/main/java/appeng/helpers/AEGlassMaterial.java +++ b/src/main/java/appeng/helpers/AEGlassMaterial.java @@ -23,25 +23,21 @@ import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; -public class AEGlassMaterial extends Material -{ +public class AEGlassMaterial extends Material { - public static final AEGlassMaterial INSTANCE = ( new AEGlassMaterial( MapColor.AIR ) ); + public static final AEGlassMaterial INSTANCE = (new AEGlassMaterial(MapColor.AIR)); - public AEGlassMaterial( final MapColor color ) - { - super( color ); - } + public AEGlassMaterial(final MapColor color) { + super(color); + } - @Override - public boolean isSolid() - { - return false; - } + @Override + public boolean isSolid() { + return false; + } - @Override - public boolean isOpaque() - { - return false; - } + @Override + public boolean isOpaque() { + return false; + } } diff --git a/src/main/java/appeng/helpers/AEMultiTile.java b/src/main/java/appeng/helpers/AEMultiTile.java index de8165324..76cecdb14 100644 --- a/src/main/java/appeng/helpers/AEMultiTile.java +++ b/src/main/java/appeng/helpers/AEMultiTile.java @@ -24,7 +24,6 @@ import appeng.api.networking.IGridHost; import appeng.api.parts.IPartHost; -public interface AEMultiTile extends IGridHost, IPartHost, IColorableTile -{ +public interface AEMultiTile extends IGridHost, IPartHost, IColorableTile { } diff --git a/src/main/java/appeng/helpers/DualityInterface.java b/src/main/java/appeng/helpers/DualityInterface.java index 71d00303b..b2e936fe0 100644 --- a/src/main/java/appeng/helpers/DualityInterface.java +++ b/src/main/java/appeng/helpers/DualityInterface.java @@ -92,7 +92,6 @@ import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; @@ -102,1710 +101,1339 @@ import javax.annotation.Nullable; import java.util.*; -public class DualityInterface implements IGridTickable, IStorageMonitorable, IInventoryDestination, IAEAppEngInventory, IConfigManagerHost, ICraftingProvider, IUpgradeableHost -{ - public static final int NUMBER_OF_STORAGE_SLOTS = 9; - public static final int NUMBER_OF_CONFIG_SLOTS = 9; - public static final int NUMBER_OF_PATTERN_SLOTS = 36; - - private static final Collection BAD_BLOCKS = new HashSet<>( 100 ); - private final IAEItemStack[] requireWork = {null, null, null, null, null, null, null, null, null}; - private final MultiCraftingTracker craftingTracker; - private final AENetworkProxy gridProxy; - private final IInterfaceHost iHost; - private final IActionSource mySource; - private final IActionSource interfaceRequestSource; - private final ConfigManager cm = new ConfigManager( this ); - private final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, NUMBER_OF_CONFIG_SLOTS ); - private final AppEngInternalInventory storage = new AppEngInternalInventory( this, NUMBER_OF_STORAGE_SLOTS ); - private final AppEngInternalInventory patterns = new AppEngInternalInventory( this, NUMBER_OF_PATTERN_SLOTS ); - private final MEMonitorPassThrough items = new MEMonitorPassThrough<>( new NullInventory(), AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - private final MEMonitorPassThrough fluids = new MEMonitorPassThrough<>( new NullInventory(), AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ); - private final UpgradeInventory upgrades; - private final Accessor accessor = new Accessor(); - private boolean hasConfig = false; - private int priority; - private List craftingList = null; - private List waitingToSend = null; - private IMEInventory destination; - private int isWorking = -1; - private EnumSet visitedFaces = EnumSet.noneOf( EnumFacing.class ); - private EnumMap> waitingToSendFacing = new EnumMap<>( EnumFacing.class ); - private boolean resetConfigCache = true; - private IMEMonitor configCachedHandler; - - public DualityInterface( final AENetworkProxy networkProxy, final IInterfaceHost ih ) - { - this.gridProxy = networkProxy; - this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL ); - - this.upgrades = new StackUpgradeInventory( this.gridProxy.getMachineRepresentation(), this, 4 ); - this.cm.registerSetting( Settings.BLOCK, YesNo.NO ); - this.cm.registerSetting( Settings.INTERFACE_TERMINAL, YesNo.YES ); - - this.iHost = ih; - this.craftingTracker = new MultiCraftingTracker( this.iHost, 9 ); - - final MachineSource actionSource = new MachineSource( this.iHost ); - this.mySource = actionSource; - this.fluids.setChangeSource( actionSource ); - this.items.setChangeSource( actionSource ); - - this.interfaceRequestSource = new InterfaceRequestSource( this.iHost ); - } - - private static boolean invIsCustomBlocking( BlockingInventoryAdaptor inv ) - { - return ( inv.containsBlockingItems() ); - } - - @Override - public void saveChanges() - { - this.iHost.saveChanges(); - } - - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( this.isWorking == slot ) - { - return; - } - if( inv == this.config && ( !removed.isEmpty() || !added.isEmpty() ) ) - { - boolean cfg = hasConfig(); - this.readConfig(); - if( cfg != hasConfig ) - { - resetConfigCache = true; - this.notifyNeighbors(); - } - } - else if( inv == this.patterns && ( !removed.isEmpty() || !added.isEmpty() ) ) - { - this.updateCraftingList(); - } - else if( inv == this.storage && slot >= 0 ) - { - final boolean had = this.hasWorkToDo(); - - this.updatePlan( slot ); - - final boolean now = this.hasWorkToDo(); - - if( had != now ) - { - try - { - if( now ) - { - this.gridProxy.getTick().alertDevice( this.gridProxy.getNode() ); - } - else - { - this.gridProxy.getTick().sleepDevice( this.gridProxy.getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - } - } - - public void writeToNBT( final NBTTagCompound data ) - { - this.config.writeToNBT( data, "config" ); - this.patterns.writeToNBT( data, "patterns" ); - this.storage.writeToNBT( data, "storage" ); - this.upgrades.writeToNBT( data, "upgrades" ); - this.cm.writeToNBT( data ); - this.craftingTracker.writeToNBT( data ); - data.setInteger( "priority", this.priority ); - - final NBTTagList waitingToSend = new NBTTagList(); - if( this.waitingToSend != null ) - { - for( final ItemStack is : this.waitingToSend ) - { - final NBTTagCompound item = new NBTTagCompound(); - is.writeToNBT( item ); - waitingToSend.appendTag( item ); - } - } - data.setTag( "waitingToSend", waitingToSend ); - - NBTTagCompound sidedWaitList = new NBTTagCompound(); - - if( this.waitingToSendFacing != null ) - { - for( EnumFacing s : this.iHost.getTargets() ) - { - NBTTagList waitingListSided = new NBTTagList(); - if( this.waitingToSendFacing.containsKey( s ) ) - { - for( final ItemStack is : this.waitingToSendFacing.get( s ) ) - { - final NBTTagCompound item = new NBTTagCompound(); - is.writeToNBT( item ); - waitingListSided.appendTag( item ); - } - sidedWaitList.setTag( s.name(), waitingListSided ); - } - } - } - data.setTag( "sidedWaitList", sidedWaitList ); - } - - public void readFromNBT( final NBTTagCompound data ) - { - this.waitingToSend = null; - final NBTTagList waitingList = data.getTagList( "waitingToSend", 10 ); - if( waitingList != null ) - { - for( int x = 0; x < waitingList.tagCount(); x++ ) - { - final NBTTagCompound c = waitingList.getCompoundTagAt( x ); - if( c != null ) - { - final ItemStack is = new ItemStack( c ); - this.addToSendList( is ); - } - } - } - - this.waitingToSendFacing = null; - final NBTTagCompound waitingListSided = data.getCompoundTag( "sidedWaitList" ); - - for( EnumFacing s : EnumFacing.values() ) - { - if( waitingListSided.hasKey( s.name() ) ) - { - NBTTagList w = waitingListSided.getTagList( s.name(), 10 ); - for( int x = 0; x < w.tagCount(); x++ ) - { - final NBTTagCompound c = w.getCompoundTagAt( x ); - if( c != null ) - { - final ItemStack is = new ItemStack( c ); - this.addToSendListFacing( is, EnumFacing.getFront( s.getIndex() ) ); - } - } - } - } - - this.craftingTracker.readFromNBT( data ); - - // fix upgrade slot size mismatch - NBTTagCompound up = data.getCompoundTag( "upgrades" ); - if( up.hasKey( "Size" ) && up.getInteger( "Size" ) != this.upgrades.getSlots() ) - { - up.setInteger( "Size", this.upgrades.getSlots() ); - this.upgrades.writeToNBT( up, "upgrades" ); - } - - this.upgrades.readFromNBT( data, "upgrades" ); - this.config.readFromNBT( data, "config" ); - - NBTTagCompound pa = data.getCompoundTag( "patterns" ); - if( pa.hasKey( "Size" ) && pa.getInteger( "Size" ) != this.patterns.getSlots() ) - { - pa.setInteger( "Size", this.patterns.getSlots() ); - this.upgrades.writeToNBT( pa, "patterns" ); - } - - this.patterns.readFromNBT( data, "patterns" ); - this.storage.readFromNBT( data, "storage" ); - this.priority = data.getInteger( "priority" ); - this.cm.readFromNBT( data ); - this.readConfig(); - this.updateCraftingList(); - } - - private void addToSendList( final ItemStack is ) - { - if( is.isEmpty() ) - { - return; - } - - if( this.waitingToSend == null ) - { - this.waitingToSend = new ArrayList<>(); - } - - this.waitingToSend.add( is ); - - try - { - this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - private void addToSendListFacing( final ItemStack is, EnumFacing f ) - { - if( is.isEmpty() ) - { - return; - } - if( this.waitingToSendFacing == null ) - { - this.waitingToSendFacing = new EnumMap<>( EnumFacing.class ); - } - - this.waitingToSendFacing.computeIfAbsent( f, k -> new ArrayList<>() ); - - this.waitingToSendFacing.get( f ).add( is ); - - try - { - this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - private void readConfig() - { - this.hasConfig = false; - - for( final ItemStack p : this.config ) - { - if( !p.isEmpty() ) - { - this.hasConfig = true; - break; - } - } - - final boolean had = this.hasWorkToDo(); - - for( int x = 0; x < NUMBER_OF_CONFIG_SLOTS; x++ ) - { - this.updatePlan( x ); - } - - final boolean has = this.hasWorkToDo(); - - if( had != has ) - { - try - { - if( has ) - { - this.gridProxy.getTick().alertDevice( this.gridProxy.getNode() ); - } - else - { - this.gridProxy.getTick().sleepDevice( this.gridProxy.getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - this.notifyNeighbors(); - } - - private void updateCraftingList() - { - final Boolean[] accountedFor = new Boolean[this.patterns.getSlots()]; - Arrays.fill( accountedFor, false ); - - if( !this.gridProxy.isReady() ) - { - return; - } - - boolean removed = false; - - if( this.craftingList != null ) - { - final Iterator i = this.craftingList.iterator(); - while ( i.hasNext() ) - { - final ICraftingPatternDetails details = i.next(); - boolean found = false; - - for( int x = 0; x < accountedFor.length; x++ ) - { - final ItemStack is = this.patterns.getStackInSlot( x ); - if( details.getPattern() == is ) - { - accountedFor[x] = found = true; - } - } - - if( !found ) - { - removed = true; - i.remove(); - } - } - } - - boolean newPattern = false; - - for( int x = 0; x < accountedFor.length; x++ ) - { - if( !accountedFor[x] ) - { - newPattern = true; - this.addToCraftingList( this.patterns.getStackInSlot( x ) ); - } - } - try - { - this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) ); - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - } - - private boolean hasWorkToDo() - { - - if( hasItemsToSend() ) - { - return true; - } - - if( hasItemsToSendFacing() ) - { - return true; - } - - for( final IAEItemStack requiredWork : this.requireWork ) - { - if( requiredWork != null ) - { - return true; - } - } - return false; - } - - private void updatePlan( final int slot ) - { - IAEItemStack req = this.config.getAEStackInSlot( slot ); - if( req != null && req.getStackSize() <= 0 ) - { - this.config.setStackInSlot( slot, ItemStack.EMPTY ); - req = null; - } - - final ItemStack stored = this.storage.getStackInSlot( slot ); - - if( req == null && !stored.isEmpty() ) - { - final IAEItemStack work = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( stored ); - this.requireWork[slot] = work.setStackSize( -work.getStackSize() ); - return; - } - else if( req != null ) - { - if( stored.isEmpty() ) // need to add stuff! - { - this.requireWork[slot] = req.copy(); - return; - } - else if( req.isSameType( stored ) ) // same type and quantity )! - { - if( req.getStackSize() == stored.getCount() ) - { - this.requireWork[slot] = null; - } - else // same type ( qty different? )! - { - this.requireWork[slot] = req.copy(); - this.requireWork[slot].setStackSize( req.getStackSize() - stored.getCount() ); - } - return; - } - else - // Stored != null; dispose! - { - final IAEItemStack work = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( stored ); - this.requireWork[slot] = work.setStackSize( -work.getStackSize() ); - return; - } - } - - // else - - this.requireWork[slot] = null; - } - - public void notifyNeighbors() - { - if( this.gridProxy.isActive() ) - { - try - { - this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) ); - this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - final TileEntity te = this.iHost.getTileEntity(); - if( te != null && te.getWorld() != null ) - { - Platform.notifyBlocksOfNeighbors( te.getWorld(), te.getPos() ); - } - } - - private void addToCraftingList( final ItemStack is ) - { - if( is.isEmpty() ) - { - return; - } - - if( is.getItem() instanceof ICraftingPatternItem ) - { - final ICraftingPatternItem cpi = (ICraftingPatternItem) is.getItem(); - final ICraftingPatternDetails details = cpi.getPatternForItem( is, this.iHost.getTileEntity().getWorld() ); - - if( details != null ) - { - if( this.craftingList == null ) - { - this.craftingList = new ArrayList<>(); - } - - this.craftingList.add( details ); - } - } - } - - private boolean hasItemsToSend() - { - return this.waitingToSend != null && !this.waitingToSend.isEmpty(); - } - - private boolean hasItemsToSendFacing() - { - if( waitingToSendFacing != null ) - { - for( EnumFacing enumFacing : waitingToSendFacing.keySet() ) - { - if( !waitingToSendFacing.get( enumFacing ).isEmpty() ) - { - return true; - } - } - } - return false; - } - - public void dropExcessPatterns() - { - IItemHandler patterns = getPatterns(); - - List dropList = new ArrayList<>(); - for( int invSlot = 0; invSlot < patterns.getSlots(); invSlot++ ) - { - if( invSlot > 8 + this.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION ) * 9 ) - { - ItemStack is = patterns.getStackInSlot( invSlot ); - if( is.isEmpty() ) - { - continue; - } - dropList.add( patterns.extractItem( invSlot, Integer.MAX_VALUE, false ) ); - } - } - if( dropList.size() > 0 ) - { - World world = this.getLocation().getWorld(); - BlockPos blockPos = this.getLocation().getPos(); - Platform.spawnDrops( world, blockPos, dropList ); - } - - this.gridProxy.setIdlePowerUsage( Math.pow( 4, ( this.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION ) ) ) ); - } - - @Override - public boolean canInsert( final ItemStack stack ) - { - final IAEItemStack out = this.destination.injectItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( stack ), Actionable.SIMULATE, null ); - if( out == null ) - { - return true; - } - return out.getStackSize() != stack.getCount(); - } - - public IItemHandler getConfig() - { - return this.config; - } - - public IItemHandler getPatterns() - { - return this.patterns; - } - - public void gridChanged() - { - try - { - this.items.setInternal( this.gridProxy.getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) ); - this.fluids.setInternal( this.gridProxy.getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) ); - } - catch( final GridAccessException gae ) - { - this.items.setInternal( new NullInventory() ); - this.fluids.setInternal( new NullInventory() ); - } - - this.notifyNeighbors(); - } - - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.SMART; - } - - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this.iHost.getTileEntity() ); - } - - public IItemHandler getInternalInventory() - { - return this.storage; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.Interface.getMin(), TickRates.Interface.getMax(), !this.hasWorkToDo(), true ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( !this.gridProxy.isActive() ) - { - return TickRateModulation.SLEEP; - } - - //Previous version might have items saved in this list - //recover them - if( this.hasItemsToSend() ) - { - this.pushItemsOut( this.iHost.getTargets() ); - } - - if( hasItemsToSendFacing() ) - { - for( EnumFacing enumFacing : waitingToSendFacing.keySet() ) - { - this.pushItemsOut( enumFacing ); - } - } - - final boolean couldDoWork = this.updateStorage(); - return this.hasWorkToDo() ? ( couldDoWork ? TickRateModulation.URGENT : TickRateModulation.SLOWER ) : TickRateModulation.SLEEP; - } - - private void pushItemsOut( final EnumSet possibleDirections ) - { - if( !this.hasItemsToSend() ) - { - return; - } - - final TileEntity tile = this.iHost.getTileEntity(); - final World w = tile.getWorld(); - - final Iterator i = this.waitingToSend.iterator(); - while ( i.hasNext() ) - { - ItemStack whatToSend = i.next(); - - for( final EnumFacing s : possibleDirections ) - { - final TileEntity te = w.getTileEntity( tile.getPos().offset( s ) ); - if( te == null ) - { - continue; - } - - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); - if( ad != null ) - { - final ItemStack result = ad.addItems( whatToSend ); - - if( result.isEmpty() ) - { - whatToSend = ItemStack.EMPTY; - } - else - { - whatToSend.setCount( whatToSend.getCount() - ( whatToSend.getCount() - result.getCount() ) ); - } - - if( whatToSend.isEmpty() ) - { - break; - } - } - } - - if( whatToSend.isEmpty() ) - { - i.remove(); - } - } - - if( this.waitingToSend.isEmpty() ) - { - this.waitingToSend = null; - } - } - - private void pushItemsOut( final EnumFacing s ) - { - if( !this.waitingToSendFacing.containsKey( s ) || ( this.waitingToSendFacing.containsKey( s ) && this.waitingToSendFacing.get( s ).isEmpty() ) ) - { - return; - } - - final TileEntity tile = this.iHost.getTileEntity(); - final World w = tile.getWorld(); - - final TileEntity te = w.getTileEntity( tile.getPos().offset( s ) ); - if( te == null ) - { - return; - } - - if( te instanceof IInterfaceHost || ( te instanceof TileCableBus && ( (TileCableBus) te ).getPart( s.getOpposite() ) instanceof PartInterface ) ) - { - try - { - IInterfaceHost targetTE; - if( te instanceof IInterfaceHost ) - { - targetTE = (IInterfaceHost) te; - } - else - { - targetTE = (IInterfaceHost) ( (TileCableBus) te ).getPart( s.getOpposite() ); - } - - if( !targetTE.getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) ) - { - IStorageMonitorableAccessor mon = te.getCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, s.getOpposite() ); - if( mon != null ) - { - IStorageMonitorable sm = mon.getInventory( this.mySource ); - if( sm != null && Platform.canAccess( targetTE.getInterfaceDuality().gridProxy, this.mySource ) ) - { - IMEMonitor inv = sm.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - if( inv != null ) - { - final Iterator i = this.waitingToSendFacing.get( s ).iterator(); - while ( i.hasNext() ) - { - ItemStack whatToSend = i.next(); - final IAEItemStack result = inv.injectItems( AEItemStack.fromItemStack( whatToSend ), Actionable.MODULATE, this.mySource ); - if( result != null ) - { - whatToSend.setCount( (int) result.getStackSize() ); - } - else - { - i.remove(); - } - } - if( this.waitingToSendFacing.get( s ).isEmpty() ) - { - this.waitingToSendFacing.remove( s ); - } - } - } - } - } - else - { - return; - } - } - catch( GridAccessException e ) - { - throw new RuntimeException( e ); - } - return; - } - - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); - - final Iterator i = this.waitingToSendFacing.get( s ).iterator(); - while ( i.hasNext() ) - { - ItemStack whatToSend = i.next(); - if( ad != null ) - { - final ItemStack result = ad.addItems( whatToSend ); - if( !result.isEmpty() ) - { - whatToSend.setCount( result.getCount() ); - } - else - { - i.remove(); - } - } - } - - if( this.waitingToSendFacing.get( s ).isEmpty() ) - { - this.waitingToSendFacing.remove( s ); - } - } - - private boolean updateStorage() - { - boolean didSomething = false; - - for( int x = 0; x < NUMBER_OF_STORAGE_SLOTS; x++ ) - { - if( this.requireWork[x] != null ) - { - didSomething = this.usePlan( x, this.requireWork[x] ) || didSomething; - } - } - - return didSomething; - } - - private boolean usePlan( final int x, final IAEItemStack itemStack ) - { - final InventoryAdaptor adaptor = this.getAdaptor( x ); - this.isWorking = x; - - boolean changed = false; - try - { - this.destination = this.gridProxy.getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - final IEnergySource src = this.gridProxy.getEnergy(); - - if( itemStack.getStackSize() < 0 ) - { - IAEItemStack toStore = itemStack.copy(); - toStore.setStackSize( -toStore.getStackSize() ); - - long diff = toStore.getStackSize(); - - // make sure strange things didn't happen... - // TODO: check if OK - final ItemStack canExtract = adaptor.simulateRemove( (int) diff, toStore.getDefinition(), null ); - if( canExtract.isEmpty() || canExtract.getCount() != diff ) - { - changed = true; - throw new GridAccessException(); - } - - toStore = Platform.poweredInsert( src, this.destination, toStore, this.interfaceRequestSource ); - - if( toStore != null ) - { - diff -= toStore.getStackSize(); - } - - if( diff != 0 ) - { - // extract items! - changed = true; - final ItemStack removed = adaptor.removeItems( (int) diff, ItemStack.EMPTY, null ); - if( removed.isEmpty() ) - { - throw new IllegalStateException( "bad attempt at managing inventory. ( removeItems )" ); - } - else if( removed.getCount() != diff ) - { - throw new IllegalStateException( "bad attempt at managing inventory. ( removeItems )" ); - } - } - } - - if( this.craftingTracker.isBusy( x ) ) - { - changed = this.handleCrafting( x, adaptor, itemStack ) || changed; - } - else if( itemStack.getStackSize() > 0 ) - { - // make sure strange things didn't happen... - - ItemStack inputStack = itemStack.getCachedItemStack( itemStack.getStackSize() ); - - ItemStack remaining = adaptor.simulateAdd( inputStack ); - - if( !remaining.isEmpty() ) - { - itemStack.setCachedItemStack( remaining ); - changed = true; - throw new GridAccessException(); - } - - IAEItemStack storedStack = this.gridProxy.getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).getStorageList().findPrecise( itemStack ); - if( storedStack != null ) - { - final IAEItemStack acquired = Platform.poweredExtraction( src, this.destination, itemStack, this.interfaceRequestSource ); - if( acquired != null ) - { - changed = true; - inputStack.setCount( Ints.saturatedCast( acquired.getStackSize() ) ); - final ItemStack issue = adaptor.addItems( inputStack ); - if( !issue.isEmpty() ) - { - throw new IllegalStateException( "bad attempt at managing inventory. ( addItems )" ); - } - } - else if( storedStack.isCraftable() ) - { - itemStack.setCachedItemStack( inputStack ); - changed = this.handleCrafting( x, adaptor, itemStack ) || changed; - } - if( acquired == null ) - { - itemStack.setCachedItemStack( inputStack ); - } - } - } - // else wtf? - } - catch( final GridAccessException e ) - { - // :P - } - - if( changed ) - { - this.updatePlan( x ); - } - - this.isWorking = -1; - return changed; - } - - private InventoryAdaptor getAdaptor( final int slot ) - { - return new AdaptorItemHandler( new RangedWrapper( this.storage, slot, slot + 1 ) ); - } - - private boolean handleCrafting( final int x, final InventoryAdaptor d, final IAEItemStack itemStack ) - { - try - { - if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 && itemStack != null ) - { - return this.craftingTracker.handleCrafting( x, itemStack.getStackSize(), itemStack, d, this.iHost.getTileEntity().getWorld(), this.gridProxy.getGrid(), this.gridProxy.getCrafting(), this.mySource ); - } - } - catch( final GridAccessException e ) - { - // :P - } - - return false; - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - if( this.upgrades == null ) - { - return 0; - } - return this.upgrades.getInstalledUpgrades( u ); - } - - @Override - public TileEntity getTile() - { - return (TileEntity) ( this.iHost instanceof TileEntity ? this.iHost : null ); - } - - @Override - public > IMEMonitor getInventory( IStorageChannel channel ) - { - if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - if( this.hasConfig() ) - { - if( resetConfigCache ) - { - resetConfigCache = false; - configCachedHandler = new InterfaceInventory( this ); - } - return (IMEMonitor) configCachedHandler; - } - - return (IMEMonitor) this.items; - } - else if( channel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) - { - if( this.hasConfig() ) - { - return null; - } - - return (IMEMonitor) this.fluids; - } - - return null; - } - - private boolean hasConfig() - { - return this.hasConfig; - } - - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "storage" ) ) - { - return this.storage; - } - - if( name.equals( "patterns" ) ) - { - return this.patterns; - } - - if( name.equals( "config" ) ) - { - return this.config; - } - - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - return null; - } - - public IItemHandler getStorage() - { - return this.storage; - } - - @Override - public appeng.api.util.IConfigManager getConfigManager() - { - return this.cm; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - if( this.getInstalledUpgrades( Upgrades.CRAFTING ) == 0 ) - { - this.cancelCrafting(); - } - this.iHost.saveChanges(); - } - - private void cancelCrafting() - { - this.craftingTracker.cancel(); - } - - public IStorageMonitorable getMonitorable( final IActionSource src, final IStorageMonitorable myInterface ) - { - if( Platform.canAccess( this.gridProxy, src ) ) - { - return myInterface; - } - - final DualityInterface di = this; - - return new IStorageMonitorable() - { - - @Override - public > IMEMonitor getInventory( IStorageChannel channel ) - { - if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - return (IMEMonitor) new InterfaceInventory( di ); - } - return null; - } - }; - } - - private boolean invIsBlocked( InventoryAdaptor inv ) - { - return ( inv.containsItems() ); - } - - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) - { - if( this.hasItemsToSend() || this.hasItemsToSendFacing() || !this.gridProxy.isActive() || !this.craftingList.contains( patternDetails ) ) - { - return false; - } - - final TileEntity tile = this.iHost.getTileEntity(); - final World w = tile.getWorld(); - - if( this.visitedFaces.isEmpty() ) - { - this.visitedFaces = this.iHost.getTargets(); - } - - for( final EnumFacing s : visitedFaces ) - { - final TileEntity te = w.getTileEntity( tile.getPos().offset( s ) ); - if( te instanceof IInterfaceHost || ( te instanceof TileCableBus && ( (TileCableBus) te ).getPart( s.getOpposite() ) instanceof PartInterface ) ) - { - visitedFaces.remove( s ); - try - { - IInterfaceHost targetTE; - if( te instanceof IInterfaceHost ) - { - targetTE = (IInterfaceHost) te; - } - else - { - targetTE = (IInterfaceHost) ( (TileCableBus) te ).getPart( s.getOpposite() ); - } - - if( targetTE.getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) ) - { - continue; - } - else - { - IStorageMonitorableAccessor mon = te.getCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, s.getOpposite() ); - if( mon != null ) - { - IStorageMonitorable sm = mon.getInventory( this.mySource ); - if( sm != null && Platform.canAccess( targetTE.getInterfaceDuality().gridProxy, this.mySource ) ) - { - if( this.isBlocking() && sm.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).getStorageList().size() > 0 ) - { - continue; - } - else - { - IMEMonitor inv = sm.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - for( int x = 0; x < table.getSizeInventory(); x++ ) - { - final ItemStack is = table.getStackInSlot( x ); - if( is.isEmpty() ) - { - continue; - } - IAEItemStack result = inv.injectItems( AEItemStack.fromItemStack( is ), Actionable.SIMULATE, this.mySource ); - if( result != null ) - { - return false; - } - } - for( int x = 0; x < table.getSizeInventory(); x++ ) - { - final ItemStack is = table.getStackInSlot( x ); - if( !is.isEmpty() ) - { - addToSendListFacing( is, s ); - } - } - pushItemsOut( s ); - return true; - } - } - } - } - } - catch( final GridAccessException e ) - { - continue; - } - continue; - } - - if( te instanceof ICraftingMachine ) - { - final ICraftingMachine cm = (ICraftingMachine) te; - if( cm.acceptsPlans() ) - { - visitedFaces.remove( s ); - if( cm.pushPattern( patternDetails, table, s.getOpposite() ) ) - { - return true; - } - continue; - } - } - - InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); - if( ad != null ) - { - if( this.isBlocking() ) - { - IPhantomTile phantomTE; - if( Loader.isModLoaded( "actuallyadditions" ) && te instanceof IPhantomTile ) - { - phantomTE = ( (IPhantomTile) te ); - if( phantomTE.hasBoundPosition() ) - { - TileEntity phantom = w.getTileEntity( phantomTE.getBoundPosition() ); - if( NonBlockingItems.INSTANCE.getMap().containsKey( w.getBlockState( phantomTE.getBoundPosition() ).getBlock().getRegistryName().getResourceDomain() ) ) - { - if( isCustomInvBlocking( phantom, s ) ) - { - visitedFaces.remove( s ); - continue; - } - } - } - } - else if( NonBlockingItems.INSTANCE.getMap().containsKey( w.getBlockState( tile.getPos().offset( s ) ).getBlock().getRegistryName().getResourceDomain() ) ) - { - if( isCustomInvBlocking( te, s ) ) - { - visitedFaces.remove( s ); - continue; - } - } - else if( invIsBlocked( ad ) ) - { - visitedFaces.remove( s ); - continue; - } - } - - if( this.acceptsItems( ad, table ) ) - { - visitedFaces.remove( s ); - for( int x = 0; x < table.getSizeInventory(); x++ ) - { - final ItemStack is = table.getStackInSlot( x ); - if( !is.isEmpty() ) - { - addToSendListFacing( is, s ); - } - } - pushItemsOut( s ); - return true; - } - } - visitedFaces.remove( s ); - } - return false; - } - - @Override - public boolean isBusy() - { - boolean busy = false; - - if( this.hasItemsToSend() || hasItemsToSendFacing() ) - { - return true; - } - - if( this.isBlocking() ) - { - final EnumSet possibleDirections = this.iHost.getTargets(); - final TileEntity tile = this.iHost.getTileEntity(); - final World w = tile.getWorld(); - - boolean allAreBusy = true; - - for( final EnumFacing s : possibleDirections ) - { - final TileEntity te = w.getTileEntity( tile.getPos().offset( s ) ); - - if( te instanceof IInterfaceHost || ( te instanceof TileCableBus && ( (TileCableBus) te ).getPart( s.getOpposite() ) instanceof PartInterface ) ) - { - try - { - IInterfaceHost targetTE; - if( te instanceof IInterfaceHost ) - { - targetTE = (IInterfaceHost) te; - } - else - { - targetTE = (IInterfaceHost) ( (TileCableBus) te ).getPart( s.getOpposite() ); - } - - if( targetTE.getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) ) - { - continue; - } - else - { - IStorageMonitorableAccessor mon = te.getCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, s.getOpposite() ); - if( mon != null ) - { - IStorageMonitorable sm = mon.getInventory( this.mySource ); - if( sm != null && Platform.canAccess( targetTE.getInterfaceDuality().gridProxy, this.mySource ) ) - { - if( sm.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).getStorageList().isEmpty() ) - { - allAreBusy = false; - break; - } - } - } - } - } - catch( final GridAccessException e ) - { - continue; - } - continue; - } - - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); - if( ad != null ) - { - if( Loader.isModLoaded( "actuallyadditions" ) && Loader.isModLoaded( "gregtech" ) && te instanceof IPhantomTile ) - { - IPhantomTile phantomTE = ( (IPhantomTile) te ); - if( phantomTE.hasBoundPosition() ) - { - TileEntity phantom = w.getTileEntity( phantomTE.getBoundPosition() ); - if( NonBlockingItems.INSTANCE.getMap().containsKey( w.getBlockState( phantomTE.getBoundPosition() ).getBlock().getRegistryName().getResourceDomain() ) ) - { - if( !isCustomInvBlocking( phantom, s ) ) - { - allAreBusy = false; - break; - } - } - } - } - else if( NonBlockingItems.INSTANCE.getMap().containsKey( w.getBlockState( tile.getPos().offset( s ) ).getBlock().getRegistryName().getResourceDomain() ) ) - { - if( !isCustomInvBlocking( te, s ) ) - { - allAreBusy = false; - break; - } - } - else - { - if( !invIsBlocked( ad ) ) - { - allAreBusy = false; - break; - } - } - } - } - busy = allAreBusy; - } - return busy; - } - - boolean isCustomInvBlocking( TileEntity te, EnumFacing s ) - { - BlockingInventoryAdaptor blockingInventoryAdaptor = BlockingInventoryAdaptor.getAdaptor( te, s.getOpposite() ); - return invIsCustomBlocking( blockingInventoryAdaptor ); - } - - private boolean sameGrid( final IGrid grid ) throws GridAccessException - { - return grid == this.gridProxy.getGrid(); - } - - private boolean isBlocking() - { - return this.cm.getSetting( Settings.BLOCK ) == YesNo.YES; - } - - private boolean acceptsItems( final InventoryAdaptor ad, final InventoryCrafting table ) - { - for( int x = 0; x < table.getSizeInventory(); x++ ) - { - final ItemStack is = table.getStackInSlot( x ); - if( is.isEmpty() ) - { - continue; - } - - if( !ad.simulateAdd( is ).isEmpty() ) - { - return false; - } - } - - return true; - } - - @Override - public void provideCrafting( final ICraftingProviderHelper craftingTracker ) - { - if( this.gridProxy.isActive() && this.craftingList != null ) - { - for( final ICraftingPatternDetails details : this.craftingList ) - { - details.setPriority( this.priority ); - craftingTracker.addCraftingOption( this, details ); - } - } - } - - public void addDrops( final List drops ) - { - if( this.waitingToSend != null ) - { - for( final ItemStack is : this.waitingToSend ) - { - if( !is.isEmpty() ) - { - drops.add( is ); - } - } - } - - if( this.waitingToSendFacing != null ) - { - for( List itemList : waitingToSendFacing.values() ) - { - for( final ItemStack is : itemList ) - { - if( !is.isEmpty() ) - { - drops.add( is ); - } - } - } - } - - for( final ItemStack is : this.upgrades ) - { - if( !is.isEmpty() ) - { - drops.add( is ); - } - } - - for( final ItemStack is : this.storage ) - { - if( !is.isEmpty() ) - { - drops.add( is ); - } - } - - for( final ItemStack is : this.patterns ) - { - if( !is.isEmpty() ) - { - drops.add( is ); - } - } - } - - public IUpgradeableHost getHost() - { - if( this.getPart() instanceof IUpgradeableHost ) - { - return (IUpgradeableHost) this.getPart(); - } - if( this.getTile() instanceof IUpgradeableHost ) - { - return (IUpgradeableHost) this.getTile(); - } - return null; - } - - private IPart getPart() - { - return (IPart) ( this.iHost instanceof IPart ? this.iHost : null ); - } - - public ImmutableSet getRequestedJobs() - { - return this.craftingTracker.getRequestedJobs(); - } - - public IAEItemStack injectCraftedItems( final ICraftingLink link, final IAEItemStack acquired, final Actionable mode ) - { - final int slot = this.craftingTracker.getSlot( link ); - - if( acquired != null && slot >= 0 && slot <= this.requireWork.length ) - { - final InventoryAdaptor adaptor = this.getAdaptor( slot ); - - if( mode == Actionable.SIMULATE ) - { - return AEItemStack.fromItemStack( adaptor.simulateAdd( acquired.createItemStack() ) ); - } - else - { - final IAEItemStack is = AEItemStack.fromItemStack( adaptor.addItems( acquired.createItemStack() ) ); - this.updatePlan( slot ); - return is; - } - } - - return acquired; - } - - public void jobStateChange( final ICraftingLink link ) - { - this.craftingTracker.jobStateChange( link ); - } - - public String getTermName() - { - final TileEntity hostTile = this.iHost.getTileEntity(); - final World hostWorld = hostTile.getWorld(); - - if( ( (ICustomNameObject) this.iHost ).hasCustomInventoryName() ) - { - return ( (ICustomNameObject) this.iHost ).getCustomInventoryName(); - } - - final EnumSet possibleDirections = this.iHost.getTargets(); - for( final EnumFacing direction : possibleDirections ) - { - final BlockPos targ = hostTile.getPos().offset( direction ); - final TileEntity directedTile = hostWorld.getTileEntity( targ ); - - if( directedTile == null ) - { - continue; - } - - if( directedTile instanceof IInterfaceHost ) - { - try - { - if( ( (IInterfaceHost) directedTile ).getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) ) - { - continue; - } - } - catch( final GridAccessException e ) - { - continue; - } - } - - final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor( directedTile, direction.getOpposite() ); - if( directedTile instanceof ICraftingMachine || adaptor != null ) - { - if( adaptor != null && !adaptor.hasSlots() ) - { - continue; - } - - final IBlockState directedBlockState = hostWorld.getBlockState( targ ); - final Block directedBlock = directedBlockState.getBlock(); - ItemStack what = new ItemStack( directedBlock, 1, directedBlock.getMetaFromState( directedBlockState ) ); - - if( Loader.isModLoaded( "gregtech" ) && directedBlock instanceof BlockMachine ) - { - MetaTileEntity metaTileEntity = Platform.getMetaTileEntity( directedTile.getWorld(), directedTile.getPos() ); - if( metaTileEntity != null ) - { - return metaTileEntity.getMetaFullName(); - } - } - - try - { - Vec3d from = new Vec3d( hostTile.getPos().getX() + 0.5, hostTile.getPos().getY() + 0.5, hostTile.getPos().getZ() + 0.5 ); - from = from.addVector( direction.getFrontOffsetX() * 0.501, direction.getFrontOffsetY() * 0.501, direction.getFrontOffsetZ() * 0.501 ); - final Vec3d to = from.addVector( direction.getFrontOffsetX(), direction.getFrontOffsetY(), direction.getFrontOffsetZ() ); - final RayTraceResult mop = hostWorld.rayTraceBlocks( from, to, true ); - if( mop != null && !BAD_BLOCKS.contains( directedBlock ) ) - { - if( mop.getBlockPos().equals( directedTile.getPos() ) ) - { - final ItemStack g = directedBlock.getPickBlock( directedBlockState, mop, hostWorld, directedTile.getPos(), null ); - if( !g.isEmpty() ) - { - what = g; - } - } - } - } - catch( final Throwable t ) - { - BAD_BLOCKS.add( directedBlock ); // nope! - } - - if( what.getItem() != Items.AIR ) - { - return what.getItem().getItemStackDisplayName( what ); - } - - final Item item = Item.getItemFromBlock( directedBlock ); - if( item == Items.AIR ) - { - return directedBlock.getUnlocalizedName(); - } - } - } - - return "Nothing"; - } - - public long getSortValue() - { - final TileEntity te = this.iHost.getTileEntity(); - return ( te.getPos().getZ() << 24 ) ^ ( te.getPos().getX() << 8 ) ^ te.getPos().getY(); - } - - public void initialize() - { - this.updateCraftingList(); - } - - public int getPriority() - { - return this.priority; - } - - public void setPriority( final int newValue ) - { - this.priority = newValue; - this.iHost.saveChanges(); - - try - { - this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - public boolean hasCapability( Capability capabilityClass, EnumFacing facing ) - { - return capabilityClass == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || capabilityClass == Capabilities.STORAGE_MONITORABLE_ACCESSOR; - } - - @SuppressWarnings( "unchecked" ) - public T getCapability( Capability capabilityClass, EnumFacing facing ) - { - if( capabilityClass == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY ) - { - return (T) this.storage; - } - else if( capabilityClass == Capabilities.STORAGE_MONITORABLE_ACCESSOR ) - { - return (T) this.accessor; - } - return null; - } - - private class InterfaceRequestSource extends MachineSource - { - private final InterfaceRequestContext context; - - public InterfaceRequestSource( IActionHost v ) - { - super( v ); - this.context = new InterfaceRequestContext(); - } - - @Override - public Optional context( Class key ) - { - if( key == InterfaceRequestContext.class ) - { - return (Optional) Optional.of( this.context ); - } - - return super.context( key ); - } - - } - - - private class InterfaceRequestContext implements Comparable - { - - @Override - public int compareTo( Integer o ) - { - return Integer.compare( DualityInterface.this.priority, o ); - } - } - - - private class InterfaceInventory extends MEMonitorIInventory - { - - public InterfaceInventory( final DualityInterface tileInterface ) - { - super( new AdaptorItemHandler( tileInterface.storage ) ); - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final IActionSource src ) - { - final Optional context = src.context( InterfaceRequestContext.class ); - final boolean isInterface = context.isPresent(); - - if( isInterface ) - { - return input; - } - - return super.injectItems( input, type, src ); - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable type, final IActionSource src ) - { - final Optional context = src.context( InterfaceRequestContext.class ); - final boolean hasLowerOrEqualPriority = context.map( c -> c.compareTo( DualityInterface.this.priority ) <= 0 ).orElse( false ); - - if( hasLowerOrEqualPriority ) - { - return null; - } - - return super.extractItems( request, type, src ); - } - } - - - private class Accessor implements IStorageMonitorableAccessor - { - - @Nullable - @Override - public IStorageMonitorable getInventory( IActionSource src ) - { - return DualityInterface.this.getMonitorable( src, DualityInterface.this ); - } - - } +public class DualityInterface implements IGridTickable, IStorageMonitorable, IInventoryDestination, IAEAppEngInventory, IConfigManagerHost, ICraftingProvider, IUpgradeableHost { + public static final int NUMBER_OF_STORAGE_SLOTS = 9; + public static final int NUMBER_OF_CONFIG_SLOTS = 9; + public static final int NUMBER_OF_PATTERN_SLOTS = 36; + + private static final Collection BAD_BLOCKS = new HashSet<>(100); + private final IAEItemStack[] requireWork = {null, null, null, null, null, null, null, null, null}; + private final MultiCraftingTracker craftingTracker; + private final AENetworkProxy gridProxy; + private final IInterfaceHost iHost; + private final IActionSource mySource; + private final IActionSource interfaceRequestSource; + private final ConfigManager cm = new ConfigManager(this); + private final AppEngInternalAEInventory config = new AppEngInternalAEInventory(this, NUMBER_OF_CONFIG_SLOTS); + private final AppEngInternalInventory storage = new AppEngInternalInventory(this, NUMBER_OF_STORAGE_SLOTS); + private final AppEngInternalInventory patterns = new AppEngInternalInventory(this, NUMBER_OF_PATTERN_SLOTS); + private final MEMonitorPassThrough items = new MEMonitorPassThrough<>(new NullInventory(), AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + private final MEMonitorPassThrough fluids = new MEMonitorPassThrough<>(new NullInventory(), AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)); + private final UpgradeInventory upgrades; + private final Accessor accessor = new Accessor(); + private boolean hasConfig = false; + private int priority; + private List craftingList = null; + private List waitingToSend = null; + private IMEInventory destination; + private int isWorking = -1; + private EnumSet visitedFaces = EnumSet.noneOf(EnumFacing.class); + private EnumMap> waitingToSendFacing = new EnumMap<>(EnumFacing.class); + private boolean resetConfigCache = true; + private IMEMonitor configCachedHandler; + + public DualityInterface(final AENetworkProxy networkProxy, final IInterfaceHost ih) { + this.gridProxy = networkProxy; + this.gridProxy.setFlags(GridFlags.REQUIRE_CHANNEL); + + this.upgrades = new StackUpgradeInventory(this.gridProxy.getMachineRepresentation(), this, 4); + this.cm.registerSetting(Settings.BLOCK, YesNo.NO); + this.cm.registerSetting(Settings.INTERFACE_TERMINAL, YesNo.YES); + + this.iHost = ih; + this.craftingTracker = new MultiCraftingTracker(this.iHost, 9); + + final MachineSource actionSource = new MachineSource(this.iHost); + this.mySource = actionSource; + this.fluids.setChangeSource(actionSource); + this.items.setChangeSource(actionSource); + + this.interfaceRequestSource = new InterfaceRequestSource(this.iHost); + } + + private static boolean invIsCustomBlocking(BlockingInventoryAdaptor inv) { + return (inv.containsBlockingItems()); + } + + @Override + public void saveChanges() { + this.iHost.saveChanges(); + } + + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { + if (this.isWorking == slot) { + return; + } + if (inv == this.config && (!removed.isEmpty() || !added.isEmpty())) { + boolean cfg = hasConfig(); + this.readConfig(); + if (cfg != hasConfig) { + resetConfigCache = true; + this.notifyNeighbors(); + } + } else if (inv == this.patterns && (!removed.isEmpty() || !added.isEmpty())) { + this.updateCraftingList(); + } else if (inv == this.storage && slot >= 0) { + final boolean had = this.hasWorkToDo(); + + this.updatePlan(slot); + + final boolean now = this.hasWorkToDo(); + + if (had != now) { + try { + if (now) { + this.gridProxy.getTick().alertDevice(this.gridProxy.getNode()); + } else { + this.gridProxy.getTick().sleepDevice(this.gridProxy.getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + } + } + + public void writeToNBT(final NBTTagCompound data) { + this.config.writeToNBT(data, "config"); + this.patterns.writeToNBT(data, "patterns"); + this.storage.writeToNBT(data, "storage"); + this.upgrades.writeToNBT(data, "upgrades"); + this.cm.writeToNBT(data); + this.craftingTracker.writeToNBT(data); + data.setInteger("priority", this.priority); + + final NBTTagList waitingToSend = new NBTTagList(); + if (this.waitingToSend != null) { + for (final ItemStack is : this.waitingToSend) { + final NBTTagCompound item = new NBTTagCompound(); + is.writeToNBT(item); + waitingToSend.appendTag(item); + } + } + data.setTag("waitingToSend", waitingToSend); + + NBTTagCompound sidedWaitList = new NBTTagCompound(); + + if (this.waitingToSendFacing != null) { + for (EnumFacing s : this.iHost.getTargets()) { + NBTTagList waitingListSided = new NBTTagList(); + if (this.waitingToSendFacing.containsKey(s)) { + for (final ItemStack is : this.waitingToSendFacing.get(s)) { + final NBTTagCompound item = new NBTTagCompound(); + is.writeToNBT(item); + waitingListSided.appendTag(item); + } + sidedWaitList.setTag(s.name(), waitingListSided); + } + } + } + data.setTag("sidedWaitList", sidedWaitList); + } + + public void readFromNBT(final NBTTagCompound data) { + this.waitingToSend = null; + final NBTTagList waitingList = data.getTagList("waitingToSend", 10); + if (waitingList != null) { + for (int x = 0; x < waitingList.tagCount(); x++) { + final NBTTagCompound c = waitingList.getCompoundTagAt(x); + if (c != null) { + final ItemStack is = new ItemStack(c); + this.addToSendList(is); + } + } + } + + this.waitingToSendFacing = null; + final NBTTagCompound waitingListSided = data.getCompoundTag("sidedWaitList"); + + for (EnumFacing s : EnumFacing.values()) { + if (waitingListSided.hasKey(s.name())) { + NBTTagList w = waitingListSided.getTagList(s.name(), 10); + for (int x = 0; x < w.tagCount(); x++) { + final NBTTagCompound c = w.getCompoundTagAt(x); + if (c != null) { + final ItemStack is = new ItemStack(c); + this.addToSendListFacing(is, EnumFacing.getFront(s.getIndex())); + } + } + } + } + + this.craftingTracker.readFromNBT(data); + + // fix upgrade slot size mismatch + NBTTagCompound up = data.getCompoundTag("upgrades"); + if (up.hasKey("Size") && up.getInteger("Size") != this.upgrades.getSlots()) { + up.setInteger("Size", this.upgrades.getSlots()); + this.upgrades.writeToNBT(up, "upgrades"); + } + + this.upgrades.readFromNBT(data, "upgrades"); + this.config.readFromNBT(data, "config"); + + NBTTagCompound pa = data.getCompoundTag("patterns"); + if (pa.hasKey("Size") && pa.getInteger("Size") != this.patterns.getSlots()) { + pa.setInteger("Size", this.patterns.getSlots()); + this.upgrades.writeToNBT(pa, "patterns"); + } + + this.patterns.readFromNBT(data, "patterns"); + this.storage.readFromNBT(data, "storage"); + this.priority = data.getInteger("priority"); + this.cm.readFromNBT(data); + this.readConfig(); + this.updateCraftingList(); + } + + private void addToSendList(final ItemStack is) { + if (is.isEmpty()) { + return; + } + + if (this.waitingToSend == null) { + this.waitingToSend = new ArrayList<>(); + } + + this.waitingToSend.add(is); + + try { + this.gridProxy.getTick().wakeDevice(this.gridProxy.getNode()); + } catch (final GridAccessException e) { + // :P + } + } + + private void addToSendListFacing(final ItemStack is, EnumFacing f) { + if (is.isEmpty()) { + return; + } + if (this.waitingToSendFacing == null) { + this.waitingToSendFacing = new EnumMap<>(EnumFacing.class); + } + + this.waitingToSendFacing.computeIfAbsent(f, k -> new ArrayList<>()); + + this.waitingToSendFacing.get(f).add(is); + + try { + this.gridProxy.getTick().wakeDevice(this.gridProxy.getNode()); + } catch (final GridAccessException e) { + // :P + } + } + + private void readConfig() { + this.hasConfig = false; + + for (final ItemStack p : this.config) { + if (!p.isEmpty()) { + this.hasConfig = true; + break; + } + } + + final boolean had = this.hasWorkToDo(); + + for (int x = 0; x < NUMBER_OF_CONFIG_SLOTS; x++) { + this.updatePlan(x); + } + + final boolean has = this.hasWorkToDo(); + + if (had != has) { + try { + if (has) { + this.gridProxy.getTick().alertDevice(this.gridProxy.getNode()); + } else { + this.gridProxy.getTick().sleepDevice(this.gridProxy.getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + this.notifyNeighbors(); + } + + private void updateCraftingList() { + final Boolean[] accountedFor = new Boolean[this.patterns.getSlots()]; + Arrays.fill(accountedFor, false); + + if (!this.gridProxy.isReady()) { + return; + } + + boolean removed = false; + + if (this.craftingList != null) { + final Iterator i = this.craftingList.iterator(); + while (i.hasNext()) { + final ICraftingPatternDetails details = i.next(); + boolean found = false; + + for (int x = 0; x < accountedFor.length; x++) { + final ItemStack is = this.patterns.getStackInSlot(x); + if (details.getPattern() == is) { + accountedFor[x] = found = true; + } + } + + if (!found) { + removed = true; + i.remove(); + } + } + } + + boolean newPattern = false; + + for (int x = 0; x < accountedFor.length; x++) { + if (!accountedFor[x]) { + newPattern = true; + this.addToCraftingList(this.patterns.getStackInSlot(x)); + } + } + try { + this.gridProxy.getGrid().postEvent(new MENetworkCraftingPatternChange(this, this.gridProxy.getNode())); + } catch (GridAccessException e) { + e.printStackTrace(); + } + } + + private boolean hasWorkToDo() { + + if (hasItemsToSend()) { + return true; + } + + if (hasItemsToSendFacing()) { + return true; + } + + for (final IAEItemStack requiredWork : this.requireWork) { + if (requiredWork != null) { + return true; + } + } + return false; + } + + private void updatePlan(final int slot) { + IAEItemStack req = this.config.getAEStackInSlot(slot); + if (req != null && req.getStackSize() <= 0) { + this.config.setStackInSlot(slot, ItemStack.EMPTY); + req = null; + } + + final ItemStack stored = this.storage.getStackInSlot(slot); + + if (req == null && !stored.isEmpty()) { + final IAEItemStack work = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(stored); + this.requireWork[slot] = work.setStackSize(-work.getStackSize()); + return; + } else if (req != null) { + if (stored.isEmpty()) // need to add stuff! + { + this.requireWork[slot] = req.copy(); + return; + } else if (req.isSameType(stored)) // same type and quantity )! + { + if (req.getStackSize() == stored.getCount()) { + this.requireWork[slot] = null; + } else // same type ( qty different? )! + { + this.requireWork[slot] = req.copy(); + this.requireWork[slot].setStackSize(req.getStackSize() - stored.getCount()); + } + return; + } else + // Stored != null; dispose! + { + final IAEItemStack work = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(stored); + this.requireWork[slot] = work.setStackSize(-work.getStackSize()); + return; + } + } + + // else + + this.requireWork[slot] = null; + } + + public void notifyNeighbors() { + if (this.gridProxy.isActive()) { + try { + this.gridProxy.getGrid().postEvent(new MENetworkCraftingPatternChange(this, this.gridProxy.getNode())); + this.gridProxy.getTick().wakeDevice(this.gridProxy.getNode()); + } catch (final GridAccessException e) { + // :P + } + } + + final TileEntity te = this.iHost.getTileEntity(); + if (te != null && te.getWorld() != null) { + Platform.notifyBlocksOfNeighbors(te.getWorld(), te.getPos()); + } + } + + private void addToCraftingList(final ItemStack is) { + if (is.isEmpty()) { + return; + } + + if (is.getItem() instanceof ICraftingPatternItem) { + final ICraftingPatternItem cpi = (ICraftingPatternItem) is.getItem(); + final ICraftingPatternDetails details = cpi.getPatternForItem(is, this.iHost.getTileEntity().getWorld()); + + if (details != null) { + if (this.craftingList == null) { + this.craftingList = new ArrayList<>(); + } + + this.craftingList.add(details); + } + } + } + + private boolean hasItemsToSend() { + return this.waitingToSend != null && !this.waitingToSend.isEmpty(); + } + + private boolean hasItemsToSendFacing() { + if (waitingToSendFacing != null) { + for (EnumFacing enumFacing : waitingToSendFacing.keySet()) { + if (!waitingToSendFacing.get(enumFacing).isEmpty()) { + return true; + } + } + } + return false; + } + + public void dropExcessPatterns() { + IItemHandler patterns = getPatterns(); + + List dropList = new ArrayList<>(); + for (int invSlot = 0; invSlot < patterns.getSlots(); invSlot++) { + if (invSlot > 8 + this.getInstalledUpgrades(Upgrades.PATTERN_EXPANSION) * 9) { + ItemStack is = patterns.getStackInSlot(invSlot); + if (is.isEmpty()) { + continue; + } + dropList.add(patterns.extractItem(invSlot, Integer.MAX_VALUE, false)); + } + } + if (dropList.size() > 0) { + World world = this.getLocation().getWorld(); + BlockPos blockPos = this.getLocation().getPos(); + Platform.spawnDrops(world, blockPos, dropList); + } + + this.gridProxy.setIdlePowerUsage(Math.pow(4, (this.getInstalledUpgrades(Upgrades.PATTERN_EXPANSION)))); + } + + @Override + public boolean canInsert(final ItemStack stack) { + final IAEItemStack out = this.destination.injectItems(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(stack), Actionable.SIMULATE, null); + if (out == null) { + return true; + } + return out.getStackSize() != stack.getCount(); + } + + public IItemHandler getConfig() { + return this.config; + } + + public IItemHandler getPatterns() { + return this.patterns; + } + + public void gridChanged() { + try { + this.items.setInternal(this.gridProxy.getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class))); + this.fluids.setInternal(this.gridProxy.getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class))); + } catch (final GridAccessException gae) { + this.items.setInternal(new NullInventory()); + this.fluids.setInternal(new NullInventory()); + } + + this.notifyNeighbors(); + } + + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.SMART; + } + + public DimensionalCoord getLocation() { + return new DimensionalCoord(this.iHost.getTileEntity()); + } + + public IItemHandler getInternalInventory() { + return this.storage; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.Interface.getMin(), TickRates.Interface.getMax(), !this.hasWorkToDo(), true); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (!this.gridProxy.isActive()) { + return TickRateModulation.SLEEP; + } + + //Previous version might have items saved in this list + //recover them + if (this.hasItemsToSend()) { + this.pushItemsOut(this.iHost.getTargets()); + } + + if (hasItemsToSendFacing()) { + for (EnumFacing enumFacing : waitingToSendFacing.keySet()) { + this.pushItemsOut(enumFacing); + } + } + + final boolean couldDoWork = this.updateStorage(); + return this.hasWorkToDo() ? (couldDoWork ? TickRateModulation.URGENT : TickRateModulation.SLOWER) : TickRateModulation.SLEEP; + } + + private void pushItemsOut(final EnumSet possibleDirections) { + if (!this.hasItemsToSend()) { + return; + } + + final TileEntity tile = this.iHost.getTileEntity(); + final World w = tile.getWorld(); + + final Iterator i = this.waitingToSend.iterator(); + while (i.hasNext()) { + ItemStack whatToSend = i.next(); + + for (final EnumFacing s : possibleDirections) { + final TileEntity te = w.getTileEntity(tile.getPos().offset(s)); + if (te == null) { + continue; + } + + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor(te, s.getOpposite()); + if (ad != null) { + final ItemStack result = ad.addItems(whatToSend); + + if (result.isEmpty()) { + whatToSend = ItemStack.EMPTY; + } else { + whatToSend.setCount(whatToSend.getCount() - (whatToSend.getCount() - result.getCount())); + } + + if (whatToSend.isEmpty()) { + break; + } + } + } + + if (whatToSend.isEmpty()) { + i.remove(); + } + } + + if (this.waitingToSend.isEmpty()) { + this.waitingToSend = null; + } + } + + private void pushItemsOut(final EnumFacing s) { + if (!this.waitingToSendFacing.containsKey(s) || (this.waitingToSendFacing.containsKey(s) && this.waitingToSendFacing.get(s).isEmpty())) { + return; + } + + final TileEntity tile = this.iHost.getTileEntity(); + final World w = tile.getWorld(); + + final TileEntity te = w.getTileEntity(tile.getPos().offset(s)); + if (te == null) { + return; + } + + if (te instanceof IInterfaceHost || (te instanceof TileCableBus && ((TileCableBus) te).getPart(s.getOpposite()) instanceof PartInterface)) { + try { + IInterfaceHost targetTE; + if (te instanceof IInterfaceHost) { + targetTE = (IInterfaceHost) te; + } else { + targetTE = (IInterfaceHost) ((TileCableBus) te).getPart(s.getOpposite()); + } + + if (!targetTE.getInterfaceDuality().sameGrid(this.gridProxy.getGrid())) { + IStorageMonitorableAccessor mon = te.getCapability(Capabilities.STORAGE_MONITORABLE_ACCESSOR, s.getOpposite()); + if (mon != null) { + IStorageMonitorable sm = mon.getInventory(this.mySource); + if (sm != null && Platform.canAccess(targetTE.getInterfaceDuality().gridProxy, this.mySource)) { + IMEMonitor inv = sm.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + if (inv != null) { + final Iterator i = this.waitingToSendFacing.get(s).iterator(); + while (i.hasNext()) { + ItemStack whatToSend = i.next(); + final IAEItemStack result = inv.injectItems(AEItemStack.fromItemStack(whatToSend), Actionable.MODULATE, this.mySource); + if (result != null) { + whatToSend.setCount((int) result.getStackSize()); + } else { + i.remove(); + } + } + if (this.waitingToSendFacing.get(s).isEmpty()) { + this.waitingToSendFacing.remove(s); + } + } + } + } + } else { + return; + } + } catch (GridAccessException e) { + throw new RuntimeException(e); + } + return; + } + + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor(te, s.getOpposite()); + + final Iterator i = this.waitingToSendFacing.get(s).iterator(); + while (i.hasNext()) { + ItemStack whatToSend = i.next(); + if (ad != null) { + final ItemStack result = ad.addItems(whatToSend); + if (!result.isEmpty()) { + whatToSend.setCount(result.getCount()); + } else { + i.remove(); + } + } + } + + if (this.waitingToSendFacing.get(s).isEmpty()) { + this.waitingToSendFacing.remove(s); + } + } + + private boolean updateStorage() { + boolean didSomething = false; + + for (int x = 0; x < NUMBER_OF_STORAGE_SLOTS; x++) { + if (this.requireWork[x] != null) { + didSomething = this.usePlan(x, this.requireWork[x]) || didSomething; + } + } + + return didSomething; + } + + private boolean usePlan(final int x, final IAEItemStack itemStack) { + final InventoryAdaptor adaptor = this.getAdaptor(x); + this.isWorking = x; + + boolean changed = false; + try { + this.destination = this.gridProxy.getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + final IEnergySource src = this.gridProxy.getEnergy(); + + if (itemStack.getStackSize() < 0) { + IAEItemStack toStore = itemStack.copy(); + toStore.setStackSize(-toStore.getStackSize()); + + long diff = toStore.getStackSize(); + + // make sure strange things didn't happen... + // TODO: check if OK + final ItemStack canExtract = adaptor.simulateRemove((int) diff, toStore.getDefinition(), null); + if (canExtract.isEmpty() || canExtract.getCount() != diff) { + changed = true; + throw new GridAccessException(); + } + + toStore = Platform.poweredInsert(src, this.destination, toStore, this.interfaceRequestSource); + + if (toStore != null) { + diff -= toStore.getStackSize(); + } + + if (diff != 0) { + // extract items! + changed = true; + final ItemStack removed = adaptor.removeItems((int) diff, ItemStack.EMPTY, null); + if (removed.isEmpty()) { + throw new IllegalStateException("bad attempt at managing inventory. ( removeItems )"); + } else if (removed.getCount() != diff) { + throw new IllegalStateException("bad attempt at managing inventory. ( removeItems )"); + } + } + } + + if (this.craftingTracker.isBusy(x)) { + changed = this.handleCrafting(x, adaptor, itemStack) || changed; + } else if (itemStack.getStackSize() > 0) { + // make sure strange things didn't happen... + + ItemStack inputStack = itemStack.getCachedItemStack(itemStack.getStackSize()); + + ItemStack remaining = adaptor.simulateAdd(inputStack); + + if (!remaining.isEmpty()) { + itemStack.setCachedItemStack(remaining); + changed = true; + throw new GridAccessException(); + } + + IAEItemStack storedStack = this.gridProxy.getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)).getStorageList().findPrecise(itemStack); + if (storedStack != null) { + final IAEItemStack acquired = Platform.poweredExtraction(src, this.destination, itemStack, this.interfaceRequestSource); + if (acquired != null) { + changed = true; + inputStack.setCount(Ints.saturatedCast(acquired.getStackSize())); + final ItemStack issue = adaptor.addItems(inputStack); + if (!issue.isEmpty()) { + throw new IllegalStateException("bad attempt at managing inventory. ( addItems )"); + } + } else if (storedStack.isCraftable()) { + itemStack.setCachedItemStack(inputStack); + changed = this.handleCrafting(x, adaptor, itemStack) || changed; + } + if (acquired == null) { + itemStack.setCachedItemStack(inputStack); + } + } + } + // else wtf? + } catch (final GridAccessException e) { + // :P + } + + if (changed) { + this.updatePlan(x); + } + + this.isWorking = -1; + return changed; + } + + private InventoryAdaptor getAdaptor(final int slot) { + return new AdaptorItemHandler(new RangedWrapper(this.storage, slot, slot + 1)); + } + + private boolean handleCrafting(final int x, final InventoryAdaptor d, final IAEItemStack itemStack) { + try { + if (this.getInstalledUpgrades(Upgrades.CRAFTING) > 0 && itemStack != null) { + return this.craftingTracker.handleCrafting(x, itemStack.getStackSize(), itemStack, d, this.iHost.getTileEntity().getWorld(), this.gridProxy.getGrid(), this.gridProxy.getCrafting(), this.mySource); + } + } catch (final GridAccessException e) { + // :P + } + + return false; + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + if (this.upgrades == null) { + return 0; + } + return this.upgrades.getInstalledUpgrades(u); + } + + @Override + public TileEntity getTile() { + return (TileEntity) (this.iHost instanceof TileEntity ? this.iHost : null); + } + + @Override + public > IMEMonitor getInventory(IStorageChannel channel) { + if (channel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + if (this.hasConfig()) { + if (resetConfigCache) { + resetConfigCache = false; + configCachedHandler = new InterfaceInventory(this); + } + return (IMEMonitor) configCachedHandler; + } + + return (IMEMonitor) this.items; + } else if (channel == AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)) { + if (this.hasConfig()) { + return null; + } + + return (IMEMonitor) this.fluids; + } + + return null; + } + + private boolean hasConfig() { + return this.hasConfig; + } + + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("storage")) { + return this.storage; + } + + if (name.equals("patterns")) { + return this.patterns; + } + + if (name.equals("config")) { + return this.config; + } + + if (name.equals("upgrades")) { + return this.upgrades; + } + + return null; + } + + public IItemHandler getStorage() { + return this.storage; + } + + @Override + public appeng.api.util.IConfigManager getConfigManager() { + return this.cm; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + if (this.getInstalledUpgrades(Upgrades.CRAFTING) == 0) { + this.cancelCrafting(); + } + this.iHost.saveChanges(); + } + + private void cancelCrafting() { + this.craftingTracker.cancel(); + } + + public IStorageMonitorable getMonitorable(final IActionSource src, final IStorageMonitorable myInterface) { + if (Platform.canAccess(this.gridProxy, src)) { + return myInterface; + } + + final DualityInterface di = this; + + return new IStorageMonitorable() { + + @Override + public > IMEMonitor getInventory(IStorageChannel channel) { + if (channel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + return (IMEMonitor) new InterfaceInventory(di); + } + return null; + } + }; + } + + private boolean invIsBlocked(InventoryAdaptor inv) { + return (inv.containsItems()); + } + + @Override + public boolean pushPattern(final ICraftingPatternDetails patternDetails, final InventoryCrafting table) { + if (this.hasItemsToSend() || this.hasItemsToSendFacing() || !this.gridProxy.isActive() || !this.craftingList.contains(patternDetails)) { + return false; + } + + final TileEntity tile = this.iHost.getTileEntity(); + final World w = tile.getWorld(); + + if (this.visitedFaces.isEmpty()) { + this.visitedFaces = this.iHost.getTargets(); + } + + for (final EnumFacing s : visitedFaces) { + final TileEntity te = w.getTileEntity(tile.getPos().offset(s)); + if (te instanceof IInterfaceHost || (te instanceof TileCableBus && ((TileCableBus) te).getPart(s.getOpposite()) instanceof PartInterface)) { + visitedFaces.remove(s); + try { + IInterfaceHost targetTE; + if (te instanceof IInterfaceHost) { + targetTE = (IInterfaceHost) te; + } else { + targetTE = (IInterfaceHost) ((TileCableBus) te).getPart(s.getOpposite()); + } + + if (targetTE.getInterfaceDuality().sameGrid(this.gridProxy.getGrid())) { + continue; + } else { + IStorageMonitorableAccessor mon = te.getCapability(Capabilities.STORAGE_MONITORABLE_ACCESSOR, s.getOpposite()); + if (mon != null) { + IStorageMonitorable sm = mon.getInventory(this.mySource); + if (sm != null && Platform.canAccess(targetTE.getInterfaceDuality().gridProxy, this.mySource)) { + if (this.isBlocking() && sm.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)).getStorageList().size() > 0) { + continue; + } else { + IMEMonitor inv = sm.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + for (int x = 0; x < table.getSizeInventory(); x++) { + final ItemStack is = table.getStackInSlot(x); + if (is.isEmpty()) { + continue; + } + IAEItemStack result = inv.injectItems(AEItemStack.fromItemStack(is), Actionable.SIMULATE, this.mySource); + if (result != null) { + return false; + } + } + for (int x = 0; x < table.getSizeInventory(); x++) { + final ItemStack is = table.getStackInSlot(x); + if (!is.isEmpty()) { + addToSendListFacing(is, s); + } + } + pushItemsOut(s); + return true; + } + } + } + } + } catch (final GridAccessException e) { + continue; + } + continue; + } + + if (te instanceof ICraftingMachine) { + final ICraftingMachine cm = (ICraftingMachine) te; + if (cm.acceptsPlans()) { + visitedFaces.remove(s); + if (cm.pushPattern(patternDetails, table, s.getOpposite())) { + return true; + } + continue; + } + } + + InventoryAdaptor ad = InventoryAdaptor.getAdaptor(te, s.getOpposite()); + if (ad != null) { + if (this.isBlocking()) { + IPhantomTile phantomTE; + if (Loader.isModLoaded("actuallyadditions") && te instanceof IPhantomTile) { + phantomTE = ((IPhantomTile) te); + if (phantomTE.hasBoundPosition()) { + TileEntity phantom = w.getTileEntity(phantomTE.getBoundPosition()); + if (NonBlockingItems.INSTANCE.getMap().containsKey(w.getBlockState(phantomTE.getBoundPosition()).getBlock().getRegistryName().getResourceDomain())) { + if (isCustomInvBlocking(phantom, s)) { + visitedFaces.remove(s); + continue; + } + } + } + } else if (NonBlockingItems.INSTANCE.getMap().containsKey(w.getBlockState(tile.getPos().offset(s)).getBlock().getRegistryName().getResourceDomain())) { + if (isCustomInvBlocking(te, s)) { + visitedFaces.remove(s); + continue; + } + } else if (invIsBlocked(ad)) { + visitedFaces.remove(s); + continue; + } + } + + if (this.acceptsItems(ad, table)) { + visitedFaces.remove(s); + for (int x = 0; x < table.getSizeInventory(); x++) { + final ItemStack is = table.getStackInSlot(x); + if (!is.isEmpty()) { + addToSendListFacing(is, s); + } + } + pushItemsOut(s); + return true; + } + } + visitedFaces.remove(s); + } + return false; + } + + @Override + public boolean isBusy() { + boolean busy = false; + + if (this.hasItemsToSend() || hasItemsToSendFacing()) { + return true; + } + + if (this.isBlocking()) { + final EnumSet possibleDirections = this.iHost.getTargets(); + final TileEntity tile = this.iHost.getTileEntity(); + final World w = tile.getWorld(); + + boolean allAreBusy = true; + + for (final EnumFacing s : possibleDirections) { + final TileEntity te = w.getTileEntity(tile.getPos().offset(s)); + + if (te instanceof IInterfaceHost || (te instanceof TileCableBus && ((TileCableBus) te).getPart(s.getOpposite()) instanceof PartInterface)) { + try { + IInterfaceHost targetTE; + if (te instanceof IInterfaceHost) { + targetTE = (IInterfaceHost) te; + } else { + targetTE = (IInterfaceHost) ((TileCableBus) te).getPart(s.getOpposite()); + } + + if (targetTE.getInterfaceDuality().sameGrid(this.gridProxy.getGrid())) { + continue; + } else { + IStorageMonitorableAccessor mon = te.getCapability(Capabilities.STORAGE_MONITORABLE_ACCESSOR, s.getOpposite()); + if (mon != null) { + IStorageMonitorable sm = mon.getInventory(this.mySource); + if (sm != null && Platform.canAccess(targetTE.getInterfaceDuality().gridProxy, this.mySource)) { + if (sm.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)).getStorageList().isEmpty()) { + allAreBusy = false; + break; + } + } + } + } + } catch (final GridAccessException e) { + continue; + } + continue; + } + + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor(te, s.getOpposite()); + if (ad != null) { + if (Loader.isModLoaded("actuallyadditions") && Loader.isModLoaded("gregtech") && te instanceof IPhantomTile) { + IPhantomTile phantomTE = ((IPhantomTile) te); + if (phantomTE.hasBoundPosition()) { + TileEntity phantom = w.getTileEntity(phantomTE.getBoundPosition()); + if (NonBlockingItems.INSTANCE.getMap().containsKey(w.getBlockState(phantomTE.getBoundPosition()).getBlock().getRegistryName().getResourceDomain())) { + if (!isCustomInvBlocking(phantom, s)) { + allAreBusy = false; + break; + } + } + } + } else if (NonBlockingItems.INSTANCE.getMap().containsKey(w.getBlockState(tile.getPos().offset(s)).getBlock().getRegistryName().getResourceDomain())) { + if (!isCustomInvBlocking(te, s)) { + allAreBusy = false; + break; + } + } else { + if (!invIsBlocked(ad)) { + allAreBusy = false; + break; + } + } + } + } + busy = allAreBusy; + } + return busy; + } + + boolean isCustomInvBlocking(TileEntity te, EnumFacing s) { + BlockingInventoryAdaptor blockingInventoryAdaptor = BlockingInventoryAdaptor.getAdaptor(te, s.getOpposite()); + return invIsCustomBlocking(blockingInventoryAdaptor); + } + + private boolean sameGrid(final IGrid grid) throws GridAccessException { + return grid == this.gridProxy.getGrid(); + } + + private boolean isBlocking() { + return this.cm.getSetting(Settings.BLOCK) == YesNo.YES; + } + + private boolean acceptsItems(final InventoryAdaptor ad, final InventoryCrafting table) { + for (int x = 0; x < table.getSizeInventory(); x++) { + final ItemStack is = table.getStackInSlot(x); + if (is.isEmpty()) { + continue; + } + + if (!ad.simulateAdd(is).isEmpty()) { + return false; + } + } + + return true; + } + + @Override + public void provideCrafting(final ICraftingProviderHelper craftingTracker) { + if (this.gridProxy.isActive() && this.craftingList != null) { + for (final ICraftingPatternDetails details : this.craftingList) { + details.setPriority(this.priority); + craftingTracker.addCraftingOption(this, details); + } + } + } + + public void addDrops(final List drops) { + if (this.waitingToSend != null) { + for (final ItemStack is : this.waitingToSend) { + if (!is.isEmpty()) { + drops.add(is); + } + } + } + + if (this.waitingToSendFacing != null) { + for (List itemList : waitingToSendFacing.values()) { + for (final ItemStack is : itemList) { + if (!is.isEmpty()) { + drops.add(is); + } + } + } + } + + for (final ItemStack is : this.upgrades) { + if (!is.isEmpty()) { + drops.add(is); + } + } + + for (final ItemStack is : this.storage) { + if (!is.isEmpty()) { + drops.add(is); + } + } + + for (final ItemStack is : this.patterns) { + if (!is.isEmpty()) { + drops.add(is); + } + } + } + + public IUpgradeableHost getHost() { + if (this.getPart() instanceof IUpgradeableHost) { + return (IUpgradeableHost) this.getPart(); + } + if (this.getTile() instanceof IUpgradeableHost) { + return (IUpgradeableHost) this.getTile(); + } + return null; + } + + private IPart getPart() { + return (IPart) (this.iHost instanceof IPart ? this.iHost : null); + } + + public ImmutableSet getRequestedJobs() { + return this.craftingTracker.getRequestedJobs(); + } + + public IAEItemStack injectCraftedItems(final ICraftingLink link, final IAEItemStack acquired, final Actionable mode) { + final int slot = this.craftingTracker.getSlot(link); + + if (acquired != null && slot >= 0 && slot <= this.requireWork.length) { + final InventoryAdaptor adaptor = this.getAdaptor(slot); + + if (mode == Actionable.SIMULATE) { + return AEItemStack.fromItemStack(adaptor.simulateAdd(acquired.createItemStack())); + } else { + final IAEItemStack is = AEItemStack.fromItemStack(adaptor.addItems(acquired.createItemStack())); + this.updatePlan(slot); + return is; + } + } + + return acquired; + } + + public void jobStateChange(final ICraftingLink link) { + this.craftingTracker.jobStateChange(link); + } + + public String getTermName() { + final TileEntity hostTile = this.iHost.getTileEntity(); + final World hostWorld = hostTile.getWorld(); + + if (((ICustomNameObject) this.iHost).hasCustomInventoryName()) { + return ((ICustomNameObject) this.iHost).getCustomInventoryName(); + } + + final EnumSet possibleDirections = this.iHost.getTargets(); + for (final EnumFacing direction : possibleDirections) { + final BlockPos targ = hostTile.getPos().offset(direction); + final TileEntity directedTile = hostWorld.getTileEntity(targ); + + if (directedTile == null) { + continue; + } + + if (directedTile instanceof IInterfaceHost) { + try { + if (((IInterfaceHost) directedTile).getInterfaceDuality().sameGrid(this.gridProxy.getGrid())) { + continue; + } + } catch (final GridAccessException e) { + continue; + } + } + + final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor(directedTile, direction.getOpposite()); + if (directedTile instanceof ICraftingMachine || adaptor != null) { + if (adaptor != null && !adaptor.hasSlots()) { + continue; + } + + final IBlockState directedBlockState = hostWorld.getBlockState(targ); + final Block directedBlock = directedBlockState.getBlock(); + ItemStack what = new ItemStack(directedBlock, 1, directedBlock.getMetaFromState(directedBlockState)); + + if (Loader.isModLoaded("gregtech") && directedBlock instanceof BlockMachine) { + MetaTileEntity metaTileEntity = Platform.getMetaTileEntity(directedTile.getWorld(), directedTile.getPos()); + if (metaTileEntity != null) { + return metaTileEntity.getMetaFullName(); + } + } + + try { + Vec3d from = new Vec3d(hostTile.getPos().getX() + 0.5, hostTile.getPos().getY() + 0.5, hostTile.getPos().getZ() + 0.5); + from = from.addVector(direction.getFrontOffsetX() * 0.501, direction.getFrontOffsetY() * 0.501, direction.getFrontOffsetZ() * 0.501); + final Vec3d to = from.addVector(direction.getFrontOffsetX(), direction.getFrontOffsetY(), direction.getFrontOffsetZ()); + final RayTraceResult mop = hostWorld.rayTraceBlocks(from, to, true); + if (mop != null && !BAD_BLOCKS.contains(directedBlock)) { + if (mop.getBlockPos().equals(directedTile.getPos())) { + final ItemStack g = directedBlock.getPickBlock(directedBlockState, mop, hostWorld, directedTile.getPos(), null); + if (!g.isEmpty()) { + what = g; + } + } + } + } catch (final Throwable t) { + BAD_BLOCKS.add(directedBlock); // nope! + } + + if (what.getItem() != Items.AIR) { + return what.getItem().getItemStackDisplayName(what); + } + + final Item item = Item.getItemFromBlock(directedBlock); + if (item == Items.AIR) { + return directedBlock.getUnlocalizedName(); + } + } + } + + return "Nothing"; + } + + public long getSortValue() { + final TileEntity te = this.iHost.getTileEntity(); + return (te.getPos().getZ() << 24) ^ (te.getPos().getX() << 8) ^ te.getPos().getY(); + } + + public void initialize() { + this.updateCraftingList(); + } + + public int getPriority() { + return this.priority; + } + + public void setPriority(final int newValue) { + this.priority = newValue; + this.iHost.saveChanges(); + + try { + this.gridProxy.getGrid().postEvent(new MENetworkCraftingPatternChange(this, this.gridProxy.getNode())); + } catch (final GridAccessException e) { + // :P + } + } + + public boolean hasCapability(Capability capabilityClass, EnumFacing facing) { + return capabilityClass == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || capabilityClass == Capabilities.STORAGE_MONITORABLE_ACCESSOR; + } + + @SuppressWarnings("unchecked") + public T getCapability(Capability capabilityClass, EnumFacing facing) { + if (capabilityClass == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { + return (T) this.storage; + } else if (capabilityClass == Capabilities.STORAGE_MONITORABLE_ACCESSOR) { + return (T) this.accessor; + } + return null; + } + + private class InterfaceRequestSource extends MachineSource { + private final InterfaceRequestContext context; + + public InterfaceRequestSource(IActionHost v) { + super(v); + this.context = new InterfaceRequestContext(); + } + + @Override + public Optional context(Class key) { + if (key == InterfaceRequestContext.class) { + return (Optional) Optional.of(this.context); + } + + return super.context(key); + } + + } + + + private class InterfaceRequestContext implements Comparable { + + @Override + public int compareTo(Integer o) { + return Integer.compare(DualityInterface.this.priority, o); + } + } + + + private class InterfaceInventory extends MEMonitorIInventory { + + public InterfaceInventory(final DualityInterface tileInterface) { + super(new AdaptorItemHandler(tileInterface.storage)); + } + + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable type, final IActionSource src) { + final Optional context = src.context(InterfaceRequestContext.class); + final boolean isInterface = context.isPresent(); + + if (isInterface) { + return input; + } + + return super.injectItems(input, type, src); + } + + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable type, final IActionSource src) { + final Optional context = src.context(InterfaceRequestContext.class); + final boolean hasLowerOrEqualPriority = context.map(c -> c.compareTo(DualityInterface.this.priority) <= 0).orElse(false); + + if (hasLowerOrEqualPriority) { + return null; + } + + return super.extractItems(request, type, src); + } + } + + + private class Accessor implements IStorageMonitorableAccessor { + + @Nullable + @Override + public IStorageMonitorable getInventory(IActionSource src) { + return DualityInterface.this.getMonitorable(src, DualityInterface.this); + } + + } } diff --git a/src/main/java/appeng/helpers/HighlighterHandler.java b/src/main/java/appeng/helpers/HighlighterHandler.java index d795db129..b9605e86a 100644 --- a/src/main/java/appeng/helpers/HighlighterHandler.java +++ b/src/main/java/appeng/helpers/HighlighterHandler.java @@ -13,14 +13,13 @@ import org.lwjgl.opengl.GL11; // taken from McJty's McJtyLib -public class HighlighterHandler -{ +public class HighlighterHandler { - public static void tick( RenderWorldLastEvent event ) { + public static void tick(RenderWorldLastEvent event) { renderHilightedBlock(event); } - private static void renderHilightedBlock( RenderWorldLastEvent event ) { + private static void renderHilightedBlock(RenderWorldLastEvent event) { BlockPos c = BlockPosHighlighter.getHilightedBlock(); if (c == null) { return; @@ -30,7 +29,7 @@ public class HighlighterHandler long time = System.currentTimeMillis(); if (time > BlockPosHighlighter.getExpireHilight() || dimension != BlockPosHighlighter.getDimension()) { - BlockPosHighlighter.hilightBlock(null, -1, BlockPosHighlighter.getDimension() ); + BlockPosHighlighter.hilightBlock(null, -1, BlockPosHighlighter.getDimension()); return; } @@ -56,7 +55,7 @@ public class HighlighterHandler float mx = c.getX(); float my = c.getY(); float mz = c.getZ(); - buffer.begin( GL11.GL_LINES, DefaultVertexFormats.POSITION_COLOR); + buffer.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION_COLOR); renderHighLightedBlocksOutline(buffer, mx, my, mz, 1.0f, 0.0f, 0.0f, 1.0f); tessellator.draw(); diff --git a/src/main/java/appeng/helpers/IContainerCraftingPacket.java b/src/main/java/appeng/helpers/IContainerCraftingPacket.java index 338062b12..37fead1bf 100644 --- a/src/main/java/appeng/helpers/IContainerCraftingPacket.java +++ b/src/main/java/appeng/helpers/IContainerCraftingPacket.java @@ -19,40 +19,37 @@ package appeng.helpers; +import appeng.api.networking.IGridNode; +import appeng.api.networking.security.IActionSource; import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; -import appeng.api.networking.IGridNode; -import appeng.api.networking.security.IActionSource; +public interface IContainerCraftingPacket { -public interface IContainerCraftingPacket -{ + /** + * @return gain access to network infrastructure. + */ + IGridNode getNetworkNode(); - /** - * @return gain access to network infrastructure. - */ - IGridNode getNetworkNode(); + /** + * @param string name of inventory + * @return the inventory of the part/tile by name. + */ + IItemHandler getInventoryByName(String string); - /** - * @param string name of inventory - * - * @return the inventory of the part/tile by name. - */ - IItemHandler getInventoryByName( String string ); + /** + * @return who are we? + */ + IActionSource getActionSource(); - /** - * @return who are we? - */ - IActionSource getActionSource(); + /** + * @return consume items? + */ + boolean useRealItems(); - /** - * @return consume items? - */ - boolean useRealItems(); - - /** - * @return array of view cells - */ - ItemStack[] getViewCells(); + /** + * @return array of view cells + */ + ItemStack[] getViewCells(); } diff --git a/src/main/java/appeng/helpers/ICustomCollision.java b/src/main/java/appeng/helpers/ICustomCollision.java index 2a842dce8..78987cc86 100644 --- a/src/main/java/appeng/helpers/ICustomCollision.java +++ b/src/main/java/appeng/helpers/ICustomCollision.java @@ -19,17 +19,16 @@ package appeng.helpers; -import java.util.List; - import net.minecraft.entity.Entity; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import java.util.List; -public interface ICustomCollision -{ - Iterable getSelectedBoundingBoxesFromPool( World w, BlockPos pos, Entity thePlayer, boolean b ); - void addCollidingBlockToList( World w, BlockPos pos, AxisAlignedBB bb, List out, Entity e ); +public interface ICustomCollision { + Iterable getSelectedBoundingBoxesFromPool(World w, BlockPos pos, Entity thePlayer, boolean b); + + void addCollidingBlockToList(World w, BlockPos pos, AxisAlignedBB bb, List out, Entity e); } diff --git a/src/main/java/appeng/helpers/ICustomNameObject.java b/src/main/java/appeng/helpers/ICustomNameObject.java index 82c445edb..da3f81326 100644 --- a/src/main/java/appeng/helpers/ICustomNameObject.java +++ b/src/main/java/appeng/helpers/ICustomNameObject.java @@ -19,12 +19,11 @@ package appeng.helpers; -public interface ICustomNameObject -{ +public interface ICustomNameObject { - String getCustomInventoryName(); + String getCustomInventoryName(); - boolean hasCustomInventoryName(); + boolean hasCustomInventoryName(); - void setCustomName(String name); + void setCustomName(String name); } diff --git a/src/main/java/appeng/helpers/IInterfaceHost.java b/src/main/java/appeng/helpers/IInterfaceHost.java index 3593d6107..7b8769d30 100644 --- a/src/main/java/appeng/helpers/IInterfaceHost.java +++ b/src/main/java/appeng/helpers/IInterfaceHost.java @@ -19,24 +19,22 @@ package appeng.helpers; -import java.util.EnumSet; - -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; - import appeng.api.implementations.IUpgradeableHost; import appeng.api.networking.crafting.ICraftingProvider; import appeng.api.networking.crafting.ICraftingRequester; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; + +import java.util.EnumSet; -public interface IInterfaceHost extends ICraftingProvider, IUpgradeableHost, ICraftingRequester -{ +public interface IInterfaceHost extends ICraftingProvider, IUpgradeableHost, ICraftingRequester { - DualityInterface getInterfaceDuality(); + DualityInterface getInterfaceDuality(); - EnumSet getTargets(); + EnumSet getTargets(); - TileEntity getTileEntity(); + TileEntity getTileEntity(); - void saveChanges(); + void saveChanges(); } diff --git a/src/main/java/appeng/helpers/IMouseWheelItem.java b/src/main/java/appeng/helpers/IMouseWheelItem.java index cc223005d..7c2de46fa 100644 --- a/src/main/java/appeng/helpers/IMouseWheelItem.java +++ b/src/main/java/appeng/helpers/IMouseWheelItem.java @@ -22,8 +22,7 @@ package appeng.helpers; import net.minecraft.item.ItemStack; -public interface IMouseWheelItem -{ +public interface IMouseWheelItem { - void onWheel( ItemStack is, boolean up ); + void onWheel(ItemStack is, boolean up); } diff --git a/src/main/java/appeng/helpers/IPriorityHost.java b/src/main/java/appeng/helpers/IPriorityHost.java index 641e36a6b..765a5a2fe 100644 --- a/src/main/java/appeng/helpers/IPriorityHost.java +++ b/src/main/java/appeng/helpers/IPriorityHost.java @@ -19,25 +19,23 @@ package appeng.helpers; +import appeng.core.sync.GuiBridge; import net.minecraft.item.ItemStack; -import appeng.core.sync.GuiBridge; +public interface IPriorityHost { -public interface IPriorityHost -{ + /** + * get current priority. + */ + int getPriority(); - /** - * get current priority. - */ - int getPriority(); + /** + * set new priority + */ + void setPriority(int newValue); - /** - * set new priority - */ - void setPriority( int newValue ); + ItemStack getItemStackRepresentation(); - ItemStack getItemStackRepresentation(); - - GuiBridge getGuiBridge(); + GuiBridge getGuiBridge(); } diff --git a/src/main/java/appeng/helpers/InvalidPatternHelper.java b/src/main/java/appeng/helpers/InvalidPatternHelper.java index ea1e0c85d..d103dfff4 100644 --- a/src/main/java/appeng/helpers/InvalidPatternHelper.java +++ b/src/main/java/appeng/helpers/InvalidPatternHelper.java @@ -19,139 +19,117 @@ package appeng.helpers; -import java.util.ArrayList; -import java.util.List; - +import appeng.util.Platform; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.text.TextFormatting; -import appeng.util.Platform; +import java.util.ArrayList; +import java.util.List; -public class InvalidPatternHelper -{ +public class InvalidPatternHelper { - private final List outputs = new ArrayList<>(); - private final List inputs = new ArrayList<>(); - private final boolean isCrafting; - private final boolean canSubstitute; + private final List outputs = new ArrayList<>(); + private final List inputs = new ArrayList<>(); + private final boolean isCrafting; + private final boolean canSubstitute; - public InvalidPatternHelper( final ItemStack is ) - { - final NBTTagCompound encodedValue = is.getTagCompound(); + public InvalidPatternHelper(final ItemStack is) { + final NBTTagCompound encodedValue = is.getTagCompound(); - if( encodedValue == null ) - { - throw new IllegalArgumentException( "No pattern here!" ); - } + if (encodedValue == null) { + throw new IllegalArgumentException("No pattern here!"); + } - final NBTTagList inTag = encodedValue.getTagList( "in", 10 ); - final NBTTagList outTag = encodedValue.getTagList( "out", 10 ); - this.isCrafting = encodedValue.getBoolean( "crafting" ); + final NBTTagList inTag = encodedValue.getTagList("in", 10); + final NBTTagList outTag = encodedValue.getTagList("out", 10); + this.isCrafting = encodedValue.getBoolean("crafting"); - this.canSubstitute = this.isCrafting && encodedValue.getBoolean( "substitute" ); + this.canSubstitute = this.isCrafting && encodedValue.getBoolean("substitute"); - for( int i = 0; i < outTag.tagCount(); i++ ) - { - this.outputs.add( new PatternIngredient( outTag.getCompoundTagAt( i ) ) ); - } + for (int i = 0; i < outTag.tagCount(); i++) { + this.outputs.add(new PatternIngredient(outTag.getCompoundTagAt(i))); + } - for( int i = 0; i < inTag.tagCount(); i++ ) - { - NBTTagCompound in = inTag.getCompoundTagAt( i ); + for (int i = 0; i < inTag.tagCount(); i++) { + NBTTagCompound in = inTag.getCompoundTagAt(i); - // skip empty slots in the crafting grid - if( in.hasNoTags() ) - { - continue; - } + // skip empty slots in the crafting grid + if (in.hasNoTags()) { + continue; + } - this.inputs.add( new PatternIngredient( in ) ); - } - } + this.inputs.add(new PatternIngredient(in)); + } + } - public List getOutputs() - { - return this.outputs; - } + public List getOutputs() { + return this.outputs; + } - public List getInputs() - { - return this.inputs; - } + public List getInputs() { + return this.inputs; + } - public boolean isCraftable() - { - return this.isCrafting; - } + public boolean isCraftable() { + return this.isCrafting; + } - public boolean canSubstitute() - { - return this.canSubstitute; - } + public boolean canSubstitute() { + return this.canSubstitute; + } - public class PatternIngredient - { - private String id; - private int count; - private int damage; + public class PatternIngredient { + private String id; + private int count; + private int damage; - private ItemStack stack; + private final ItemStack stack; - public PatternIngredient( NBTTagCompound tag ) - { - this.stack = new ItemStack( tag ); + public PatternIngredient(NBTTagCompound tag) { + this.stack = new ItemStack(tag); - if( this.stack.isEmpty() ) - { - this.id = tag.getString( "id" ); - this.count = tag.getByte( "Count" ); - this.damage = Math.max( 0, tag.getShort( "Damage" ) ); - } - } + if (this.stack.isEmpty()) { + this.id = tag.getString("id"); + this.count = tag.getByte("Count"); + this.damage = Math.max(0, tag.getShort("Damage")); + } + } - public boolean isValid() - { - return !this.stack.isEmpty(); - } + public boolean isValid() { + return !this.stack.isEmpty(); + } - public String getName() - { - return this.isValid() ? Platform.getItemDisplayName( this.stack ) : this.id + '@' + String.valueOf( this.getDamage() ); - } + public String getName() { + return this.isValid() ? Platform.getItemDisplayName(this.stack) : this.id + '@' + this.getDamage(); + } - public int getDamage() - { - return this.isValid() ? this.stack.getItemDamage() : this.damage; - } + public int getDamage() { + return this.isValid() ? this.stack.getItemDamage() : this.damage; + } - public int getCount() - { - return this.isValid() ? this.stack.getCount() : this.count; - } + public int getCount() { + return this.isValid() ? this.stack.getCount() : this.count; + } - public ItemStack getItem() - { - if( !this.isValid() ) - { - throw new IllegalArgumentException( "There is no valid ItemStack for this PatternIngredient" ); - } + public ItemStack getItem() { + if (!this.isValid()) { + throw new IllegalArgumentException("There is no valid ItemStack for this PatternIngredient"); + } - return this.stack; - } + return this.stack; + } - public String getFormattedToolTip() - { - String result = String.valueOf( this.getCount() ) + ' ' + this.getName(); + public String getFormattedToolTip() { + String result = String.valueOf(this.getCount()) + ' ' + this.getName(); - if( !this.isValid() ) - { - result = TextFormatting.RED + ( ' ' + result ); - } + if (!this.isValid()) { + result = TextFormatting.RED + (' ' + result); + } - return result; - } - } + return result; + } + } } diff --git a/src/main/java/appeng/helpers/InventoryAction.java b/src/main/java/appeng/helpers/InventoryAction.java index 6c545e8c8..a69a1767a 100644 --- a/src/main/java/appeng/helpers/InventoryAction.java +++ b/src/main/java/appeng/helpers/InventoryAction.java @@ -19,30 +19,29 @@ package appeng.helpers; -public enum InventoryAction -{ - // standard vanilla mechanics. - PICKUP_OR_SET_DOWN, - SPLIT_OR_PLACE_SINGLE, - CREATIVE_DUPLICATE, - SHIFT_CLICK, +public enum InventoryAction { + // standard vanilla mechanics. + PICKUP_OR_SET_DOWN, + SPLIT_OR_PLACE_SINGLE, + CREATIVE_DUPLICATE, + SHIFT_CLICK, - // crafting term - CRAFT_STACK, - CRAFT_ITEM, - CRAFT_SHIFT, + // crafting term + CRAFT_STACK, + CRAFT_ITEM, + CRAFT_SHIFT, - // fluid term - FILL_ITEM, - EMPTY_ITEM, + // fluid term + FILL_ITEM, + EMPTY_ITEM, - // extra... - MOVE_REGION, - PICKUP_SINGLE, - UPDATE_HAND, - ROLL_UP, - ROLL_DOWN, - AUTO_CRAFT, - PLACE_SINGLE, - PLACE_JEI_GHOST_ITEM + // extra... + MOVE_REGION, + PICKUP_SINGLE, + UPDATE_HAND, + ROLL_UP, + ROLL_DOWN, + AUTO_CRAFT, + PLACE_SINGLE, + PLACE_JEI_GHOST_ITEM } diff --git a/src/main/java/appeng/helpers/LocationRotation.java b/src/main/java/appeng/helpers/LocationRotation.java index 6a8d7000e..5cbf32d37 100644 --- a/src/main/java/appeng/helpers/LocationRotation.java +++ b/src/main/java/appeng/helpers/LocationRotation.java @@ -19,54 +19,46 @@ package appeng.helpers; +import appeng.api.util.IOrientable; import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; -import appeng.api.util.IOrientable; +public class LocationRotation implements IOrientable { -public class LocationRotation implements IOrientable -{ + private final IBlockAccess w; + private final int x; + private final int y; + private final int z; - private final IBlockAccess w; - private final int x; - private final int y; - private final int z; + public LocationRotation(final IBlockAccess world, final int x, final int y, final int z) { + this.w = world; + this.x = x; + this.y = y; + this.z = z; + } - public LocationRotation( final IBlockAccess world, final int x, final int y, final int z ) - { - this.w = world; - this.x = x; - this.y = y; - this.z = z; - } + @Override + public boolean canBeRotated() { + return false; + } - @Override - public boolean canBeRotated() - { - return false; - } + @Override + public EnumFacing getForward() { + if (this.getUp().getFrontOffsetY() == 0) { + return EnumFacing.UP; + } + return EnumFacing.SOUTH; + } - @Override - public EnumFacing getForward() - { - if( this.getUp().getFrontOffsetY() == 0 ) - { - return EnumFacing.UP; - } - return EnumFacing.SOUTH; - } + @Override + public EnumFacing getUp() { + final int num = Math.abs(this.x + this.y + this.z) % 6; + return EnumFacing.VALUES[num]; + } - @Override - public EnumFacing getUp() - { - final int num = Math.abs( this.x + this.y + this.z ) % 6; - return EnumFacing.VALUES[num]; - } + @Override + public void setOrientation(final EnumFacing forward, final EnumFacing up) { - @Override - public void setOrientation( final EnumFacing forward, final EnumFacing up ) - { - - } + } } diff --git a/src/main/java/appeng/helpers/MetaRotation.java b/src/main/java/appeng/helpers/MetaRotation.java index 1ac643c3e..dcea32f53 100644 --- a/src/main/java/appeng/helpers/MetaRotation.java +++ b/src/main/java/appeng/helpers/MetaRotation.java @@ -19,6 +19,8 @@ package appeng.helpers; +import appeng.api.util.IOrientable; +import appeng.decorative.solid.BlockQuartzPillar; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; @@ -27,88 +29,69 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import appeng.api.util.IOrientable; -import appeng.decorative.solid.BlockQuartzPillar; +public class MetaRotation implements IOrientable { -public class MetaRotation implements IOrientable -{ + private final IProperty facingProp; + private final IBlockAccess w; + private final BlockPos pos; - private final IProperty facingProp; - private final IBlockAccess w; - private final BlockPos pos; + public MetaRotation(final IBlockAccess world, final BlockPos pos, final IProperty facingProp) { + this.w = world; + this.pos = pos; + this.facingProp = facingProp; + } - public MetaRotation( final IBlockAccess world, final BlockPos pos, final IProperty facingProp ) - { - this.w = world; - this.pos = pos; - this.facingProp = facingProp; - } + @Override + public boolean canBeRotated() { + return true; + } - @Override - public boolean canBeRotated() - { - return true; - } + @Override + public EnumFacing getForward() { + if (this.getUp().getFrontOffsetY() == 0) { + return EnumFacing.UP; + } + return EnumFacing.SOUTH; + } - @Override - public EnumFacing getForward() - { - if( this.getUp().getFrontOffsetY() == 0 ) - { - return EnumFacing.UP; - } - return EnumFacing.SOUTH; - } + @Override + public EnumFacing getUp() { + final IBlockState state = this.w.getBlockState(this.pos); - @Override - public EnumFacing getUp() - { - final IBlockState state = this.w.getBlockState( this.pos ); + if (this.facingProp != null) { + return state.getValue(this.facingProp); + } - if( this.facingProp != null ) - { - return state.getValue( this.facingProp ); - } + // TODO 1.10.2-R - Temp + Axis a = state.getValue(BlockQuartzPillar.AXIS_ORIENTATION); - // TODO 1.10.2-R - Temp - Axis a = state.getValue( BlockQuartzPillar.AXIS_ORIENTATION ); + if (a == null) { + a = Axis.Y; + } - if( a == null ) - { - a = Axis.Y; - } + switch (a) { + case X: + return EnumFacing.EAST; + case Z: + return EnumFacing.SOUTH; + default: + case Y: + return EnumFacing.UP; + } + } - switch( a ) - { - case X: - return EnumFacing.EAST; - case Z: - return EnumFacing.SOUTH; - default: - case Y: - return EnumFacing.UP; - } - } - - @Override - public void setOrientation( final EnumFacing forward, final EnumFacing up ) - { - if( this.w instanceof World ) - { - if( this.facingProp != null ) - { - ( (World) this.w ).setBlockState( this.pos, this.w.getBlockState( this.pos ).withProperty( this.facingProp, up ) ); - } - else - { - // TODO 1.10.2-R - Temp - ( (World) this.w ).setBlockState( this.pos, this.w.getBlockState( this.pos ).withProperty( BlockQuartzPillar.AXIS_ORIENTATION, up.getAxis() ) ); - } - } - else - { - throw new IllegalStateException( this.w.getClass().getName() + " received, expected World" ); - } - } + @Override + public void setOrientation(final EnumFacing forward, final EnumFacing up) { + if (this.w instanceof World) { + if (this.facingProp != null) { + ((World) this.w).setBlockState(this.pos, this.w.getBlockState(this.pos).withProperty(this.facingProp, up)); + } else { + // TODO 1.10.2-R - Temp + ((World) this.w).setBlockState(this.pos, this.w.getBlockState(this.pos).withProperty(BlockQuartzPillar.AXIS_ORIENTATION, up.getAxis())); + } + } else { + throw new IllegalStateException(this.w.getClass().getName() + " received, expected World"); + } + } } diff --git a/src/main/java/appeng/helpers/MultiCraftingTracker.java b/src/main/java/appeng/helpers/MultiCraftingTracker.java index d19590b6e..0860e33de 100644 --- a/src/main/java/appeng/helpers/MultiCraftingTracker.java +++ b/src/main/java/appeng/helpers/MultiCraftingTracker.java @@ -19,15 +19,6 @@ package appeng.helpers; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -import com.google.common.collect.ImmutableSet; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - import appeng.api.AEApi; import appeng.api.networking.IGrid; import appeng.api.networking.crafting.ICraftingGrid; @@ -37,269 +28,215 @@ import appeng.api.networking.crafting.ICraftingRequester; import appeng.api.networking.security.IActionSource; import appeng.api.storage.data.IAEItemStack; import appeng.util.InventoryAdaptor; +import com.google.common.collect.ImmutableSet; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; -public class MultiCraftingTracker -{ +public class MultiCraftingTracker { - private final int size; - private final ICraftingRequester owner; + private final int size; + private final ICraftingRequester owner; - private Future[] jobs = null; - private ICraftingLink[] links = null; + private Future[] jobs = null; + private ICraftingLink[] links = null; - public MultiCraftingTracker( final ICraftingRequester o, final int size ) - { - this.owner = o; - this.size = size; - } + public MultiCraftingTracker(final ICraftingRequester o, final int size) { + this.owner = o; + this.size = size; + } - public void readFromNBT( final NBTTagCompound extra ) - { - for( int x = 0; x < this.size; x++ ) - { - final NBTTagCompound link = extra.getCompoundTag( "links-" + x ); + public void readFromNBT(final NBTTagCompound extra) { + for (int x = 0; x < this.size; x++) { + final NBTTagCompound link = extra.getCompoundTag("links-" + x); - if( link != null && !link.hasNoTags() ) - { - this.setLink( x, AEApi.instance().storage().loadCraftingLink( link, this.owner ) ); - } - } - } + if (link != null && !link.hasNoTags()) { + this.setLink(x, AEApi.instance().storage().loadCraftingLink(link, this.owner)); + } + } + } - public void writeToNBT( final NBTTagCompound extra ) - { - for( int x = 0; x < this.size; x++ ) - { - final ICraftingLink link = this.getLink( x ); + public void writeToNBT(final NBTTagCompound extra) { + for (int x = 0; x < this.size; x++) { + final ICraftingLink link = this.getLink(x); - if( link != null ) - { - final NBTTagCompound ln = new NBTTagCompound(); - link.writeToNBT( ln ); - extra.setTag( "links-" + x, ln ); - } - } - } + if (link != null) { + final NBTTagCompound ln = new NBTTagCompound(); + link.writeToNBT(ln); + extra.setTag("links-" + x, ln); + } + } + } - public boolean handleCrafting( final int x, final long itemToCraft, final IAEItemStack ais, final InventoryAdaptor d, final World w, final IGrid g, final ICraftingGrid cg, final IActionSource mySrc ) - { - if( ais != null ) - { - ItemStack inputStack = ais.getCachedItemStack( ais.getStackSize() ); + public boolean handleCrafting(final int x, final long itemToCraft, final IAEItemStack ais, final InventoryAdaptor d, final World w, final IGrid g, final ICraftingGrid cg, final IActionSource mySrc) { + if (ais != null) { + ItemStack inputStack = ais.getCachedItemStack(ais.getStackSize()); - ItemStack remaining = d.simulateAdd( inputStack ); + ItemStack remaining = d.simulateAdd(inputStack); - if( remaining.isEmpty() ) - { - ais.setCachedItemStack( inputStack ); + if (remaining.isEmpty()) { + ais.setCachedItemStack(inputStack); - final Future craftingJob = this.getJob( x ); + final Future craftingJob = this.getJob(x); - if( this.getLink( x ) != null ) - { - return false; - } - else if( craftingJob != null ) - { + if (this.getLink(x) != null) { + return false; + } else if (craftingJob != null) { - try - { - ICraftingJob job = null; - if( craftingJob.isDone() ) - { - job = craftingJob.get(); - } + try { + ICraftingJob job = null; + if (craftingJob.isDone()) { + job = craftingJob.get(); + } - if( job != null ) - { - final ICraftingLink link = cg.submitJob( job, this.owner, null, false, mySrc ); + if (job != null) { + final ICraftingLink link = cg.submitJob(job, this.owner, null, false, mySrc); - this.setJob( x, null ); + this.setJob(x, null); - if( link != null ) - { - this.setLink( x, link ); + if (link != null) { + this.setLink(x, link); - return true; - } - } - } - catch( final InterruptedException e ) - { - // :P - } - catch( final ExecutionException e ) - { - // :P - } - } - else - { - if( this.getLink( x ) == null ) - { - final IAEItemStack aisC = ais.copy(); - aisC.setStackSize( itemToCraft ); + return true; + } + } + } catch (final InterruptedException e) { + // :P + } catch (final ExecutionException e) { + // :P + } + } else { + if (this.getLink(x) == null) { + final IAEItemStack aisC = ais.copy(); + aisC.setStackSize(itemToCraft); - this.setJob( x, cg.beginCraftingJob( w, g, mySrc, aisC, null ) ); - } - } - } - else - { - ais.setCachedItemStack( remaining ); - } - } - return false; - } + this.setJob(x, cg.beginCraftingJob(w, g, mySrc, aisC, null)); + } + } + } else { + ais.setCachedItemStack(remaining); + } + } + return false; + } - public ImmutableSet getRequestedJobs() - { - if( this.links == null ) - { - return ImmutableSet.of(); - } + public ImmutableSet getRequestedJobs() { + if (this.links == null) { + return ImmutableSet.of(); + } - return ImmutableSet.copyOf( new NonNullArrayIterator<>( this.links ) ); - } + return ImmutableSet.copyOf(new NonNullArrayIterator<>(this.links)); + } - public void jobStateChange( final ICraftingLink link ) - { - if( this.links != null ) - { - for( int x = 0; x < this.links.length; x++ ) - { - if( this.links[x] == link ) - { - this.setLink( x, null ); - return; - } - } - } - } + public void jobStateChange(final ICraftingLink link) { + if (this.links != null) { + for (int x = 0; x < this.links.length; x++) { + if (this.links[x] == link) { + this.setLink(x, null); + return; + } + } + } + } - int getSlot( final ICraftingLink link ) - { - if( this.links != null ) - { - for( int x = 0; x < this.links.length; x++ ) - { - if( this.links[x] == link ) - { - return x; - } - } - } + int getSlot(final ICraftingLink link) { + if (this.links != null) { + for (int x = 0; x < this.links.length; x++) { + if (this.links[x] == link) { + return x; + } + } + } - return -1; - } + return -1; + } - void cancel() - { - if( this.links != null ) - { - for( final ICraftingLink l : this.links ) - { - if( l != null ) - { - l.cancel(); - } - } + void cancel() { + if (this.links != null) { + for (final ICraftingLink l : this.links) { + if (l != null) { + l.cancel(); + } + } - this.links = null; - } + this.links = null; + } - if( this.jobs != null ) - { - for( final Future l : this.jobs ) - { - if( l != null ) - { - l.cancel( true ); - } - } + if (this.jobs != null) { + for (final Future l : this.jobs) { + if (l != null) { + l.cancel(true); + } + } - this.jobs = null; - } - } + this.jobs = null; + } + } - boolean isBusy( final int slot ) - { - return this.getLink( slot ) != null || this.getJob( slot ) != null; - } + boolean isBusy(final int slot) { + return this.getLink(slot) != null || this.getJob(slot) != null; + } - private ICraftingLink getLink( final int slot ) - { - if( this.links == null ) - { - return null; - } + private ICraftingLink getLink(final int slot) { + if (this.links == null) { + return null; + } - return this.links[slot]; - } + return this.links[slot]; + } - private void setLink( final int slot, final ICraftingLink l ) - { - if( this.links == null ) - { - this.links = new ICraftingLink[this.size]; - } + private void setLink(final int slot, final ICraftingLink l) { + if (this.links == null) { + this.links = new ICraftingLink[this.size]; + } - this.links[slot] = l; + this.links[slot] = l; - boolean hasStuff = false; - for( int x = 0; x < this.links.length; x++ ) - { - final ICraftingLink g = this.links[x]; + boolean hasStuff = false; + for (int x = 0; x < this.links.length; x++) { + final ICraftingLink g = this.links[x]; - if( g == null || g.isCanceled() || g.isDone() ) - { - this.links[x] = null; - } - else - { - hasStuff = true; - } - } + if (g == null || g.isCanceled() || g.isDone()) { + this.links[x] = null; + } else { + hasStuff = true; + } + } - if( !hasStuff ) - { - this.links = null; - } - } + if (!hasStuff) { + this.links = null; + } + } - private Future getJob( final int slot ) - { - if( this.jobs == null ) - { - return null; - } + private Future getJob(final int slot) { + if (this.jobs == null) { + return null; + } - return this.jobs[slot]; - } + return this.jobs[slot]; + } - private void setJob( final int slot, final Future l ) - { - if( this.jobs == null ) - { - this.jobs = new Future[this.size]; - } + private void setJob(final int slot, final Future l) { + if (this.jobs == null) { + this.jobs = new Future[this.size]; + } - this.jobs[slot] = l; + this.jobs[slot] = l; - boolean hasStuff = false; + boolean hasStuff = false; - for( final Future job : this.jobs ) - { - if( job != null ) - { - hasStuff = true; - } - } + for (final Future job : this.jobs) { + if (job != null) { + hasStuff = true; + } + } - if( !hasStuff ) - { - this.jobs = null; - } - } + if (!hasStuff) { + this.jobs = null; + } + } } diff --git a/src/main/java/appeng/helpers/NonBlockingItems.java b/src/main/java/appeng/helpers/NonBlockingItems.java index b5f00fd01..dfa4bd6bc 100644 --- a/src/main/java/appeng/helpers/NonBlockingItems.java +++ b/src/main/java/appeng/helpers/NonBlockingItems.java @@ -6,128 +6,103 @@ import appeng.util.Platform; import gregtech.api.items.metaitem.MetaItem; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.objects.*; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.oredict.OreDictionary; -import java.util.*; +import java.util.HashMap; +import java.util.Map; -public class NonBlockingItems -{ - public static Map> NON_BLOCKING_MAP = new HashMap<>(); - public static NonBlockingItems INSTANCE = new NonBlockingItems(); +public class NonBlockingItems { + public static Map> NON_BLOCKING_MAP = new HashMap<>(); + public static NonBlockingItems INSTANCE = new NonBlockingItems(); - private NonBlockingItems() - { - String[] strings = AEConfig.instance().getNonBlockingItems(); - String[] modids = new String[0]; - if( strings.length > 0 ) - { - for( String s : strings ) - { - if( s.startsWith( "[" ) && s.endsWith( "]" ) ) - { - modids = s.substring( 1, s.length() - 1 ).split( "\\|" ); - } - else - { - for( String modid : modids ) - { - if( !Loader.isModLoaded( modid ) ) - { - continue; - } - NON_BLOCKING_MAP.putIfAbsent( modid, new Object2ObjectOpenHashMap<>() ); + private NonBlockingItems() { + String[] strings = AEConfig.instance().getNonBlockingItems(); + String[] modids = new String[0]; + if (strings.length > 0) { + for (String s : strings) { + if (s.startsWith("[") && s.endsWith("]")) { + modids = s.substring(1, s.length() - 1).split("\\|"); + } else { + for (String modid : modids) { + if (!Loader.isModLoaded(modid)) { + continue; + } + NON_BLOCKING_MAP.putIfAbsent(modid, new Object2ObjectOpenHashMap<>()); - String[] ModItemMeta = s.split( ":" ); + String[] ModItemMeta = s.split(":"); - if( ModItemMeta.length < 2 || ModItemMeta.length > 3 ) - { - AELog.error( "Invalid non blocking item entry: " + s ); - continue; - } + if (ModItemMeta.length < 2 || ModItemMeta.length > 3) { + AELog.error("Invalid non blocking item entry: " + s); + continue; + } - if( ModItemMeta[0].equals( "gregtech" ) && Platform.isModLoaded( "gregtech" ) ) - { - boolean found = false; - for( MetaItem metaItem : MetaItem.getMetaItems() ) - { - MetaItem.MetaValueItem metaItem2 = metaItem.getItem( ModItemMeta[1] ); - if( metaItem.getItem( ModItemMeta[1] ) != null ) - { - found = true; - ItemStack itemStack = metaItem2.getStackForm(); - NON_BLOCKING_MAP.get( modid ).putIfAbsent( itemStack.getItem(), new IntOpenHashSet() ); - NON_BLOCKING_MAP.get( modid ).computeIfPresent( itemStack.getItem(), ( item, intSet ) -> - { - intSet.add( itemStack.getItemDamage() ); - return intSet; - } ); - } - else - { - ItemStack itemStack = GameRegistry.makeItemStack( ModItemMeta[0] + ":" + ModItemMeta[1], ModItemMeta.length == 3 ? Integer.parseInt( ModItemMeta[2] ) : 0, 1, null ); - if( !itemStack.isEmpty() ) - { - NON_BLOCKING_MAP.get( modid ).putIfAbsent( itemStack.getItem(), new IntOpenHashSet() ); - NON_BLOCKING_MAP.get( modid ).computeIfPresent( itemStack.getItem(), ( item, intSet ) -> - { - intSet.add( itemStack.getItemDamage() ); - return intSet; - } ); - } - } - } - if( !found ) - { - AELog.error( "Item not found on nonBlocking config: " + s ); - } - } - else if( ModItemMeta[0].equals( "ore" ) ) - { - OreDictionary.getOres( ModItemMeta[1] ).forEach( itemStack -> - { - NON_BLOCKING_MAP.get( modid ).putIfAbsent( itemStack.getItem(), new IntOpenHashSet() ); - NON_BLOCKING_MAP.get( modid ).computeIfPresent( itemStack.getItem(), ( item, intSet ) -> - { - intSet.add( itemStack.getItemDamage() ); - return intSet; - } ); - } ); - } - else - { - ItemStack itemStack = GameRegistry.makeItemStack( ModItemMeta[0] + ":" + ModItemMeta[1], ModItemMeta.length == 3 ? Integer.parseInt( ModItemMeta[2] ) : 0, 1, null ); - if( !itemStack.isEmpty() ) - { - NON_BLOCKING_MAP.get( modid ).putIfAbsent( itemStack.getItem(), new IntOpenHashSet() ); - NON_BLOCKING_MAP.get( modid ).computeIfPresent( itemStack.getItem(), ( item, intSet ) -> - { - intSet.add( itemStack.getItemDamage() ); - return intSet; - } ); - } - else - { - AELog.error( "Item not found on nonBlocking config: " + s ); - } - } - } - } - } - } - } + if (ModItemMeta[0].equals("gregtech") && Platform.isModLoaded("gregtech")) { + boolean found = false; + for (MetaItem metaItem : MetaItem.getMetaItems()) { + MetaItem.MetaValueItem metaItem2 = metaItem.getItem(ModItemMeta[1]); + if (metaItem.getItem(ModItemMeta[1]) != null) { + found = true; + ItemStack itemStack = metaItem2.getStackForm(); + NON_BLOCKING_MAP.get(modid).putIfAbsent(itemStack.getItem(), new IntOpenHashSet()); + NON_BLOCKING_MAP.get(modid).computeIfPresent(itemStack.getItem(), (item, intSet) -> + { + intSet.add(itemStack.getItemDamage()); + return intSet; + }); + } else { + ItemStack itemStack = GameRegistry.makeItemStack(ModItemMeta[0] + ":" + ModItemMeta[1], ModItemMeta.length == 3 ? Integer.parseInt(ModItemMeta[2]) : 0, 1, null); + if (!itemStack.isEmpty()) { + NON_BLOCKING_MAP.get(modid).putIfAbsent(itemStack.getItem(), new IntOpenHashSet()); + NON_BLOCKING_MAP.get(modid).computeIfPresent(itemStack.getItem(), (item, intSet) -> + { + intSet.add(itemStack.getItemDamage()); + return intSet; + }); + } + } + } + if (!found) { + AELog.error("Item not found on nonBlocking config: " + s); + } + } else if (ModItemMeta[0].equals("ore")) { + OreDictionary.getOres(ModItemMeta[1]).forEach(itemStack -> + { + NON_BLOCKING_MAP.get(modid).putIfAbsent(itemStack.getItem(), new IntOpenHashSet()); + NON_BLOCKING_MAP.get(modid).computeIfPresent(itemStack.getItem(), (item, intSet) -> + { + intSet.add(itemStack.getItemDamage()); + return intSet; + }); + }); + } else { + ItemStack itemStack = GameRegistry.makeItemStack(ModItemMeta[0] + ":" + ModItemMeta[1], ModItemMeta.length == 3 ? Integer.parseInt(ModItemMeta[2]) : 0, 1, null); + if (!itemStack.isEmpty()) { + NON_BLOCKING_MAP.get(modid).putIfAbsent(itemStack.getItem(), new IntOpenHashSet()); + NON_BLOCKING_MAP.get(modid).computeIfPresent(itemStack.getItem(), (item, intSet) -> + { + intSet.add(itemStack.getItemDamage()); + return intSet; + }); + } else { + AELog.error("Item not found on nonBlocking config: " + s); + } + } + } + } + } + } + } - public Map> getMap() - { - return NON_BLOCKING_MAP; - } + public Map> getMap() { + return NON_BLOCKING_MAP; + } - public void init() - { - } + public void init() { + } } diff --git a/src/main/java/appeng/helpers/NonNullArrayIterator.java b/src/main/java/appeng/helpers/NonNullArrayIterator.java index 7c964168b..bb5070fdc 100644 --- a/src/main/java/appeng/helpers/NonNullArrayIterator.java +++ b/src/main/java/appeng/helpers/NonNullArrayIterator.java @@ -22,40 +22,34 @@ package appeng.helpers; import java.util.Iterator; -public class NonNullArrayIterator implements Iterator -{ +public class NonNullArrayIterator implements Iterator { - private final E[] g; - private int offset = 0; + private final E[] g; + private int offset = 0; - public NonNullArrayIterator( final E[] o ) - { - this.g = o; - } + public NonNullArrayIterator(final E[] o) { + this.g = o; + } - @Override - public boolean hasNext() - { - while( this.offset < this.g.length && this.g[this.offset] == null ) - { - this.offset++; - } + @Override + public boolean hasNext() { + while (this.offset < this.g.length && this.g[this.offset] == null) { + this.offset++; + } - return this.offset != this.g.length; - } + return this.offset != this.g.length; + } - @Override - public E next() - { - final E result = this.g[this.offset]; - this.offset++; + @Override + public E next() { + final E result = this.g[this.offset]; + this.offset++; - return result; - } + return result; + } - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/helpers/NullRotation.java b/src/main/java/appeng/helpers/NullRotation.java index 1c18237eb..330817735 100644 --- a/src/main/java/appeng/helpers/NullRotation.java +++ b/src/main/java/appeng/helpers/NullRotation.java @@ -19,40 +19,33 @@ package appeng.helpers; +import appeng.api.util.IOrientable; import net.minecraft.util.EnumFacing; -import appeng.api.util.IOrientable; +public class NullRotation implements IOrientable { -public class NullRotation implements IOrientable -{ + public NullRotation() { - public NullRotation() - { + } - } + @Override + public boolean canBeRotated() { + return false; + } - @Override - public boolean canBeRotated() - { - return false; - } + @Override + public EnumFacing getForward() { + return EnumFacing.SOUTH; + } - @Override - public EnumFacing getForward() - { - return EnumFacing.SOUTH; - } + @Override + public EnumFacing getUp() { + return EnumFacing.UP; + } - @Override - public EnumFacing getUp() - { - return EnumFacing.UP; - } + @Override + public void setOrientation(final EnumFacing forward, final EnumFacing up) { - @Override - public void setOrientation( final EnumFacing forward, final EnumFacing up ) - { - - } + } } diff --git a/src/main/java/appeng/helpers/PatternHelper.java b/src/main/java/appeng/helpers/PatternHelper.java index d695c72ce..39231d57f 100644 --- a/src/main/java/appeng/helpers/PatternHelper.java +++ b/src/main/java/appeng/helpers/PatternHelper.java @@ -19,8 +19,13 @@ package appeng.helpers; -import java.util.*; - +import appeng.api.AEApi; +import appeng.api.networking.crafting.ICraftingPatternDetails; +import appeng.api.storage.channels.IItemStorageChannel; +import appeng.api.storage.data.IAEItemStack; +import appeng.container.ContainerNull; +import appeng.util.Platform; +import appeng.util.item.AEItemStack; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -31,560 +36,463 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.NonNullList; import net.minecraft.world.World; - -import appeng.api.AEApi; -import appeng.api.networking.crafting.ICraftingPatternDetails; -import appeng.api.storage.channels.IItemStorageChannel; -import appeng.api.storage.data.IAEItemStack; -import appeng.container.ContainerNull; -import appeng.util.Platform; -import appeng.util.item.AEItemStack; import net.minecraftforge.common.crafting.IShapedRecipe; -import net.minecraftforge.fml.common.Optional; - - -public class PatternHelper implements ICraftingPatternDetails, Comparable -{ - - private static final int CRAFTING_GRID_DIMENSION = 3; - private static final int CRAFTING_INPUT_LIMIT = CRAFTING_GRID_DIMENSION * CRAFTING_GRID_DIMENSION; - public static final int PROCESSING_INPUT_HEIGHT = 4; - public static final int PROCESSING_INPUT_WIDTH = 4; - public static final int PROCESSING_INPUT_LIMIT = PROCESSING_INPUT_HEIGHT * PROCESSING_INPUT_WIDTH; - private static final int CRAFTING_OUTPUT_LIMIT = 1; - public static final int PROCESSING_OUTPUT_LIMIT = 6; - - private final ItemStack patternItem; - private final InventoryCrafting crafting; - private final InventoryCrafting testFrame; - private final ItemStack correctOutput; - private final IRecipe standardRecipe; - private final IAEItemStack[] condensedInputs; - private final IAEItemStack[] condensedOutputs; - private final IAEItemStack[] inputs; - private final IAEItemStack[] outputs; - private final Map> substituteInputs; - private final boolean isCrafting; - private final boolean canSubstitute; - private final Set failCache = new HashSet<>(); - private final Set passCache = new HashSet<>(); - private final IAEItemStack pattern; - private int priority = 0; - - public PatternHelper( final ItemStack is, final World w ) - { - final NBTTagCompound encodedValue = is.getTagCompound(); - - if( encodedValue == null ) - { - throw new IllegalArgumentException( "No pattern here!" ); - } - - final NBTTagList inTag = encodedValue.getTagList( "in", 10 ); - final NBTTagList outTag = encodedValue.getTagList( "out", 10 ); - this.isCrafting = encodedValue.getBoolean( "crafting" ); - - crafting = new InventoryCrafting( new ContainerNull(), isCrafting ? 3 : 4, isCrafting ? 3 : 4 ); - testFrame = new InventoryCrafting( new ContainerNull(), isCrafting ? 3 : 4, isCrafting ? 3 : 4 ); - - this.canSubstitute = this.isCrafting && encodedValue.getBoolean( "substitute" ); - this.patternItem = is; - this.pattern = AEItemStack.fromItemStack( is ); - - final List in = new ArrayList<>(); - final List out = new ArrayList<>(); - - for( int x = 0; x < inTag.tagCount(); x++ ) - { - NBTTagCompound ingredient = inTag.getCompoundTagAt( x ); - final ItemStack gs = new ItemStack( ingredient ); - - if( !ingredient.hasNoTags() && gs.isEmpty() ) - { - throw new IllegalArgumentException( "No pattern here!" ); - } - - this.crafting.setInventorySlotContents( x, gs ); - - if( !gs.isEmpty() && ( !this.isCrafting || !gs.hasTagCompound() ) ) - { - this.markItemAs( x, gs, TestStatus.ACCEPT ); - } - - in.add( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( gs ) ); - this.testFrame.setInventorySlotContents( x, gs ); - } - - if( this.isCrafting ) - { - this.standardRecipe = CraftingManager.findMatchingRecipe( this.crafting, w ); - - if( this.standardRecipe != null ) - { - this.correctOutput = this.standardRecipe.getCraftingResult( this.crafting ); - out.add( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( this.correctOutput ) ); - } - else - { - throw new IllegalStateException( "No pattern here!" ); - } - } - else - { - this.standardRecipe = null; - this.correctOutput = ItemStack.EMPTY; - - for( int x = 0; x < outTag.tagCount(); x++ ) - { - NBTTagCompound resultItemTag = outTag.getCompoundTagAt( x ); - final ItemStack gs = new ItemStack( resultItemTag ); - - if( !resultItemTag.hasNoTags() && gs.isEmpty() ) - { - throw new IllegalArgumentException( "No pattern here!" ); - } - - if( !gs.isEmpty() ) - { - out.add( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( gs ) ); - } - } - } - final int outputLength = out.size(); - - this.inputs = in.toArray( new IAEItemStack[isCrafting ? CRAFTING_INPUT_LIMIT : PROCESSING_INPUT_LIMIT] ); - this.outputs = out.toArray( new IAEItemStack[outputLength] ); - this.substituteInputs = new HashMap<>( CRAFTING_INPUT_LIMIT ); - - final Map tmpOutputs = new HashMap<>(); - - for( final IAEItemStack io : this.outputs ) - { - if( io == null ) - { - continue; - } - - final IAEItemStack g = tmpOutputs.get( io ); - - if( g == null ) - { - tmpOutputs.put( io, io.copy() ); - } - else - { - g.add( io ); - } - } - - final Map tmpInputs = new HashMap<>(); - - for( final IAEItemStack io : this.inputs ) - { - if( io == null ) - { - continue; - } - - final IAEItemStack g = tmpInputs.get( io ); - - if( g == null ) - { - tmpInputs.put( io, io.copy() ); - } - else - { - g.add( io ); - } - } - - if( tmpOutputs.isEmpty() || tmpInputs.isEmpty() ) - { - throw new IllegalStateException( "No pattern here!" ); - } - - this.condensedInputs = new IAEItemStack[tmpInputs.size()]; - int offset = 0; - - for( final IAEItemStack io : tmpInputs.values() ) - { - this.condensedInputs[offset] = io; - offset++; - } - - offset = 0; - this.condensedOutputs = new IAEItemStack[tmpOutputs.size()]; - - for( final IAEItemStack io : tmpOutputs.values() ) - { - this.condensedOutputs[offset] = io; - offset++; - } - } - - private void markItemAs( final int slotIndex, final ItemStack i, final TestStatus b ) - { - if( b == TestStatus.TEST || i.hasTagCompound() ) - { - return; - } - - ( b == TestStatus.ACCEPT ? this.passCache : this.failCache ).add( new TestLookup( slotIndex, i ) ); - } - - @Override - public ItemStack getPattern() - { - return this.patternItem; - } - - @Override - public synchronized boolean isValidItemForSlot( final int slotIndex, final ItemStack i, final World w ) - { - if( !this.isCrafting ) - { - throw new IllegalStateException( "Only crafting recipes supported." ); - } - - final TestStatus result = this.getStatus( slotIndex, i ); - - switch ( result ) - { - case ACCEPT: - return true; - case DECLINE: - return false; - case TEST: - default: - break; - } - - for( int x = 0; x < this.crafting.getSizeInventory(); x++ ) - { - this.testFrame.setInventorySlotContents( x, this.crafting.getStackInSlot( x ) ); - } - - this.testFrame.setInventorySlotContents( slotIndex, i ); - - // If we cannot substitute, the items must match exactly - if( ( !( i.getItem().isDamageable() || Platform.isGTDamageableItem( i.getItem() ) ) && !canSubstitute ) && slotIndex < inputs.length ) - { - if( !inputs[slotIndex].isSameType( i ) ) - { - this.markItemAs( slotIndex, i, TestStatus.DECLINE ); - return false; - } - } - - if( this.standardRecipe.matches( this.testFrame, w ) ) - { - final ItemStack testOutput = this.standardRecipe.getCraftingResult( this.testFrame ); - - if( Platform.itemComparisons().isSameItem( this.correctOutput, testOutput ) ) - { - this.testFrame.setInventorySlotContents( slotIndex, this.crafting.getStackInSlot( slotIndex ) ); - this.markItemAs( slotIndex, i, TestStatus.ACCEPT ); - return true; - } - } - - this.markItemAs( slotIndex, i, TestStatus.DECLINE ); - return false; - } - - @Override - public boolean isCraftable() - { - return this.isCrafting; - } - - @Override - public IAEItemStack[] getInputs() - { - return this.inputs; - } - - @Override - public IAEItemStack[] getCondensedInputs() - { - return this.condensedInputs; - } - - @Override - public IAEItemStack[] getCondensedOutputs() - { - return this.condensedOutputs; - } - - @Override - public IAEItemStack[] getOutputs() - { - return this.outputs; - } - - @Override - public boolean canSubstitute() - { - return this.canSubstitute; - } - - @Override - public List getSubstituteInputs( int slot ) - { - if( this.inputs[slot] == null ) - { - return Collections.emptyList(); - } - - return this.substituteInputs.computeIfAbsent( slot, value -> { - ItemStack[] matchingStacks = getRecipeIngredient( slot ).getMatchingStacks(); - List itemList = new ArrayList<>( matchingStacks.length + 1 ); - for( ItemStack matchingStack : matchingStacks ) - { - itemList.add( AEItemStack.fromItemStack( matchingStack ) ); - } - - // Ensure that the specific item put in by the user is at the beginning, - // so that it takes precedence over substitutions - itemList.add( 0, this.inputs[slot] ); - return itemList; - } ); - } - - /** - * Gets the {@link Ingredient} from the actual used recipe for a given slot-index into {@link #getInputs()}. - *

- * Conversion is needed for two reasons: our sparse ingredients are always organized in a 3x3 grid, while Vanilla's - * ingredient list will be condensed to the actual recipe's grid size. In addition, in our 3x3 grid, the user can - * shift the actual recipe input to the right and down. - */ - private Ingredient getRecipeIngredient( int slot ) - { - - if( standardRecipe instanceof IShapedRecipe ) - { - IShapedRecipe shapedRecipe = (IShapedRecipe) standardRecipe; - - return getShapedRecipeIngredient( slot, shapedRecipe.getRecipeWidth() ); - } - else - { - return getShapelessRecipeIngredient( slot ); - } - } - - private Ingredient getShapedRecipeIngredient( int slot, int recipeWidth ) - { - // Compute the offset of the user's input vs. crafting grid origin - // Which is >0 if they have empty rows above or to the left of their input - int topOffset = 0; - if( inputs[0] == null && inputs[1] == null && inputs[2] == null ) - { - topOffset++; // First row is fully empty - if( inputs[3] == null && inputs[4] == null && inputs[5] == null ) - { - topOffset++; // Second row is fully empty - } - } - int leftOffset = 0; - if( inputs[0] == null && inputs[3] == null && inputs[6] == null ) - { - leftOffset++; // First column is fully empty - if( inputs[1] == null && inputs[4] == null && inputs[7] == null ) - { - leftOffset++; // Second column is fully empty - } - } - - // Compute the x,y of the slot, as-if the recipe was anchored to 0,0 - int slotX = slot % CRAFTING_GRID_DIMENSION - leftOffset; - int slotY = slot / CRAFTING_GRID_DIMENSION - topOffset; - - // Compute the index into the recipe's ingredient list now - int ingredientIndex = slotY * recipeWidth + slotX; - - NonNullList ingredients = standardRecipe.getIngredients(); - - if( ingredientIndex < 0 || ingredientIndex > ingredients.size() ) - { - return Ingredient.EMPTY; - } - - return ingredients.get( ingredientIndex ); - } - - private Ingredient getShapelessRecipeIngredient( int slot ) - { - // We map the list of *filled* sparse inputs to the shapeless (ergo unordered) - // ingredients. While these do not actually correspond to each other, - // since both lists have the same length, the mapping is at least stable. - int ingredientIndex = 0; - for( int i = 0; i < slot; i++ ) - { - if( inputs[i] != null ) - { - ingredientIndex++; - } - } - - NonNullList ingredients = standardRecipe.getIngredients(); - if( ingredientIndex < ingredients.size() ) - { - return ingredients.get( ingredientIndex ); - } - - return Ingredient.EMPTY; - } - - @Override - public ItemStack getOutput( final InventoryCrafting craftingInv, final World w ) - { - if( !this.isCrafting ) - { - throw new IllegalStateException( "Only crafting recipes supported." ); - } - - for( int x = 0; x < craftingInv.getSizeInventory(); x++ ) - { - if( !this.isValidItemForSlot( x, craftingInv.getStackInSlot( x ), w ) ) - { - return ItemStack.EMPTY; - } - } - - if( this.outputs != null && this.outputs.length > 0 ) - { - return this.outputs[0].createItemStack(); - } - - return ItemStack.EMPTY; - } - - private TestStatus getStatus( final int slotIndex, final ItemStack i ) - { - if( this.crafting.getStackInSlot( slotIndex ).isEmpty() ) - { - return i.isEmpty() ? TestStatus.ACCEPT : TestStatus.DECLINE; - } - - if( i.isEmpty() ) - { - return TestStatus.DECLINE; - } - - if( i.hasTagCompound() ) - { - return TestStatus.TEST; - } - - if( this.passCache.contains( new TestLookup( slotIndex, i ) ) ) - { - return TestStatus.ACCEPT; - } - - if( this.failCache.contains( new TestLookup( slotIndex, i ) ) ) - { - return TestStatus.DECLINE; - } - - return TestStatus.TEST; - } - - @Override - public int getPriority() - { - return this.priority; - } - - @Override - public void setPriority( final int priority ) - { - this.priority = priority; - } - - @Override - public int compareTo( final PatternHelper o ) - { - return Integer.compare( o.priority, this.priority ); - } - - @Override - public int hashCode() - { - return this.pattern.hashCode(); - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - - final PatternHelper other = (PatternHelper) obj; - - if( this.pattern != null && other.pattern != null ) - { - return this.pattern.equals( other.pattern ); - } - return false; - } - - private enum TestStatus - { - ACCEPT, - DECLINE, - TEST - } - - private static final class TestLookup - { - - private final int slot; - private final int ref; - private final int hash; - - public TestLookup( final int slot, final ItemStack i ) - { - this( slot, i.getItem(), i.getItemDamage() ); - } - - public TestLookup( final int slot, final Item item, final int dmg ) - { - this.slot = slot; - this.ref = ( dmg << Platform.DEF_OFFSET ) | ( Item.getIdFromItem( item ) & 0xffff ); - final int offset = 3 * slot; - this.hash = ( this.ref << offset ) | ( this.ref >> ( offset + 32 ) ); - } - - @Override - public int hashCode() - { - return this.hash; - } - - @Override - public boolean equals( final Object obj ) - { - final boolean equality; - - if( obj instanceof TestLookup ) - { - final TestLookup b = (TestLookup) obj; - - equality = b.slot == this.slot && b.ref == this.ref; - } - else - { - equality = false; - } - - return equality; - } - } + +import java.util.*; + + +public class PatternHelper implements ICraftingPatternDetails, Comparable { + + private static final int CRAFTING_GRID_DIMENSION = 3; + private static final int CRAFTING_INPUT_LIMIT = CRAFTING_GRID_DIMENSION * CRAFTING_GRID_DIMENSION; + public static final int PROCESSING_INPUT_HEIGHT = 4; + public static final int PROCESSING_INPUT_WIDTH = 4; + public static final int PROCESSING_INPUT_LIMIT = PROCESSING_INPUT_HEIGHT * PROCESSING_INPUT_WIDTH; + private static final int CRAFTING_OUTPUT_LIMIT = 1; + public static final int PROCESSING_OUTPUT_LIMIT = 6; + + private final ItemStack patternItem; + private final InventoryCrafting crafting; + private final InventoryCrafting testFrame; + private final ItemStack correctOutput; + private final IRecipe standardRecipe; + private final IAEItemStack[] condensedInputs; + private final IAEItemStack[] condensedOutputs; + private final IAEItemStack[] inputs; + private final IAEItemStack[] outputs; + private final Map> substituteInputs; + private final boolean isCrafting; + private final boolean canSubstitute; + private final Set failCache = new HashSet<>(); + private final Set passCache = new HashSet<>(); + private final IAEItemStack pattern; + private int priority = 0; + + public PatternHelper(final ItemStack is, final World w) { + final NBTTagCompound encodedValue = is.getTagCompound(); + + if (encodedValue == null) { + throw new IllegalArgumentException("No pattern here!"); + } + + final NBTTagList inTag = encodedValue.getTagList("in", 10); + final NBTTagList outTag = encodedValue.getTagList("out", 10); + this.isCrafting = encodedValue.getBoolean("crafting"); + + crafting = new InventoryCrafting(new ContainerNull(), isCrafting ? 3 : 4, isCrafting ? 3 : 4); + testFrame = new InventoryCrafting(new ContainerNull(), isCrafting ? 3 : 4, isCrafting ? 3 : 4); + + this.canSubstitute = this.isCrafting && encodedValue.getBoolean("substitute"); + this.patternItem = is; + this.pattern = AEItemStack.fromItemStack(is); + + final List in = new ArrayList<>(); + final List out = new ArrayList<>(); + + for (int x = 0; x < inTag.tagCount(); x++) { + NBTTagCompound ingredient = inTag.getCompoundTagAt(x); + final ItemStack gs = new ItemStack(ingredient); + + if (!ingredient.hasNoTags() && gs.isEmpty()) { + throw new IllegalArgumentException("No pattern here!"); + } + + this.crafting.setInventorySlotContents(x, gs); + + if (!gs.isEmpty() && (!this.isCrafting || !gs.hasTagCompound())) { + this.markItemAs(x, gs, TestStatus.ACCEPT); + } + + in.add(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(gs)); + this.testFrame.setInventorySlotContents(x, gs); + } + + if (this.isCrafting) { + this.standardRecipe = CraftingManager.findMatchingRecipe(this.crafting, w); + + if (this.standardRecipe != null) { + this.correctOutput = this.standardRecipe.getCraftingResult(this.crafting); + out.add(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(this.correctOutput)); + } else { + throw new IllegalStateException("No pattern here!"); + } + } else { + this.standardRecipe = null; + this.correctOutput = ItemStack.EMPTY; + + for (int x = 0; x < outTag.tagCount(); x++) { + NBTTagCompound resultItemTag = outTag.getCompoundTagAt(x); + final ItemStack gs = new ItemStack(resultItemTag); + + if (!resultItemTag.hasNoTags() && gs.isEmpty()) { + throw new IllegalArgumentException("No pattern here!"); + } + + if (!gs.isEmpty()) { + out.add(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(gs)); + } + } + } + final int outputLength = out.size(); + + this.inputs = in.toArray(new IAEItemStack[isCrafting ? CRAFTING_INPUT_LIMIT : PROCESSING_INPUT_LIMIT]); + this.outputs = out.toArray(new IAEItemStack[outputLength]); + this.substituteInputs = new HashMap<>(CRAFTING_INPUT_LIMIT); + + final Map tmpOutputs = new HashMap<>(); + + for (final IAEItemStack io : this.outputs) { + if (io == null) { + continue; + } + + final IAEItemStack g = tmpOutputs.get(io); + + if (g == null) { + tmpOutputs.put(io, io.copy()); + } else { + g.add(io); + } + } + + final Map tmpInputs = new HashMap<>(); + + for (final IAEItemStack io : this.inputs) { + if (io == null) { + continue; + } + + final IAEItemStack g = tmpInputs.get(io); + + if (g == null) { + tmpInputs.put(io, io.copy()); + } else { + g.add(io); + } + } + + if (tmpOutputs.isEmpty() || tmpInputs.isEmpty()) { + throw new IllegalStateException("No pattern here!"); + } + + this.condensedInputs = new IAEItemStack[tmpInputs.size()]; + int offset = 0; + + for (final IAEItemStack io : tmpInputs.values()) { + this.condensedInputs[offset] = io; + offset++; + } + + offset = 0; + this.condensedOutputs = new IAEItemStack[tmpOutputs.size()]; + + for (final IAEItemStack io : tmpOutputs.values()) { + this.condensedOutputs[offset] = io; + offset++; + } + } + + private void markItemAs(final int slotIndex, final ItemStack i, final TestStatus b) { + if (b == TestStatus.TEST || i.hasTagCompound()) { + return; + } + + (b == TestStatus.ACCEPT ? this.passCache : this.failCache).add(new TestLookup(slotIndex, i)); + } + + @Override + public ItemStack getPattern() { + return this.patternItem; + } + + @Override + public synchronized boolean isValidItemForSlot(final int slotIndex, final ItemStack i, final World w) { + if (!this.isCrafting) { + throw new IllegalStateException("Only crafting recipes supported."); + } + + final TestStatus result = this.getStatus(slotIndex, i); + + switch (result) { + case ACCEPT: + return true; + case DECLINE: + return false; + case TEST: + default: + break; + } + + for (int x = 0; x < this.crafting.getSizeInventory(); x++) { + this.testFrame.setInventorySlotContents(x, this.crafting.getStackInSlot(x)); + } + + this.testFrame.setInventorySlotContents(slotIndex, i); + + // If we cannot substitute, the items must match exactly + if ((!(i.getItem().isDamageable() || Platform.isGTDamageableItem(i.getItem())) && !canSubstitute) && slotIndex < inputs.length) { + if (!inputs[slotIndex].isSameType(i)) { + this.markItemAs(slotIndex, i, TestStatus.DECLINE); + return false; + } + } + + if (this.standardRecipe.matches(this.testFrame, w)) { + final ItemStack testOutput = this.standardRecipe.getCraftingResult(this.testFrame); + + if (Platform.itemComparisons().isSameItem(this.correctOutput, testOutput)) { + this.testFrame.setInventorySlotContents(slotIndex, this.crafting.getStackInSlot(slotIndex)); + this.markItemAs(slotIndex, i, TestStatus.ACCEPT); + return true; + } + } + + this.markItemAs(slotIndex, i, TestStatus.DECLINE); + return false; + } + + @Override + public boolean isCraftable() { + return this.isCrafting; + } + + @Override + public IAEItemStack[] getInputs() { + return this.inputs; + } + + @Override + public IAEItemStack[] getCondensedInputs() { + return this.condensedInputs; + } + + @Override + public IAEItemStack[] getCondensedOutputs() { + return this.condensedOutputs; + } + + @Override + public IAEItemStack[] getOutputs() { + return this.outputs; + } + + @Override + public boolean canSubstitute() { + return this.canSubstitute; + } + + @Override + public List getSubstituteInputs(int slot) { + if (this.inputs[slot] == null) { + return Collections.emptyList(); + } + + return this.substituteInputs.computeIfAbsent(slot, value -> { + ItemStack[] matchingStacks = getRecipeIngredient(slot).getMatchingStacks(); + List itemList = new ArrayList<>(matchingStacks.length + 1); + for (ItemStack matchingStack : matchingStacks) { + itemList.add(AEItemStack.fromItemStack(matchingStack)); + } + + // Ensure that the specific item put in by the user is at the beginning, + // so that it takes precedence over substitutions + itemList.add(0, this.inputs[slot]); + return itemList; + }); + } + + /** + * Gets the {@link Ingredient} from the actual used recipe for a given slot-index into {@link #getInputs()}. + *

+ * Conversion is needed for two reasons: our sparse ingredients are always organized in a 3x3 grid, while Vanilla's + * ingredient list will be condensed to the actual recipe's grid size. In addition, in our 3x3 grid, the user can + * shift the actual recipe input to the right and down. + */ + private Ingredient getRecipeIngredient(int slot) { + + if (standardRecipe instanceof IShapedRecipe) { + IShapedRecipe shapedRecipe = (IShapedRecipe) standardRecipe; + + return getShapedRecipeIngredient(slot, shapedRecipe.getRecipeWidth()); + } else { + return getShapelessRecipeIngredient(slot); + } + } + + private Ingredient getShapedRecipeIngredient(int slot, int recipeWidth) { + // Compute the offset of the user's input vs. crafting grid origin + // Which is >0 if they have empty rows above or to the left of their input + int topOffset = 0; + if (inputs[0] == null && inputs[1] == null && inputs[2] == null) { + topOffset++; // First row is fully empty + if (inputs[3] == null && inputs[4] == null && inputs[5] == null) { + topOffset++; // Second row is fully empty + } + } + int leftOffset = 0; + if (inputs[0] == null && inputs[3] == null && inputs[6] == null) { + leftOffset++; // First column is fully empty + if (inputs[1] == null && inputs[4] == null && inputs[7] == null) { + leftOffset++; // Second column is fully empty + } + } + + // Compute the x,y of the slot, as-if the recipe was anchored to 0,0 + int slotX = slot % CRAFTING_GRID_DIMENSION - leftOffset; + int slotY = slot / CRAFTING_GRID_DIMENSION - topOffset; + + // Compute the index into the recipe's ingredient list now + int ingredientIndex = slotY * recipeWidth + slotX; + + NonNullList ingredients = standardRecipe.getIngredients(); + + if (ingredientIndex < 0 || ingredientIndex > ingredients.size()) { + return Ingredient.EMPTY; + } + + return ingredients.get(ingredientIndex); + } + + private Ingredient getShapelessRecipeIngredient(int slot) { + // We map the list of *filled* sparse inputs to the shapeless (ergo unordered) + // ingredients. While these do not actually correspond to each other, + // since both lists have the same length, the mapping is at least stable. + int ingredientIndex = 0; + for (int i = 0; i < slot; i++) { + if (inputs[i] != null) { + ingredientIndex++; + } + } + + NonNullList ingredients = standardRecipe.getIngredients(); + if (ingredientIndex < ingredients.size()) { + return ingredients.get(ingredientIndex); + } + + return Ingredient.EMPTY; + } + + @Override + public ItemStack getOutput(final InventoryCrafting craftingInv, final World w) { + if (!this.isCrafting) { + throw new IllegalStateException("Only crafting recipes supported."); + } + + for (int x = 0; x < craftingInv.getSizeInventory(); x++) { + if (!this.isValidItemForSlot(x, craftingInv.getStackInSlot(x), w)) { + return ItemStack.EMPTY; + } + } + + if (this.outputs != null && this.outputs.length > 0) { + return this.outputs[0].createItemStack(); + } + + return ItemStack.EMPTY; + } + + private TestStatus getStatus(final int slotIndex, final ItemStack i) { + if (this.crafting.getStackInSlot(slotIndex).isEmpty()) { + return i.isEmpty() ? TestStatus.ACCEPT : TestStatus.DECLINE; + } + + if (i.isEmpty()) { + return TestStatus.DECLINE; + } + + if (i.hasTagCompound()) { + return TestStatus.TEST; + } + + if (this.passCache.contains(new TestLookup(slotIndex, i))) { + return TestStatus.ACCEPT; + } + + if (this.failCache.contains(new TestLookup(slotIndex, i))) { + return TestStatus.DECLINE; + } + + return TestStatus.TEST; + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(final int priority) { + this.priority = priority; + } + + @Override + public int compareTo(final PatternHelper o) { + return Integer.compare(o.priority, this.priority); + } + + @Override + public int hashCode() { + return this.pattern.hashCode(); + } + + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + + final PatternHelper other = (PatternHelper) obj; + + if (this.pattern != null && other.pattern != null) { + return this.pattern.equals(other.pattern); + } + return false; + } + + private enum TestStatus { + ACCEPT, + DECLINE, + TEST + } + + private static final class TestLookup { + + private final int slot; + private final int ref; + private final int hash; + + public TestLookup(final int slot, final ItemStack i) { + this(slot, i.getItem(), i.getItemDamage()); + } + + public TestLookup(final int slot, final Item item, final int dmg) { + this.slot = slot; + this.ref = (dmg << Platform.DEF_OFFSET) | (Item.getIdFromItem(item) & 0xffff); + final int offset = 3 * slot; + this.hash = (this.ref << offset) | (this.ref >> (offset + 32)); + } + + @Override + public int hashCode() { + return this.hash; + } + + @Override + public boolean equals(final Object obj) { + final boolean equality; + + if (obj instanceof TestLookup) { + final TestLookup b = (TestLookup) obj; + + equality = b.slot == this.slot && b.ref == this.ref; + } else { + equality = false; + } + + return equality; + } + } } diff --git a/src/main/java/appeng/helpers/PlayerSecurityWrapper.java b/src/main/java/appeng/helpers/PlayerSecurityWrapper.java index a79e4207d..6ae3da270 100644 --- a/src/main/java/appeng/helpers/PlayerSecurityWrapper.java +++ b/src/main/java/appeng/helpers/PlayerSecurityWrapper.java @@ -19,26 +19,23 @@ package appeng.helpers; -import java.util.EnumSet; -import java.util.Map; - import appeng.api.config.SecurityPermissions; import appeng.api.networking.security.ISecurityRegistry; +import java.util.EnumSet; +import java.util.Map; -public class PlayerSecurityWrapper implements ISecurityRegistry -{ - private final Map> target; +public class PlayerSecurityWrapper implements ISecurityRegistry { - public PlayerSecurityWrapper( final Map> playerPerms ) - { - this.target = playerPerms; - } + private final Map> target; - @Override - public void addPlayer( final int playerID, final EnumSet permissions ) - { - this.target.put( playerID, permissions ); - } + public PlayerSecurityWrapper(final Map> playerPerms) { + this.target = playerPerms; + } + + @Override + public void addPlayer(final int playerID, final EnumSet permissions) { + this.target.put(playerID, permissions); + } } diff --git a/src/main/java/appeng/helpers/Reflected.java b/src/main/java/appeng/helpers/Reflected.java index 7d12ac499..a69c6db1a 100644 --- a/src/main/java/appeng/helpers/Reflected.java +++ b/src/main/java/appeng/helpers/Reflected.java @@ -28,9 +28,8 @@ import java.lang.annotation.Target; /** * Marker interface to help identify invocation of reflection */ -@Retention( RetentionPolicy.SOURCE ) -@Target( { ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.TYPE, ElementType.METHOD } ) -public @interface Reflected -{ +@Retention(RetentionPolicy.SOURCE) +@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.TYPE, ElementType.METHOD}) +public @interface Reflected { } diff --git a/src/main/java/appeng/helpers/Splotch.java b/src/main/java/appeng/helpers/Splotch.java index cf5001976..8e4f42eb4 100644 --- a/src/main/java/appeng/helpers/Splotch.java +++ b/src/main/java/appeng/helpers/Splotch.java @@ -19,101 +19,82 @@ package appeng.helpers; +import appeng.api.util.AEColor; import io.netty.buffer.ByteBuf; - import net.minecraft.util.EnumFacing; import net.minecraft.util.math.Vec3d; -import appeng.api.util.AEColor; +public class Splotch { -public class Splotch -{ + private final EnumFacing side; + private final boolean lumen; + private final AEColor color; + private final int pos; - private final EnumFacing side; - private final boolean lumen; - private final AEColor color; - private final int pos; + public Splotch(final AEColor col, final boolean lit, final EnumFacing side, final Vec3d position) { + this.color = col; + this.lumen = lit; - public Splotch( final AEColor col, final boolean lit, final EnumFacing side, final Vec3d position ) - { - this.color = col; - this.lumen = lit; + final double x; + final double y; - final double x; - final double y; + if (side == EnumFacing.SOUTH || side == EnumFacing.NORTH) { + x = position.x; + y = position.y; + } else if (side == EnumFacing.UP || side == EnumFacing.DOWN) { + x = position.x; + y = position.z; + } else { + x = position.y; + y = position.z; + } - if( side == EnumFacing.SOUTH || side == EnumFacing.NORTH ) - { - x = position.x; - y = position.y; - } + final int a = (int) (x * 0xF); + final int b = (int) (y * 0xF); + this.pos = a | (b << 4); - else if( side == EnumFacing.UP || side == EnumFacing.DOWN ) - { - x = position.x; - y = position.z; - } + this.side = side; + } - else - { - x = position.y; - y = position.z; - } + public Splotch(final ByteBuf data) { - final int a = (int) ( x * 0xF ); - final int b = (int) ( y * 0xF ); - this.pos = a | ( b << 4 ); + this.pos = data.readByte(); + final int val = data.readByte(); - this.side = side; - } + this.side = EnumFacing.VALUES[val & 0x07]; + this.color = AEColor.values()[(val >> 3) & 0x0F]; + this.lumen = ((val >> 7) & 0x01) > 0; + } - public Splotch( final ByteBuf data ) - { + public void writeToStream(final ByteBuf stream) { + stream.writeByte(this.pos); + final int val = this.getSide().ordinal() | (this.getColor().ordinal() << 3) | (this.isLumen() ? 0x80 : 0x00); + stream.writeByte(val); + } - this.pos = data.readByte(); - final int val = data.readByte(); + public float x() { + return (this.pos & 0x0f) / 15.0f; + } - this.side = EnumFacing.VALUES[val & 0x07]; - this.color = AEColor.values()[( val >> 3 ) & 0x0F]; - this.lumen = ( ( val >> 7 ) & 0x01 ) > 0; - } + public float y() { + return ((this.pos >> 4) & 0x0f) / 15.0f; + } - public void writeToStream( final ByteBuf stream ) - { - stream.writeByte( this.pos ); - final int val = this.getSide().ordinal() | ( this.getColor().ordinal() << 3 ) | ( this.isLumen() ? 0x80 : 0x00 ); - stream.writeByte( val ); - } + public int getSeed() { + final int val = this.getSide().ordinal() | (this.getColor().ordinal() << 3) | (this.isLumen() ? 0x80 : 0x00); + return Math.abs(this.pos + val); + } - public float x() - { - return ( this.pos & 0x0f ) / 15.0f; - } + public EnumFacing getSide() { + return this.side; + } - public float y() - { - return ( ( this.pos >> 4 ) & 0x0f ) / 15.0f; - } + public AEColor getColor() { + return this.color; + } - public int getSeed() - { - final int val = this.getSide().ordinal() | ( this.getColor().ordinal() << 3 ) | ( this.isLumen() ? 0x80 : 0x00 ); - return Math.abs( this.pos + val ); - } - - public EnumFacing getSide() - { - return this.side; - } - - public AEColor getColor() - { - return this.color; - } - - public boolean isLumen() - { - return this.lumen; - } + public boolean isLumen() { + return this.lumen; + } } diff --git a/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java b/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java index 35edefea1..ece89e8ec 100644 --- a/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java +++ b/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java @@ -19,10 +19,6 @@ package appeng.helpers; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -48,300 +44,246 @@ import appeng.api.util.DimensionalCoord; import appeng.api.util.IConfigManager; import appeng.container.interfaces.IInventorySlotAware; import appeng.tile.networking.TileWireless; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; -public class WirelessTerminalGuiObject implements IPortableCell, IActionHost, IInventorySlotAware -{ +public class WirelessTerminalGuiObject implements IPortableCell, IActionHost, IInventorySlotAware { - private final ItemStack effectiveItem; - private final IWirelessTermHandler wth; - private final String encryptionKey; - private final EntityPlayer myPlayer; - private IGrid targetGrid; - private IStorageGrid sg; - private IMEMonitor itemStorage; - private IWirelessAccessPoint myWap; - private double sqRange = Double.MAX_VALUE; - private double myRange = Double.MAX_VALUE; - private final int inventorySlot; + private final ItemStack effectiveItem; + private final IWirelessTermHandler wth; + private final String encryptionKey; + private final EntityPlayer myPlayer; + private IGrid targetGrid; + private IStorageGrid sg; + private IMEMonitor itemStorage; + private IWirelessAccessPoint myWap; + private double sqRange = Double.MAX_VALUE; + private double myRange = Double.MAX_VALUE; + private final int inventorySlot; - public WirelessTerminalGuiObject( final IWirelessTermHandler wh, final ItemStack is, final EntityPlayer ep, final World w, final int x, final int y, final int z ) - { - this.encryptionKey = wh.getEncryptionKey( is ); - this.effectiveItem = is; - this.myPlayer = ep; - this.wth = wh; - this.inventorySlot = x; + public WirelessTerminalGuiObject(final IWirelessTermHandler wh, final ItemStack is, final EntityPlayer ep, final World w, final int x, final int y, final int z) { + this.encryptionKey = wh.getEncryptionKey(is); + this.effectiveItem = is; + this.myPlayer = ep; + this.wth = wh; + this.inventorySlot = x; - ILocatable obj = null; + ILocatable obj = null; - try - { - final long encKey = Long.parseLong( this.encryptionKey ); - obj = AEApi.instance().registries().locatable().getLocatableBy( encKey ); - } - catch( final NumberFormatException err ) - { - // :P - } + try { + final long encKey = Long.parseLong(this.encryptionKey); + obj = AEApi.instance().registries().locatable().getLocatableBy(encKey); + } catch (final NumberFormatException err) { + // :P + } - if( obj instanceof IActionHost ) - { - final IGridNode n = ( (IActionHost) obj ).getActionableNode(); - if( n != null ) - { - this.targetGrid = n.getGrid(); - if( this.targetGrid != null ) - { - this.sg = this.targetGrid.getCache( IStorageGrid.class ); - if( this.sg != null ) - { - this.itemStorage = this.sg.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - } - } - } - } - } + if (obj instanceof IActionHost) { + final IGridNode n = ((IActionHost) obj).getActionableNode(); + if (n != null) { + this.targetGrid = n.getGrid(); + if (this.targetGrid != null) { + this.sg = this.targetGrid.getCache(IStorageGrid.class); + if (this.sg != null) { + this.itemStorage = this.sg.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + } + } + } + } + } - public double getRange() - { - return this.myRange; - } + public double getRange() { + return this.myRange; + } - @Override - public > IMEMonitor getInventory( IStorageChannel channel ) - { - return this.sg.getInventory( channel ); - } + @Override + public > IMEMonitor getInventory(IStorageChannel channel) { + return this.sg.getInventory(channel); + } - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - if( this.itemStorage != null ) - { - this.itemStorage.addListener( l, verificationToken ); - } - } + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + if (this.itemStorage != null) { + this.itemStorage.addListener(l, verificationToken); + } + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - if( this.itemStorage != null ) - { - this.itemStorage.removeListener( l ); - } - } + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + if (this.itemStorage != null) { + this.itemStorage.removeListener(l); + } + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.getAvailableItems( out ); - } - return out; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + if (this.itemStorage != null) { + return this.itemStorage.getAvailableItems(out); + } + return out; + } - @Override - public IItemList getStorageList() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getStorageList(); - } - return null; - } + @Override + public IItemList getStorageList() { + if (this.itemStorage != null) { + return this.itemStorage.getStorageList(); + } + return null; + } - @Override - public AccessRestriction getAccess() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getAccess(); - } - return AccessRestriction.NO_ACCESS; - } + @Override + public AccessRestriction getAccess() { + if (this.itemStorage != null) { + return this.itemStorage.getAccess(); + } + return AccessRestriction.NO_ACCESS; + } - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.isPrioritized( input ); - } - return false; - } + @Override + public boolean isPrioritized(final IAEItemStack input) { + if (this.itemStorage != null) { + return this.itemStorage.isPrioritized(input); + } + return false; + } - @Override - public boolean canAccept( final IAEItemStack input ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.canAccept( input ); - } - return false; - } + @Override + public boolean canAccept(final IAEItemStack input) { + if (this.itemStorage != null) { + return this.itemStorage.canAccept(input); + } + return false; + } - @Override - public int getPriority() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getPriority(); - } - return 0; - } + @Override + public int getPriority() { + if (this.itemStorage != null) { + return this.itemStorage.getPriority(); + } + return 0; + } - @Override - public int getSlot() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getSlot(); - } - return 0; - } + @Override + public int getSlot() { + if (this.itemStorage != null) { + return this.itemStorage.getSlot(); + } + return 0; + } - @Override - public boolean validForPass( final int i ) - { - return this.itemStorage.validForPass( i ); - } + @Override + public boolean validForPass(final int i) { + return this.itemStorage.validForPass(i); + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final IActionSource src ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.injectItems( input, type, src ); - } - return input; - } + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable type, final IActionSource src) { + if (this.itemStorage != null) { + return this.itemStorage.injectItems(input, type, src); + } + return input; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final IActionSource src ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.extractItems( request, mode, src ); - } - return null; - } + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final IActionSource src) { + if (this.itemStorage != null) { + return this.itemStorage.extractItems(request, mode, src); + } + return null; + } - @Override - public IStorageChannel getChannel() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getChannel(); - } - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + if (this.itemStorage != null) { + return this.itemStorage.getChannel(); + } + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } - @Override - public double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier ) - { - if( this.wth != null && this.effectiveItem != null ) - { - if( mode == Actionable.SIMULATE ) - { - return this.wth.hasPower( this.myPlayer, amt, this.effectiveItem ) ? amt : 0; - } - return this.wth.usePower( this.myPlayer, amt, this.effectiveItem ) ? amt : 0; - } - return 0.0; - } + @Override + public double extractAEPower(final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier) { + if (this.wth != null && this.effectiveItem != null) { + if (mode == Actionable.SIMULATE) { + return this.wth.hasPower(this.myPlayer, amt, this.effectiveItem) ? amt : 0; + } + return this.wth.usePower(this.myPlayer, amt, this.effectiveItem) ? amt : 0; + } + return 0.0; + } - @Override - public ItemStack getItemStack() - { - return this.effectiveItem; - } + @Override + public ItemStack getItemStack() { + return this.effectiveItem; + } - @Override - public IConfigManager getConfigManager() - { - return this.wth.getConfigManager( this.effectiveItem ); - } + @Override + public IConfigManager getConfigManager() { + return this.wth.getConfigManager(this.effectiveItem); + } - @Override - public IGridNode getActionableNode() - { - this.rangeCheck(); - if( this.myWap != null ) - { - return this.myWap.getActionableNode(); - } - return null; - } + @Override + public IGridNode getActionableNode() { + this.rangeCheck(); + if (this.myWap != null) { + return this.myWap.getActionableNode(); + } + return null; + } - public boolean rangeCheck() - { - this.sqRange = this.myRange = Double.MAX_VALUE; + public boolean rangeCheck() { + this.sqRange = this.myRange = Double.MAX_VALUE; - if( this.targetGrid != null && this.itemStorage != null ) - { - if( this.myWap != null ) - { - if( this.myWap.getGrid() == this.targetGrid ) - { - if( this.testWap( this.myWap ) ) - { - return true; - } - } - return false; - } + if (this.targetGrid != null && this.itemStorage != null) { + if (this.myWap != null) { + if (this.myWap.getGrid() == this.targetGrid) { + return this.testWap(this.myWap); + } + return false; + } - final IMachineSet tw = this.targetGrid.getMachines( TileWireless.class ); + final IMachineSet tw = this.targetGrid.getMachines(TileWireless.class); - this.myWap = null; + this.myWap = null; - for( final IGridNode n : tw ) - { - final IWirelessAccessPoint wap = (IWirelessAccessPoint) n.getMachine(); - if( this.testWap( wap ) ) - { - this.myWap = wap; - } - } + for (final IGridNode n : tw) { + final IWirelessAccessPoint wap = (IWirelessAccessPoint) n.getMachine(); + if (this.testWap(wap)) { + this.myWap = wap; + } + } - return this.myWap != null; - } - return false; - } + return this.myWap != null; + } + return false; + } - private boolean testWap( final IWirelessAccessPoint wap ) - { - double rangeLimit = wap.getRange(); - rangeLimit *= rangeLimit; + private boolean testWap(final IWirelessAccessPoint wap) { + double rangeLimit = wap.getRange(); + rangeLimit *= rangeLimit; - final DimensionalCoord dc = wap.getLocation(); + final DimensionalCoord dc = wap.getLocation(); - if( dc.getWorld() == this.myPlayer.world ) - { - final double offX = dc.x - this.myPlayer.posX; - final double offY = dc.y - this.myPlayer.posY; - final double offZ = dc.z - this.myPlayer.posZ; + if (dc.getWorld() == this.myPlayer.world) { + final double offX = dc.x - this.myPlayer.posX; + final double offY = dc.y - this.myPlayer.posY; + final double offZ = dc.z - this.myPlayer.posZ; - final double r = offX * offX + offY * offY + offZ * offZ; - if( r < rangeLimit && this.sqRange > r ) - { - if( wap.isActive() ) - { - this.sqRange = r; - this.myRange = Math.sqrt( r ); - return true; - } - } - } - return false; - } + final double r = offX * offX + offY * offY + offZ * offZ; + if (r < rangeLimit && this.sqRange > r) { + if (wap.isActive()) { + this.sqRange = r; + this.myRange = Math.sqrt(r); + return true; + } + } + } + return false; + } - @Override - public int getInventorySlot() - { - return this.inventorySlot; - } + @Override + public int getInventorySlot() { + return this.inventorySlot; + } } diff --git a/src/main/java/appeng/hooks/AETrading.java b/src/main/java/appeng/hooks/AETrading.java index 20ba43120..81e33b043 100644 --- a/src/main/java/appeng/hooks/AETrading.java +++ b/src/main/java/appeng/hooks/AETrading.java @@ -21,79 +21,78 @@ package appeng.hooks; // TODO Villager Trading!??!?! -public class AETrading -{ +public class AETrading { - /* - * @Override - * public void manipulateTradesForVillager( EntityVillager villager, MerchantRecipeList recipeList, Random random ) - * { - * final IMaterials materials = AEApi.instance().definitions().materials(); - * this.addMerchant( recipeList, materials.silicon(), 1, random, 2 ); - * this.addMerchant( recipeList, materials.certusQuartzCrystal(), 2, random, 4 ); - * this.addMerchant( recipeList, materials.certusQuartzDust(), 1, random, 3 ); - * this.addTrade( recipeList, materials.certusQuartzDust(), materials.certusQuartzCrystal(), random, 2 ); - * } - * private void addMerchant( MerchantRecipeList list, IItemDefinition item, int emera, Random rand, int greed ) - * { - * for( ItemStack itemStack : item.maybeStack( 1 ).asSet() ) - * { - * // Sell - * ItemStack from = itemStack.copy(); - * ItemStack to = new ItemStack( Items.emerald ); - * int multiplier = ( Math.abs( rand.nextInt() ) % 6 ); - * final int emeraldCost = emera + ( Math.abs( rand.nextInt() ) % greed ) - multiplier; - * int mood = rand.nextInt() % 2; - * from.stackSize = multiplier + mood; - * to.stackSize = multiplier * emeraldCost - mood; - * if( to.stackSize < 0 ) - * { - * from.stackSize -= to.stackSize; - * to.stackSize -= to.stackSize; - * } - * this.addToList( list, from, to ); - * // Buy - * ItemStack reverseTo = from.copy(); - * ItemStack reverseFrom = to.copy(); - * reverseFrom.stackSize *= rand.nextFloat() * 3.0f + 1.0f; - * this.addToList( list, reverseFrom, reverseTo ); - * } - * } - * private void addTrade( MerchantRecipeList list, IItemDefinition inputDefinition, IItemDefinition - * outputDefinition, Random rand, int conversionVariance ) - * { - * final Optional maybeInputStack = inputDefinition.maybeStack( 1 ); - * final Optional maybeOutputStack = outputDefinition.maybeStack( 1 ); - * if( maybeInputStack.isPresent() && maybeOutputStack.isPresent() ) - * { - * // Sell - * ItemStack inputStack = maybeInputStack.get().copy(); - * ItemStack outputStack = maybeOutputStack.get().copy(); - * inputStack.stackSize = 1 + ( Math.abs( rand.nextInt() ) % ( 1 + conversionVariance ) ); - * outputStack.stackSize = 1; - * this.addToList( list, inputStack, outputStack ); - * } - * } - * private void addToList( MerchantRecipeList l, ItemStack a, ItemStack b ) - * { - * if( a.stackSize < 1 ) - * { - * a.stackSize = 1; - * } - * if( b.stackSize < 1 ) - * { - * b.stackSize = 1; - * } - * if( a.stackSize > a.getMaxStackSize() ) - * { - * a.stackSize = a.getMaxStackSize(); - * } - * if( b.stackSize > b.getMaxStackSize() ) - * { - * b.stackSize = b.getMaxStackSize(); - * } - * l.add( new MerchantRecipe( a, b ) ); - * } - */ + /* + * @Override + * public void manipulateTradesForVillager( EntityVillager villager, MerchantRecipeList recipeList, Random random ) + * { + * final IMaterials materials = AEApi.instance().definitions().materials(); + * this.addMerchant( recipeList, materials.silicon(), 1, random, 2 ); + * this.addMerchant( recipeList, materials.certusQuartzCrystal(), 2, random, 4 ); + * this.addMerchant( recipeList, materials.certusQuartzDust(), 1, random, 3 ); + * this.addTrade( recipeList, materials.certusQuartzDust(), materials.certusQuartzCrystal(), random, 2 ); + * } + * private void addMerchant( MerchantRecipeList list, IItemDefinition item, int emera, Random rand, int greed ) + * { + * for( ItemStack itemStack : item.maybeStack( 1 ).asSet() ) + * { + * // Sell + * ItemStack from = itemStack.copy(); + * ItemStack to = new ItemStack( Items.emerald ); + * int multiplier = ( Math.abs( rand.nextInt() ) % 6 ); + * final int emeraldCost = emera + ( Math.abs( rand.nextInt() ) % greed ) - multiplier; + * int mood = rand.nextInt() % 2; + * from.stackSize = multiplier + mood; + * to.stackSize = multiplier * emeraldCost - mood; + * if( to.stackSize < 0 ) + * { + * from.stackSize -= to.stackSize; + * to.stackSize -= to.stackSize; + * } + * this.addToList( list, from, to ); + * // Buy + * ItemStack reverseTo = from.copy(); + * ItemStack reverseFrom = to.copy(); + * reverseFrom.stackSize *= rand.nextFloat() * 3.0f + 1.0f; + * this.addToList( list, reverseFrom, reverseTo ); + * } + * } + * private void addTrade( MerchantRecipeList list, IItemDefinition inputDefinition, IItemDefinition + * outputDefinition, Random rand, int conversionVariance ) + * { + * final Optional maybeInputStack = inputDefinition.maybeStack( 1 ); + * final Optional maybeOutputStack = outputDefinition.maybeStack( 1 ); + * if( maybeInputStack.isPresent() && maybeOutputStack.isPresent() ) + * { + * // Sell + * ItemStack inputStack = maybeInputStack.get().copy(); + * ItemStack outputStack = maybeOutputStack.get().copy(); + * inputStack.stackSize = 1 + ( Math.abs( rand.nextInt() ) % ( 1 + conversionVariance ) ); + * outputStack.stackSize = 1; + * this.addToList( list, inputStack, outputStack ); + * } + * } + * private void addToList( MerchantRecipeList l, ItemStack a, ItemStack b ) + * { + * if( a.stackSize < 1 ) + * { + * a.stackSize = 1; + * } + * if( b.stackSize < 1 ) + * { + * b.stackSize = 1; + * } + * if( a.stackSize > a.getMaxStackSize() ) + * { + * a.stackSize = a.getMaxStackSize(); + * } + * if( b.stackSize > b.getMaxStackSize() ) + * { + * b.stackSize = b.getMaxStackSize(); + * } + * l.add( new MerchantRecipe( a, b ) ); + * } + */ } diff --git a/src/main/java/appeng/hooks/CompassManager.java b/src/main/java/appeng/hooks/CompassManager.java index 25379ed2f..df8609ef1 100644 --- a/src/main/java/appeng/hooks/CompassManager.java +++ b/src/main/java/appeng/hooks/CompassManager.java @@ -19,104 +19,88 @@ package appeng.hooks; -import java.util.HashMap; -import java.util.Iterator; - import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketCompassRequest; +import java.util.HashMap; +import java.util.Iterator; -public class CompassManager -{ - public static final CompassManager INSTANCE = new CompassManager(); - private final HashMap requests = new HashMap<>(); +public class CompassManager { - public void postResult( final long attunement, final int x, final int y, final int z, final CompassResult result ) - { - final CompassRequest r = new CompassRequest( attunement, x, y, z ); - this.requests.put( r, result ); - } + public static final CompassManager INSTANCE = new CompassManager(); + private final HashMap requests = new HashMap<>(); - public CompassResult getCompassDirection( final long attunement, final int x, final int y, final int z ) - { - final long now = System.currentTimeMillis(); + public void postResult(final long attunement, final int x, final int y, final int z, final CompassResult result) { + final CompassRequest r = new CompassRequest(attunement, x, y, z); + this.requests.put(r, result); + } - final Iterator i = this.requests.values().iterator(); - while( i.hasNext() ) - { - final CompassResult res = i.next(); - final long diff = now - res.getTime(); - if( diff > 20000 ) - { - i.remove(); - } - } + public CompassResult getCompassDirection(final long attunement, final int x, final int y, final int z) { + final long now = System.currentTimeMillis(); - final CompassRequest r = new CompassRequest( attunement, x, y, z ); - CompassResult res = this.requests.get( r ); + final Iterator i = this.requests.values().iterator(); + while (i.hasNext()) { + final CompassResult res = i.next(); + final long diff = now - res.getTime(); + if (diff > 20000) { + i.remove(); + } + } - if( res == null ) - { - res = new CompassResult( false, true, 0 ); - this.requests.put( r, res ); - this.requestUpdate( r ); - } - else if( now - res.getTime() > 1000 * 3 ) - { - if( !res.isRequested() ) - { - res.setRequested( true ); - this.requestUpdate( r ); - } - } + final CompassRequest r = new CompassRequest(attunement, x, y, z); + CompassResult res = this.requests.get(r); - return res; - } + if (res == null) { + res = new CompassResult(false, true, 0); + this.requests.put(r, res); + this.requestUpdate(r); + } else if (now - res.getTime() > 1000 * 3) { + if (!res.isRequested()) { + res.setRequested(true); + this.requestUpdate(r); + } + } - private void requestUpdate( final CompassRequest r ) - { - NetworkHandler.instance().sendToServer( new PacketCompassRequest( r.attunement, r.cx, r.cz, r.cdy ) ); - } + return res; + } - private static class CompassRequest - { + private void requestUpdate(final CompassRequest r) { + NetworkHandler.instance().sendToServer(new PacketCompassRequest(r.attunement, r.cx, r.cz, r.cdy)); + } - private final int hash; - private final long attunement; - private final int cx; - private final int cdy; - private final int cz; + private static class CompassRequest { - public CompassRequest( final long attunement, final int x, final int y, final int z ) - { - this.attunement = attunement; - this.cx = x >> 4; - this.cdy = y >> 5; - this.cz = z >> 4; - this.hash = ( (Integer) this.cx ).hashCode() ^ ( (Integer) this.cdy ).hashCode() ^ ( (Integer) this.cz ).hashCode() ^ ( (Long) attunement ) - .hashCode(); - } + private final int hash; + private final long attunement; + private final int cx; + private final int cdy; + private final int cz; - @Override - public int hashCode() - { - return this.hash; - } + public CompassRequest(final long attunement, final int x, final int y, final int z) { + this.attunement = attunement; + this.cx = x >> 4; + this.cdy = y >> 5; + this.cz = z >> 4; + this.hash = ((Integer) this.cx).hashCode() ^ ((Integer) this.cdy).hashCode() ^ ((Integer) this.cz).hashCode() ^ ((Long) attunement) + .hashCode(); + } - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final CompassRequest other = (CompassRequest) obj; - return this.attunement == other.attunement && this.cx == other.cx && this.cdy == other.cdy && this.cz == other.cz; - } - } + @Override + public int hashCode() { + return this.hash; + } + + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final CompassRequest other = (CompassRequest) obj; + return this.attunement == other.attunement && this.cx == other.cx && this.cdy == other.cdy && this.cz == other.cz; + } + } } diff --git a/src/main/java/appeng/hooks/CompassResult.java b/src/main/java/appeng/hooks/CompassResult.java index 53c0982cb..656523352 100644 --- a/src/main/java/appeng/hooks/CompassResult.java +++ b/src/main/java/appeng/hooks/CompassResult.java @@ -19,50 +19,42 @@ package appeng.hooks; -public class CompassResult -{ +public class CompassResult { - private final boolean hasResult; - private final boolean spin; - private final double rad; - private final long time; - private boolean requested = false; + private final boolean hasResult; + private final boolean spin; + private final double rad; + private final long time; + private boolean requested = false; - public CompassResult( final boolean hasResult, final boolean spin, final double rad ) - { - this.hasResult = hasResult; - this.spin = spin; - this.rad = rad; - this.time = System.currentTimeMillis(); - } + public CompassResult(final boolean hasResult, final boolean spin, final double rad) { + this.hasResult = hasResult; + this.spin = spin; + this.rad = rad; + this.time = System.currentTimeMillis(); + } - public boolean isValidResult() - { - return this.hasResult; - } + public boolean isValidResult() { + return this.hasResult; + } - public boolean isSpin() - { - return this.spin; - } + public boolean isSpin() { + return this.spin; + } - public double getRad() - { - return this.rad; - } + public double getRad() { + return this.rad; + } - boolean isRequested() - { - return this.requested; - } + boolean isRequested() { + return this.requested; + } - void setRequested( final boolean requested ) - { - this.requested = requested; - } + void setRequested(final boolean requested) { + this.requested = requested; + } - long getTime() - { - return this.time; - } + long getTime() { + return this.time; + } } diff --git a/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java b/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java index 75031b828..9f78b5912 100644 --- a/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java +++ b/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java @@ -19,6 +19,7 @@ package appeng.hooks; +import appeng.entity.EntityTinyTNTPrimed; import net.minecraft.block.BlockDispenser; import net.minecraft.dispenser.BehaviorDefaultDispenseItem; import net.minecraft.dispenser.IBlockSource; @@ -26,23 +27,19 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -import appeng.entity.EntityTinyTNTPrimed; +public final class DispenserBehaviorTinyTNT extends BehaviorDefaultDispenseItem { -public final class DispenserBehaviorTinyTNT extends BehaviorDefaultDispenseItem -{ - - @Override - protected ItemStack dispenseStack( final IBlockSource dispenser, final ItemStack dispensedItem ) - { - final EnumFacing enumfacing = dispenser.getBlockState().getValue( BlockDispenser.FACING ); - final World world = dispenser.getWorld(); - final int i = dispenser.getBlockPos().getX() + enumfacing.getFrontOffsetX(); - final int j = dispenser.getBlockPos().getY() + enumfacing.getFrontOffsetY(); - final int k = dispenser.getBlockPos().getZ() + enumfacing.getFrontOffsetZ(); - final EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed( world, i + 0.5F, j + 0.5F, k + 0.5F, null ); - world.spawnEntity( primedTinyTNTEntity ); - dispensedItem.setCount( dispensedItem.getCount() - 1 ); - return dispensedItem; - } + @Override + protected ItemStack dispenseStack(final IBlockSource dispenser, final ItemStack dispensedItem) { + final EnumFacing enumfacing = dispenser.getBlockState().getValue(BlockDispenser.FACING); + final World world = dispenser.getWorld(); + final int i = dispenser.getBlockPos().getX() + enumfacing.getFrontOffsetX(); + final int j = dispenser.getBlockPos().getY() + enumfacing.getFrontOffsetY(); + final int k = dispenser.getBlockPos().getZ() + enumfacing.getFrontOffsetZ(); + final EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed(world, i + 0.5F, j + 0.5F, k + 0.5F, null); + world.spawnEntity(primedTinyTNTEntity); + dispensedItem.setCount(dispensedItem.getCount() - 1); + return dispensedItem; + } } diff --git a/src/main/java/appeng/hooks/DispenserBlockTool.java b/src/main/java/appeng/hooks/DispenserBlockTool.java index 65db383bf..aa4ea77d2 100644 --- a/src/main/java/appeng/hooks/DispenserBlockTool.java +++ b/src/main/java/appeng/hooks/DispenserBlockTool.java @@ -19,6 +19,7 @@ package appeng.hooks; +import appeng.util.Platform; import net.minecraft.block.BlockDispenser; import net.minecraft.dispenser.BehaviorDefaultDispenseItem; import net.minecraft.dispenser.IBlockSource; @@ -29,28 +30,22 @@ import net.minecraft.util.EnumHand; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -import appeng.util.Platform; +public final class DispenserBlockTool extends BehaviorDefaultDispenseItem { -public final class DispenserBlockTool extends BehaviorDefaultDispenseItem -{ + @Override + protected ItemStack dispenseStack(final IBlockSource dispenser, final ItemStack dispensedItem) { + final Item i = dispensedItem.getItem(); + if (i instanceof IBlockTool) { + final EnumFacing enumfacing = dispenser.getBlockState().getValue(BlockDispenser.FACING); + final IBlockTool tm = (IBlockTool) i; - @Override - protected ItemStack dispenseStack( final IBlockSource dispenser, final ItemStack dispensedItem ) - { - final Item i = dispensedItem.getItem(); - if( i instanceof IBlockTool ) - { - final EnumFacing enumfacing = dispenser.getBlockState().getValue( BlockDispenser.FACING ); - final IBlockTool tm = (IBlockTool) i; - - final World w = dispenser.getWorld(); - if( w instanceof WorldServer ) - { - tm.onItemUse( dispensedItem, Platform.getPlayer( (WorldServer) w ), w, dispenser.getBlockPos().offset( enumfacing ), EnumHand.MAIN_HAND, - enumfacing, 0.5f, 0.5f, 0.5f ); - } - } - return dispensedItem; - } + final World w = dispenser.getWorld(); + if (w instanceof WorldServer) { + tm.onItemUse(dispensedItem, Platform.getPlayer((WorldServer) w), w, dispenser.getBlockPos().offset(enumfacing), EnumHand.MAIN_HAND, + enumfacing, 0.5f, 0.5f, 0.5f); + } + } + return dispensedItem; + } } diff --git a/src/main/java/appeng/hooks/DispenserMatterCannon.java b/src/main/java/appeng/hooks/DispenserMatterCannon.java index 1eae245dc..adb2aa35f 100644 --- a/src/main/java/appeng/hooks/DispenserMatterCannon.java +++ b/src/main/java/appeng/hooks/DispenserMatterCannon.java @@ -19,6 +19,9 @@ package appeng.hooks; +import appeng.api.util.AEPartLocation; +import appeng.items.tools.powered.ToolMatterCannon; +import appeng.util.Platform; import net.minecraft.block.BlockDispenser; import net.minecraft.dispenser.BehaviorDefaultDispenseItem; import net.minecraft.dispenser.IBlockSource; @@ -29,45 +32,35 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -import appeng.api.util.AEPartLocation; -import appeng.items.tools.powered.ToolMatterCannon; -import appeng.util.Platform; +public final class DispenserMatterCannon extends BehaviorDefaultDispenseItem { -public final class DispenserMatterCannon extends BehaviorDefaultDispenseItem -{ + @Override + protected ItemStack dispenseStack(final IBlockSource dispenser, ItemStack dispensedItem) { + final Item i = dispensedItem.getItem(); + if (i instanceof ToolMatterCannon) { + final EnumFacing enumfacing = dispenser.getBlockState().getValue(BlockDispenser.FACING); + AEPartLocation dir = AEPartLocation.INTERNAL; + for (final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS) { + if (enumfacing.getFrontOffsetX() == d.xOffset && enumfacing.getFrontOffsetY() == d.yOffset && enumfacing.getFrontOffsetZ() == d.zOffset) { + dir = d; + } + } - @Override - protected ItemStack dispenseStack( final IBlockSource dispenser, ItemStack dispensedItem ) - { - final Item i = dispensedItem.getItem(); - if( i instanceof ToolMatterCannon ) - { - final EnumFacing enumfacing = dispenser.getBlockState().getValue( BlockDispenser.FACING ); - AEPartLocation dir = AEPartLocation.INTERNAL; - for( final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS ) - { - if( enumfacing.getFrontOffsetX() == d.xOffset && enumfacing.getFrontOffsetY() == d.yOffset && enumfacing.getFrontOffsetZ() == d.zOffset ) - { - dir = d; - } - } + final ToolMatterCannon tm = (ToolMatterCannon) i; - final ToolMatterCannon tm = (ToolMatterCannon) i; + final World w = dispenser.getWorld(); + if (w instanceof WorldServer) { + final EntityPlayer p = Platform.getPlayer((WorldServer) w); + Platform.configurePlayer(p, dir, dispenser.getBlockTileEntity()); - final World w = dispenser.getWorld(); - if( w instanceof WorldServer ) - { - final EntityPlayer p = Platform.getPlayer( (WorldServer) w ); - Platform.configurePlayer( p, dir, dispenser.getBlockTileEntity() ); + p.posX += dir.xOffset; + p.posY += dir.yOffset; + p.posZ += dir.zOffset; - p.posX += dir.xOffset; - p.posY += dir.yOffset; - p.posZ += dir.zOffset; - - dispensedItem = tm.onItemRightClick( w, p, null ).getResult(); - } - } - return dispensedItem; - } + dispensedItem = tm.onItemRightClick(w, p, null).getResult(); + } + } + return dispensedItem; + } } diff --git a/src/main/java/appeng/hooks/IBlockTool.java b/src/main/java/appeng/hooks/IBlockTool.java index f002018fc..0d1c7e91f 100644 --- a/src/main/java/appeng/hooks/IBlockTool.java +++ b/src/main/java/appeng/hooks/IBlockTool.java @@ -28,11 +28,10 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -public interface IBlockTool -{ - // Workaround for dispenser logic. - EnumActionResult onItemUse( ItemStack is, EntityPlayer p, World w, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ ); +public interface IBlockTool { + // Workaround for dispenser logic. + EnumActionResult onItemUse(ItemStack is, EntityPlayer p, World w, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ); - EnumActionResult onItemUse( EntityPlayer p, World w, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ ); + EnumActionResult onItemUse(EntityPlayer p, World w, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ); } diff --git a/src/main/java/appeng/hooks/TickHandler.java b/src/main/java/appeng/hooks/TickHandler.java index 1da6a733a..788e8906f 100644 --- a/src/main/java/appeng/hooks/TickHandler.java +++ b/src/main/java/appeng/hooks/TickHandler.java @@ -19,30 +19,6 @@ package appeng.hooks; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Queue; -import java.util.Set; -import java.util.WeakHashMap; -import java.util.concurrent.TimeUnit; - -import com.google.common.base.Stopwatch; -import com.google.common.collect.LinkedListMultimap; -import com.google.common.collect.Multimap; - -import net.minecraft.world.World; -import net.minecraftforge.event.world.WorldEvent; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.TickEvent; -import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; -import net.minecraftforge.fml.common.gameevent.TickEvent.Type; -import net.minecraftforge.fml.common.gameevent.TickEvent.WorldTickEvent; - import appeng.api.AEApi; import appeng.api.networking.IGridNode; import appeng.api.parts.CableRenderMode; @@ -56,291 +32,253 @@ import appeng.me.Grid; import appeng.tile.AEBaseTile; import appeng.util.IWorldCallable; import appeng.util.Platform; +import com.google.common.base.Stopwatch; +import com.google.common.collect.LinkedListMultimap; +import com.google.common.collect.Multimap; +import net.minecraft.world.World; +import net.minecraftforge.event.world.WorldEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; +import net.minecraftforge.fml.common.gameevent.TickEvent.Type; +import net.minecraftforge.fml.common.gameevent.TickEvent.WorldTickEvent; + +import java.util.*; +import java.util.concurrent.TimeUnit; -public class TickHandler -{ +public class TickHandler { - public static final TickHandler INSTANCE = new TickHandler(); - private final Queue> serverQueue = new ArrayDeque<>(); - private final Multimap craftingJobs = LinkedListMultimap.create(); - private final WeakHashMap>> callQueue = new WeakHashMap<>(); - private final HandlerRep server = new HandlerRep(); - private final HandlerRep client = new HandlerRep(); - private final HashMap cliPlayerColors = new HashMap<>(); - private final HashMap srvPlayerColors = new HashMap<>(); - private CableRenderMode crm = CableRenderMode.STANDARD; + public static final TickHandler INSTANCE = new TickHandler(); + private final Queue> serverQueue = new ArrayDeque<>(); + private final Multimap craftingJobs = LinkedListMultimap.create(); + private final WeakHashMap>> callQueue = new WeakHashMap<>(); + private final HandlerRep server = new HandlerRep(); + private final HandlerRep client = new HandlerRep(); + private final HashMap cliPlayerColors = new HashMap<>(); + private final HashMap srvPlayerColors = new HashMap<>(); + private CableRenderMode crm = CableRenderMode.STANDARD; - public HashMap getPlayerColors() - { - if( Platform.isServer() ) - { - return this.srvPlayerColors; - } - return this.cliPlayerColors; - } + public HashMap getPlayerColors() { + if (Platform.isServer()) { + return this.srvPlayerColors; + } + return this.cliPlayerColors; + } - public void addCallable( final World w, final IWorldCallable c ) - { - if( w == null ) - { - this.serverQueue.add( c ); - } - else - { - Queue> queue = this.callQueue.get( w ); + public void addCallable(final World w, final IWorldCallable c) { + if (w == null) { + this.serverQueue.add(c); + } else { + Queue> queue = this.callQueue.get(w); - if( queue == null ) - { - queue = new ArrayDeque<>(); - this.callQueue.put( w, queue ); - } + if (queue == null) { + queue = new ArrayDeque<>(); + this.callQueue.put(w, queue); + } - queue.add( c ); - } - } + queue.add(c); + } + } - public void addInit( final AEBaseTile tile ) - { - if( Platform.isServer() ) // for no there is no reason to care about this on the client... - { - this.getRepo().tiles.add( tile ); - } - } + public void addInit(final AEBaseTile tile) { + if (Platform.isServer()) // for no there is no reason to care about this on the client... + { + this.getRepo().tiles.add(tile); + } + } - private HandlerRep getRepo() - { - if( Platform.isServer() ) - { - return this.server; - } - return this.client; - } + private HandlerRep getRepo() { + if (Platform.isServer()) { + return this.server; + } + return this.client; + } - public void addNetwork( final Grid grid ) - { - if( Platform.isServer() ) // for no there is no reason to care about this on the client... - { - this.getRepo().addNetwork( grid ); - } - } + public void addNetwork(final Grid grid) { + if (Platform.isServer()) // for no there is no reason to care about this on the client... + { + this.getRepo().addNetwork(grid); + } + } - public void removeNetwork( final Grid grid ) - { - if( Platform.isServer() ) // for no there is no reason to care about this on the client... - { - this.getRepo().removeNetwork( grid ); - } - } + public void removeNetwork(final Grid grid) { + if (Platform.isServer()) // for no there is no reason to care about this on the client... + { + this.getRepo().removeNetwork(grid); + } + } - public Iterable getGridList() - { - return this.getRepo().networks; - } + public Iterable getGridList() { + return this.getRepo().networks; + } - public void shutdown() - { - this.getRepo().clear(); - } + public void shutdown() { + this.getRepo().clear(); + } - @SubscribeEvent - public void unloadWorld( final WorldEvent.Unload ev ) - { - if( Platform.isServer() ) // for no there is no reason to care about this on the client... - { - final List toDestroy = new ArrayList<>(); + @SubscribeEvent + public void unloadWorld(final WorldEvent.Unload ev) { + if (Platform.isServer()) // for no there is no reason to care about this on the client... + { + final List toDestroy = new ArrayList<>(); - this.getRepo().updateNetworks(); - for( final Grid g : this.getRepo().networks ) - { - for( final IGridNode n : g.getNodes() ) - { - if( n.getWorld() == ev.getWorld() ) - { - toDestroy.add( n ); - } - } - } + this.getRepo().updateNetworks(); + for (final Grid g : this.getRepo().networks) { + for (final IGridNode n : g.getNodes()) { + if (n.getWorld() == ev.getWorld()) { + toDestroy.add(n); + } + } + } - for( final IGridNode n : toDestroy ) - { - n.destroy(); - } - } - } + for (final IGridNode n : toDestroy) { + n.destroy(); + } + } + } - @SubscribeEvent - public void onTick( final TickEvent ev ) - { + @SubscribeEvent + public void onTick(final TickEvent ev) { - if( ev.type == Type.CLIENT && ev.phase == Phase.START ) - { - this.tickColors( this.cliPlayerColors ); - final CableRenderMode currentMode = AEApi.instance().partHelper().getCableRenderMode(); - if( currentMode != this.crm ) - { - this.crm = currentMode; - AppEng.proxy.triggerUpdates(); - } - } + if (ev.type == Type.CLIENT && ev.phase == Phase.START) { + this.tickColors(this.cliPlayerColors); + final CableRenderMode currentMode = AEApi.instance().partHelper().getCableRenderMode(); + if (currentMode != this.crm) { + this.crm = currentMode; + AppEng.proxy.triggerUpdates(); + } + } - if( ev.type == Type.WORLD && ev.phase == Phase.END ) - { - final WorldTickEvent wte = (WorldTickEvent) ev; - synchronized ( this.craftingJobs ) - { - final Collection jobSet = this.craftingJobs.get( wte.world ); - if( !jobSet.isEmpty() ) - { - final int jobSize = jobSet.size(); - final int microSecondsPerTick = AEConfig.instance().getCraftingCalculationTimePerTick() * 1000; - final int simTime = Math.max( 1, microSecondsPerTick / jobSize ); + if (ev.type == Type.WORLD && ev.phase == Phase.END) { + final WorldTickEvent wte = (WorldTickEvent) ev; + synchronized (this.craftingJobs) { + final Collection jobSet = this.craftingJobs.get(wte.world); + if (!jobSet.isEmpty()) { + final int jobSize = jobSet.size(); + final int microSecondsPerTick = AEConfig.instance().getCraftingCalculationTimePerTick() * 1000; + final int simTime = Math.max(1, microSecondsPerTick / jobSize); - jobSet.removeIf( cj -> !cj.simulateFor( simTime ) ); - } - } - } + jobSet.removeIf(cj -> !cj.simulateFor(simTime)); + } + } + } - // for no there is no reason to care about this on the client... - else if( ev.type == Type.SERVER && ev.phase == Phase.END ) - { - this.tickColors( this.srvPlayerColors ); - // ready tiles. - final HandlerRep repo = this.getRepo(); - while ( !repo.tiles.isEmpty() ) - { - final AEBaseTile bt = repo.tiles.poll(); - if( !bt.isInvalid() ) - { - bt.onReady(); - } - } + // for no there is no reason to care about this on the client... + else if (ev.type == Type.SERVER && ev.phase == Phase.END) { + this.tickColors(this.srvPlayerColors); + // ready tiles. + final HandlerRep repo = this.getRepo(); + while (!repo.tiles.isEmpty()) { + final AEBaseTile bt = repo.tiles.poll(); + if (!bt.isInvalid()) { + bt.onReady(); + } + } - // tick networks. - this.getRepo().updateNetworks(); - for( final Grid g : this.getRepo().networks ) - { - g.update(); - } + // tick networks. + this.getRepo().updateNetworks(); + for (final Grid g : this.getRepo().networks) { + g.update(); + } - // cross world queue. - this.processQueue( this.serverQueue, null ); - } + // cross world queue. + this.processQueue(this.serverQueue, null); + } - // world synced queue(s) - if( ev.type == Type.WORLD && ev.phase == Phase.START ) - { - final World world = ( (WorldTickEvent) ev ).world; - final Queue> queue = this.callQueue.get( world ); - this.processQueue( queue, world ); - } - } + // world synced queue(s) + if (ev.type == Type.WORLD && ev.phase == Phase.START) { + final World world = ((WorldTickEvent) ev).world; + final Queue> queue = this.callQueue.get(world); + this.processQueue(queue, world); + } + } - private void tickColors( final HashMap playerSet ) - { - final Iterator i = playerSet.values().iterator(); - while ( i.hasNext() ) - { - final PlayerColor pc = i.next(); - if( pc.ticksLeft <= 0 ) - { - i.remove(); - } - pc.ticksLeft--; - } - } + private void tickColors(final HashMap playerSet) { + final Iterator i = playerSet.values().iterator(); + while (i.hasNext()) { + final PlayerColor pc = i.next(); + if (pc.ticksLeft <= 0) { + i.remove(); + } + pc.ticksLeft--; + } + } - private void processQueue( final Queue> queue, final World world ) - { - if( queue == null ) - { - return; - } + private void processQueue(final Queue> queue, final World world) { + if (queue == null) { + return; + } - final Stopwatch sw = Stopwatch.createStarted(); + final Stopwatch sw = Stopwatch.createStarted(); - IWorldCallable c = null; - while ( ( c = queue.poll() ) != null ) - { - try - { - c.call( world ); + IWorldCallable c = null; + while ((c = queue.poll()) != null) { + try { + c.call(world); - if( sw.elapsed( TimeUnit.MILLISECONDS ) > 50 ) - { - break; - } - } - catch( final Exception e ) - { - AELog.debug( e ); - } - } - } + if (sw.elapsed(TimeUnit.MILLISECONDS) > 50) { + break; + } + } catch (final Exception e) { + AELog.debug(e); + } + } + } - public void registerCraftingSimulation( final World world, final CraftingJob craftingJob ) - { - synchronized ( this.craftingJobs ) - { - this.craftingJobs.put( world, craftingJob ); - } - } + public void registerCraftingSimulation(final World world, final CraftingJob craftingJob) { + synchronized (this.craftingJobs) { + this.craftingJobs.put(world, craftingJob); + } + } - private static class HandlerRep - { + private static class HandlerRep { - private Queue tiles = new ArrayDeque<>(); - private Set networks = new HashSet<>(); - private Set toAdd = new HashSet<>(); - private Set toRemove = new HashSet<>(); + private Queue tiles = new ArrayDeque<>(); + private Set networks = new HashSet<>(); + private Set toAdd = new HashSet<>(); + private Set toRemove = new HashSet<>(); - private void clear() - { - this.tiles = new ArrayDeque<>(); - this.networks = new HashSet<>(); - this.toAdd = new HashSet<>(); - this.toRemove = new HashSet<>(); - } + private void clear() { + this.tiles = new ArrayDeque<>(); + this.networks = new HashSet<>(); + this.toAdd = new HashSet<>(); + this.toRemove = new HashSet<>(); + } - private synchronized void addNetwork( Grid g ) - { - this.toAdd.add( g ); - this.toRemove.remove( g ); - } + private synchronized void addNetwork(Grid g) { + this.toAdd.add(g); + this.toRemove.remove(g); + } - private synchronized void removeNetwork( Grid g ) - { - this.toRemove.add( g ); - this.toAdd.remove( g ); - } + private synchronized void removeNetwork(Grid g) { + this.toRemove.add(g); + this.toAdd.remove(g); + } - private synchronized void updateNetworks() - { - this.networks.removeAll( this.toRemove ); - this.toRemove.clear(); + private synchronized void updateNetworks() { + this.networks.removeAll(this.toRemove); + this.toRemove.clear(); - this.networks.addAll( this.toAdd ); - this.toAdd.clear(); - } - } + this.networks.addAll(this.toAdd); + this.toAdd.clear(); + } + } - public static class PlayerColor - { + public static class PlayerColor { - public final AEColor myColor; - private final int myEntity; - private int ticksLeft; + public final AEColor myColor; + private final int myEntity; + private int ticksLeft; - public PlayerColor( final int id, final AEColor col, final int ticks ) - { - this.myEntity = id; - this.myColor = col; - this.ticksLeft = ticks; - } + public PlayerColor(final int id, final AEColor col, final int ticks) { + this.myEntity = id; + this.myColor = col; + this.ticksLeft = ticks; + } - public PacketPaintedEntity getPacket() - { - return new PacketPaintedEntity( this.myEntity, this.myColor, this.ticksLeft ); - } - } + public PacketPaintedEntity getPacket() { + return new PacketPaintedEntity(this.myEntity, this.myColor, this.ticksLeft); + } + } } diff --git a/src/main/java/appeng/integration/IIntegrationModule.java b/src/main/java/appeng/integration/IIntegrationModule.java index 2d4be8967..4fd7d7ff1 100644 --- a/src/main/java/appeng/integration/IIntegrationModule.java +++ b/src/main/java/appeng/integration/IIntegrationModule.java @@ -19,32 +19,25 @@ package appeng.integration; -public interface IIntegrationModule -{ +public interface IIntegrationModule { - default boolean isEnabled() - { - return true; - } + default boolean isEnabled() { + return true; + } - default void preInit() throws Throwable - { - } + default void preInit() throws Throwable { + } - default void init() throws Throwable - { - } + default void init() throws Throwable { + } - default void postInit() - { - } + default void postInit() { + } - class Stub implements IIntegrationModule - { - @Override - public boolean isEnabled() - { - return false; - } - } + class Stub implements IIntegrationModule { + @Override + public boolean isEnabled() { + return false; + } + } } diff --git a/src/main/java/appeng/integration/IntegrationHelper.java b/src/main/java/appeng/integration/IntegrationHelper.java index 783bbd48a..88f85b6db 100644 --- a/src/main/java/appeng/integration/IntegrationHelper.java +++ b/src/main/java/appeng/integration/IntegrationHelper.java @@ -19,11 +19,9 @@ package appeng.integration; -public class IntegrationHelper -{ +public class IntegrationHelper { - public static void testClassExistence( final Object o, final Class clz ) - { - clz.isInstance( o ); - } + public static void testClassExistence(final Object o, final Class clz) { + clz.isInstance(o); + } } diff --git a/src/main/java/appeng/integration/IntegrationNode.java b/src/main/java/appeng/integration/IntegrationNode.java index 271936202..03412ab74 100644 --- a/src/main/java/appeng/integration/IntegrationNode.java +++ b/src/main/java/appeng/integration/IntegrationNode.java @@ -19,142 +19,116 @@ package appeng.integration; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.ModAPIManager; - import appeng.api.exceptions.ModNotInstalledException; import appeng.core.AEConfig; import appeng.core.AELog; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.common.ModAPIManager; -final class IntegrationNode -{ +final class IntegrationNode { - private final String displayName; - private final String modID; - private final IntegrationType type; - private IntegrationStage state = IntegrationStage.PRE_INIT; - private Throwable exception = null; - private IIntegrationModule mod = null; + private final String displayName; + private final String modID; + private final IntegrationType type; + private IntegrationStage state = IntegrationStage.PRE_INIT; + private Throwable exception = null; + private IIntegrationModule mod = null; - IntegrationNode( final String displayName, final String modID, final IntegrationType type ) - { - this.displayName = displayName; - this.type = type; - this.modID = modID; - } + IntegrationNode(final String displayName, final String modID, final IntegrationType type) { + this.displayName = displayName; + this.type = type; + this.modID = modID; + } - @Override - public String toString() - { - return this.getType().name() + ':' + this.getState().name(); - } + @Override + public String toString() { + return this.getType().name() + ':' + this.getState().name(); + } - boolean isActive() - { - if( this.getState() == IntegrationStage.PRE_INIT ) - { - this.call( IntegrationStage.PRE_INIT ); - } + boolean isActive() { + if (this.getState() == IntegrationStage.PRE_INIT) { + this.call(IntegrationStage.PRE_INIT); + } - return this.getState() != IntegrationStage.FAILED; - } + return this.getState() != IntegrationStage.FAILED; + } - void call( final IntegrationStage stage ) - { - if( this.getState() != IntegrationStage.FAILED ) - { - if( this.getState().ordinal() > stage.ordinal() ) - { - return; - } + void call(final IntegrationStage stage) { + if (this.getState() != IntegrationStage.FAILED) { + if (this.getState().ordinal() > stage.ordinal()) { + return; + } - try - { - switch( stage ) - { - case PRE_INIT: - final ModAPIManager apiManager = ModAPIManager.INSTANCE; - boolean enabled = this.modID == null || Loader.isModLoaded( this.modID ) || apiManager.hasAPI( this.modID ); + try { + switch (stage) { + case PRE_INIT: + final ModAPIManager apiManager = ModAPIManager.INSTANCE; + boolean enabled = this.modID == null || Loader.isModLoaded(this.modID) || apiManager.hasAPI(this.modID); - AEConfig.instance() - .addCustomCategoryComment( "ModIntegration", - "Valid Values are 'AUTO', 'ON', or 'OFF' - defaults to 'AUTO' ; Suggested that you leave this alone unless your experiencing an issue, or wish to disable the integration for a reason." ); - final String mode = AEConfig.instance().get( "ModIntegration", this.displayName.replace( " ", "" ), "AUTO" ).getString(); + AEConfig.instance() + .addCustomCategoryComment("ModIntegration", + "Valid Values are 'AUTO', 'ON', or 'OFF' - defaults to 'AUTO' ; Suggested that you leave this alone unless your experiencing an issue, or wish to disable the integration for a reason."); + final String mode = AEConfig.instance().get("ModIntegration", this.displayName.replace(" ", ""), "AUTO").getString(); - if( mode.toUpperCase().equals( "ON" ) ) - { - enabled = true; - } - if( mode.toUpperCase().equals( "OFF" ) ) - { - enabled = false; - } + if (mode.equalsIgnoreCase("ON")) { + enabled = true; + } + if (mode.equalsIgnoreCase("OFF")) { + enabled = false; + } - if( enabled ) - { - this.mod = this.type.createInstance(); - } - else - { - throw new ModNotInstalledException( this.modID ); - } + if (enabled) { + this.mod = this.type.createInstance(); + } else { + throw new ModNotInstalledException(this.modID); + } - this.mod.preInit(); - this.setState( IntegrationStage.INIT ); + this.mod.preInit(); + this.setState(IntegrationStage.INIT); - break; - case INIT: - this.mod.init(); - this.setState( IntegrationStage.POST_INIT ); + break; + case INIT: + this.mod.init(); + this.setState(IntegrationStage.POST_INIT); - break; - case POST_INIT: - this.mod.postInit(); - this.setState( IntegrationStage.READY ); + break; + case POST_INIT: + this.mod.postInit(); + this.setState(IntegrationStage.READY); - break; - case FAILED: - default: - break; - } - } - catch( final Throwable t ) - { - this.exception = t; - this.setState( IntegrationStage.FAILED ); - } - } + break; + case FAILED: + default: + break; + } + } catch (final Throwable t) { + this.exception = t; + this.setState(IntegrationStage.FAILED); + } + } - if( stage == IntegrationStage.POST_INIT ) - { - if( this.getState() == IntegrationStage.FAILED ) - { - AELog.info( this.displayName + " - Integration Disabled" ); - if( !( this.exception instanceof ModNotInstalledException ) ) - { - AELog.integration( this.exception ); - } - } - else - { - AELog.info( this.displayName + " - Integration Enable" ); - } - } - } + if (stage == IntegrationStage.POST_INIT) { + if (this.getState() == IntegrationStage.FAILED) { + AELog.info(this.displayName + " - Integration Disabled"); + if (!(this.exception instanceof ModNotInstalledException)) { + AELog.integration(this.exception); + } + } else { + AELog.info(this.displayName + " - Integration Enable"); + } + } + } - IntegrationType getType() - { - return this.type; - } + IntegrationType getType() { + return this.type; + } - IntegrationStage getState() - { - return this.state; - } + IntegrationStage getState() { + return this.state; + } - private void setState( final IntegrationStage state ) - { - this.state = state; - } + private void setState(final IntegrationStage state) { + this.state = state; + } } diff --git a/src/main/java/appeng/integration/IntegrationRegistry.java b/src/main/java/appeng/integration/IntegrationRegistry.java index d4cfbf453..b60dcac50 100644 --- a/src/main/java/appeng/integration/IntegrationRegistry.java +++ b/src/main/java/appeng/integration/IntegrationRegistry.java @@ -19,86 +19,70 @@ package appeng.integration; -import java.util.ArrayList; -import java.util.Collection; - import net.minecraftforge.fml.relauncher.FMLLaunchHandler; import net.minecraftforge.fml.relauncher.Side; +import java.util.ArrayList; +import java.util.Collection; -public enum IntegrationRegistry -{ - INSTANCE; - private final Collection modules = new ArrayList<>(); +public enum IntegrationRegistry { + INSTANCE; - public void add( final IntegrationType type ) - { - if( type.side == IntegrationSide.CLIENT && FMLLaunchHandler.side() == Side.SERVER ) - { - return; - } + private final Collection modules = new ArrayList<>(); - if( type.side == IntegrationSide.SERVER && FMLLaunchHandler.side() == Side.CLIENT ) - { - return; - } + public void add(final IntegrationType type) { + if (type.side == IntegrationSide.CLIENT && FMLLaunchHandler.side() == Side.SERVER) { + return; + } - this.modules.add( new IntegrationNode( type.dspName, type.modID, type ) ); - } + if (type.side == IntegrationSide.SERVER && FMLLaunchHandler.side() == Side.CLIENT) { + return; + } - public void preInit() - { - for( final IntegrationNode node : this.modules ) - { - node.call( IntegrationStage.PRE_INIT ); - } - } + this.modules.add(new IntegrationNode(type.dspName, type.modID, type)); + } - public void init() - { - for( final IntegrationNode node : this.modules ) - { - node.call( IntegrationStage.INIT ); - } - } + public void preInit() { + for (final IntegrationNode node : this.modules) { + node.call(IntegrationStage.PRE_INIT); + } + } - public void postInit() - { - for( final IntegrationNode node : this.modules ) - { - node.call( IntegrationStage.POST_INIT ); - } - } + public void init() { + for (final IntegrationNode node : this.modules) { + node.call(IntegrationStage.INIT); + } + } - public String getStatus() - { - final StringBuilder builder = new StringBuilder( this.modules.size() * 3 ); + public void postInit() { + for (final IntegrationNode node : this.modules) { + node.call(IntegrationStage.POST_INIT); + } + } - for( final IntegrationNode node : this.modules ) - { - if( builder.length() != 0 ) - { - builder.append( ", " ); - } + public String getStatus() { + final StringBuilder builder = new StringBuilder(this.modules.size() * 3); - final String integrationState = node.getType() + ":" + ( node.getState() == IntegrationStage.FAILED ? "OFF" : "ON" ); - builder.append( integrationState ); - } + for (final IntegrationNode node : this.modules) { + if (builder.length() != 0) { + builder.append(", "); + } - return builder.toString(); - } + final String integrationState = node.getType() + ":" + (node.getState() == IntegrationStage.FAILED ? "OFF" : "ON"); + builder.append(integrationState); + } - public boolean isEnabled( final IntegrationType name ) - { - for( final IntegrationNode node : this.modules ) - { - if( node.getType() == name ) - { - return node.isActive(); - } - } - return false; - } + return builder.toString(); + } + + public boolean isEnabled(final IntegrationType name) { + for (final IntegrationNode node : this.modules) { + if (node.getType() == name) { + return node.isActive(); + } + } + return false; + } } diff --git a/src/main/java/appeng/integration/IntegrationSide.java b/src/main/java/appeng/integration/IntegrationSide.java index 0e4a4b333..f0f0c866f 100644 --- a/src/main/java/appeng/integration/IntegrationSide.java +++ b/src/main/java/appeng/integration/IntegrationSide.java @@ -19,7 +19,6 @@ package appeng.integration; -enum IntegrationSide -{ - CLIENT, SERVER, BOTH +enum IntegrationSide { + CLIENT, SERVER, BOTH } diff --git a/src/main/java/appeng/integration/IntegrationStage.java b/src/main/java/appeng/integration/IntegrationStage.java index 4b65d76d5..ad86af70e 100644 --- a/src/main/java/appeng/integration/IntegrationStage.java +++ b/src/main/java/appeng/integration/IntegrationStage.java @@ -19,14 +19,13 @@ package appeng.integration; -enum IntegrationStage -{ +enum IntegrationStage { - PRE_INIT, - INIT, - POST_INIT, + PRE_INIT, + INIT, + POST_INIT, - FAILED, - READY + FAILED, + READY } diff --git a/src/main/java/appeng/integration/IntegrationType.java b/src/main/java/appeng/integration/IntegrationType.java index 82dbe1af3..0bb611ff7 100644 --- a/src/main/java/appeng/integration/IntegrationType.java +++ b/src/main/java/appeng/integration/IntegrationType.java @@ -27,90 +27,74 @@ import appeng.integration.modules.theoneprobe.TheOneProbeModule; import appeng.integration.modules.waila.WailaModule; -public enum IntegrationType -{ - IC2( IntegrationSide.BOTH, "Industrial Craft 2", "ic2" ) - { - @Override - public IIntegrationModule createInstance() - { - return Integrations.setIc2( new IC2Module() ); - } - }, +public enum IntegrationType { + IC2(IntegrationSide.BOTH, "Industrial Craft 2", "ic2") { + @Override + public IIntegrationModule createInstance() { + return Integrations.setIc2(new IC2Module()); + } + }, - GTCE( IntegrationSide.BOTH, "GregTech", "gregtech" ), + GTCE(IntegrationSide.BOTH, "GregTech", "gregtech"), - RC( IntegrationSide.BOTH, "Railcraft", "railcraft" ), + RC(IntegrationSide.BOTH, "Railcraft", "railcraft"), - MFR( IntegrationSide.BOTH, "Mine Factory Reloaded", "minefactoryreloaded" ), + MFR(IntegrationSide.BOTH, "Mine Factory Reloaded", "minefactoryreloaded"), - Waila( IntegrationSide.BOTH, "Waila", "waila" ) - { - @Override - public IIntegrationModule createInstance() - { - return new WailaModule(); - } - }, + Waila(IntegrationSide.BOTH, "Waila", "waila") { + @Override + public IIntegrationModule createInstance() { + return new WailaModule(); + } + }, - InvTweaks( IntegrationSide.CLIENT, "Inventory Tweaks", "inventorytweaks" ) - { - @Override - public IIntegrationModule createInstance() - { - return Integrations.setInvTweaks( new InventoryTweaksModule() ); - } - }, + InvTweaks(IntegrationSide.CLIENT, "Inventory Tweaks", "inventorytweaks") { + @Override + public IIntegrationModule createInstance() { + return Integrations.setInvTweaks(new InventoryTweaksModule()); + } + }, - JEI( IntegrationSide.CLIENT, "Just Enough Items", "jei" ) - { - @Override - public IIntegrationModule createInstance() - { - return Integrations.setJei( new JEIModule() ); - } - }, + JEI(IntegrationSide.CLIENT, "Just Enough Items", "jei") { + @Override + public IIntegrationModule createInstance() { + return Integrations.setJei(new JEIModule()); + } + }, - Mekanism( IntegrationSide.BOTH, "Mekanism", "mekanism" ), + Mekanism(IntegrationSide.BOTH, "Mekanism", "mekanism"), - OpenComputers( IntegrationSide.BOTH, "OpenComputers", "opencomputers" ), + OpenComputers(IntegrationSide.BOTH, "OpenComputers", "opencomputers"), - THE_ONE_PROBE( IntegrationSide.BOTH, "TheOneProbe", "theoneprobe" ) - { - @Override - public IIntegrationModule createInstance() - { - return new TheOneProbeModule(); - } - }, + THE_ONE_PROBE(IntegrationSide.BOTH, "TheOneProbe", "theoneprobe") { + @Override + public IIntegrationModule createInstance() { + return new TheOneProbeModule(); + } + }, - TESLA( IntegrationSide.BOTH, "Tesla", "tesla" ), + TESLA(IntegrationSide.BOTH, "Tesla", "tesla"), - CRAFTTWEAKER( IntegrationSide.BOTH, "CraftTweaker", "crafttweaker" ) - { - @Override - public IIntegrationModule createInstance() - { - return new CTModule(); - } - }; + CRAFTTWEAKER(IntegrationSide.BOTH, "CraftTweaker", "crafttweaker") { + @Override + public IIntegrationModule createInstance() { + return new CTModule(); + } + }; - public final IntegrationSide side; - public final String dspName; - public final String modID; + public final IntegrationSide side; + public final String dspName; + public final String modID; - IntegrationType( final IntegrationSide side, final String name, final String modid ) - { - this.side = side; - this.dspName = name; - this.modID = modid; - } + IntegrationType(final IntegrationSide side, final String name, final String modid) { + this.side = side; + this.dspName = name; + this.modID = modid; + } - public IIntegrationModule createInstance() - { - return new IIntegrationModule() - { - }; - } + public IIntegrationModule createInstance() { + return new IIntegrationModule() { + }; + } } diff --git a/src/main/java/appeng/integration/Integrations.java b/src/main/java/appeng/integration/Integrations.java index 871b4cb06..0685892b3 100644 --- a/src/main/java/appeng/integration/Integrations.java +++ b/src/main/java/appeng/integration/Integrations.java @@ -19,86 +19,70 @@ package appeng.integration; -import appeng.integration.abstraction.IIC2; -import appeng.integration.abstraction.IInvTweaks; -import appeng.integration.abstraction.IJEI; -import appeng.integration.abstraction.IMekanism; -import appeng.integration.abstraction.IRC; +import appeng.integration.abstraction.*; /** * Provides convenient access to various integrations with other mods. */ -public final class Integrations -{ +public final class Integrations { - static IIC2 ic2 = new IIC2.Stub(); + static IIC2 ic2 = new IIC2.Stub(); - static IJEI jei = new IJEI.Stub(); + static IJEI jei = new IJEI.Stub(); - static IRC rc = new IRC.Stub(); + static IRC rc = new IRC.Stub(); - static IMekanism mekanism = new IMekanism.Stub(); + static IMekanism mekanism = new IMekanism.Stub(); - static IInvTweaks invTweaks = new IInvTweaks.Stub(); + static IInvTweaks invTweaks = new IInvTweaks.Stub(); - private Integrations() - { - } + private Integrations() { + } - public static IIC2 ic2() - { - return ic2; - } + public static IIC2 ic2() { + return ic2; + } - public static IJEI jei() - { - return jei; - } + public static IJEI jei() { + return jei; + } - public static IRC rc() - { - return rc; - } + public static IRC rc() { + return rc; + } - public static IMekanism mekanism() - { - return mekanism; - } + public static IMekanism mekanism() { + return mekanism; + } - public static IInvTweaks invTweaks() - { - return invTweaks; - } + public static IInvTweaks invTweaks() { + return invTweaks; + } - static IIC2 setIc2( IIC2 ic2 ) - { - Integrations.ic2 = ic2; - return ic2; - } + static IIC2 setIc2(IIC2 ic2) { + Integrations.ic2 = ic2; + return ic2; + } - static IJEI setJei( IJEI jei ) - { - Integrations.jei = jei; - return jei; - } + static IJEI setJei(IJEI jei) { + Integrations.jei = jei; + return jei; + } - static IRC setRc( IRC rc ) - { - Integrations.rc = rc; - return rc; - } + static IRC setRc(IRC rc) { + Integrations.rc = rc; + return rc; + } - static IMekanism setMekanism( IMekanism mekanism ) - { - Integrations.mekanism = mekanism; - return mekanism; - } + static IMekanism setMekanism(IMekanism mekanism) { + Integrations.mekanism = mekanism; + return mekanism; + } - static IInvTweaks setInvTweaks( IInvTweaks invTweaks ) - { - Integrations.invTweaks = invTweaks; - return invTweaks; - } + static IInvTweaks setInvTweaks(IInvTweaks invTweaks) { + Integrations.invTweaks = invTweaks; + return invTweaks; + } } diff --git a/src/main/java/appeng/integration/abstraction/IAEFacade.java b/src/main/java/appeng/integration/abstraction/IAEFacade.java index 22102d08a..335e728ed 100644 --- a/src/main/java/appeng/integration/abstraction/IAEFacade.java +++ b/src/main/java/appeng/integration/abstraction/IAEFacade.java @@ -19,42 +19,38 @@ package appeng.integration.abstraction; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraftforge.fml.common.Optional; - import team.chisel.ctm.api.IFacade; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + /** * Neat abstraction class for All the IFacade interfaces. * * @author covers1624 */ -@Optional.Interface( iface = "team.chisel.ctm.api.IFacade", modid = "ctm-api" ) -public interface IAEFacade extends IFacade -{ +@Optional.Interface(iface = "team.chisel.ctm.api.IFacade", modid = "ctm-api") +public interface IAEFacade extends IFacade { - IBlockState getFacadeState( IBlockAccess world, BlockPos pos, EnumFacing side ); + IBlockState getFacadeState(IBlockAccess world, BlockPos pos, EnumFacing side); - @Nonnull - @Override - @Optional.Method( modid = "ctm-api" ) - default IBlockState getFacade( @Nonnull IBlockAccess world, @Nonnull BlockPos pos, @Nullable EnumFacing side, @Nonnull BlockPos connection ) - { - return getFacadeState( world, pos, side ); - } + @Nonnull + @Override + @Optional.Method(modid = "ctm-api") + default IBlockState getFacade(@Nonnull IBlockAccess world, @Nonnull BlockPos pos, @Nullable EnumFacing side, @Nonnull BlockPos connection) { + return getFacadeState(world, pos, side); + } - @Nonnull - @Override - @Optional.Method( modid = "ctm-api" ) - default IBlockState getFacade( @Nonnull IBlockAccess world, @Nonnull BlockPos pos, @Nullable EnumFacing side ) - { - return getFacadeState( world, pos, side ); - } + @Nonnull + @Override + @Optional.Method(modid = "ctm-api") + default IBlockState getFacade(@Nonnull IBlockAccess world, @Nonnull BlockPos pos, @Nullable EnumFacing side) { + return getFacadeState(world, pos, side); + } } diff --git a/src/main/java/appeng/integration/abstraction/IC2PowerSink.java b/src/main/java/appeng/integration/abstraction/IC2PowerSink.java index c3f7f7e54..cee07f7c2 100644 --- a/src/main/java/appeng/integration/abstraction/IC2PowerSink.java +++ b/src/main/java/appeng/integration/abstraction/IC2PowerSink.java @@ -19,31 +19,26 @@ package appeng.integration.abstraction; -import java.util.Set; - import net.minecraft.util.EnumFacing; +import java.util.Set; + /** * Provides an abstraction for the IC2 Basic Sink so it can be stubbed out easily when the integration is disabled, or * if the IC2 API is not available. */ -public interface IC2PowerSink -{ +public interface IC2PowerSink { - default void invalidate() - { - } + default void invalidate() { + } - default void onChunkUnload() - { - } + default void onChunkUnload() { + } - default void onLoad() - { - } + default void onLoad() { + } - default void setValidFaces( Set faces ) - { - } + default void setValidFaces(Set faces) { + } } diff --git a/src/main/java/appeng/integration/abstraction/ICraftTweaker.java b/src/main/java/appeng/integration/abstraction/ICraftTweaker.java index f608607a8..9100a51b2 100644 --- a/src/main/java/appeng/integration/abstraction/ICraftTweaker.java +++ b/src/main/java/appeng/integration/abstraction/ICraftTweaker.java @@ -22,7 +22,6 @@ package appeng.integration.abstraction; import appeng.integration.IIntegrationModule; -public interface ICraftTweaker extends IIntegrationModule -{ +public interface ICraftTweaker extends IIntegrationModule { } diff --git a/src/main/java/appeng/integration/abstraction/IIC2.java b/src/main/java/appeng/integration/abstraction/IIC2.java index c76784c87..24e1db19c 100644 --- a/src/main/java/appeng/integration/abstraction/IIC2.java +++ b/src/main/java/appeng/integration/abstraction/IIC2.java @@ -19,31 +19,26 @@ package appeng.integration.abstraction; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - import appeng.integration.IIntegrationModule; import appeng.integration.modules.ic2.IC2PowerSinkStub; import appeng.tile.powersink.IExternalPowerSink; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; -public interface IIC2 extends IIntegrationModule -{ +public interface IIC2 extends IIntegrationModule { - default void maceratorRecipe( ItemStack in, ItemStack out ) - { - } + default void maceratorRecipe(ItemStack in, ItemStack out) { + } - /** - * Create an IC2 power sink for the given external sink. - */ - default IC2PowerSink createPowerSink( TileEntity tileEntity, IExternalPowerSink externalSink ) - { - return IC2PowerSinkStub.INSTANCE; - } + /** + * Create an IC2 power sink for the given external sink. + */ + default IC2PowerSink createPowerSink(TileEntity tileEntity, IExternalPowerSink externalSink) { + return IC2PowerSinkStub.INSTANCE; + } - class Stub extends IIntegrationModule.Stub implements IIC2 - { + class Stub extends IIntegrationModule.Stub implements IIC2 { - } + } } diff --git a/src/main/java/appeng/integration/abstraction/IInvTweaks.java b/src/main/java/appeng/integration/abstraction/IInvTweaks.java index f24d5c746..8144a9d0d 100644 --- a/src/main/java/appeng/integration/abstraction/IInvTweaks.java +++ b/src/main/java/appeng/integration/abstraction/IInvTweaks.java @@ -19,21 +19,17 @@ package appeng.integration.abstraction; +import appeng.integration.IIntegrationModule; import net.minecraft.item.ItemStack; -import appeng.integration.IIntegrationModule; +public interface IInvTweaks extends IIntegrationModule { -public interface IInvTweaks extends IIntegrationModule -{ + default int compareItems(ItemStack i, ItemStack j) { + throw new UnsupportedOperationException(); + } - default int compareItems( ItemStack i, ItemStack j ) - { - throw new UnsupportedOperationException(); - } - - class Stub extends IIntegrationModule.Stub implements IInvTweaks - { - } + class Stub extends IIntegrationModule.Stub implements IInvTweaks { + } } diff --git a/src/main/java/appeng/integration/abstraction/IJEI.java b/src/main/java/appeng/integration/abstraction/IJEI.java index 7f934ebae..492a6b662 100644 --- a/src/main/java/appeng/integration/abstraction/IJEI.java +++ b/src/main/java/appeng/integration/abstraction/IJEI.java @@ -25,19 +25,15 @@ import appeng.integration.IIntegrationModule; /** * Abstracts access to the JEI API functionality. */ -public interface IJEI extends IIntegrationModule -{ +public interface IJEI extends IIntegrationModule { - default String getSearchText() - { - return ""; - } + default String getSearchText() { + return ""; + } - default void setSearchText( String searchText ) - { - } + default void setSearchText(String searchText) { + } - class Stub extends IIntegrationModule.Stub implements IJEI - { - } + class Stub extends IIntegrationModule.Stub implements IJEI { + } } diff --git a/src/main/java/appeng/integration/abstraction/IMekanism.java b/src/main/java/appeng/integration/abstraction/IMekanism.java index cc1b48dd3..246020855 100644 --- a/src/main/java/appeng/integration/abstraction/IMekanism.java +++ b/src/main/java/appeng/integration/abstraction/IMekanism.java @@ -19,23 +19,18 @@ package appeng.integration.abstraction; +import appeng.integration.IIntegrationModule; import net.minecraft.item.ItemStack; -import appeng.integration.IIntegrationModule; +public interface IMekanism extends IIntegrationModule { -public interface IMekanism extends IIntegrationModule -{ + default void addCrusherRecipe(ItemStack in, ItemStack out) { + } - default void addCrusherRecipe( ItemStack in, ItemStack out ) - { - } + default void addEnrichmentChamberRecipe(ItemStack in, ItemStack out) { + } - default void addEnrichmentChamberRecipe( ItemStack in, ItemStack out ) - { - } - - class Stub extends IIntegrationModule.Stub implements IMekanism - { - } + class Stub extends IIntegrationModule.Stub implements IMekanism { + } } diff --git a/src/main/java/appeng/integration/abstraction/IRC.java b/src/main/java/appeng/integration/abstraction/IRC.java index 74adda35b..c4ed474a6 100644 --- a/src/main/java/appeng/integration/abstraction/IRC.java +++ b/src/main/java/appeng/integration/abstraction/IRC.java @@ -19,20 +19,16 @@ package appeng.integration.abstraction; +import appeng.integration.IIntegrationModule; import net.minecraft.item.ItemStack; -import appeng.integration.IIntegrationModule; +public interface IRC extends IIntegrationModule { -public interface IRC extends IIntegrationModule -{ + default void rockCrusher(ItemStack input, ItemStack output) { + } - default void rockCrusher( ItemStack input, ItemStack output ) - { - } - - class Stub extends IIntegrationModule.Stub implements IRC - { - } + class Stub extends IIntegrationModule.Stub implements IRC { + } } diff --git a/src/main/java/appeng/integration/modules/bogosorter/InventoryBogoSortModule.java b/src/main/java/appeng/integration/modules/bogosorter/InventoryBogoSortModule.java index 3ee6bd1f3..cefee1a14 100644 --- a/src/main/java/appeng/integration/modules/bogosorter/InventoryBogoSortModule.java +++ b/src/main/java/appeng/integration/modules/bogosorter/InventoryBogoSortModule.java @@ -6,8 +6,7 @@ import net.minecraftforge.fml.common.Loader; import java.util.Comparator; -public class InventoryBogoSortModule -{ +public class InventoryBogoSortModule { private static final boolean loaded = Loader.isModLoaded("bogosorter"); public static final Comparator COMPARATOR = (o1, o2) -> SortHandler.ITEM_COMPARATOR.compare(o1.getDefinition(), o2.getDefinition()); diff --git a/src/main/java/appeng/integration/modules/crafttweaker/AttunementRegistry.java b/src/main/java/appeng/integration/modules/crafttweaker/AttunementRegistry.java index 8bc7f4c60..440e9dd51 100644 --- a/src/main/java/appeng/integration/modules/crafttweaker/AttunementRegistry.java +++ b/src/main/java/appeng/integration/modules/crafttweaker/AttunementRegistry.java @@ -19,114 +19,95 @@ package appeng.integration.modules.crafttweaker; +import appeng.api.AEApi; +import appeng.api.config.TunnelType; +import appeng.api.features.IP2PTunnelRegistry; import crafttweaker.api.item.IIngredient; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; -import appeng.api.AEApi; -import appeng.api.config.TunnelType; -import appeng.api.features.IP2PTunnelRegistry; +@ZenClass("mods.appliedenergistics2.Attunement") +public class AttunementRegistry { + private AttunementRegistry() { + } -@ZenClass( "mods.appliedenergistics2.Attunement" ) -public class AttunementRegistry -{ - private AttunementRegistry() - { - } + @ZenMethod + public static void attuneME(IIngredient itemStack) { + attune(itemStack, TunnelType.ME); + } - @ZenMethod - public static void attuneME( IIngredient itemStack ) - { - attune( itemStack, TunnelType.ME ); - } + @ZenMethod + public static void attuneME(String modId) { + attune(modId, TunnelType.ME); + } - @ZenMethod - public static void attuneME( String modId ) - { - attune( modId, TunnelType.ME ); - } + @ZenMethod + public static void attuneItem(IIngredient itemStack) { + attune(itemStack, TunnelType.ITEM); + } - @ZenMethod - public static void attuneItem( IIngredient itemStack ) - { - attune( itemStack, TunnelType.ITEM ); - } + @ZenMethod + public static void attuneItem(String modId) { + attune(modId, TunnelType.ITEM); + } - @ZenMethod - public static void attuneItem( String modId ) - { - attune( modId, TunnelType.ITEM ); - } + @ZenMethod + public static void attuneFluid(IIngredient itemStack) { + attune(itemStack, TunnelType.FLUID); + } - @ZenMethod - public static void attuneFluid( IIngredient itemStack ) - { - attune( itemStack, TunnelType.FLUID ); - } + @ZenMethod + public static void attuneFluid(String modId) { + attune(modId, TunnelType.FLUID); + } - @ZenMethod - public static void attuneFluid( String modId ) - { - attune( modId, TunnelType.FLUID ); - } + @ZenMethod + public static void attuneRedstone(IIngredient itemStack) { + attune(itemStack, TunnelType.REDSTONE); + } - @ZenMethod - public static void attuneRedstone( IIngredient itemStack ) - { - attune( itemStack, TunnelType.REDSTONE ); - } + @ZenMethod + public static void attuneRedstone(String modId) { + attune(modId, TunnelType.REDSTONE); + } - @ZenMethod - public static void attuneRedstone( String modId ) - { - attune( modId, TunnelType.REDSTONE ); - } + @ZenMethod + public static void attuneRF(IIngredient itemStack) { + attune(itemStack, TunnelType.FE_POWER); + } - @ZenMethod - public static void attuneRF( IIngredient itemStack ) - { - attune( itemStack, TunnelType.FE_POWER ); - } + @ZenMethod + public static void attuneRF(String modId) { + attune(modId, TunnelType.FE_POWER); + } - @ZenMethod - public static void attuneRF( String modId ) - { - attune( modId, TunnelType.FE_POWER ); - } + @ZenMethod + public static void attuneIC2(IIngredient itemStack) { + attune(itemStack, TunnelType.IC2_POWER); + } - @ZenMethod - public static void attuneIC2( IIngredient itemStack ) - { - attune( itemStack, TunnelType.IC2_POWER ); - } + @ZenMethod + public static void attuneIC2(String modId) { + attune(modId, TunnelType.IC2_POWER); + } - @ZenMethod - public static void attuneIC2( String modId ) - { - attune( modId, TunnelType.IC2_POWER ); - } + @ZenMethod + public static void attuneLight(IIngredient itemStack) { + attune(itemStack, TunnelType.LIGHT); + } - @ZenMethod - public static void attuneLight( IIngredient itemStack ) - { - attune( itemStack, TunnelType.LIGHT ); - } + @ZenMethod + public static void attuneLight(String modId) { + attune(modId, TunnelType.LIGHT); + } - @ZenMethod - public static void attuneLight( String modId ) - { - attune( modId, TunnelType.LIGHT ); - } + private static void attune(IIngredient itemStack, TunnelType type) { + IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); + CTModule.toStacks(itemStack).ifPresent(c -> c.forEach(i -> registry.addNewAttunement(i, type))); + } - private static void attune( IIngredient itemStack, TunnelType type ) - { - IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); - CTModule.toStacks( itemStack ).ifPresent( c -> c.forEach( i -> registry.addNewAttunement( i, type ) ) ); - } - - private static void attune( String modid, TunnelType type ) - { - AEApi.instance().registries().p2pTunnel().addNewAttunement( modid, type ); - } + private static void attune(String modid, TunnelType type) { + AEApi.instance().registries().p2pTunnel().addNewAttunement(modid, type); + } } diff --git a/src/main/java/appeng/integration/modules/crafttweaker/CTModule.java b/src/main/java/appeng/integration/modules/crafttweaker/CTModule.java index a6ca92318..27c806ea8 100644 --- a/src/main/java/appeng/integration/modules/crafttweaker/CTModule.java +++ b/src/main/java/appeng/integration/modules/crafttweaker/CTModule.java @@ -19,112 +19,83 @@ package appeng.integration.modules.crafttweaker; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.TreeSet; -import java.util.stream.Collectors; - +import appeng.integration.abstraction.ICraftTweaker; +import appeng.util.Platform; +import crafttweaker.CraftTweakerAPI; +import crafttweaker.IAction; +import crafttweaker.api.item.IIngredient; +import crafttweaker.api.item.IItemStack; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraftforge.oredict.OreDictionary; -import crafttweaker.CraftTweakerAPI; -import crafttweaker.IAction; -import crafttweaker.api.item.IIngredient; -import crafttweaker.api.item.IItemStack; - -import appeng.integration.abstraction.ICraftTweaker; -import appeng.util.Platform; +import java.util.*; +import java.util.stream.Collectors; -public class CTModule implements ICraftTweaker -{ - static final List MODIFICATIONS = new ArrayList<>(); +public class CTModule implements ICraftTweaker { + static final List MODIFICATIONS = new ArrayList<>(); - @Override - public void preInit() - { - CraftTweakerAPI.registerClass( GrinderRecipes.class ); - CraftTweakerAPI.registerClass( InscriberRecipes.class ); - CraftTweakerAPI.registerClass( SpatialRegistry.class ); - CraftTweakerAPI.registerClass( AttunementRegistry.class ); - CraftTweakerAPI.registerClass( CannonRegistry.class ); - } + @Override + public void preInit() { + CraftTweakerAPI.registerClass(GrinderRecipes.class); + CraftTweakerAPI.registerClass(InscriberRecipes.class); + CraftTweakerAPI.registerClass(SpatialRegistry.class); + CraftTweakerAPI.registerClass(AttunementRegistry.class); + CraftTweakerAPI.registerClass(CannonRegistry.class); + } - @Override - public void postInit() - { - MODIFICATIONS.forEach( CraftTweakerAPI::apply ); - } + @Override + public void postInit() { + MODIFICATIONS.forEach(CraftTweakerAPI::apply); + } - public static ItemStack toStack( IItemStack iStack ) - { - if( iStack == null ) - { - return ItemStack.EMPTY; - } - else - { - return (ItemStack) iStack.getInternal(); - } - } + public static ItemStack toStack(IItemStack iStack) { + if (iStack == null) { + return ItemStack.EMPTY; + } else { + return (ItemStack) iStack.getInternal(); + } + } - public static List toStackExpand( IItemStack iStack ) - { - if( iStack == null ) - { - return Collections.emptyList(); - } - else - { - ItemStack is = (ItemStack) iStack.getInternal(); - if( !is.isItemStackDamageable() && is.getItemDamage() == OreDictionary.WILDCARD_VALUE ) - { - NonNullList ret = NonNullList.create(); - is.getItem().getSubItems( CreativeTabs.SEARCH, ret ); - return ret.stream().map( i -> new ItemStack( i.getItem(), iStack.getAmount(), i.getItemDamage() ) ).collect( Collectors.toList() ); - } - else - { - return Collections.singletonList( is ); - } - } - } + public static List toStackExpand(IItemStack iStack) { + if (iStack == null) { + return Collections.emptyList(); + } else { + ItemStack is = (ItemStack) iStack.getInternal(); + if (!is.isItemStackDamageable() && is.getItemDamage() == OreDictionary.WILDCARD_VALUE) { + NonNullList ret = NonNullList.create(); + is.getItem().getSubItems(CreativeTabs.SEARCH, ret); + return ret.stream().map(i -> new ItemStack(i.getItem(), iStack.getAmount(), i.getItemDamage())).collect(Collectors.toList()); + } else { + return Collections.singletonList(is); + } + } + } - public static Optional> toStacks( IIngredient ingredient ) - { - if( ingredient == null ) - { - return Optional.empty(); - } - Set ret = new TreeSet<>( CTModule::compareItemStacks ); - ingredient.getItems().stream().map( CTModule::toStackExpand ).forEach( ret::addAll ); - if( ret.isEmpty() ) - { - return Optional.empty(); - } - return Optional.of( ret ); - } + public static Optional> toStacks(IIngredient ingredient) { + if (ingredient == null) { + return Optional.empty(); + } + Set ret = new TreeSet<>(CTModule::compareItemStacks); + ingredient.getItems().stream().map(CTModule::toStackExpand).forEach(ret::addAll); + if (ret.isEmpty()) { + return Optional.empty(); + } + return Optional.of(ret); + } - private static int compareItemStacks( ItemStack a, ItemStack b ) - { - if( Platform.itemComparisons().isSameItem( a, b ) ) - { - return 0; - } - if( a == null ) - { - return -1; - } - if( b == null ) - { - return 1; - } - return System.identityHashCode( a ) - System.identityHashCode( b ); - } + private static int compareItemStacks(ItemStack a, ItemStack b) { + if (Platform.itemComparisons().isSameItem(a, b)) { + return 0; + } + if (a == null) { + return -1; + } + if (b == null) { + return 1; + } + return System.identityHashCode(a) - System.identityHashCode(b); + } } diff --git a/src/main/java/appeng/integration/modules/crafttweaker/CannonRegistry.java b/src/main/java/appeng/integration/modules/crafttweaker/CannonRegistry.java index 8b64999a8..e368b67c3 100644 --- a/src/main/java/appeng/integration/modules/crafttweaker/CannonRegistry.java +++ b/src/main/java/appeng/integration/modules/crafttweaker/CannonRegistry.java @@ -19,25 +19,21 @@ package appeng.integration.modules.crafttweaker; +import appeng.api.AEApi; +import appeng.api.features.IMatterCannonAmmoRegistry; import crafttweaker.api.item.IIngredient; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; -import appeng.api.AEApi; -import appeng.api.features.IMatterCannonAmmoRegistry; +@ZenClass("mods.appliedenergistics2.Cannon") +public class CannonRegistry { + private CannonRegistry() { + } -@ZenClass( "mods.appliedenergistics2.Cannon" ) -public class CannonRegistry -{ - private CannonRegistry() - { - } - - @ZenMethod - public static void registerAmmo( IIngredient itemStack, double weight ) - { - IMatterCannonAmmoRegistry registry = AEApi.instance().registries().matterCannon(); - CTModule.toStacks( itemStack ).ifPresent( c -> c.forEach( i -> registry.registerAmmo( i, weight ) ) ); - } + @ZenMethod + public static void registerAmmo(IIngredient itemStack, double weight) { + IMatterCannonAmmoRegistry registry = AEApi.instance().registries().matterCannon(); + CTModule.toStacks(itemStack).ifPresent(c -> c.forEach(i -> registry.registerAmmo(i, weight))); + } } diff --git a/src/main/java/appeng/integration/modules/crafttweaker/GrinderRecipes.java b/src/main/java/appeng/integration/modules/crafttweaker/GrinderRecipes.java index 2e8b74429..b51d3cff6 100644 --- a/src/main/java/appeng/integration/modules/crafttweaker/GrinderRecipes.java +++ b/src/main/java/appeng/integration/modules/crafttweaker/GrinderRecipes.java @@ -19,109 +19,90 @@ package appeng.integration.modules.crafttweaker; -import java.util.Collection; -import java.util.Collections; - -import net.minecraft.item.ItemStack; - -import crafttweaker.IAction; -import crafttweaker.api.item.IIngredient; -import crafttweaker.api.item.IItemStack; -import stanhebben.zenscript.annotations.ZenClass; -import stanhebben.zenscript.annotations.ZenMethod; - import appeng.api.AEApi; import appeng.api.features.IGrinderRecipe; import appeng.api.features.IGrinderRecipeBuilder; +import crafttweaker.IAction; +import crafttweaker.api.item.IIngredient; +import crafttweaker.api.item.IItemStack; +import net.minecraft.item.ItemStack; +import stanhebben.zenscript.annotations.ZenClass; +import stanhebben.zenscript.annotations.ZenMethod; + +import java.util.Collection; +import java.util.Collections; -@ZenClass( "mods.appliedenergistics2.Grinder" ) -public class GrinderRecipes -{ - private GrinderRecipes() - { - } +@ZenClass("mods.appliedenergistics2.Grinder") +public class GrinderRecipes { + private GrinderRecipes() { + } - @ZenMethod - public static void addRecipe( IItemStack output, IIngredient input, int turns, @stanhebben.zenscript.annotations.Optional IItemStack secondary1Output, @stanhebben.zenscript.annotations.Optional Float secondary1Chance, @stanhebben.zenscript.annotations.Optional IItemStack secondary2Output, @stanhebben.zenscript.annotations.Optional Float secondary2Chance ) - { - Collection inStacks = CTModule.toStacks( input ).orElse( Collections.emptySet() ); + @ZenMethod + public static void addRecipe(IItemStack output, IIngredient input, int turns, @stanhebben.zenscript.annotations.Optional IItemStack secondary1Output, @stanhebben.zenscript.annotations.Optional Float secondary1Chance, @stanhebben.zenscript.annotations.Optional IItemStack secondary2Output, @stanhebben.zenscript.annotations.Optional Float secondary2Chance) { + Collection inStacks = CTModule.toStacks(input).orElse(Collections.emptySet()); - for( ItemStack inStack : inStacks ) - { - IGrinderRecipeBuilder builder = AEApi.instance().registries().grinder().builder(); - builder.withInput( inStack ) - .withOutput( CTModule.toStack( output ) ) - .withTurns( turns ); + for (ItemStack inStack : inStacks) { + IGrinderRecipeBuilder builder = AEApi.instance().registries().grinder().builder(); + builder.withInput(inStack) + .withOutput(CTModule.toStack(output)) + .withTurns(turns); - final ItemStack s1 = CTModule.toStack( secondary1Output ); - if( !s1.isEmpty() ) - { - builder.withFirstOptional( s1, secondary1Chance == null ? 1.0f : secondary1Chance ); - } - final ItemStack s2 = CTModule.toStack( secondary2Output ); - if( !s2.isEmpty() ) - { - builder.withSecondOptional( s2, secondary2Chance == null ? 1.0f : secondary2Chance ); - } - CTModule.MODIFICATIONS.add( new Add( builder.build() ) ); - } - } + final ItemStack s1 = CTModule.toStack(secondary1Output); + if (!s1.isEmpty()) { + builder.withFirstOptional(s1, secondary1Chance == null ? 1.0f : secondary1Chance); + } + final ItemStack s2 = CTModule.toStack(secondary2Output); + if (!s2.isEmpty()) { + builder.withSecondOptional(s2, secondary2Chance == null ? 1.0f : secondary2Chance); + } + CTModule.MODIFICATIONS.add(new Add(builder.build())); + } + } - @ZenMethod - public static void removeRecipe( IIngredient input ) - { - for( ItemStack inStack : CTModule.toStacks( input ).orElse( Collections.emptySet() ) ) - { - CTModule.MODIFICATIONS.add( new Remove( inStack ) ); - } - } + @ZenMethod + public static void removeRecipe(IIngredient input) { + for (ItemStack inStack : CTModule.toStacks(input).orElse(Collections.emptySet())) { + CTModule.MODIFICATIONS.add(new Remove(inStack)); + } + } - private static class Add implements IAction - { - private final IGrinderRecipe entry; + private static class Add implements IAction { + private final IGrinderRecipe entry; - private Add( IGrinderRecipe entry ) - { - this.entry = entry; - } + private Add(IGrinderRecipe entry) { + this.entry = entry; + } - @Override - public void apply() - { - AEApi.instance().registries().grinder().addRecipe( this.entry ); - } + @Override + public void apply() { + AEApi.instance().registries().grinder().addRecipe(this.entry); + } - @Override - public String describe() - { - return "Adding Grinder Entry for " + this.entry.getInput().getDisplayName(); - } - } + @Override + public String describe() { + return "Adding Grinder Entry for " + this.entry.getInput().getDisplayName(); + } + } - private static class Remove implements IAction - { - private final ItemStack stack; + private static class Remove implements IAction { + private final ItemStack stack; - private Remove( ItemStack stack ) - { - this.stack = stack; - } + private Remove(ItemStack stack) { + this.stack = stack; + } - @Override - public void apply() - { - IGrinderRecipe recipe = AEApi.instance().registries().grinder().getRecipeForInput( this.stack ); - if( recipe != null ) - { - AEApi.instance().registries().grinder().removeRecipe( recipe ); - } - } + @Override + public void apply() { + IGrinderRecipe recipe = AEApi.instance().registries().grinder().getRecipeForInput(this.stack); + if (recipe != null) { + AEApi.instance().registries().grinder().removeRecipe(recipe); + } + } - @Override - public String describe() - { - return "Removing Grinder Entry for " + this.stack.getDisplayName(); - } - } + @Override + public String describe() { + return "Removing Grinder Entry for " + this.stack.getDisplayName(); + } + } } diff --git a/src/main/java/appeng/integration/modules/crafttweaker/InscriberRecipes.java b/src/main/java/appeng/integration/modules/crafttweaker/InscriberRecipes.java index d5511018d..1d688d039 100644 --- a/src/main/java/appeng/integration/modules/crafttweaker/InscriberRecipes.java +++ b/src/main/java/appeng/integration/modules/crafttweaker/InscriberRecipes.java @@ -19,120 +19,101 @@ package appeng.integration.modules.crafttweaker; -import java.util.Collection; -import java.util.Collections; -import java.util.Optional; -import java.util.stream.Collectors; - -import net.minecraft.item.ItemStack; - -import crafttweaker.IAction; -import crafttweaker.api.item.IIngredient; -import crafttweaker.api.item.IItemStack; -import stanhebben.zenscript.annotations.ZenClass; -import stanhebben.zenscript.annotations.ZenMethod; - import appeng.api.AEApi; import appeng.api.features.IInscriberRecipe; import appeng.api.features.IInscriberRecipeBuilder; import appeng.api.features.IInscriberRegistry; import appeng.api.features.InscriberProcessType; +import crafttweaker.IAction; +import crafttweaker.api.item.IIngredient; +import crafttweaker.api.item.IItemStack; +import net.minecraft.item.ItemStack; +import stanhebben.zenscript.annotations.ZenClass; +import stanhebben.zenscript.annotations.ZenMethod; + +import java.util.Collection; +import java.util.Collections; +import java.util.Optional; +import java.util.stream.Collectors; -@ZenClass( "mods.appliedenergistics2.Inscriber" ) -public class InscriberRecipes -{ - private InscriberRecipes() - { - } +@ZenClass("mods.appliedenergistics2.Inscriber") +public class InscriberRecipes { + private InscriberRecipes() { + } - @ZenMethod - public static void addRecipe( IItemStack output, IIngredient input, boolean inscribe, @stanhebben.zenscript.annotations.Optional IIngredient top, @stanhebben.zenscript.annotations.Optional IIngredient bottom ) - { - Optional> inStacks = CTModule.toStacks( input ); - if( !inStacks.isPresent() ) - { - return; - } + @ZenMethod + public static void addRecipe(IItemStack output, IIngredient input, boolean inscribe, @stanhebben.zenscript.annotations.Optional IIngredient top, @stanhebben.zenscript.annotations.Optional IIngredient bottom) { + Optional> inStacks = CTModule.toStacks(input); + if (!inStacks.isPresent()) { + return; + } - Collection topList = CTModule.toStacks( top ).orElse( Collections.singleton( ItemStack.EMPTY ) ); - Collection bottomList = CTModule.toStacks( bottom ).orElse( Collections.singleton( ItemStack.EMPTY ) ); + Collection topList = CTModule.toStacks(top).orElse(Collections.singleton(ItemStack.EMPTY)); + Collection bottomList = CTModule.toStacks(bottom).orElse(Collections.singleton(ItemStack.EMPTY)); - for( ItemStack topStack : topList ) - { - for( ItemStack bottomStack : bottomList ) - { - final IInscriberRecipeBuilder builder = AEApi.instance().registries().inscriber().builder(); - builder.withProcessType( inscribe ? InscriberProcessType.INSCRIBE : InscriberProcessType.PRESS ) - .withOutput( CTModule.toStack( output ) ) - .withInputs( inStacks.get() ); + for (ItemStack topStack : topList) { + for (ItemStack bottomStack : bottomList) { + final IInscriberRecipeBuilder builder = AEApi.instance().registries().inscriber().builder(); + builder.withProcessType(inscribe ? InscriberProcessType.INSCRIBE : InscriberProcessType.PRESS) + .withOutput(CTModule.toStack(output)) + .withInputs(inStacks.get()); - if( !topStack.isEmpty() ) - { - builder.withTopOptional( topStack ); - } - if( !bottomStack.isEmpty() ) - { - builder.withBottomOptional( bottomStack ); - } - CTModule.MODIFICATIONS.add( new Add( builder.build() ) ); - } - } - } + if (!topStack.isEmpty()) { + builder.withTopOptional(topStack); + } + if (!bottomStack.isEmpty()) { + builder.withBottomOptional(bottomStack); + } + CTModule.MODIFICATIONS.add(new Add(builder.build())); + } + } + } - @ZenMethod - public static void removeRecipe( IItemStack output ) - { - CTModule.MODIFICATIONS.add( new Remove( (ItemStack) output.getInternal() ) ); - } + @ZenMethod + public static void removeRecipe(IItemStack output) { + CTModule.MODIFICATIONS.add(new Remove((ItemStack) output.getInternal())); + } - private static class Add implements IAction - { - private final IInscriberRecipe entry; + private static class Add implements IAction { + private final IInscriberRecipe entry; - private Add( IInscriberRecipe entry ) - { - this.entry = entry; - } + private Add(IInscriberRecipe entry) { + this.entry = entry; + } - @Override - public void apply() - { - AEApi.instance().registries().inscriber().addRecipe( this.entry ); - } + @Override + public void apply() { + AEApi.instance().registries().inscriber().addRecipe(this.entry); + } - @Override - public String describe() - { - return "Adding Inscriber Entry for " + this.entry.getOutput().getDisplayName(); - } - } + @Override + public String describe() { + return "Adding Inscriber Entry for " + this.entry.getOutput().getDisplayName(); + } + } - private static class Remove implements IAction - { - private final ItemStack stack; + private static class Remove implements IAction { + private final ItemStack stack; - private Remove( ItemStack stack ) - { - this.stack = stack; - } + private Remove(ItemStack stack) { + this.stack = stack; + } - @Override - public void apply() - { - final IInscriberRegistry inscriber = AEApi.instance().registries().inscriber(); - inscriber.getRecipes() - .stream() - .filter( r -> r.getOutput().isItemEqual( this.stack ) ) - .collect( Collectors.toList() ) - .forEach( inscriber::removeRecipe ); - } + @Override + public void apply() { + final IInscriberRegistry inscriber = AEApi.instance().registries().inscriber(); + inscriber.getRecipes() + .stream() + .filter(r -> r.getOutput().isItemEqual(this.stack)) + .collect(Collectors.toList()) + .forEach(inscriber::removeRecipe); + } - @Override - public String describe() - { - return "Removing Inscriber Entry for " + this.stack.getDisplayName(); - } - } + @Override + public String describe() { + return "Removing Inscriber Entry for " + this.stack.getDisplayName(); + } + } } diff --git a/src/main/java/appeng/integration/modules/crafttweaker/SpatialRegistry.java b/src/main/java/appeng/integration/modules/crafttweaker/SpatialRegistry.java index d92e9c4bf..db457f370 100644 --- a/src/main/java/appeng/integration/modules/crafttweaker/SpatialRegistry.java +++ b/src/main/java/appeng/integration/modules/crafttweaker/SpatialRegistry.java @@ -19,43 +19,33 @@ package appeng.integration.modules.crafttweaker; +import appeng.api.AEApi; +import appeng.core.AELog; import net.minecraft.tileentity.TileEntity; - import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; -import appeng.api.AEApi; -import appeng.core.AELog; +@ZenClass("mods.appliedenergistics2.Spatial") +public class SpatialRegistry { + private SpatialRegistry() { + } -@ZenClass( "mods.appliedenergistics2.Spatial" ) -public class SpatialRegistry -{ - private SpatialRegistry() - { - } + @ZenMethod + public static void whitelistEntity(String entityClassName) { + Class entityClass = loadClass(entityClassName); + if (entityClass != null) { + AEApi.instance().registries().movable().whiteListTileEntity(entityClass); + } + } - @ZenMethod - public static void whitelistEntity( String entityClassName ) - { - Class entityClass = loadClass( entityClassName ); - if( entityClass != null ) - { - AEApi.instance().registries().movable().whiteListTileEntity( entityClass ); - } - } - - @SuppressWarnings( "unchecked" ) - private static Class loadClass( String className ) - { - try - { - return (Class) Class.forName( className ); - } - catch( Exception e ) - { - AELog.warn( e, "Failed to load TileEntity class '" + className + "'" ); - } - return null; - } + @SuppressWarnings("unchecked") + private static Class loadClass(String className) { + try { + return (Class) Class.forName(className); + } catch (Exception e) { + AELog.warn(e, "Failed to load TileEntity class '" + className + "'"); + } + return null; + } } diff --git a/src/main/java/appeng/integration/modules/ic2/IC2Module.java b/src/main/java/appeng/integration/modules/ic2/IC2Module.java index d19782bb9..e49196212 100644 --- a/src/main/java/appeng/integration/modules/ic2/IC2Module.java +++ b/src/main/java/appeng/integration/modules/ic2/IC2Module.java @@ -19,11 +19,6 @@ package appeng.integration.modules.ic2; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - -import ic2.api.item.ElectricItem; - import appeng.api.AEApi; import appeng.api.config.TunnelType; import appeng.api.features.IP2PTunnelRegistry; @@ -32,60 +27,55 @@ import appeng.integration.abstraction.IC2PowerSink; import appeng.integration.abstraction.IIC2; import appeng.integration.modules.ic2.energy.PoweredItemManager; import appeng.tile.powersink.IExternalPowerSink; +import ic2.api.item.ElectricItem; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; -public class IC2Module implements IIC2 -{ +public class IC2Module implements IIC2 { - private static final String[] IC2_CABLE_TYPES = { "copper", "glass", "gold", "iron", "tin", "detector", "splitter" }; + private static final String[] IC2_CABLE_TYPES = {"copper", "glass", "gold", "iron", "tin", "detector", "splitter"}; - public IC2Module() - { - IntegrationHelper.testClassExistence( this, ic2.api.energy.tile.IEnergyTile.class ); - IntegrationHelper.testClassExistence( this, ic2.api.energy.tile.IEnergyAcceptor.class ); - IntegrationHelper.testClassExistence( this, ic2.api.energy.tile.IEnergyEmitter.class ); - IntegrationHelper.testClassExistence( this, ic2.api.energy.prefab.BasicSinkSource.class ); - IntegrationHelper.testClassExistence( this, ic2.api.item.IC2Items.class ); - IntegrationHelper.testClassExistence( this, ic2.api.item.IBackupElectricItemManager.class ); - IntegrationHelper.testClassExistence( this, ic2.api.recipe.Recipes.class ); - IntegrationHelper.testClassExistence( this, ic2.api.recipe.IRecipeInput.class ); - } + public IC2Module() { + IntegrationHelper.testClassExistence(this, ic2.api.energy.tile.IEnergyTile.class); + IntegrationHelper.testClassExistence(this, ic2.api.energy.tile.IEnergyAcceptor.class); + IntegrationHelper.testClassExistence(this, ic2.api.energy.tile.IEnergyEmitter.class); + IntegrationHelper.testClassExistence(this, ic2.api.energy.prefab.BasicSinkSource.class); + IntegrationHelper.testClassExistence(this, ic2.api.item.IC2Items.class); + IntegrationHelper.testClassExistence(this, ic2.api.item.IBackupElectricItemManager.class); + IntegrationHelper.testClassExistence(this, ic2.api.recipe.Recipes.class); + IntegrationHelper.testClassExistence(this, ic2.api.recipe.IRecipeInput.class); + } - @Override - public void postInit() - { - final IP2PTunnelRegistry reg = AEApi.instance().registries().p2pTunnel(); + @Override + public void postInit() { + final IP2PTunnelRegistry reg = AEApi.instance().registries().p2pTunnel(); - for( String string : IC2_CABLE_TYPES ) - { - reg.addNewAttunement( this.getCable( string ), TunnelType.IC2_POWER ); - } + for (String string : IC2_CABLE_TYPES) { + reg.addNewAttunement(this.getCable(string), TunnelType.IC2_POWER); + } - ElectricItem.registerBackupManager( new PoweredItemManager() ); - } + ElectricItem.registerBackupManager(new PoweredItemManager()); + } - private ItemStack getItem( final String name, String variant ) - { - return ic2.api.item.IC2Items.getItem( name, variant ); - } + private ItemStack getItem(final String name, String variant) { + return ic2.api.item.IC2Items.getItem(name, variant); + } - private ItemStack getCable( final String type ) - { - return this.getItem( "cable", "type:" + type ); - } + private ItemStack getCable(final String type) { + return this.getItem("cable", "type:" + type); + } - /** - * Create an IC2 power sink for the given external sink. - */ - @Override - public IC2PowerSink createPowerSink( TileEntity tileEntity, IExternalPowerSink externalSink ) - { - return new IC2PowerSinkAdapter( tileEntity, externalSink ); - } + /** + * Create an IC2 power sink for the given external sink. + */ + @Override + public IC2PowerSink createPowerSink(TileEntity tileEntity, IExternalPowerSink externalSink) { + return new IC2PowerSinkAdapter(tileEntity, externalSink); + } - @Override - public void maceratorRecipe( ItemStack in, ItemStack out ) - { - ic2.api.recipe.Recipes.macerator.addRecipe( new IC2RecipeInput( in, in.getCount() ), null, false, out ); - } + @Override + public void maceratorRecipe(ItemStack in, ItemStack out) { + ic2.api.recipe.Recipes.macerator.addRecipe(new IC2RecipeInput(in, in.getCount()), null, false, out); + } } diff --git a/src/main/java/appeng/integration/modules/ic2/IC2PowerSinkAdapter.java b/src/main/java/appeng/integration/modules/ic2/IC2PowerSinkAdapter.java index b15740d4b..b4dae7057 100644 --- a/src/main/java/appeng/integration/modules/ic2/IC2PowerSinkAdapter.java +++ b/src/main/java/appeng/integration/modules/ic2/IC2PowerSinkAdapter.java @@ -19,77 +19,66 @@ package appeng.integration.modules.ic2; -import java.util.EnumSet; -import java.util.Set; - -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; - -import ic2.api.energy.prefab.BasicSink; -import ic2.api.energy.tile.IEnergyEmitter; - import appeng.api.config.Actionable; import appeng.api.config.PowerUnits; import appeng.integration.abstraction.IC2PowerSink; import appeng.tile.powersink.IExternalPowerSink; +import ic2.api.energy.prefab.BasicSink; +import ic2.api.energy.tile.IEnergyEmitter; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; + +import java.util.EnumSet; +import java.util.Set; /** * The real implementation of IC2PowerSink. */ -public class IC2PowerSinkAdapter extends BasicSink implements IC2PowerSink -{ +public class IC2PowerSinkAdapter extends BasicSink implements IC2PowerSink { - private final IExternalPowerSink powerSink; + private final IExternalPowerSink powerSink; - private final Set validFaces = EnumSet.allOf( EnumFacing.class ); + private final Set validFaces = EnumSet.allOf(EnumFacing.class); - public IC2PowerSinkAdapter( TileEntity tileEntity, IExternalPowerSink powerSink ) - { - super( tileEntity, 0, Integer.MAX_VALUE ); - this.powerSink = powerSink; - } + public IC2PowerSinkAdapter(TileEntity tileEntity, IExternalPowerSink powerSink) { + super(tileEntity, 0, Integer.MAX_VALUE); + this.powerSink = powerSink; + } - @Override - public void invalidate() - { - super.onChunkUnload(); - } + @Override + public void invalidate() { + super.onChunkUnload(); + } - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - } + @Override + public void onChunkUnload() { + super.onChunkUnload(); + } - @Override - public void onLoad() - { - super.onLoad(); - } + @Override + public void onLoad() { + super.onLoad(); + } - @Override - public double getDemandedEnergy() - { - return this.powerSink.getExternalPowerDemand( PowerUnits.EU, Double.MAX_VALUE ); - } + @Override + public double getDemandedEnergy() { + return this.powerSink.getExternalPowerDemand(PowerUnits.EU, Double.MAX_VALUE); + } - @Override - public double injectEnergy( EnumFacing directionFrom, double amount, double voltage ) - { - return PowerUnits.EU.convertTo( PowerUnits.AE, this.powerSink.injectExternalPower( PowerUnits.EU, amount, Actionable.MODULATE ) ); - } + @Override + public double injectEnergy(EnumFacing directionFrom, double amount, double voltage) { + return PowerUnits.EU.convertTo(PowerUnits.AE, this.powerSink.injectExternalPower(PowerUnits.EU, amount, Actionable.MODULATE)); + } - @Override - public boolean acceptsEnergyFrom( IEnergyEmitter iEnergyEmitter, EnumFacing side ) - { - return this.validFaces.contains( side ); - } + @Override + public boolean acceptsEnergyFrom(IEnergyEmitter iEnergyEmitter, EnumFacing side) { + return this.validFaces.contains(side); + } - @Override - public void setValidFaces( Set faces ) - { - this.validFaces.clear(); - this.validFaces.addAll( faces ); - } + @Override + public void setValidFaces(Set faces) { + this.validFaces.clear(); + this.validFaces.addAll(faces); + } } diff --git a/src/main/java/appeng/integration/modules/ic2/IC2PowerSinkStub.java b/src/main/java/appeng/integration/modules/ic2/IC2PowerSinkStub.java index a77654402..b49a1aebd 100644 --- a/src/main/java/appeng/integration/modules/ic2/IC2PowerSinkStub.java +++ b/src/main/java/appeng/integration/modules/ic2/IC2PowerSinkStub.java @@ -25,7 +25,6 @@ import appeng.integration.abstraction.IC2PowerSink; /** * Implementation of IC2PowerSink that just stubs out all methods and does nothing. */ -public enum IC2PowerSinkStub implements IC2PowerSink -{ - INSTANCE +public enum IC2PowerSinkStub implements IC2PowerSink { + INSTANCE } diff --git a/src/main/java/appeng/integration/modules/ic2/IC2RecipeInput.java b/src/main/java/appeng/integration/modules/ic2/IC2RecipeInput.java index b96693e5e..be45885eb 100644 --- a/src/main/java/appeng/integration/modules/ic2/IC2RecipeInput.java +++ b/src/main/java/appeng/integration/modules/ic2/IC2RecipeInput.java @@ -19,14 +19,12 @@ package appeng.integration.modules.ic2; -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nonnull; - +import ic2.api.recipe.IRecipeInput; import net.minecraft.item.ItemStack; -import ic2.api.recipe.IRecipeInput; +import javax.annotation.Nonnull; +import java.util.Collections; +import java.util.List; /** @@ -34,33 +32,28 @@ import ic2.api.recipe.IRecipeInput; * * @author GuntherDW */ -public class IC2RecipeInput implements IRecipeInput -{ - @Nonnull - private final ItemStack itemstack; - private final int amount; +public class IC2RecipeInput implements IRecipeInput { + @Nonnull + private final ItemStack itemstack; + private final int amount; - public IC2RecipeInput( ItemStack in, int amount ) - { - this.itemstack = in; - this.amount = amount; - } + public IC2RecipeInput(ItemStack in, int amount) { + this.itemstack = in; + this.amount = amount; + } - @Override - public boolean matches( ItemStack itemStack ) - { - return this.itemstack.isItemEqual( itemStack ); - } + @Override + public boolean matches(ItemStack itemStack) { + return this.itemstack.isItemEqual(itemStack); + } - @Override - public int getAmount() - { - return this.amount; - } + @Override + public int getAmount() { + return this.amount; + } - @Override - public List getInputs() - { - return Collections.unmodifiableList( Collections.singletonList( this.itemstack ) ); - } + @Override + public List getInputs() { + return Collections.unmodifiableList(Collections.singletonList(this.itemstack)); + } } diff --git a/src/main/java/appeng/integration/modules/ic2/energy/PoweredItemManager.java b/src/main/java/appeng/integration/modules/ic2/energy/PoweredItemManager.java index 16dd809a0..3fd78779e 100644 --- a/src/main/java/appeng/integration/modules/ic2/energy/PoweredItemManager.java +++ b/src/main/java/appeng/integration/modules/ic2/energy/PoweredItemManager.java @@ -19,108 +19,92 @@ package appeng.integration.modules.ic2.energy; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.item.ItemStack; - -import ic2.api.item.IBackupElectricItemManager; - import appeng.api.config.Actionable; import appeng.api.config.PowerUnits; import appeng.api.implementations.items.IAEItemPowerStorage; +import ic2.api.item.IBackupElectricItemManager; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.item.ItemStack; -public class PoweredItemManager implements IBackupElectricItemManager -{ +public class PoweredItemManager implements IBackupElectricItemManager { - @Override - public double charge( ItemStack stack, double amount, int tier, boolean ignoreTransferLimit, boolean simulate ) - { - final double limit = this.getTransferLimit( stack ); - final IAEItemPowerStorage poweredItem = (IAEItemPowerStorage) stack.getItem(); - final double convertedPower = PowerUnits.EU.convertTo( PowerUnits.AE, amount ); + @Override + public double charge(ItemStack stack, double amount, int tier, boolean ignoreTransferLimit, boolean simulate) { + final double limit = this.getTransferLimit(stack); + final IAEItemPowerStorage poweredItem = (IAEItemPowerStorage) stack.getItem(); + final double convertedPower = PowerUnits.EU.convertTo(PowerUnits.AE, amount); - double toAdd = convertedPower; + double toAdd = convertedPower; - if( !ignoreTransferLimit && amount > limit ) - { - toAdd = limit; - } + if (!ignoreTransferLimit && amount > limit) { + toAdd = limit; + } - final double overflow = poweredItem.injectAEPower( stack, toAdd, simulate ? Actionable.SIMULATE : Actionable.MODULATE ); - final double addedAmount = toAdd - (int) overflow; + final double overflow = poweredItem.injectAEPower(stack, toAdd, simulate ? Actionable.SIMULATE : Actionable.MODULATE); + final double addedAmount = toAdd - (int) overflow; - return PowerUnits.AE.convertTo( PowerUnits.EU, addedAmount ); - } + return PowerUnits.AE.convertTo(PowerUnits.EU, addedAmount); + } - @Override - public double discharge( ItemStack stack, double amount, int tier, boolean ignoreTransferLimit, boolean externally, boolean simulate ) - { - return 0; - } + @Override + public double discharge(ItemStack stack, double amount, int tier, boolean ignoreTransferLimit, boolean externally, boolean simulate) { + return 0; + } - @Override - public double getCharge( ItemStack stack ) - { - final IAEItemPowerStorage poweredItem = (IAEItemPowerStorage) stack.getItem(); - return (int) PowerUnits.AE.convertTo( PowerUnits.EU, poweredItem.getAECurrentPower( stack ) ); - } + @Override + public double getCharge(ItemStack stack) { + final IAEItemPowerStorage poweredItem = (IAEItemPowerStorage) stack.getItem(); + return (int) PowerUnits.AE.convertTo(PowerUnits.EU, poweredItem.getAECurrentPower(stack)); + } - @Override - public double getMaxCharge( ItemStack stack ) - { - final IAEItemPowerStorage poweredItem = (IAEItemPowerStorage) stack.getItem(); - return PowerUnits.AE.convertTo( PowerUnits.EU, poweredItem.getAEMaxPower( stack ) ); - } + @Override + public double getMaxCharge(ItemStack stack) { + final IAEItemPowerStorage poweredItem = (IAEItemPowerStorage) stack.getItem(); + return PowerUnits.AE.convertTo(PowerUnits.EU, poweredItem.getAEMaxPower(stack)); + } - @Override - public boolean canUse( ItemStack stack, double amount ) - { - return this.getCharge( stack ) > amount; - } + @Override + public boolean canUse(ItemStack stack, double amount) { + return this.getCharge(stack) > amount; + } - @Override - public boolean use( ItemStack stack, double amount, EntityLivingBase entity ) - { - final IAEItemPowerStorage poweredItem = (IAEItemPowerStorage) stack.getItem(); + @Override + public boolean use(ItemStack stack, double amount, EntityLivingBase entity) { + final IAEItemPowerStorage poweredItem = (IAEItemPowerStorage) stack.getItem(); - if( this.canUse( stack, amount ) ) - { - final double toUse = PowerUnits.EU.convertTo( PowerUnits.AE, amount ); + if (this.canUse(stack, amount)) { + final double toUse = PowerUnits.EU.convertTo(PowerUnits.AE, amount); - poweredItem.extractAEPower( stack, toUse, Actionable.MODULATE ); + poweredItem.extractAEPower(stack, toUse, Actionable.MODULATE); - return true; - } - return false; - } + return true; + } + return false; + } - @Override - public void chargeFromArmor( ItemStack stack, EntityLivingBase entity ) - { - // TODO Auto-generated method stub - } + @Override + public void chargeFromArmor(ItemStack stack, EntityLivingBase entity) { + // TODO Auto-generated method stub + } - @Override - public String getToolTip( ItemStack stack ) - { - return null; - } + @Override + public String getToolTip(ItemStack stack) { + return null; + } - @Override - public int getTier( ItemStack stack ) - { - return 1; - } + @Override + public int getTier(ItemStack stack) { + return 1; + } - @Override - public boolean handles( ItemStack stack ) - { - return !stack.isEmpty() && ( stack.getItem() instanceof IAEItemPowerStorage ); - } + @Override + public boolean handles(ItemStack stack) { + return !stack.isEmpty() && (stack.getItem() instanceof IAEItemPowerStorage); + } - private double getTransferLimit( ItemStack itemStack ) - { - return Math.max( 32, this.getMaxCharge( itemStack ) / 200 ); - } + private double getTransferLimit(ItemStack itemStack) { + return Math.max(32, this.getMaxCharge(itemStack) / 200); + } } diff --git a/src/main/java/appeng/integration/modules/inventorytweaks/InventoryTweaksModule.java b/src/main/java/appeng/integration/modules/inventorytweaks/InventoryTweaksModule.java index c428a9a5f..ad3d3d9c4 100644 --- a/src/main/java/appeng/integration/modules/inventorytweaks/InventoryTweaksModule.java +++ b/src/main/java/appeng/integration/modules/inventorytweaks/InventoryTweaksModule.java @@ -1,41 +1,31 @@ - package appeng.integration.modules.inventorytweaks; +import appeng.integration.abstraction.IInvTweaks; +import invtweaks.api.InvTweaksAPI; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.Loader; -import invtweaks.api.InvTweaksAPI; -import appeng.integration.abstraction.IInvTweaks; +public class InventoryTweaksModule implements IInvTweaks { + InvTweaksAPI api = null; + public InventoryTweaksModule() { + try { + this.api = (InvTweaksAPI) Class.forName("invtweaks.forge.InvTweaksMod", true, Loader.instance().getModClassLoader()) + .getField("instance") + .get(null); + } catch (Exception ex) { + } + } -public class InventoryTweaksModule implements IInvTweaks -{ - InvTweaksAPI api = null; + @Override + public boolean isEnabled() { + return this.api != null; + } - public InventoryTweaksModule() - { - try - { - this.api = (InvTweaksAPI) Class.forName( "invtweaks.forge.InvTweaksMod", true, Loader.instance().getModClassLoader() ) - .getField( "instance" ) - .get( null ); - } - catch( Exception ex ) - { - } - } - - @Override - public boolean isEnabled() - { - return this.api != null; - } - - @Override - public int compareItems( ItemStack i, ItemStack j ) - { - return this.api.compareItems( i, j ); - } + @Override + public int compareItems(ItemStack i, ItemStack j) { + return this.api.compareItems(i, j); + } } diff --git a/src/main/java/appeng/integration/modules/jei/CondenserCategory.java b/src/main/java/appeng/integration/modules/jei/CondenserCategory.java index f44e5c6ce..335a78318 100644 --- a/src/main/java/appeng/integration/modules/jei/CondenserCategory.java +++ b/src/main/java/appeng/integration/modules/jei/CondenserCategory.java @@ -19,132 +19,115 @@ package appeng.integration.modules.jei; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.resources.I18n; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - -import mezz.jei.api.IGuiHelper; -import mezz.jei.api.gui.IDrawable; -import mezz.jei.api.gui.IDrawableAnimated; -import mezz.jei.api.gui.IDrawableStatic; -import mezz.jei.api.gui.IGuiItemStackGroup; -import mezz.jei.api.gui.IRecipeLayout; -import mezz.jei.api.ingredients.IIngredients; -import mezz.jei.api.recipe.IRecipeCategory; - import appeng.api.AEApi; import appeng.api.config.CondenserOutput; import appeng.api.definitions.IMaterials; import appeng.api.implementations.items.IStorageComponent; import appeng.core.AppEng; import appeng.tile.misc.TileCondenser; +import mezz.jei.api.IGuiHelper; +import mezz.jei.api.gui.*; +import mezz.jei.api.ingredients.IIngredients; +import mezz.jei.api.recipe.IRecipeCategory; +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.I18n; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; + +import java.util.ArrayList; +import java.util.List; -class CondenserCategory implements IRecipeCategory -{ +class CondenserCategory implements IRecipeCategory { - public static final String UID = "appliedenergistics2.condenser"; + public static final String UID = "appliedenergistics2.condenser"; - private final String localizedName; + private final String localizedName; - private final IDrawable background; + private final IDrawable background; - private final IDrawable iconTrash; + private final IDrawable iconTrash; - private final IDrawableAnimated progress; + private final IDrawableAnimated progress; - private final IDrawable iconButton; + private final IDrawable iconButton; - public CondenserCategory( IGuiHelper guiHelper ) - { - this.localizedName = I18n.format( "gui.appliedenergistics2.Condenser" ); + public CondenserCategory(IGuiHelper guiHelper) { + this.localizedName = I18n.format("gui.appliedenergistics2.Condenser"); - ResourceLocation location = new ResourceLocation( AppEng.MOD_ID, "textures/guis/condenser.png" ); - this.background = guiHelper.createDrawable( location, 50, 25, 94, 48 ); + ResourceLocation location = new ResourceLocation(AppEng.MOD_ID, "textures/guis/condenser.png"); + this.background = guiHelper.createDrawable(location, 50, 25, 94, 48); - ResourceLocation statesLocation = new ResourceLocation( AppEng.MOD_ID, "textures/guis/states.png" ); - this.iconTrash = guiHelper.createDrawable( statesLocation, 241, 81, 14, 14, 28, 0, 2, 0 ); - this.iconButton = guiHelper.createDrawable( statesLocation, 240, 240, 16, 16, 28, 0, 78, 0 ); + ResourceLocation statesLocation = new ResourceLocation(AppEng.MOD_ID, "textures/guis/states.png"); + this.iconTrash = guiHelper.createDrawable(statesLocation, 241, 81, 14, 14, 28, 0, 2, 0); + this.iconButton = guiHelper.createDrawable(statesLocation, 240, 240, 16, 16, 28, 0, 78, 0); - IDrawableStatic progressDrawable = guiHelper.createDrawable( location, 178, 25, 6, 18, 0, 0, 70, 0 ); - this.progress = guiHelper.createAnimatedDrawable( progressDrawable, 40, IDrawableAnimated.StartDirection.BOTTOM, false ); - } + IDrawableStatic progressDrawable = guiHelper.createDrawable(location, 178, 25, 6, 18, 0, 0, 70, 0); + this.progress = guiHelper.createAnimatedDrawable(progressDrawable, 40, IDrawableAnimated.StartDirection.BOTTOM, false); + } - @Override - public String getUid() - { - return CondenserCategory.UID; - } + @Override + public String getUid() { + return CondenserCategory.UID; + } - @Override - public String getTitle() - { - return this.localizedName; - } + @Override + public String getTitle() { + return this.localizedName; + } - /** - * Return the name of the mod associated with this recipe category. - * Used for the recipe category tab's tooltip. - * - * @since JEI 4.5.0 - */ - @Override - public String getModName() - { - return AppEng.MOD_NAME; - } + /** + * Return the name of the mod associated with this recipe category. + * Used for the recipe category tab's tooltip. + * + * @since JEI 4.5.0 + */ + @Override + public String getModName() { + return AppEng.MOD_NAME; + } - @Override - public IDrawable getBackground() - { - return this.background; - } + @Override + public IDrawable getBackground() { + return this.background; + } - @Override - public void drawExtras( Minecraft minecraft ) - { - this.progress.draw( minecraft ); - this.iconTrash.draw( minecraft ); - this.iconButton.draw( minecraft ); - } + @Override + public void drawExtras(Minecraft minecraft) { + this.progress.draw(minecraft); + this.iconTrash.draw(minecraft); + this.iconButton.draw(minecraft); + } - @Override - public void setRecipe( IRecipeLayout recipeLayout, CondenserOutputWrapper recipeWrapper, IIngredients ingredients ) - { - IGuiItemStackGroup itemStacks = recipeLayout.getItemStacks(); - itemStacks.init( 0, false, 54, 26 ); + @Override + public void setRecipe(IRecipeLayout recipeLayout, CondenserOutputWrapper recipeWrapper, IIngredients ingredients) { + IGuiItemStackGroup itemStacks = recipeLayout.getItemStacks(); + itemStacks.init(0, false, 54, 26); - // Get all storage cells and cycle them through a fake input slot - itemStacks.init( 1, true, 50, 0 ); - itemStacks.set( 1, this.getViableStorageComponents( recipeWrapper ) ); + // Get all storage cells and cycle them through a fake input slot + itemStacks.init(1, true, 50, 0); + itemStacks.set(1, this.getViableStorageComponents(recipeWrapper)); - // This only sets the output - itemStacks.set( ingredients ); - } + // This only sets the output + itemStacks.set(ingredients); + } - private List getViableStorageComponents( CondenserOutputWrapper recipeWrapper ) - { - CondenserOutput condenserOutput = recipeWrapper.getCondenserOutput(); - IMaterials materials = AEApi.instance().definitions().materials(); - List viableComponents = new ArrayList<>(); - materials.cell1kPart().maybeStack( 1 ).ifPresent( itemStack -> this.addViableComponent( condenserOutput, viableComponents, itemStack ) ); - materials.cell4kPart().maybeStack( 1 ).ifPresent( itemStack -> this.addViableComponent( condenserOutput, viableComponents, itemStack ) ); - materials.cell16kPart().maybeStack( 1 ).ifPresent( itemStack -> this.addViableComponent( condenserOutput, viableComponents, itemStack ) ); - materials.cell64kPart().maybeStack( 1 ).ifPresent( itemStack -> this.addViableComponent( condenserOutput, viableComponents, itemStack ) ); - return viableComponents; - } + private List getViableStorageComponents(CondenserOutputWrapper recipeWrapper) { + CondenserOutput condenserOutput = recipeWrapper.getCondenserOutput(); + IMaterials materials = AEApi.instance().definitions().materials(); + List viableComponents = new ArrayList<>(); + materials.cell1kPart().maybeStack(1).ifPresent(itemStack -> this.addViableComponent(condenserOutput, viableComponents, itemStack)); + materials.cell4kPart().maybeStack(1).ifPresent(itemStack -> this.addViableComponent(condenserOutput, viableComponents, itemStack)); + materials.cell16kPart().maybeStack(1).ifPresent(itemStack -> this.addViableComponent(condenserOutput, viableComponents, itemStack)); + materials.cell64kPart().maybeStack(1).ifPresent(itemStack -> this.addViableComponent(condenserOutput, viableComponents, itemStack)); + return viableComponents; + } - private void addViableComponent( CondenserOutput condenserOutput, List viableComponents, ItemStack itemStack ) - { - IStorageComponent comp = (IStorageComponent) itemStack.getItem(); - int storage = comp.getBytes( itemStack ) * TileCondenser.BYTE_MULTIPLIER; - if( storage >= condenserOutput.requiredPower ) - { - viableComponents.add( itemStack ); - } - } + private void addViableComponent(CondenserOutput condenserOutput, List viableComponents, ItemStack itemStack) { + IStorageComponent comp = (IStorageComponent) itemStack.getItem(); + int storage = comp.getBytes(itemStack) * TileCondenser.BYTE_MULTIPLIER; + if (storage >= condenserOutput.requiredPower) { + viableComponents.add(itemStack); + } + } } diff --git a/src/main/java/appeng/integration/modules/jei/CondenserOutputHandler.java b/src/main/java/appeng/integration/modules/jei/CondenserOutputHandler.java index 9369960e6..5e5509e1e 100644 --- a/src/main/java/appeng/integration/modules/jei/CondenserOutputHandler.java +++ b/src/main/java/appeng/integration/modules/jei/CondenserOutputHandler.java @@ -19,47 +19,41 @@ package appeng.integration.modules.jei; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - +import appeng.api.config.CondenserOutput; +import appeng.core.AppEng; import mezz.jei.api.IGuiHelper; import mezz.jei.api.gui.IDrawable; import mezz.jei.api.recipe.IRecipeWrapper; import mezz.jei.api.recipe.IRecipeWrapperFactory; - -import appeng.api.config.CondenserOutput; -import appeng.core.AppEng; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; -class CondenserOutputHandler implements IRecipeWrapperFactory -{ +class CondenserOutputHandler implements IRecipeWrapperFactory { - private final ItemStack matterBall; - private final ItemStack singularity; - private final IDrawable iconButtonMatterBall; - private final IDrawable iconButtonSingularity; + private final ItemStack matterBall; + private final ItemStack singularity; + private final IDrawable iconButtonMatterBall; + private final IDrawable iconButtonSingularity; - public CondenserOutputHandler( IGuiHelper guiHelper, ItemStack matterBall, ItemStack singularity ) - { - this.matterBall = matterBall; - this.singularity = singularity; + public CondenserOutputHandler(IGuiHelper guiHelper, ItemStack matterBall, ItemStack singularity) { + this.matterBall = matterBall; + this.singularity = singularity; - ResourceLocation statesLocation = new ResourceLocation( AppEng.MOD_ID, "textures/guis/states.png" ); - this.iconButtonMatterBall = guiHelper.createDrawable( statesLocation, 16, 112, 14, 14, 28, 0, 78, 0 ); - this.iconButtonSingularity = guiHelper.createDrawable( statesLocation, 32, 112, 14, 14, 28, 0, 78, 0 ); - } + ResourceLocation statesLocation = new ResourceLocation(AppEng.MOD_ID, "textures/guis/states.png"); + this.iconButtonMatterBall = guiHelper.createDrawable(statesLocation, 16, 112, 14, 14, 28, 0, 78, 0); + this.iconButtonSingularity = guiHelper.createDrawable(statesLocation, 32, 112, 14, 14, 28, 0, 78, 0); + } - @Override - public IRecipeWrapper getRecipeWrapper( CondenserOutput recipe ) - { - switch( recipe ) - { - case MATTER_BALLS: - return new CondenserOutputWrapper( recipe, this.matterBall, this.iconButtonMatterBall ); - case SINGULARITY: - return new CondenserOutputWrapper( recipe, this.singularity, this.iconButtonSingularity ); - default: - return null; - } - } + @Override + public IRecipeWrapper getRecipeWrapper(CondenserOutput recipe) { + switch (recipe) { + case MATTER_BALLS: + return new CondenserOutputWrapper(recipe, this.matterBall, this.iconButtonMatterBall); + case SINGULARITY: + return new CondenserOutputWrapper(recipe, this.singularity, this.iconButtonSingularity); + default: + return null; + } + } } diff --git a/src/main/java/appeng/integration/modules/jei/CondenserOutputWrapper.java b/src/main/java/appeng/integration/modules/jei/CondenserOutputWrapper.java index b7754333f..4c1c0afe0 100644 --- a/src/main/java/appeng/integration/modules/jei/CondenserOutputWrapper.java +++ b/src/main/java/appeng/integration/modules/jei/CondenserOutputWrapper.java @@ -19,82 +19,70 @@ package appeng.integration.modules.jei; -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nullable; - +import appeng.api.config.CondenserOutput; import com.google.common.base.Splitter; - +import mezz.jei.api.gui.IDrawable; +import mezz.jei.api.ingredients.IIngredients; +import mezz.jei.api.recipe.IRecipeWrapper; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.client.config.HoverChecker; -import mezz.jei.api.gui.IDrawable; -import mezz.jei.api.ingredients.IIngredients; -import mezz.jei.api.recipe.IRecipeWrapper; - -import appeng.api.config.CondenserOutput; +import javax.annotation.Nullable; +import java.util.Collections; +import java.util.List; -class CondenserOutputWrapper implements IRecipeWrapper -{ - private final ItemStack outputItem; +class CondenserOutputWrapper implements IRecipeWrapper { + private final ItemStack outputItem; - private final CondenserOutput condenserOutput; + private final CondenserOutput condenserOutput; - private final HoverChecker buttonHoverChecker; + private final HoverChecker buttonHoverChecker; - private final IDrawable buttonIcon; + private final IDrawable buttonIcon; - CondenserOutputWrapper( CondenserOutput condenserOutput, ItemStack outputItem, IDrawable buttonIcon ) - { - this.condenserOutput = condenserOutput; - this.outputItem = outputItem; - this.buttonIcon = buttonIcon; - this.buttonHoverChecker = new HoverChecker( 28, 28 + 16, 78, 78 + 16, 0 ); - } + CondenserOutputWrapper(CondenserOutput condenserOutput, ItemStack outputItem, IDrawable buttonIcon) { + this.condenserOutput = condenserOutput; + this.outputItem = outputItem; + this.buttonIcon = buttonIcon; + this.buttonHoverChecker = new HoverChecker(28, 28 + 16, 78, 78 + 16, 0); + } - @Override - public void getIngredients( IIngredients ingredients ) - { - ingredients.setOutput( ItemStack.class, this.outputItem ); - } + @Override + public void getIngredients(IIngredients ingredients) { + ingredients.setOutput(ItemStack.class, this.outputItem); + } - public CondenserOutput getCondenserOutput() - { - return this.condenserOutput; - } + public CondenserOutput getCondenserOutput() { + return this.condenserOutput; + } - @Nullable - @Override - public List getTooltipStrings( int mouseX, int mouseY ) - { - if( this.buttonHoverChecker.checkHover( mouseX, mouseY ) ) - { - String key; + @Nullable + @Override + public List getTooltipStrings(int mouseX, int mouseY) { + if (this.buttonHoverChecker.checkHover(mouseX, mouseY)) { + String key; - switch( this.condenserOutput ) - { - case MATTER_BALLS: - key = "gui.tooltips.appliedenergistics2.MatterBalls"; - break; - case SINGULARITY: - key = "gui.tooltips.appliedenergistics2.Singularity"; - break; - default: - return Collections.emptyList(); - } + switch (this.condenserOutput) { + case MATTER_BALLS: + key = "gui.tooltips.appliedenergistics2.MatterBalls"; + break; + case SINGULARITY: + key = "gui.tooltips.appliedenergistics2.Singularity"; + break; + default: + return Collections.emptyList(); + } - return Splitter.on( "\\n" ).splitToList( I18n.format( key, this.condenserOutput.requiredPower ) ); - } - return Collections.emptyList(); - } + return Splitter.on("\\n").splitToList(I18n.format(key, this.condenserOutput.requiredPower)); + } + return Collections.emptyList(); + } - @Override - public void drawInfo( Minecraft minecraft, int recipeWidth, int recipeHeight, int mouseX, int mouseY ) - { - this.buttonIcon.draw( minecraft ); - } + @Override + public void drawInfo(Minecraft minecraft, int recipeWidth, int recipeHeight, int mouseX, int mouseY) { + this.buttonIcon.draw(minecraft); + } } diff --git a/src/main/java/appeng/integration/modules/jei/FacadeRecipeWrapper.java b/src/main/java/appeng/integration/modules/jei/FacadeRecipeWrapper.java index badd96b73..f407099ff 100644 --- a/src/main/java/appeng/integration/modules/jei/FacadeRecipeWrapper.java +++ b/src/main/java/appeng/integration/modules/jei/FacadeRecipeWrapper.java @@ -19,64 +19,58 @@ package appeng.integration.modules.jei; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.item.ItemStack; - import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.wrapper.IShapedCraftingRecipeWrapper; +import net.minecraft.item.ItemStack; + +import java.util.ArrayList; +import java.util.List; /** * Acts as a fake facade recipe wrapper, created by {@link FacadeRegistryPlugin}. */ -class FacadeRecipeWrapper implements IShapedCraftingRecipeWrapper -{ +class FacadeRecipeWrapper implements IShapedCraftingRecipeWrapper { - private final ItemStack textureItem; + private final ItemStack textureItem; - private final ItemStack cableAnchor; + private final ItemStack cableAnchor; - private final ItemStack facade; + private final ItemStack facade; - FacadeRecipeWrapper( ItemStack textureItem, ItemStack cableAnchor, ItemStack facade ) - { - this.textureItem = textureItem; - this.cableAnchor = cableAnchor; - this.facade = facade; - } + FacadeRecipeWrapper(ItemStack textureItem, ItemStack cableAnchor, ItemStack facade) { + this.textureItem = textureItem; + this.cableAnchor = cableAnchor; + this.facade = facade; + } - @Override - public int getWidth() - { - return 3; - } + @Override + public int getWidth() { + return 3; + } - @Override - public int getHeight() - { - return 3; - } + @Override + public int getHeight() { + return 3; + } - @Override - public void getIngredients( IIngredients ingredients ) - { - List input = new ArrayList<>( 9 ); + @Override + public void getIngredients(IIngredients ingredients) { + List input = new ArrayList<>(9); - input.add( ItemStack.EMPTY ); - input.add( this.cableAnchor ); - input.add( ItemStack.EMPTY ); + input.add(ItemStack.EMPTY); + input.add(this.cableAnchor); + input.add(ItemStack.EMPTY); - input.add( this.cableAnchor ); - input.add( this.textureItem ); - input.add( this.cableAnchor ); + input.add(this.cableAnchor); + input.add(this.textureItem); + input.add(this.cableAnchor); - input.add( ItemStack.EMPTY ); - input.add( this.cableAnchor ); - input.add( ItemStack.EMPTY ); + input.add(ItemStack.EMPTY); + input.add(this.cableAnchor); + input.add(ItemStack.EMPTY); - ingredients.setInputs( ItemStack.class, input ); - ingredients.setOutput( ItemStack.class, this.facade ); - } + ingredients.setInputs(ItemStack.class, input); + ingredients.setOutput(ItemStack.class, this.facade); + } } diff --git a/src/main/java/appeng/integration/modules/jei/FacadeRegistryPlugin.java b/src/main/java/appeng/integration/modules/jei/FacadeRegistryPlugin.java index 3c20d5b23..90f3766f3 100644 --- a/src/main/java/appeng/integration/modules/jei/FacadeRegistryPlugin.java +++ b/src/main/java/appeng/integration/modules/jei/FacadeRegistryPlugin.java @@ -19,101 +19,79 @@ package appeng.integration.modules.jei; -import java.util.Collections; -import java.util.List; - +import appeng.items.parts.ItemFacade; +import mezz.jei.api.recipe.*; import net.minecraft.item.ItemStack; -import mezz.jei.api.recipe.IFocus; -import mezz.jei.api.recipe.IRecipeCategory; -import mezz.jei.api.recipe.IRecipeRegistryPlugin; -import mezz.jei.api.recipe.IRecipeWrapper; -import mezz.jei.api.recipe.VanillaRecipeCategoryUid; - -import appeng.items.parts.ItemFacade; +import java.util.Collections; +import java.util.List; /** * This plugin will dynamically add facade recipes for any item that can be turned into a facade. */ -class FacadeRegistryPlugin implements IRecipeRegistryPlugin -{ +class FacadeRegistryPlugin implements IRecipeRegistryPlugin { - private final ItemFacade itemFacade; + private final ItemFacade itemFacade; - private final ItemStack cableAnchor; + private final ItemStack cableAnchor; - FacadeRegistryPlugin( ItemFacade itemFacade, ItemStack cableAnchor ) - { - this.itemFacade = itemFacade; - this.cableAnchor = cableAnchor; - } + FacadeRegistryPlugin(ItemFacade itemFacade, ItemStack cableAnchor) { + this.itemFacade = itemFacade; + this.cableAnchor = cableAnchor; + } - @Override - public List getRecipeCategoryUids( IFocus focus ) - { - if( focus.getMode() == IFocus.Mode.OUTPUT && focus.getValue() instanceof ItemStack ) - { - // Looking up how a certain facade is crafted - ItemStack itemStack = (ItemStack) focus.getValue(); - if( itemStack.getItem() instanceof ItemFacade ) - { - return Collections.singletonList( VanillaRecipeCategoryUid.CRAFTING ); - } - } - else if( focus.getMode() == IFocus.Mode.INPUT && focus.getValue() instanceof ItemStack ) - { - // Looking up if a certain block can be used to make a facade - ItemStack itemStack = (ItemStack) focus.getValue(); + @Override + public List getRecipeCategoryUids(IFocus focus) { + if (focus.getMode() == IFocus.Mode.OUTPUT && focus.getValue() instanceof ItemStack) { + // Looking up how a certain facade is crafted + ItemStack itemStack = (ItemStack) focus.getValue(); + if (itemStack.getItem() instanceof ItemFacade) { + return Collections.singletonList(VanillaRecipeCategoryUid.CRAFTING); + } + } else if (focus.getMode() == IFocus.Mode.INPUT && focus.getValue() instanceof ItemStack) { + // Looking up if a certain block can be used to make a facade + ItemStack itemStack = (ItemStack) focus.getValue(); - if( !this.itemFacade.createFacadeForItem( itemStack, true ).isEmpty() ) - { - return Collections.singletonList( VanillaRecipeCategoryUid.CRAFTING ); - } - } + if (!this.itemFacade.createFacadeForItem(itemStack, true).isEmpty()) { + return Collections.singletonList(VanillaRecipeCategoryUid.CRAFTING); + } + } - return Collections.emptyList(); - } + return Collections.emptyList(); + } - @SuppressWarnings( "unchecked" ) - @Override - public List getRecipeWrappers( IRecipeCategory recipeCategory, IFocus focus ) - { - if( !VanillaRecipeCategoryUid.CRAFTING.equals( recipeCategory.getUid() ) ) - { - return Collections.emptyList(); - } + @SuppressWarnings("unchecked") + @Override + public List getRecipeWrappers(IRecipeCategory recipeCategory, IFocus focus) { + if (!VanillaRecipeCategoryUid.CRAFTING.equals(recipeCategory.getUid())) { + return Collections.emptyList(); + } - if( focus.getMode() == IFocus.Mode.OUTPUT && focus.getValue() instanceof ItemStack ) - { - // Looking up how a certain facade is crafted - ItemStack itemStack = (ItemStack) focus.getValue(); - if( itemStack.getItem() instanceof ItemFacade ) - { - ItemFacade facadeItem = (ItemFacade) itemStack.getItem(); - ItemStack textureItem = facadeItem.getTextureItem( itemStack ); - return Collections.singletonList( (T) new FacadeRecipeWrapper( textureItem, this.cableAnchor, itemStack ) ); - } - } - else if( focus.getMode() == IFocus.Mode.INPUT && focus.getValue() instanceof ItemStack ) - { - // Looking up if a certain block can be used to make a facade + if (focus.getMode() == IFocus.Mode.OUTPUT && focus.getValue() instanceof ItemStack) { + // Looking up how a certain facade is crafted + ItemStack itemStack = (ItemStack) focus.getValue(); + if (itemStack.getItem() instanceof ItemFacade) { + ItemFacade facadeItem = (ItemFacade) itemStack.getItem(); + ItemStack textureItem = facadeItem.getTextureItem(itemStack); + return Collections.singletonList((T) new FacadeRecipeWrapper(textureItem, this.cableAnchor, itemStack)); + } + } else if (focus.getMode() == IFocus.Mode.INPUT && focus.getValue() instanceof ItemStack) { + // Looking up if a certain block can be used to make a facade - ItemStack itemStack = (ItemStack) focus.getValue(); - ItemStack facade = this.itemFacade.createFacadeForItem( itemStack, false ); + ItemStack itemStack = (ItemStack) focus.getValue(); + ItemStack facade = this.itemFacade.createFacadeForItem(itemStack, false); - if( !facade.isEmpty() ) - { - return Collections.singletonList( (T) new FacadeRecipeWrapper( itemStack, this.cableAnchor, facade ) ); - } - } + if (!facade.isEmpty()) { + return Collections.singletonList((T) new FacadeRecipeWrapper(itemStack, this.cableAnchor, facade)); + } + } - return Collections.emptyList(); - } + return Collections.emptyList(); + } - @Override - public List getRecipeWrappers( IRecipeCategory recipeCategory ) - { - return Collections.emptyList(); - } + @Override + public List getRecipeWrappers(IRecipeCategory recipeCategory) { + return Collections.emptyList(); + } } diff --git a/src/main/java/appeng/integration/modules/jei/GrinderRecipeCategory.java b/src/main/java/appeng/integration/modules/jei/GrinderRecipeCategory.java index cfd09d818..125ec4cbb 100644 --- a/src/main/java/appeng/integration/modules/jei/GrinderRecipeCategory.java +++ b/src/main/java/appeng/integration/modules/jei/GrinderRecipeCategory.java @@ -19,9 +19,7 @@ package appeng.integration.modules.jei; -import net.minecraft.client.resources.I18n; -import net.minecraft.util.ResourceLocation; - +import appeng.core.AppEng; import mezz.jei.api.IGuiHelper; import mezz.jei.api.IJeiHelpers; import mezz.jei.api.gui.IDrawable; @@ -30,73 +28,64 @@ import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeCategory; import mezz.jei.api.recipe.IRecipeCategoryRegistration; - -import appeng.core.AppEng; +import net.minecraft.client.resources.I18n; +import net.minecraft.util.ResourceLocation; -class GrinderRecipeCategory implements IRecipeCategory, IRecipeCategoryRegistration -{ +class GrinderRecipeCategory implements IRecipeCategory, IRecipeCategoryRegistration { - public static final String UID = "appliedenergistics2.grinder"; + public static final String UID = "appliedenergistics2.grinder"; - private final String localizedName; + private final String localizedName; - private final IDrawable background; + private final IDrawable background; - public GrinderRecipeCategory( IGuiHelper guiHelper ) - { - this.localizedName = I18n.format( "tile.appliedenergistics2.grindstone.name" ); + public GrinderRecipeCategory(IGuiHelper guiHelper) { + this.localizedName = I18n.format("tile.appliedenergistics2.grindstone.name"); - ResourceLocation location = new ResourceLocation( AppEng.MOD_ID, "textures/guis/grinder.png" ); - this.background = guiHelper.createDrawable( location, 11, 16, 154, 70 ); - } + ResourceLocation location = new ResourceLocation(AppEng.MOD_ID, "textures/guis/grinder.png"); + this.background = guiHelper.createDrawable(location, 11, 16, 154, 70); + } - @Override - public String getModName() - { - return AppEng.MOD_NAME; - } + @Override + public String getModName() { + return AppEng.MOD_NAME; + } - @Override - public String getUid() - { - return GrinderRecipeCategory.UID; - } + @Override + public String getUid() { + return GrinderRecipeCategory.UID; + } - @Override - public String getTitle() - { - return this.localizedName; - } + @Override + public String getTitle() { + return this.localizedName; + } - @Override - public IDrawable getBackground() - { - return this.background; - } + @Override + public IDrawable getBackground() { + return this.background; + } - @Override - public void setRecipe( IRecipeLayout recipeLayout, GrinderRecipeWrapper recipeWrapper, IIngredients ingredients ) - { - IGuiItemStackGroup itemStacks = recipeLayout.getItemStacks(); + @Override + public void setRecipe(IRecipeLayout recipeLayout, GrinderRecipeWrapper recipeWrapper, IIngredients ingredients) { + IGuiItemStackGroup itemStacks = recipeLayout.getItemStacks(); - itemStacks.init( 0, true, 0, 0 ); - itemStacks.init( 1, false, 100, 46 ); - itemStacks.init( 2, false, 118, 46 ); - itemStacks.init( 3, false, 136, 46 ); + itemStacks.init(0, true, 0, 0); + itemStacks.init(1, false, 100, 46); + itemStacks.init(2, false, 118, 46); + itemStacks.init(3, false, 136, 46); - itemStacks.set( ingredients ); - } + itemStacks.set(ingredients); + } - @Override - public void addRecipeCategories( IRecipeCategory... recipeCategories ) - { + @Override + public void addRecipeCategories(IRecipeCategory... recipeCategories) { - } + } - @Override - public IJeiHelpers getJeiHelpers() - { - return null; - } + @Override + public IJeiHelpers getJeiHelpers() { + return null; + } } diff --git a/src/main/java/appeng/integration/modules/jei/GrinderRecipeHandler.java b/src/main/java/appeng/integration/modules/jei/GrinderRecipeHandler.java index 74853e20d..e44aa7b42 100644 --- a/src/main/java/appeng/integration/modules/jei/GrinderRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/jei/GrinderRecipeHandler.java @@ -19,17 +19,14 @@ package appeng.integration.modules.jei; +import appeng.api.features.IGrinderRecipe; import mezz.jei.api.recipe.IRecipeWrapper; import mezz.jei.api.recipe.IRecipeWrapperFactory; -import appeng.api.features.IGrinderRecipe; - -class GrinderRecipeHandler implements IRecipeWrapperFactory -{ - @Override - public IRecipeWrapper getRecipeWrapper( IGrinderRecipe recipe ) - { - return new GrinderRecipeWrapper( recipe ); - } +class GrinderRecipeHandler implements IRecipeWrapperFactory { + @Override + public IRecipeWrapper getRecipeWrapper(IGrinderRecipe recipe) { + return new GrinderRecipeWrapper(recipe); + } } diff --git a/src/main/java/appeng/integration/modules/jei/GrinderRecipeWrapper.java b/src/main/java/appeng/integration/modules/jei/GrinderRecipeWrapper.java index 016c478e8..d0ee15882 100644 --- a/src/main/java/appeng/integration/modules/jei/GrinderRecipeWrapper.java +++ b/src/main/java/appeng/integration/modules/jei/GrinderRecipeWrapper.java @@ -19,71 +19,63 @@ package appeng.integration.modules.jei; -import java.awt.Color; -import java.util.ArrayList; -import java.util.List; - +import appeng.api.features.IGrinderRecipe; +import mezz.jei.api.ingredients.IIngredients; +import mezz.jei.api.recipe.IRecipeWrapper; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.item.ItemStack; -import mezz.jei.api.ingredients.IIngredients; -import mezz.jei.api.recipe.IRecipeWrapper; - -import appeng.api.features.IGrinderRecipe; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; -class GrinderRecipeWrapper implements IRecipeWrapper -{ +class GrinderRecipeWrapper implements IRecipeWrapper { - private final IGrinderRecipe recipe; + private final IGrinderRecipe recipe; - GrinderRecipeWrapper( IGrinderRecipe recipe ) - { - this.recipe = recipe; - } + GrinderRecipeWrapper(IGrinderRecipe recipe) { + this.recipe = recipe; + } - @Override - public void getIngredients( IIngredients ingredients ) - { - ingredients.setInput( ItemStack.class, this.recipe.getInput() ); - List outputs = new ArrayList<>( 3 ); - outputs.add( this.recipe.getOutput() ); - this.recipe.getOptionalOutput().ifPresent( outputs::add ); - this.recipe.getSecondOptionalOutput().ifPresent( outputs::add ); - ingredients.setOutputs( ItemStack.class, outputs ); - } + @Override + public void getIngredients(IIngredients ingredients) { + ingredients.setInput(ItemStack.class, this.recipe.getInput()); + List outputs = new ArrayList<>(3); + outputs.add(this.recipe.getOutput()); + this.recipe.getOptionalOutput().ifPresent(outputs::add); + this.recipe.getSecondOptionalOutput().ifPresent(outputs::add); + ingredients.setOutputs(ItemStack.class, outputs); + } - @Override - public void drawInfo( Minecraft minecraft, int recipeWidth, int recipeHeight, int mouseX, int mouseY ) - { + @Override + public void drawInfo(Minecraft minecraft, int recipeWidth, int recipeHeight, int mouseX, int mouseY) { - FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - int x = 118; + int x = 118; - final float scale = 0.85f; - final float invScale = 1 / scale; - GlStateManager.scale( scale, scale, 1 ); + final float scale = 0.85f; + final float invScale = 1 / scale; + GlStateManager.scale(scale, scale, 1); - if( this.recipe.getOptionalOutput() != null ) - { - String text = String.format( "%d%%", (int) ( this.recipe.getOptionalChance() * 100 ) ); - float width = fr.getStringWidth( text ) * scale; - int xScaled = Math.round( ( x + ( 18 - width ) / 2 ) * invScale ); - fr.drawString( text, xScaled, (int) ( 65 * invScale ), Color.gray.getRGB() ); - x += 18; - } + if (this.recipe.getOptionalOutput() != null) { + String text = String.format("%d%%", (int) (this.recipe.getOptionalChance() * 100)); + float width = fr.getStringWidth(text) * scale; + int xScaled = Math.round((x + (18 - width) / 2) * invScale); + fr.drawString(text, xScaled, (int) (65 * invScale), Color.gray.getRGB()); + x += 18; + } - if( this.recipe.getSecondOptionalOutput() != null ) - { - String text = String.format( "%d%%", (int) ( this.recipe.getSecondOptionalChance() * 100 ) ); - float width = fr.getStringWidth( text ) * scale; - int xScaled = Math.round( ( x + ( 18 - width ) / 2 ) * invScale ); - fr.drawString( text, xScaled, (int) ( 65 * invScale ), Color.gray.getRGB() ); - } + if (this.recipe.getSecondOptionalOutput() != null) { + String text = String.format("%d%%", (int) (this.recipe.getSecondOptionalChance() * 100)); + float width = fr.getStringWidth(text) * scale; + int xScaled = Math.round((x + (18 - width) / 2) * invScale); + fr.drawString(text, xScaled, (int) (65 * invScale), Color.gray.getRGB()); + } - GlStateManager.scale( invScale, invScale, 1 ); - } + GlStateManager.scale(invScale, invScale, 1); + } } diff --git a/src/main/java/appeng/integration/modules/jei/InscriberRecipeCategory.java b/src/main/java/appeng/integration/modules/jei/InscriberRecipeCategory.java index f5415c277..2d5306d5c 100644 --- a/src/main/java/appeng/integration/modules/jei/InscriberRecipeCategory.java +++ b/src/main/java/appeng/integration/modules/jei/InscriberRecipeCategory.java @@ -19,94 +19,80 @@ package appeng.integration.modules.jei; +import appeng.core.AppEng; +import mezz.jei.api.IGuiHelper; +import mezz.jei.api.gui.*; +import mezz.jei.api.ingredients.IIngredients; +import mezz.jei.api.recipe.IRecipeCategory; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import net.minecraft.util.ResourceLocation; -import mezz.jei.api.IGuiHelper; -import mezz.jei.api.gui.IDrawable; -import mezz.jei.api.gui.IDrawableAnimated; -import mezz.jei.api.gui.IDrawableStatic; -import mezz.jei.api.gui.IGuiItemStackGroup; -import mezz.jei.api.gui.IRecipeLayout; -import mezz.jei.api.ingredients.IIngredients; -import mezz.jei.api.recipe.IRecipeCategory; -import appeng.core.AppEng; +class InscriberRecipeCategory implements IRecipeCategory { + private static final int SLOT_INPUT_TOP = 0; + private static final int SLOT_INPUT_MIDDLE = 1; + private static final int SLOT_INPUT_BOTTOM = 2; + private static final int SLOT_OUTPUT = 3; -class InscriberRecipeCategory implements IRecipeCategory -{ + static final String UID = "appliedenergistics2.inscriber"; - private static final int SLOT_INPUT_TOP = 0; - private static final int SLOT_INPUT_MIDDLE = 1; - private static final int SLOT_INPUT_BOTTOM = 2; - private static final int SLOT_OUTPUT = 3; + private final IDrawable background; - static final String UID = "appliedenergistics2.inscriber"; + private final String localizedName; - private final IDrawable background; + private final IDrawableAnimated progress; - private final String localizedName; + public InscriberRecipeCategory(IGuiHelper guiHelper) { + ResourceLocation location = new ResourceLocation(AppEng.MOD_ID, "textures/guis/inscriber.png"); + this.background = guiHelper.createDrawable(location, 44, 15, 97, 64); + this.localizedName = I18n.format("tile.appliedenergistics2.inscriber.name"); - private final IDrawableAnimated progress; + IDrawableStatic progressDrawable = guiHelper.createDrawable(location, 135, 177, 6, 18, 24, 0, 91, 0); + this.progress = guiHelper.createAnimatedDrawable(progressDrawable, 40, IDrawableAnimated.StartDirection.BOTTOM, false); + } - public InscriberRecipeCategory( IGuiHelper guiHelper ) - { - ResourceLocation location = new ResourceLocation( AppEng.MOD_ID, "textures/guis/inscriber.png" ); - this.background = guiHelper.createDrawable( location, 44, 15, 97, 64 ); - this.localizedName = I18n.format( "tile.appliedenergistics2.inscriber.name" ); + @Override + public String getUid() { + return UID; + } - IDrawableStatic progressDrawable = guiHelper.createDrawable( location, 135, 177, 6, 18, 24, 0, 91, 0 ); - this.progress = guiHelper.createAnimatedDrawable( progressDrawable, 40, IDrawableAnimated.StartDirection.BOTTOM, false ); - } + @Override + public String getTitle() { + return this.localizedName; + } - @Override - public String getUid() - { - return UID; - } + /** + * Return the name of the mod associated with this recipe category. + * Used for the recipe category tab's tooltip. + * + * @since JEI 4.5.0 + */ + @Override + public String getModName() { + return AppEng.MOD_NAME; + } - @Override - public String getTitle() - { - return this.localizedName; - } + @Override + public IDrawable getBackground() { + return this.background; + } - /** - * Return the name of the mod associated with this recipe category. - * Used for the recipe category tab's tooltip. - * - * @since JEI 4.5.0 - */ - @Override - public String getModName() - { - return AppEng.MOD_NAME; - } + @Override + public void drawExtras(Minecraft minecraft) { + this.progress.draw(minecraft); + } - @Override - public IDrawable getBackground() - { - return this.background; - } + @Override + public void setRecipe(IRecipeLayout recipeLayout, InscriberRecipeWrapper recipeWrapper, IIngredients ingredients) { + IGuiItemStackGroup itemStacks = recipeLayout.getItemStacks(); - @Override - public void drawExtras( Minecraft minecraft ) - { - this.progress.draw( minecraft ); - } + itemStacks.init(SLOT_INPUT_TOP, true, 0, 0); + itemStacks.init(SLOT_INPUT_MIDDLE, true, 18, 23); + itemStacks.init(SLOT_INPUT_BOTTOM, true, 0, 46); + itemStacks.init(SLOT_OUTPUT, false, 68, 24); - @Override - public void setRecipe( IRecipeLayout recipeLayout, InscriberRecipeWrapper recipeWrapper, IIngredients ingredients ) - { - IGuiItemStackGroup itemStacks = recipeLayout.getItemStacks(); - - itemStacks.init( SLOT_INPUT_TOP, true, 0, 0 ); - itemStacks.init( SLOT_INPUT_MIDDLE, true, 18, 23 ); - itemStacks.init( SLOT_INPUT_BOTTOM, true, 0, 46 ); - itemStacks.init( SLOT_OUTPUT, false, 68, 24 ); - - itemStacks.set( ingredients ); - } + itemStacks.set(ingredients); + } } diff --git a/src/main/java/appeng/integration/modules/jei/InscriberRecipeHandler.java b/src/main/java/appeng/integration/modules/jei/InscriberRecipeHandler.java index e87371d04..3454be2dd 100644 --- a/src/main/java/appeng/integration/modules/jei/InscriberRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/jei/InscriberRecipeHandler.java @@ -19,18 +19,15 @@ package appeng.integration.modules.jei; +import appeng.api.features.IInscriberRecipe; import mezz.jei.api.recipe.IRecipeWrapper; import mezz.jei.api.recipe.IRecipeWrapperFactory; -import appeng.api.features.IInscriberRecipe; - -class InscriberRecipeHandler implements IRecipeWrapperFactory -{ - @Override - public IRecipeWrapper getRecipeWrapper( IInscriberRecipe recipe ) - { - return new InscriberRecipeWrapper( recipe ); - } +class InscriberRecipeHandler implements IRecipeWrapperFactory { + @Override + public IRecipeWrapper getRecipeWrapper(IInscriberRecipe recipe) { + return new InscriberRecipeWrapper(recipe); + } } diff --git a/src/main/java/appeng/integration/modules/jei/InscriberRecipeWrapper.java b/src/main/java/appeng/integration/modules/jei/InscriberRecipeWrapper.java index 40e6fab53..f0fa4cbc4 100644 --- a/src/main/java/appeng/integration/modules/jei/InscriberRecipeWrapper.java +++ b/src/main/java/appeng/integration/modules/jei/InscriberRecipeWrapper.java @@ -19,37 +19,32 @@ package appeng.integration.modules.jei; +import appeng.api.features.IInscriberRecipe; +import mezz.jei.api.ingredients.IIngredients; +import mezz.jei.api.recipe.IRecipeWrapper; +import net.minecraft.item.ItemStack; + import java.util.ArrayList; import java.util.Collections; import java.util.List; -import net.minecraft.item.ItemStack; -import mezz.jei.api.ingredients.IIngredients; -import mezz.jei.api.recipe.IRecipeWrapper; +class InscriberRecipeWrapper implements IRecipeWrapper { -import appeng.api.features.IInscriberRecipe; + private final IInscriberRecipe recipe; + public InscriberRecipeWrapper(IInscriberRecipe recipe) { + this.recipe = recipe; + } -class InscriberRecipeWrapper implements IRecipeWrapper -{ + @Override + public void getIngredients(IIngredients ingredients) { + List> inputSlots = new ArrayList<>(3); + inputSlots.add(Collections.singletonList(this.recipe.getTopOptional().orElse(ItemStack.EMPTY))); + inputSlots.add(this.recipe.getInputs()); + inputSlots.add(Collections.singletonList(this.recipe.getBottomOptional().orElse(ItemStack.EMPTY))); + ingredients.setInputLists(ItemStack.class, inputSlots); - private final IInscriberRecipe recipe; - - public InscriberRecipeWrapper( IInscriberRecipe recipe ) - { - this.recipe = recipe; - } - - @Override - public void getIngredients( IIngredients ingredients ) - { - List> inputSlots = new ArrayList<>( 3 ); - inputSlots.add( Collections.singletonList( this.recipe.getTopOptional().orElse( ItemStack.EMPTY ) ) ); - inputSlots.add( this.recipe.getInputs() ); - inputSlots.add( Collections.singletonList( this.recipe.getBottomOptional().orElse( ItemStack.EMPTY ) ) ); - ingredients.setInputLists( ItemStack.class, inputSlots ); - - ingredients.setOutput( ItemStack.class, this.recipe.getOutput() ); - } + ingredients.setOutput(ItemStack.class, this.recipe.getOutput()); + } } diff --git a/src/main/java/appeng/integration/modules/jei/InscriberRegistryPlugin.java b/src/main/java/appeng/integration/modules/jei/InscriberRegistryPlugin.java index 441cd6747..5c5b46b8e 100644 --- a/src/main/java/appeng/integration/modules/jei/InscriberRegistryPlugin.java +++ b/src/main/java/appeng/integration/modules/jei/InscriberRegistryPlugin.java @@ -19,57 +19,48 @@ package appeng.integration.modules.jei; -import java.util.Collections; -import java.util.List; - -import net.minecraft.item.ItemStack; - +import appeng.api.AEApi; +import appeng.api.features.IInscriberRegistry; import mezz.jei.api.recipe.IFocus; import mezz.jei.api.recipe.IRecipeCategory; import mezz.jei.api.recipe.IRecipeRegistryPlugin; import mezz.jei.api.recipe.IRecipeWrapper; +import net.minecraft.item.ItemStack; -import appeng.api.AEApi; -import appeng.api.features.IInscriberRegistry; +import java.util.Collections; +import java.util.List; /** * Exposes the inscriber registry recipes to JEI. */ -class InscriberRegistryPlugin implements IRecipeRegistryPlugin -{ +class InscriberRegistryPlugin implements IRecipeRegistryPlugin { - private final IInscriberRegistry inscriber = AEApi.instance().registries().inscriber(); + private final IInscriberRegistry inscriber = AEApi.instance().registries().inscriber(); - @Override - public List getRecipeCategoryUids( IFocus focus ) - { - if( !( focus.getValue() instanceof ItemStack ) ) - { - return Collections.emptyList(); - } + @Override + public List getRecipeCategoryUids(IFocus focus) { + if (!(focus.getValue() instanceof ItemStack)) { + return Collections.emptyList(); + } - if( focus.getMode() == IFocus.Mode.INPUT ) - { - ItemStack input = (ItemStack) focus.getValue(); - for( ItemStack validInput : this.inscriber.getInputs() ) - { + if (focus.getMode() == IFocus.Mode.INPUT) { + ItemStack input = (ItemStack) focus.getValue(); + for (ItemStack validInput : this.inscriber.getInputs()) { - } - } + } + } - return Collections.emptyList(); - } + return Collections.emptyList(); + } - @Override - public List getRecipeWrappers( IRecipeCategory recipeCategory, IFocus focus ) - { - return null; - } + @Override + public List getRecipeWrappers(IRecipeCategory recipeCategory, IFocus focus) { + return null; + } - @Override - public List getRecipeWrappers( IRecipeCategory recipeCategory ) - { - return null; - } + @Override + public List getRecipeWrappers(IRecipeCategory recipeCategory) { + return null; + } } diff --git a/src/main/java/appeng/integration/modules/jei/JEIModule.java b/src/main/java/appeng/integration/modules/jei/JEIModule.java index a20314f25..f4f54b7d2 100644 --- a/src/main/java/appeng/integration/modules/jei/JEIModule.java +++ b/src/main/java/appeng/integration/modules/jei/JEIModule.java @@ -22,37 +22,31 @@ package appeng.integration.modules.jei; import appeng.integration.abstraction.IJEI; -public class JEIModule implements IJEI -{ +public class JEIModule implements IJEI { - private IJEI jei = new IJEI.Stub(); + private IJEI jei = new IJEI.Stub(); - public void setJei( IJEI jei ) - { - this.jei = jei; - } + public void setJei(IJEI jei) { + this.jei = jei; + } - public IJEI getJei() - { - return this.jei; - } + public IJEI getJei() { + return this.jei; + } - @Override - public String getSearchText() - { - return this.jei.getSearchText(); - } + @Override + public String getSearchText() { + return this.jei.getSearchText(); + } - @Override - public void setSearchText( String searchText ) - { - this.jei.setSearchText( searchText ); - } + @Override + public void setSearchText(String searchText) { + this.jei.setSearchText(searchText); + } - @Override - public boolean isEnabled() - { - return this.jei.isEnabled(); - } + @Override + public boolean isEnabled() { + return this.jei.isEnabled(); + } } diff --git a/src/main/java/appeng/integration/modules/jei/JEIPlugin.java b/src/main/java/appeng/integration/modules/jei/JEIPlugin.java index cf1c17164..fa70a2188 100644 --- a/src/main/java/appeng/integration/modules/jei/JEIPlugin.java +++ b/src/main/java/appeng/integration/modules/jei/JEIPlugin.java @@ -19,25 +19,6 @@ package appeng.integration.modules.jei; -import javax.annotation.Nullable; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import appeng.client.gui.AEGuiHandler; -import appeng.container.implementations.ContainerExpandedProcessingPatternTerm; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - -import mezz.jei.api.*; -import mezz.jei.config.Constants; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import mezz.jei.api.recipe.IRecipeCategoryRegistration; -import mezz.jei.api.recipe.VanillaRecipeCategoryUid; - import appeng.api.AEApi; import appeng.api.config.CondenserOutput; import appeng.api.definitions.IDefinitions; @@ -45,181 +26,174 @@ import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.IMaterials; import appeng.api.features.IGrinderRecipe; import appeng.api.features.IInscriberRecipe; +import appeng.client.gui.AEGuiHandler; import appeng.container.implementations.ContainerCraftingTerm; +import appeng.container.implementations.ContainerExpandedProcessingPatternTerm; import appeng.container.implementations.ContainerPatternTerm; import appeng.core.AEConfig; import appeng.core.features.AEFeature; import appeng.core.localization.GuiText; import appeng.integration.Integrations; import appeng.items.parts.ItemFacade; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import mezz.jei.api.IJeiRuntime; +import mezz.jei.api.IModPlugin; +import mezz.jei.api.IModRegistry; +import mezz.jei.api.ISubtypeRegistry; +import mezz.jei.api.recipe.IRecipeCategoryRegistration; +import mezz.jei.api.recipe.VanillaRecipeCategoryUid; +import mezz.jei.config.Constants; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; @mezz.jei.api.JEIPlugin -public class JEIPlugin implements IModPlugin -{ - public static IJeiRuntime runtime; - public static AEGuiHandler aeGuiHandler; +public class JEIPlugin implements IModPlugin { + public static IJeiRuntime runtime; + public static AEGuiHandler aeGuiHandler; - @Override - public void registerItemSubtypes( ISubtypeRegistry subtypeRegistry ) - { - final Optional maybeFacade = AEApi.instance().definitions().items().facade().maybeItem(); - maybeFacade.ifPresent( subtypeRegistry::useNbtForSubtypes ); - } + @Override + public void registerItemSubtypes(ISubtypeRegistry subtypeRegistry) { + final Optional maybeFacade = AEApi.instance().definitions().items().facade().maybeItem(); + maybeFacade.ifPresent(subtypeRegistry::useNbtForSubtypes); + } - @Override - public void registerCategories( IRecipeCategoryRegistration registry ) - { - registry.addRecipeCategories( new GrinderRecipeCategory( registry.getJeiHelpers().getGuiHelper() ) ); - registry.addRecipeCategories( new CondenserCategory( registry.getJeiHelpers().getGuiHelper() ) ); - registry.addRecipeCategories( new InscriberRecipeCategory( registry.getJeiHelpers().getGuiHelper() ) ); - } + @Override + public void registerCategories(IRecipeCategoryRegistration registry) { + registry.addRecipeCategories(new GrinderRecipeCategory(registry.getJeiHelpers().getGuiHelper())); + registry.addRecipeCategories(new CondenserCategory(registry.getJeiHelpers().getGuiHelper())); + registry.addRecipeCategories(new InscriberRecipeCategory(registry.getJeiHelpers().getGuiHelper())); + } - @Override - public void register( IModRegistry registry ) - { - IDefinitions definitions = AEApi.instance().definitions(); + @Override + public void register(IModRegistry registry) { + IDefinitions definitions = AEApi.instance().definitions(); - this.registerFacadeRecipe( definitions, registry ); + this.registerFacadeRecipe(definitions, registry); - this.registerInscriberRecipes( definitions, registry ); + this.registerInscriberRecipes(definitions, registry); - this.registerCondenserRecipes( definitions, registry ); + this.registerCondenserRecipes(definitions, registry); - this.registerGrinderRecipes( definitions, registry ); + this.registerGrinderRecipes(definitions, registry); - this.registerDescriptions( definitions, registry ); + this.registerDescriptions(definitions, registry); - // Allow recipe transfer from JEI to crafting and pattern terminal - registry.getRecipeTransferRegistry().addRecipeTransferHandler( new RecipeTransferHandler<>( ContainerCraftingTerm.class ), VanillaRecipeCategoryUid.CRAFTING ); - registry.getRecipeTransferRegistry().addRecipeTransferHandler( new RecipeTransferHandler<>( ContainerPatternTerm.class ), Constants.UNIVERSAL_RECIPE_TRANSFER_UID ); - registry.getRecipeTransferRegistry().addRecipeTransferHandler( new RecipeTransferHandler<>( ContainerExpandedProcessingPatternTerm.class ), Constants.UNIVERSAL_RECIPE_TRANSFER_UID ); + // Allow recipe transfer from JEI to crafting and pattern terminal + registry.getRecipeTransferRegistry().addRecipeTransferHandler(new RecipeTransferHandler<>(ContainerCraftingTerm.class), VanillaRecipeCategoryUid.CRAFTING); + registry.getRecipeTransferRegistry().addRecipeTransferHandler(new RecipeTransferHandler<>(ContainerPatternTerm.class), Constants.UNIVERSAL_RECIPE_TRANSFER_UID); + registry.getRecipeTransferRegistry().addRecipeTransferHandler(new RecipeTransferHandler<>(ContainerExpandedProcessingPatternTerm.class), Constants.UNIVERSAL_RECIPE_TRANSFER_UID); - aeGuiHandler = new AEGuiHandler(); - registry.addAdvancedGuiHandlers( aeGuiHandler ); - registry.addGhostIngredientHandler( aeGuiHandler.getGuiContainerClass(), aeGuiHandler ); - } + aeGuiHandler = new AEGuiHandler(); + registry.addAdvancedGuiHandlers(aeGuiHandler); + registry.addGhostIngredientHandler(aeGuiHandler.getGuiContainerClass(), aeGuiHandler); + } - private void registerDescriptions( IDefinitions definitions, IModRegistry registry ) - { - IMaterials materials = definitions.materials(); + private void registerDescriptions(IDefinitions definitions, IModRegistry registry) { + IMaterials materials = definitions.materials(); - final String message; - if( AEConfig.instance().isFeatureEnabled( AEFeature.CERTUS_QUARTZ_WORLD_GEN ) ) - { - message = GuiText.ChargedQuartz.getLocal() + "\n\n" + GuiText.ChargedQuartzFind.getLocal(); - } - else - { - message = GuiText.ChargedQuartzFind.getLocal(); - } - this.addDescription( registry, materials.certusQuartzCrystalCharged(), message ); + final String message; + if (AEConfig.instance().isFeatureEnabled(AEFeature.CERTUS_QUARTZ_WORLD_GEN)) { + message = GuiText.ChargedQuartz.getLocal() + "\n\n" + GuiText.ChargedQuartzFind.getLocal(); + } else { + message = GuiText.ChargedQuartzFind.getLocal(); + } + this.addDescription(registry, materials.certusQuartzCrystalCharged(), message); - if( AEConfig.instance().isFeatureEnabled( AEFeature.METEORITE_WORLD_GEN ) ) - { - this.addDescription( registry, materials.logicProcessorPress(), GuiText.inWorldCraftingPresses.getLocal() ); - this.addDescription( registry, materials.calcProcessorPress(), GuiText.inWorldCraftingPresses.getLocal() ); - this.addDescription( registry, materials.engProcessorPress(), GuiText.inWorldCraftingPresses.getLocal() ); - } + if (AEConfig.instance().isFeatureEnabled(AEFeature.METEORITE_WORLD_GEN)) { + this.addDescription(registry, materials.logicProcessorPress(), GuiText.inWorldCraftingPresses.getLocal()); + this.addDescription(registry, materials.calcProcessorPress(), GuiText.inWorldCraftingPresses.getLocal()); + this.addDescription(registry, materials.engProcessorPress(), GuiText.inWorldCraftingPresses.getLocal()); + } - if( AEConfig.instance().isFeatureEnabled( AEFeature.IN_WORLD_FLUIX ) ) - { - this.addDescription( registry, materials.fluixCrystal(), GuiText.inWorldFluix.getLocal() ); - } + if (AEConfig.instance().isFeatureEnabled(AEFeature.IN_WORLD_FLUIX)) { + this.addDescription(registry, materials.fluixCrystal(), GuiText.inWorldFluix.getLocal()); + } - if( AEConfig.instance().isFeatureEnabled( AEFeature.IN_WORLD_SINGULARITY ) ) - { - this.addDescription( registry, materials.qESingularity(), GuiText.inWorldSingularity.getLocal() ); - } + if (AEConfig.instance().isFeatureEnabled(AEFeature.IN_WORLD_SINGULARITY)) { + this.addDescription(registry, materials.qESingularity(), GuiText.inWorldSingularity.getLocal()); + } - if( AEConfig.instance().isFeatureEnabled( AEFeature.IN_WORLD_PURIFICATION ) ) - { - this.addDescription( registry, materials.purifiedCertusQuartzCrystal(), GuiText.inWorldPurificationCertus.getLocal() ); - this.addDescription( registry, materials.purifiedNetherQuartzCrystal(), GuiText.inWorldPurificationNether.getLocal() ); - this.addDescription( registry, materials.purifiedFluixCrystal(), GuiText.inWorldPurificationFluix.getLocal() ); - } + if (AEConfig.instance().isFeatureEnabled(AEFeature.IN_WORLD_PURIFICATION)) { + this.addDescription(registry, materials.purifiedCertusQuartzCrystal(), GuiText.inWorldPurificationCertus.getLocal()); + this.addDescription(registry, materials.purifiedNetherQuartzCrystal(), GuiText.inWorldPurificationNether.getLocal()); + this.addDescription(registry, materials.purifiedFluixCrystal(), GuiText.inWorldPurificationFluix.getLocal()); + } - } + } - private void addDescription( IModRegistry registry, IItemDefinition itemDefinition, String message ) - { - itemDefinition.maybeStack( 1 ).ifPresent( itemStack -> registry.addIngredientInfo( itemStack, ItemStack.class, message ) ); - } + private void addDescription(IModRegistry registry, IItemDefinition itemDefinition, String message) { + itemDefinition.maybeStack(1).ifPresent(itemStack -> registry.addIngredientInfo(itemStack, ItemStack.class, message)); + } - private void registerGrinderRecipes( IDefinitions definitions, IModRegistry registry ) - { + private void registerGrinderRecipes(IDefinitions definitions, IModRegistry registry) { - ItemStack grindstone = definitions.blocks().grindstone().maybeStack( 1 ).orElse( ItemStack.EMPTY ); + ItemStack grindstone = definitions.blocks().grindstone().maybeStack(1).orElse(ItemStack.EMPTY); - if( grindstone.isEmpty() ) - { - return; - } + if (grindstone.isEmpty()) { + return; + } - registry.handleRecipes( IGrinderRecipe.class, new GrinderRecipeHandler(), GrinderRecipeCategory.UID ); - registry.addRecipes( Lists.newArrayList( AEApi.instance().registries().grinder().getRecipes() ), GrinderRecipeCategory.UID ); - registry.addRecipeCatalyst( grindstone, GrinderRecipeCategory.UID ); - } + registry.handleRecipes(IGrinderRecipe.class, new GrinderRecipeHandler(), GrinderRecipeCategory.UID); + registry.addRecipes(Lists.newArrayList(AEApi.instance().registries().grinder().getRecipes()), GrinderRecipeCategory.UID); + registry.addRecipeCatalyst(grindstone, GrinderRecipeCategory.UID); + } - private void registerCondenserRecipes( IDefinitions definitions, IModRegistry registry ) - { + private void registerCondenserRecipes(IDefinitions definitions, IModRegistry registry) { - ItemStack condenser = definitions.blocks().condenser().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - if( condenser.isEmpty() ) - { - return; - } + ItemStack condenser = definitions.blocks().condenser().maybeStack(1).orElse(ItemStack.EMPTY); + if (condenser.isEmpty()) { + return; + } - ItemStack matterBall = definitions.materials().matterBall().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - if( !matterBall.isEmpty() ) - { - registry.addRecipes( ImmutableList.of( CondenserOutput.MATTER_BALLS ), CondenserCategory.UID ); - } + ItemStack matterBall = definitions.materials().matterBall().maybeStack(1).orElse(ItemStack.EMPTY); + if (!matterBall.isEmpty()) { + registry.addRecipes(ImmutableList.of(CondenserOutput.MATTER_BALLS), CondenserCategory.UID); + } - ItemStack singularity = definitions.materials().singularity().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - if( !singularity.isEmpty() ) - { - registry.addRecipes( ImmutableList.of( CondenserOutput.SINGULARITY ), CondenserCategory.UID ); - } + ItemStack singularity = definitions.materials().singularity().maybeStack(1).orElse(ItemStack.EMPTY); + if (!singularity.isEmpty()) { + registry.addRecipes(ImmutableList.of(CondenserOutput.SINGULARITY), CondenserCategory.UID); + } - if( !matterBall.isEmpty() || !singularity.isEmpty() ) - { - registry.addRecipeCatalyst( condenser, CondenserCategory.UID ); - registry.handleRecipes( CondenserOutput.class, new CondenserOutputHandler( registry.getJeiHelpers().getGuiHelper(), matterBall, singularity ), - CondenserCategory.UID ); - } - } + if (!matterBall.isEmpty() || !singularity.isEmpty()) { + registry.addRecipeCatalyst(condenser, CondenserCategory.UID); + registry.handleRecipes(CondenserOutput.class, new CondenserOutputHandler(registry.getJeiHelpers().getGuiHelper(), matterBall, singularity), + CondenserCategory.UID); + } + } - private void registerInscriberRecipes( IDefinitions definitions, IModRegistry registry ) - { - registry.handleRecipes( IInscriberRecipe.class, new InscriberRecipeHandler(), InscriberRecipeCategory.UID ); + private void registerInscriberRecipes(IDefinitions definitions, IModRegistry registry) { + registry.handleRecipes(IInscriberRecipe.class, new InscriberRecipeHandler(), InscriberRecipeCategory.UID); - // Register the inscriber as the crafting item for the inscription category - definitions.blocks().inscriber().maybeStack( 1 ).ifPresent( inscriber -> - { - registry.addRecipeCatalyst( inscriber, InscriberRecipeCategory.UID ); - } ); + // Register the inscriber as the crafting item for the inscription category + definitions.blocks().inscriber().maybeStack(1).ifPresent(inscriber -> + { + registry.addRecipeCatalyst(inscriber, InscriberRecipeCategory.UID); + }); - List inscriberRecipes = new ArrayList<>( AEApi.instance().registries().inscriber().getRecipes() ); - registry.addRecipes( inscriberRecipes, InscriberRecipeCategory.UID ); - } + List inscriberRecipes = new ArrayList<>(AEApi.instance().registries().inscriber().getRecipes()); + registry.addRecipes(inscriberRecipes, InscriberRecipeCategory.UID); + } - // Handle the generic crafting recipe for patterns in JEI - private void registerFacadeRecipe( IDefinitions definitions, IModRegistry registry ) - { - Optional itemFacade = definitions.items().facade().maybeItem(); - Optional cableAnchor = definitions.parts().cableAnchor().maybeStack( 1 ); - if( itemFacade.isPresent() && cableAnchor.isPresent() && AEConfig.instance().isFeatureEnabled( AEFeature.ENABLE_FACADE_CRAFTING ) ) - { - registry.addRecipeRegistryPlugin( new FacadeRegistryPlugin( (ItemFacade) itemFacade.get(), cableAnchor.get() ) ); - } - } + // Handle the generic crafting recipe for patterns in JEI + private void registerFacadeRecipe(IDefinitions definitions, IModRegistry registry) { + Optional itemFacade = definitions.items().facade().maybeItem(); + Optional cableAnchor = definitions.parts().cableAnchor().maybeStack(1); + if (itemFacade.isPresent() && cableAnchor.isPresent() && AEConfig.instance().isFeatureEnabled(AEFeature.ENABLE_FACADE_CRAFTING)) { + registry.addRecipeRegistryPlugin(new FacadeRegistryPlugin((ItemFacade) itemFacade.get(), cableAnchor.get())); + } + } - @Override - public void onRuntimeAvailable( IJeiRuntime jeiRuntime ) - { - JEIModule jeiModule = (JEIModule) Integrations.jei(); - jeiModule.setJei( new JeiRuntimeAdapter( jeiRuntime ) ); - runtime = jeiRuntime; - } + @Override + public void onRuntimeAvailable(IJeiRuntime jeiRuntime) { + JEIModule jeiModule = (JEIModule) Integrations.jei(); + jeiModule.setJei(new JeiRuntimeAdapter(jeiRuntime)); + runtime = jeiRuntime; + } } diff --git a/src/main/java/appeng/integration/modules/jei/JeiRuntimeAdapter.java b/src/main/java/appeng/integration/modules/jei/JeiRuntimeAdapter.java index bf603697e..29f2add7e 100644 --- a/src/main/java/appeng/integration/modules/jei/JeiRuntimeAdapter.java +++ b/src/main/java/appeng/integration/modules/jei/JeiRuntimeAdapter.java @@ -19,38 +19,31 @@ package appeng.integration.modules.jei; +import appeng.integration.abstraction.IJEI; import com.google.common.base.Strings; - import mezz.jei.api.IJeiRuntime; -import appeng.integration.abstraction.IJEI; +class JeiRuntimeAdapter implements IJEI { -class JeiRuntimeAdapter implements IJEI -{ + private final IJeiRuntime runtime; - private final IJeiRuntime runtime; + JeiRuntimeAdapter(IJeiRuntime jeiRuntime) { + this.runtime = jeiRuntime; + } - JeiRuntimeAdapter( IJeiRuntime jeiRuntime ) - { - this.runtime = jeiRuntime; - } + @Override + public boolean isEnabled() { + return true; + } - @Override - public boolean isEnabled() - { - return true; - } + @Override + public String getSearchText() { + return Strings.nullToEmpty(this.runtime.getIngredientFilter().getFilterText()); + } - @Override - public String getSearchText() - { - return Strings.nullToEmpty( this.runtime.getIngredientFilter().getFilterText() ); - } - - @Override - public void setSearchText( String searchText ) - { - this.runtime.getIngredientFilter().setFilterText( Strings.nullToEmpty( searchText ) ); - } + @Override + public void setSearchText(String searchText) { + this.runtime.getIngredientFilter().setFilterText(Strings.nullToEmpty(searchText)); + } } diff --git a/src/main/java/appeng/integration/modules/jei/RecipeTransferHandler.java b/src/main/java/appeng/integration/modules/jei/RecipeTransferHandler.java index c89293b98..c3af96d49 100644 --- a/src/main/java/appeng/integration/modules/jei/RecipeTransferHandler.java +++ b/src/main/java/appeng/integration/modules/jei/RecipeTransferHandler.java @@ -19,19 +19,20 @@ package appeng.integration.modules.jei; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.annotation.Nullable; - import appeng.container.implementations.ContainerPatternTerm; +import appeng.container.slot.SlotCraftingMatrix; +import appeng.container.slot.SlotFakeCraftingMatrix; +import appeng.core.AELog; +import appeng.core.sync.network.NetworkHandler; +import appeng.core.sync.packets.PacketJEIRecipe; import appeng.core.sync.packets.PacketValueConfig; +import appeng.util.Platform; +import mezz.jei.api.gui.IGuiIngredient; +import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.recipe.VanillaRecipeCategoryUid; +import mezz.jei.api.recipe.transfer.IRecipeTransferError; +import mezz.jei.api.recipe.transfer.IRecipeTransferHandler; import mezz.jei.transfer.RecipeTransferErrorInternal; -import mezz.jei.transfer.RecipeTransferErrorTooltip; -import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; @@ -39,157 +40,121 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import mezz.jei.api.gui.IGuiIngredient; -import mezz.jei.api.gui.IRecipeLayout; -import mezz.jei.api.recipe.transfer.IRecipeTransferError; -import mezz.jei.api.recipe.transfer.IRecipeTransferHandler; - -import appeng.container.slot.SlotCraftingMatrix; -import appeng.container.slot.SlotFakeCraftingMatrix; -import appeng.core.AELog; -import appeng.core.sync.network.NetworkHandler; -import appeng.core.sync.packets.PacketJEIRecipe; -import appeng.util.Platform; +import javax.annotation.Nullable; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; -class RecipeTransferHandler implements IRecipeTransferHandler -{ +class RecipeTransferHandler implements IRecipeTransferHandler { - private final Class containerClass; + private final Class containerClass; - RecipeTransferHandler( Class containerClass ) - { - this.containerClass = containerClass; - } + RecipeTransferHandler(Class containerClass) { + this.containerClass = containerClass; + } - @Override - public Class getContainerClass() - { - return this.containerClass; - } + @Override + public Class getContainerClass() { + return this.containerClass; + } - @Nullable - @Override - public IRecipeTransferError transferRecipe( T container, IRecipeLayout recipeLayout, EntityPlayer player, boolean maxTransfer, boolean doTransfer ) - { - final String recipeType = recipeLayout.getRecipeCategory().getUid(); + @Nullable + @Override + public IRecipeTransferError transferRecipe(T container, IRecipeLayout recipeLayout, EntityPlayer player, boolean maxTransfer, boolean doTransfer) { + final String recipeType = recipeLayout.getRecipeCategory().getUid(); - if (recipeType.equals( VanillaRecipeCategoryUid.INFORMATION) || recipeType.equals(VanillaRecipeCategoryUid.FUEL)) - { - return RecipeTransferErrorInternal.INSTANCE; - } + if (recipeType.equals(VanillaRecipeCategoryUid.INFORMATION) || recipeType.equals(VanillaRecipeCategoryUid.FUEL)) { + return RecipeTransferErrorInternal.INSTANCE; + } - if( !doTransfer ) - { - return null; - } + if (!doTransfer) { + return null; + } - if( container instanceof ContainerPatternTerm ) - { - try - { - if( !( (ContainerPatternTerm) container ).isCraftingMode() ) - { - if( recipeType.equals( VanillaRecipeCategoryUid.CRAFTING ) ) - { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.CraftMode", "1" ) ); - } - } - else if( !recipeType.equals( VanillaRecipeCategoryUid.CRAFTING ) ) - { + if (container instanceof ContainerPatternTerm) { + try { + if (!((ContainerPatternTerm) container).isCraftingMode()) { + if (recipeType.equals(VanillaRecipeCategoryUid.CRAFTING)) { + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.CraftMode", "1")); + } + } else if (!recipeType.equals(VanillaRecipeCategoryUid.CRAFTING)) { - NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.CraftMode", "0" ) ); - } + NetworkHandler.instance().sendToServer(new PacketValueConfig("PatternTerminal.CraftMode", "0")); + } - } - catch( IOException e ) - { - e.printStackTrace(); - } - } + } catch (IOException e) { + e.printStackTrace(); + } + } - Map> ingredients = recipeLayout.getItemStacks().getGuiIngredients(); + Map> ingredients = recipeLayout.getItemStacks().getGuiIngredients(); - final NBTTagCompound recipe = new NBTTagCompound(); - final NBTTagList outputs = new NBTTagList(); + final NBTTagCompound recipe = new NBTTagCompound(); + final NBTTagList outputs = new NBTTagList(); - int slotIndex = 0; - for( Map.Entry> ingredientEntry : ingredients.entrySet() ) - { - IGuiIngredient ingredient = ingredientEntry.getValue(); - if( !ingredient.isInput() ) - { - ItemStack output = ingredient.getDisplayedIngredient(); - if( output != null ) - { - final NBTTagCompound tag = new NBTTagCompound(); - output.writeToNBT( tag ); - outputs.appendTag( tag ); - } - continue; - } + int slotIndex = 0; + for (Map.Entry> ingredientEntry : ingredients.entrySet()) { + IGuiIngredient ingredient = ingredientEntry.getValue(); + if (!ingredient.isInput()) { + ItemStack output = ingredient.getDisplayedIngredient(); + if (output != null) { + final NBTTagCompound tag = new NBTTagCompound(); + output.writeToNBT(tag); + outputs.appendTag(tag); + } + continue; + } - for( final Slot slot : container.inventorySlots ) - { - if( slot instanceof SlotCraftingMatrix || slot instanceof SlotFakeCraftingMatrix ) - { - if( slot.getSlotIndex() == slotIndex ) - { - final NBTTagList tags = new NBTTagList(); - final List list = new ArrayList<>(); - final ItemStack displayed = ingredient.getDisplayedIngredient(); + for (final Slot slot : container.inventorySlots) { + if (slot instanceof SlotCraftingMatrix || slot instanceof SlotFakeCraftingMatrix) { + if (slot.getSlotIndex() == slotIndex) { + final NBTTagList tags = new NBTTagList(); + final List list = new ArrayList<>(); + final ItemStack displayed = ingredient.getDisplayedIngredient(); - // prefer currently displayed item - if( displayed != null && !displayed.isEmpty() ) - { - list.add( displayed ); - } + // prefer currently displayed item + if (displayed != null && !displayed.isEmpty()) { + list.add(displayed); + } - // prefer pure crystals. - for ( ItemStack stack : ingredient.getAllIngredients() ) - { - if( stack == null ) - { - continue; - } - if( Platform.isRecipePrioritized( stack ) ) - { - list.add( 0, stack ); - } - else - { - list.add( stack ); - } - } + // prefer pure crystals. + for (ItemStack stack : ingredient.getAllIngredients()) { + if (stack == null) { + continue; + } + if (Platform.isRecipePrioritized(stack)) { + list.add(0, stack); + } else { + list.add(stack); + } + } - for ( final ItemStack is : list ) - { - final NBTTagCompound tag = new NBTTagCompound(); - is.writeToNBT( tag ); - tags.appendTag( tag ); - } + for (final ItemStack is : list) { + final NBTTagCompound tag = new NBTTagCompound(); + is.writeToNBT(tag); + tags.appendTag(tag); + } - recipe.setTag( "#" + slot.getSlotIndex(), tags ); - break; - } - } - } + recipe.setTag("#" + slot.getSlotIndex(), tags); + break; + } + } + } - slotIndex++; - } + slotIndex++; + } - recipe.setTag( "outputs", outputs ); + recipe.setTag("outputs", outputs); - try - { - NetworkHandler.instance().sendToServer( new PacketJEIRecipe( recipe ) ); - } - catch( IOException e ) - { - AELog.debug( e ); - } + try { + NetworkHandler.instance().sendToServer(new PacketJEIRecipe(recipe)); + } catch (IOException e) { + AELog.debug(e); + } - return null; - } + return null; + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/PartInfoProvider.java b/src/main/java/appeng/integration/modules/theoneprobe/PartInfoProvider.java index ea598efed..4d0153aa7 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/PartInfoProvider.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/PartInfoProvider.java @@ -19,68 +19,54 @@ package appeng.integration.modules.theoneprobe; -import java.util.List; -import java.util.Optional; - +import appeng.api.parts.IPart; +import appeng.core.AppEng; +import appeng.integration.modules.theoneprobe.part.*; import com.google.common.collect.Lists; - +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeInfo; +import mcjty.theoneprobe.api.IProbeInfoProvider; +import mcjty.theoneprobe.api.ProbeMode; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import mcjty.theoneprobe.api.IProbeHitData; -import mcjty.theoneprobe.api.IProbeInfo; -import mcjty.theoneprobe.api.IProbeInfoProvider; -import mcjty.theoneprobe.api.ProbeMode; - -import appeng.api.parts.IPart; -import appeng.core.AppEng; -import appeng.integration.modules.theoneprobe.part.ChannelInfoProvider; -import appeng.integration.modules.theoneprobe.part.IPartProbInfoProvider; -import appeng.integration.modules.theoneprobe.part.P2PStateInfoProvider; -import appeng.integration.modules.theoneprobe.part.PartAccessor; -import appeng.integration.modules.theoneprobe.part.PowerStateInfoProvider; -import appeng.integration.modules.theoneprobe.part.StorageMonitorInfoProvider; +import java.util.List; +import java.util.Optional; -public final class PartInfoProvider implements IProbeInfoProvider -{ - private final List providers; +public final class PartInfoProvider implements IProbeInfoProvider { + private final List providers; - private final PartAccessor accessor = new PartAccessor(); + private final PartAccessor accessor = new PartAccessor(); - public PartInfoProvider() - { - final IPartProbInfoProvider channel = new ChannelInfoProvider(); - final IPartProbInfoProvider power = new PowerStateInfoProvider(); - final IPartProbInfoProvider storageMonitor = new StorageMonitorInfoProvider(); - final IPartProbInfoProvider p2p = new P2PStateInfoProvider(); + public PartInfoProvider() { + final IPartProbInfoProvider channel = new ChannelInfoProvider(); + final IPartProbInfoProvider power = new PowerStateInfoProvider(); + final IPartProbInfoProvider storageMonitor = new StorageMonitorInfoProvider(); + final IPartProbInfoProvider p2p = new P2PStateInfoProvider(); - this.providers = Lists.newArrayList( channel, power, p2p, storageMonitor ); - } + this.providers = Lists.newArrayList(channel, power, p2p, storageMonitor); + } - @Override - public String getID() - { - return AppEng.MOD_ID + ":PartInfoProvider"; - } + @Override + public String getID() { + return AppEng.MOD_ID + ":PartInfoProvider"; + } - @Override - public void addProbeInfo( ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data ) - { - final TileEntity te = world.getTileEntity( data.getPos() ); - final Optional maybePart = this.accessor.getMaybePart( te, data ); + @Override + public void addProbeInfo(ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { + final TileEntity te = world.getTileEntity(data.getPos()); + final Optional maybePart = this.accessor.getMaybePart(te, data); - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); - for( final IPartProbInfoProvider provider : this.providers ) - { - provider.addProbeInfo( part, mode, probeInfo, player, world, blockState, data ); - } - } + for (final IPartProbInfoProvider provider : this.providers) { + provider.addProbeInfo(part, mode, probeInfo, player, world, blockState, data); + } + } - } + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/TheOneProbeModule.java b/src/main/java/appeng/integration/modules/theoneprobe/TheOneProbeModule.java index 0fb0b0172..0eb44f3bf 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/TheOneProbeModule.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/TheOneProbeModule.java @@ -19,33 +19,28 @@ package appeng.integration.modules.theoneprobe; -import java.util.function.Function; - -import net.minecraftforge.fml.common.event.FMLInterModComms; - -import mcjty.theoneprobe.api.ITheOneProbe; - import appeng.integration.IIntegrationModule; import appeng.integration.modules.theoneprobe.config.AEConfigProvider; +import mcjty.theoneprobe.api.ITheOneProbe; +import net.minecraftforge.fml.common.event.FMLInterModComms; + +import java.util.function.Function; -public class TheOneProbeModule implements IIntegrationModule, Function -{ - @Override - public void preInit() throws Throwable - { - FMLInterModComms.sendFunctionMessage( "theoneprobe", "getTheOneProbe", this.getClass().getName() ); - } +public class TheOneProbeModule implements IIntegrationModule, Function { + @Override + public void preInit() throws Throwable { + FMLInterModComms.sendFunctionMessage("theoneprobe", "getTheOneProbe", this.getClass().getName()); + } - @Override - public Void apply( ITheOneProbe input ) - { - input.registerProbeConfigProvider( new AEConfigProvider() ); + @Override + public Void apply(ITheOneProbe input) { + input.registerProbeConfigProvider(new AEConfigProvider()); - input.registerProvider( new TileInfoProvider() ); + input.registerProvider(new TileInfoProvider()); - input.registerProvider( new PartInfoProvider() ); + input.registerProvider(new PartInfoProvider()); - return null; - } + return null; + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/TheOneProbeText.java b/src/main/java/appeng/integration/modules/theoneprobe/TheOneProbeText.java index b5c03e515..d9323c663 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/TheOneProbeText.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/TheOneProbeText.java @@ -19,51 +19,47 @@ package appeng.integration.modules.theoneprobe; -import java.util.Locale; - import net.minecraft.util.text.translation.I18n; +import java.util.Locale; -public enum TheOneProbeText -{ - CRAFTING, - DEVICE_ONLINE, - DEVICE_OFFLINE, - DEVICE_MISSING_CHANNEL, +public enum TheOneProbeText { + CRAFTING, - P2P_UNLINKED, - P2P_INPUT_ONE_OUTPUT, - P2P_INPUT_MANY_OUTPUTS, - P2P_OUTPUT_ONE_INPUT, - P2P_OUTPUT_MANY_INPUTS, - P2P_OUTPUT, - P2P_FREQUENCY, + DEVICE_ONLINE, + DEVICE_OFFLINE, + DEVICE_MISSING_CHANNEL, - LOCKED, - UNLOCKED, - SHOWING, + P2P_UNLINKED, + P2P_INPUT_ONE_OUTPUT, + P2P_INPUT_MANY_OUTPUTS, + P2P_OUTPUT_ONE_INPUT, + P2P_OUTPUT_MANY_INPUTS, + P2P_OUTPUT, + P2P_FREQUENCY, - CONTAINS, - CHANNELS, + LOCKED, + UNLOCKED, + SHOWING, - STORED_ENERGY; + CONTAINS, + CHANNELS, - private final String root; + STORED_ENERGY; - TheOneProbeText() - { - this.root = "theoneprobe.appliedenergistics2"; - } + private final String root; - public String getLocal() - { - return I18n.translateToLocal( this.getUnlocalized() ); - } + TheOneProbeText() { + this.root = "theoneprobe.appliedenergistics2"; + } - public String getUnlocalized() - { - return this.root + '.' + this.name().toLowerCase( Locale.ENGLISH ); - } + public String getLocal() { + return I18n.translateToLocal(this.getUnlocalized()); + } + + public String getUnlocalized() { + return this.root + '.' + this.name().toLowerCase(Locale.ENGLISH); + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/TileInfoProvider.java b/src/main/java/appeng/integration/modules/theoneprobe/TileInfoProvider.java index 82baa640b..1475b456c 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/TileInfoProvider.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/TileInfoProvider.java @@ -19,62 +19,49 @@ package appeng.integration.modules.theoneprobe; -import java.util.List; - +import appeng.core.AppEng; +import appeng.integration.modules.theoneprobe.tile.*; +import appeng.tile.AEBaseTile; import com.google.common.collect.Lists; - +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeInfo; +import mcjty.theoneprobe.api.IProbeInfoProvider; +import mcjty.theoneprobe.api.ProbeMode; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import mcjty.theoneprobe.api.IProbeHitData; -import mcjty.theoneprobe.api.IProbeInfo; -import mcjty.theoneprobe.api.IProbeInfoProvider; -import mcjty.theoneprobe.api.ProbeMode; - -import appeng.core.AppEng; -import appeng.integration.modules.theoneprobe.tile.ChargerInfoProvider; -import appeng.integration.modules.theoneprobe.tile.CraftingMonitorInfoProvider; -import appeng.integration.modules.theoneprobe.tile.ITileProbInfoProvider; -import appeng.integration.modules.theoneprobe.tile.PowerStateInfoProvider; -import appeng.integration.modules.theoneprobe.tile.PowerStorageInfoProvider; -import appeng.tile.AEBaseTile; +import java.util.List; -public final class TileInfoProvider implements IProbeInfoProvider -{ - private final List providers; +public final class TileInfoProvider implements IProbeInfoProvider { + private final List providers; - public TileInfoProvider() - { - final ITileProbInfoProvider charger = new ChargerInfoProvider(); - final ITileProbInfoProvider energyCell = new CraftingMonitorInfoProvider(); - final ITileProbInfoProvider craftingBlock = new PowerStateInfoProvider(); - final ITileProbInfoProvider craftingMonitor = new PowerStorageInfoProvider(); + public TileInfoProvider() { + final ITileProbInfoProvider charger = new ChargerInfoProvider(); + final ITileProbInfoProvider energyCell = new CraftingMonitorInfoProvider(); + final ITileProbInfoProvider craftingBlock = new PowerStateInfoProvider(); + final ITileProbInfoProvider craftingMonitor = new PowerStorageInfoProvider(); - this.providers = Lists.newArrayList( charger, energyCell, craftingBlock, craftingMonitor ); - } + this.providers = Lists.newArrayList(charger, energyCell, craftingBlock, craftingMonitor); + } - @Override - public String getID() - { - return AppEng.MOD_ID + ":TileInfoProvider"; - } + @Override + public String getID() { + return AppEng.MOD_ID + ":TileInfoProvider"; + } - @Override - public void addProbeInfo( ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data ) - { - final TileEntity tile = world.getTileEntity( data.getPos() ); + @Override + public void addProbeInfo(ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { + final TileEntity tile = world.getTileEntity(data.getPos()); - if( tile instanceof AEBaseTile ) - { - final AEBaseTile aeBaseTile = (AEBaseTile) tile; + if (tile instanceof AEBaseTile) { + final AEBaseTile aeBaseTile = (AEBaseTile) tile; - for( final ITileProbInfoProvider provider : this.providers ) - { - provider.addProbeInfo( aeBaseTile, mode, probeInfo, player, world, blockState, data ); - } - } - } + for (final ITileProbInfoProvider provider : this.providers) { + provider.addProbeInfo(aeBaseTile, mode, probeInfo, player, world, blockState, data); + } + } + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/config/AEConfigProvider.java b/src/main/java/appeng/integration/modules/theoneprobe/config/AEConfigProvider.java index f575e9add..4c0dec04a 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/config/AEConfigProvider.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/config/AEConfigProvider.java @@ -19,35 +19,29 @@ package appeng.integration.modules.theoneprobe.config; +import appeng.tile.AEBaseTile; +import mcjty.theoneprobe.api.IProbeConfig; +import mcjty.theoneprobe.api.IProbeConfigProvider; +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeHitEntityData; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; -import mcjty.theoneprobe.api.IProbeConfig; -import mcjty.theoneprobe.api.IProbeConfigProvider; -import mcjty.theoneprobe.api.IProbeHitData; -import mcjty.theoneprobe.api.IProbeHitEntityData; -import appeng.tile.AEBaseTile; +public class AEConfigProvider implements IProbeConfigProvider { + @Override + public void getProbeConfig(IProbeConfig config, EntityPlayer player, World world, Entity entity, IProbeHitEntityData data) { + // Still no AE entities. + } -public class AEConfigProvider implements IProbeConfigProvider -{ - - @Override - public void getProbeConfig( IProbeConfig config, EntityPlayer player, World world, Entity entity, IProbeHitEntityData data ) - { - // Still no AE entities. - } - - @Override - public void getProbeConfig( IProbeConfig config, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data ) - { - if( world.getTileEntity( data.getPos() ) instanceof AEBaseTile ) - { - config.setRFMode( 0 ); - } - } + @Override + public void getProbeConfig(IProbeConfig config, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { + if (world.getTileEntity(data.getPos()) instanceof AEBaseTile) { + config.setRFMode(0); + } + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/part/ChannelInfoProvider.java b/src/main/java/appeng/integration/modules/theoneprobe/part/ChannelInfoProvider.java index dd908621b..93a2a3d77 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/part/ChannelInfoProvider.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/part/ChannelInfoProvider.java @@ -19,54 +19,45 @@ package appeng.integration.modules.theoneprobe.part; +import appeng.api.parts.IPart; import appeng.core.AEConfig; import appeng.core.features.AEFeature; +import appeng.integration.modules.theoneprobe.TheOneProbeText; +import appeng.parts.networking.PartCableSmart; +import appeng.parts.networking.PartDenseCableSmart; +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeInfo; +import mcjty.theoneprobe.api.ProbeMode; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import mcjty.theoneprobe.api.IProbeHitData; -import mcjty.theoneprobe.api.IProbeInfo; -import mcjty.theoneprobe.api.ProbeMode; -import appeng.api.parts.IPart; -import appeng.integration.modules.theoneprobe.TheOneProbeText; -import appeng.parts.networking.PartCableSmart; -import appeng.parts.networking.PartDenseCableSmart; +public class ChannelInfoProvider implements IPartProbInfoProvider { + @Override + public void addProbeInfo(IPart part, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { + if (!AEConfig.instance().isFeatureEnabled(AEFeature.CHANNELS)) { + return; + } + if (part instanceof PartDenseCableSmart || part instanceof PartCableSmart) { + final int usedChannels; + final int maxChannels = (part instanceof PartDenseCableSmart) ? 32 : 8; -public class ChannelInfoProvider implements IPartProbInfoProvider -{ + if (part.getGridNode().isActive()) { + final NBTTagCompound tmp = new NBTTagCompound(); + part.writeToNBT(tmp); + usedChannels = tmp.getByte("usedChannels"); + } else { + usedChannels = 0; + } - @Override - public void addProbeInfo( IPart part, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data ) - { - if( !AEConfig.instance().isFeatureEnabled( AEFeature.CHANNELS ) ) - { - return; - } - if( part instanceof PartDenseCableSmart || part instanceof PartCableSmart ) - { - final int usedChannels; - final int maxChannels = ( part instanceof PartDenseCableSmart ) ? 32 : 8; + final String formattedChannelString = String.format(TheOneProbeText.CHANNELS.getLocal(), usedChannels, maxChannels); - if( part.getGridNode().isActive() ) - { - final NBTTagCompound tmp = new NBTTagCompound(); - part.writeToNBT( tmp ); - usedChannels = tmp.getByte( "usedChannels" ); - } - else - { - usedChannels = 0; - } + probeInfo.text(formattedChannelString); + } - final String formattedChannelString = String.format( TheOneProbeText.CHANNELS.getLocal(), usedChannels, maxChannels ); - - probeInfo.text( formattedChannelString ); - } - - } + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/part/IPartProbInfoProvider.java b/src/main/java/appeng/integration/modules/theoneprobe/part/IPartProbInfoProvider.java index 15e877073..80391921d 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/part/IPartProbInfoProvider.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/part/IPartProbInfoProvider.java @@ -19,27 +19,23 @@ package appeng.integration.modules.theoneprobe.part; -import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.World; - +import appeng.api.parts.IPart; import mcjty.theoneprobe.api.IProbeHitData; import mcjty.theoneprobe.api.IProbeInfo; import mcjty.theoneprobe.api.IProbeInfoProvider; import mcjty.theoneprobe.api.ProbeMode; - -import appeng.api.parts.IPart; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; /** * Similar to {@link IProbeInfoProvider}, but already providing the {@link IPart} being looked at. - * */ -public interface IPartProbInfoProvider -{ +public interface IPartProbInfoProvider { - /** - * @see IProbeInfoProvider#addProbeInfo(ProbeMode, IProbeInfo, EntityPlayer, World, IBlockState, IProbeHitData) - */ - void addProbeInfo( IPart part, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data ); + /** + * @see IProbeInfoProvider#addProbeInfo(ProbeMode, IProbeInfo, EntityPlayer, World, IBlockState, IProbeHitData) + */ + void addProbeInfo(IPart part, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data); } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/part/P2PStateInfoProvider.java b/src/main/java/appeng/integration/modules/theoneprobe/part/P2PStateInfoProvider.java index 42b6f185f..f7a4001b5 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/part/P2PStateInfoProvider.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/part/P2PStateInfoProvider.java @@ -19,131 +19,102 @@ package appeng.integration.modules.theoneprobe.part; -import com.google.common.collect.Iterators; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.World; - -import mcjty.theoneprobe.api.IProbeHitData; -import mcjty.theoneprobe.api.IProbeInfo; -import mcjty.theoneprobe.api.ProbeMode; - import appeng.api.parts.IPart; import appeng.integration.modules.theoneprobe.TheOneProbeText; import appeng.me.GridAccessException; import appeng.parts.p2p.PartP2PTunnel; import appeng.util.Platform; +import com.google.common.collect.Iterators; +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeInfo; +import mcjty.theoneprobe.api.ProbeMode; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; -public class P2PStateInfoProvider implements IPartProbInfoProvider -{ +public class P2PStateInfoProvider implements IPartProbInfoProvider { - private static final int STATE_UNLINKED = 0; - private static final int STATE_OUTPUT = 1; - private static final int STATE_INPUT = 2; + private static final int STATE_UNLINKED = 0; + private static final int STATE_OUTPUT = 1; + private static final int STATE_INPUT = 2; - @Override - public void addProbeInfo( IPart part, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data ) - { - if( part instanceof PartP2PTunnel ) - { - final PartP2PTunnel tunnel = (PartP2PTunnel) part; + @Override + public void addProbeInfo(IPart part, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { + if (part instanceof PartP2PTunnel) { + final PartP2PTunnel tunnel = (PartP2PTunnel) part; - if( !tunnel.isPowered() ) - { - return; - } + if (!tunnel.isPowered()) { + return; + } - // The default state - int state = STATE_UNLINKED; - int outputCount = getOutputCount( tunnel ); - int inputCount = getInputCount( tunnel ); + // The default state + int state = STATE_UNLINKED; + int outputCount = getOutputCount(tunnel); + int inputCount = getInputCount(tunnel); - if( !tunnel.isOutput() ) - { - if( outputCount > 0 ) - { - // Only set it to INPUT if we know there are any outputs - state = STATE_INPUT; - } - } - else - { - if( inputCount > 0 ) - { - state = STATE_OUTPUT; - } - } + if (!tunnel.isOutput()) { + if (outputCount > 0) { + // Only set it to INPUT if we know there are any outputs + state = STATE_INPUT; + } + } else { + if (inputCount > 0) { + state = STATE_OUTPUT; + } + } - switch( state ) - { - case STATE_UNLINKED: - probeInfo.text( TheOneProbeText.P2P_UNLINKED.getLocal() ); - break; - case STATE_OUTPUT: - probeInfo.text( getInputText( inputCount ) ); - break; - case STATE_INPUT: - probeInfo.text( getOutputText( outputCount ) ); - break; - } + switch (state) { + case STATE_UNLINKED: + probeInfo.text(TheOneProbeText.P2P_UNLINKED.getLocal()); + break; + case STATE_OUTPUT: + probeInfo.text(getInputText(inputCount)); + break; + case STATE_INPUT: + probeInfo.text(getOutputText(outputCount)); + break; + } - final short freq = tunnel.getFrequency(); - final String freqTooltip = Platform.p2p().toHexString( freq ); + final short freq = tunnel.getFrequency(); + final String freqTooltip = Platform.p2p().toHexString(freq); - probeInfo.text( freqTooltip ); - } - } + probeInfo.text(freqTooltip); + } + } - private static int getOutputCount( PartP2PTunnel tunnel ) - { - try - { - return Iterators.size( tunnel.getOutputs().iterator() ); - } - catch( GridAccessException e ) - { - // Well... unknown size it is! - return 0; - } - } + private static int getOutputCount(PartP2PTunnel tunnel) { + try { + return Iterators.size(tunnel.getOutputs().iterator()); + } catch (GridAccessException e) { + // Well... unknown size it is! + return 0; + } + } - private static int getInputCount( PartP2PTunnel tunnel ) - { - try - { - return Iterators.size( tunnel.getInputs().iterator() ); - } - catch( GridAccessException e ) - { - // Well... unknown size it is! - return 0; - } - } + private static int getInputCount(PartP2PTunnel tunnel) { + try { + return Iterators.size(tunnel.getInputs().iterator()); + } catch (GridAccessException e) { + // Well... unknown size it is! + return 0; + } + } - private static String getOutputText( int outputs ) - { - if( outputs <= 1 ) - { - return TheOneProbeText.P2P_INPUT_ONE_OUTPUT.getLocal(); - } - else - { - return String.format( TheOneProbeText.P2P_INPUT_MANY_OUTPUTS.getLocal(), outputs ); - } - } + private static String getOutputText(int outputs) { + if (outputs <= 1) { + return TheOneProbeText.P2P_INPUT_ONE_OUTPUT.getLocal(); + } else { + return String.format(TheOneProbeText.P2P_INPUT_MANY_OUTPUTS.getLocal(), outputs); + } + } - private static String getInputText( int inputs ) - { - if( inputs <= 1 ) - { - return TheOneProbeText.P2P_OUTPUT_ONE_INPUT.getLocal(); - } - else - { - return String.format( TheOneProbeText.P2P_OUTPUT_MANY_INPUTS.getLocal(), inputs ); - } - } + private static String getInputText(int inputs) { + if (inputs <= 1) { + return TheOneProbeText.P2P_OUTPUT_ONE_INPUT.getLocal(); + } else { + return String.format(TheOneProbeText.P2P_OUTPUT_MANY_INPUTS.getLocal(), inputs); + } + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/part/PartAccessor.java b/src/main/java/appeng/integration/modules/theoneprobe/part/PartAccessor.java index 3534d519a..d9e9a7840 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/part/PartAccessor.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/part/PartAccessor.java @@ -19,37 +19,31 @@ package appeng.integration.modules.theoneprobe.part; -import java.util.Optional; - +import appeng.api.parts.IPart; +import appeng.api.parts.IPartHost; +import appeng.api.parts.SelectedPart; +import mcjty.theoneprobe.api.IProbeHitData; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; -import mcjty.theoneprobe.api.IProbeHitData; - -import appeng.api.parts.IPart; -import appeng.api.parts.IPartHost; -import appeng.api.parts.SelectedPart; +import java.util.Optional; -public final class PartAccessor -{ +public final class PartAccessor { - public Optional getMaybePart( final TileEntity te, final IProbeHitData data ) - { - if( te instanceof IPartHost ) - { - BlockPos pos = data.getPos(); - final Vec3d position = data.getHitVec().addVector( -pos.getX(), -pos.getY(), -pos.getZ() ); - final IPartHost host = (IPartHost) te; - final SelectedPart sp = host.selectPart( position ); + public Optional getMaybePart(final TileEntity te, final IProbeHitData data) { + if (te instanceof IPartHost) { + BlockPos pos = data.getPos(); + final Vec3d position = data.getHitVec().addVector(-pos.getX(), -pos.getY(), -pos.getZ()); + final IPartHost host = (IPartHost) te; + final SelectedPart sp = host.selectPart(position); - if( sp.part != null ) - { - return Optional.of( sp.part ); - } - } + if (sp.part != null) { + return Optional.of(sp.part); + } + } - return Optional.empty(); - } + return Optional.empty(); + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/part/PowerStateInfoProvider.java b/src/main/java/appeng/integration/modules/theoneprobe/part/PowerStateInfoProvider.java index 951a62cfc..8f3d63b87 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/part/PowerStateInfoProvider.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/part/PowerStateInfoProvider.java @@ -19,53 +19,42 @@ package appeng.integration.modules.theoneprobe.part; +import appeng.api.implementations.IPowerChannelState; +import appeng.api.parts.IPart; +import appeng.integration.modules.theoneprobe.TheOneProbeText; +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeInfo; +import mcjty.theoneprobe.api.ProbeMode; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; -import mcjty.theoneprobe.api.IProbeHitData; -import mcjty.theoneprobe.api.IProbeInfo; -import mcjty.theoneprobe.api.ProbeMode; -import appeng.api.implementations.IPowerChannelState; -import appeng.api.parts.IPart; -import appeng.integration.modules.theoneprobe.TheOneProbeText; +public class PowerStateInfoProvider implements IPartProbInfoProvider { + @Override + public void addProbeInfo(IPart part, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { + if (part instanceof IPowerChannelState) { + final IPowerChannelState state = (IPowerChannelState) part; + final String tooltip = this.getToolTip(state.isActive(), state.isPowered()); -public class PowerStateInfoProvider implements IPartProbInfoProvider -{ + probeInfo.text(tooltip); + } - @Override - public void addProbeInfo( IPart part, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data ) - { - if( part instanceof IPowerChannelState ) - { - final IPowerChannelState state = (IPowerChannelState) part; - final String tooltip = this.getToolTip( state.isActive(), state.isPowered() ); + } - probeInfo.text( tooltip ); - } + private String getToolTip(final boolean isActive, final boolean isPowered) { + final String result; - } + if (isActive && isPowered) { + result = TheOneProbeText.DEVICE_ONLINE.getLocal(); + } else if (isPowered) { + result = TheOneProbeText.DEVICE_MISSING_CHANNEL.getLocal(); + } else { + result = TheOneProbeText.DEVICE_OFFLINE.getLocal(); + } - private String getToolTip( final boolean isActive, final boolean isPowered ) - { - final String result; - - if( isActive && isPowered ) - { - result = TheOneProbeText.DEVICE_ONLINE.getLocal(); - } - else if( isPowered ) - { - result = TheOneProbeText.DEVICE_MISSING_CHANNEL.getLocal(); - } - else - { - result = TheOneProbeText.DEVICE_OFFLINE.getLocal(); - } - - return result; - } + return result; + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/part/StorageMonitorInfoProvider.java b/src/main/java/appeng/integration/modules/theoneprobe/part/StorageMonitorInfoProvider.java index 976999ff6..c0442a225 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/part/StorageMonitorInfoProvider.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/part/StorageMonitorInfoProvider.java @@ -19,49 +19,41 @@ package appeng.integration.modules.theoneprobe.part; -import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.World; - -import mcjty.theoneprobe.api.IProbeHitData; -import mcjty.theoneprobe.api.IProbeInfo; -import mcjty.theoneprobe.api.ProbeMode; - import appeng.api.implementations.parts.IPartStorageMonitor; import appeng.api.parts.IPart; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEStack; import appeng.integration.modules.theoneprobe.TheOneProbeText; +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeInfo; +import mcjty.theoneprobe.api.ProbeMode; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; -public class StorageMonitorInfoProvider implements IPartProbInfoProvider -{ +public class StorageMonitorInfoProvider implements IPartProbInfoProvider { - @Override - public void addProbeInfo( IPart part, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data ) - { - if( part instanceof IPartStorageMonitor ) - { - final IPartStorageMonitor monitor = (IPartStorageMonitor) part; + @Override + public void addProbeInfo(IPart part, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { + if (part instanceof IPartStorageMonitor) { + final IPartStorageMonitor monitor = (IPartStorageMonitor) part; - final IAEStack displayed = monitor.getDisplayed(); - final boolean isLocked = monitor.isLocked(); + final IAEStack displayed = monitor.getDisplayed(); + final boolean isLocked = monitor.isLocked(); - // TODO: generalize - if( displayed instanceof IAEItemStack ) - { - final IAEItemStack ais = (IAEItemStack) displayed; - probeInfo.text( TheOneProbeText.SHOWING.getLocal() + ": " + ais.asItemStackRepresentation().getDisplayName() ); - } - else if( displayed instanceof IAEFluidStack ) - { - final IAEFluidStack ais = (IAEFluidStack) displayed; - probeInfo.text( TheOneProbeText.SHOWING.getLocal() + ": " + ais.getFluid().getLocalizedName( ais.getFluidStack() ) ); - } + // TODO: generalize + if (displayed instanceof IAEItemStack) { + final IAEItemStack ais = (IAEItemStack) displayed; + probeInfo.text(TheOneProbeText.SHOWING.getLocal() + ": " + ais.asItemStackRepresentation().getDisplayName()); + } else if (displayed instanceof IAEFluidStack) { + final IAEFluidStack ais = (IAEFluidStack) displayed; + probeInfo.text(TheOneProbeText.SHOWING.getLocal() + ": " + ais.getFluid().getLocalizedName(ais.getFluidStack())); + } - probeInfo.text( isLocked ? TheOneProbeText.LOCKED.getLocal() : TheOneProbeText.UNLOCKED.getLocal() ); - } - } + probeInfo.text(isLocked ? TheOneProbeText.LOCKED.getLocal() : TheOneProbeText.UNLOCKED.getLocal()); + } + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/tile/ChargerInfoProvider.java b/src/main/java/appeng/integration/modules/theoneprobe/tile/ChargerInfoProvider.java index b6b843b8e..f095f9c0a 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/tile/ChargerInfoProvider.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/tile/ChargerInfoProvider.java @@ -19,43 +19,37 @@ package appeng.integration.modules.theoneprobe.tile; +import appeng.tile.AEBaseTile; +import appeng.tile.misc.TileCharger; +import mcjty.theoneprobe.api.ElementAlignment; +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeInfo; +import mcjty.theoneprobe.api.ProbeMode; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.items.IItemHandler; -import mcjty.theoneprobe.api.ElementAlignment; -import mcjty.theoneprobe.api.IProbeHitData; -import mcjty.theoneprobe.api.IProbeInfo; -import mcjty.theoneprobe.api.ProbeMode; -import appeng.tile.AEBaseTile; -import appeng.tile.misc.TileCharger; +public class ChargerInfoProvider implements ITileProbInfoProvider { + @Override + public void addProbeInfo(AEBaseTile tile, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { + if (tile instanceof TileCharger) { + final TileCharger charger = (TileCharger) tile; + final IItemHandler chargerInventory = charger.getInternalInventory(); + final ItemStack chargingItem = chargerInventory.getStackInSlot(0); -public class ChargerInfoProvider implements ITileProbInfoProvider -{ + if (!chargingItem.isEmpty()) { + final String currentInventory = chargingItem.getDisplayName(); + final IProbeInfo centerAlignedHorizontalLayout = probeInfo + .horizontal(probeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)); - @Override - public void addProbeInfo( AEBaseTile tile, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data ) - { - if( tile instanceof TileCharger ) - { - final TileCharger charger = (TileCharger) tile; - final IItemHandler chargerInventory = charger.getInternalInventory(); - final ItemStack chargingItem = chargerInventory.getStackInSlot( 0 ); - - if( !chargingItem.isEmpty() ) - { - final String currentInventory = chargingItem.getDisplayName(); - final IProbeInfo centerAlignedHorizontalLayout = probeInfo - .horizontal( probeInfo.defaultLayoutStyle().alignment( ElementAlignment.ALIGN_CENTER ) ); - - centerAlignedHorizontalLayout.item( chargingItem ); - centerAlignedHorizontalLayout.text( currentInventory ); - } - } - } + centerAlignedHorizontalLayout.item(chargingItem); + centerAlignedHorizontalLayout.text(currentInventory); + } + } + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/tile/CraftingMonitorInfoProvider.java b/src/main/java/appeng/integration/modules/theoneprobe/tile/CraftingMonitorInfoProvider.java index d1557c909..6d08e91e4 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/tile/CraftingMonitorInfoProvider.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/tile/CraftingMonitorInfoProvider.java @@ -19,47 +19,41 @@ package appeng.integration.modules.theoneprobe.tile; +import appeng.api.storage.data.IAEItemStack; +import appeng.integration.modules.theoneprobe.TheOneProbeText; +import appeng.tile.AEBaseTile; +import appeng.tile.crafting.TileCraftingMonitorTile; +import mcjty.theoneprobe.api.ElementAlignment; +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeInfo; +import mcjty.theoneprobe.api.ProbeMode; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import mcjty.theoneprobe.api.ElementAlignment; -import mcjty.theoneprobe.api.IProbeHitData; -import mcjty.theoneprobe.api.IProbeInfo; -import mcjty.theoneprobe.api.ProbeMode; -import appeng.api.storage.data.IAEItemStack; -import appeng.integration.modules.theoneprobe.TheOneProbeText; -import appeng.tile.AEBaseTile; -import appeng.tile.crafting.TileCraftingMonitorTile; +public class CraftingMonitorInfoProvider implements ITileProbInfoProvider { + @Override + public void addProbeInfo(AEBaseTile tile, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { + if (tile instanceof TileCraftingMonitorTile) { + final TileCraftingMonitorTile monitor = (TileCraftingMonitorTile) tile; + final IAEItemStack displayStack = monitor.getJobProgress(); -public class CraftingMonitorInfoProvider implements ITileProbInfoProvider -{ + if (displayStack != null) { + // TODO: check if OK + final ItemStack itemStack = displayStack.asItemStackRepresentation(); + final String itemName = itemStack.getDisplayName(); + final String formattedCrafting = String.format(TheOneProbeText.CRAFTING.getLocal(), itemName); - @Override - public void addProbeInfo( AEBaseTile tile, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data ) - { - if( tile instanceof TileCraftingMonitorTile ) - { - final TileCraftingMonitorTile monitor = (TileCraftingMonitorTile) tile; - final IAEItemStack displayStack = monitor.getJobProgress(); + final IProbeInfo centerAlignedHorizontalLayout = probeInfo + .horizontal(probeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)); - if( displayStack != null ) - { - // TODO: check if OK - final ItemStack itemStack = displayStack.asItemStackRepresentation(); - final String itemName = itemStack.getDisplayName(); - final String formattedCrafting = String.format( TheOneProbeText.CRAFTING.getLocal(), itemName ); - - final IProbeInfo centerAlignedHorizontalLayout = probeInfo - .horizontal( probeInfo.defaultLayoutStyle().alignment( ElementAlignment.ALIGN_CENTER ) ); - - centerAlignedHorizontalLayout.item( itemStack ); - centerAlignedHorizontalLayout.text( formattedCrafting ); - } - } - } + centerAlignedHorizontalLayout.item(itemStack); + centerAlignedHorizontalLayout.text(formattedCrafting); + } + } + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/tile/ITileProbInfoProvider.java b/src/main/java/appeng/integration/modules/theoneprobe/tile/ITileProbInfoProvider.java index d7051da2b..feae85eec 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/tile/ITileProbInfoProvider.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/tile/ITileProbInfoProvider.java @@ -19,27 +19,23 @@ package appeng.integration.modules.theoneprobe.tile; -import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.World; - +import appeng.tile.AEBaseTile; import mcjty.theoneprobe.api.IProbeHitData; import mcjty.theoneprobe.api.IProbeInfo; import mcjty.theoneprobe.api.IProbeInfoProvider; import mcjty.theoneprobe.api.ProbeMode; - -import appeng.tile.AEBaseTile; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; /** * Similar to {@link IProbeInfoProvider}, but already providing the {@link AEBaseTile} being looked at. - * */ -public interface ITileProbInfoProvider -{ +public interface ITileProbInfoProvider { - /** - * @see IProbeInfoProvider#addProbeInfo(ProbeMode, IProbeInfo, EntityPlayer, World, IBlockState, IProbeHitData) - */ - void addProbeInfo( AEBaseTile tile, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data ); + /** + * @see IProbeInfoProvider#addProbeInfo(ProbeMode, IProbeInfo, EntityPlayer, World, IBlockState, IProbeHitData) + */ + void addProbeInfo(AEBaseTile tile, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data); } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/tile/PowerStateInfoProvider.java b/src/main/java/appeng/integration/modules/theoneprobe/tile/PowerStateInfoProvider.java index 6bd9346db..7b5c4a91c 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/tile/PowerStateInfoProvider.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/tile/PowerStateInfoProvider.java @@ -19,46 +19,36 @@ package appeng.integration.modules.theoneprobe.tile; +import appeng.api.implementations.IPowerChannelState; +import appeng.integration.modules.theoneprobe.TheOneProbeText; +import appeng.tile.AEBaseTile; +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeInfo; +import mcjty.theoneprobe.api.ProbeMode; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; -import mcjty.theoneprobe.api.IProbeHitData; -import mcjty.theoneprobe.api.IProbeInfo; -import mcjty.theoneprobe.api.ProbeMode; -import appeng.api.implementations.IPowerChannelState; -import appeng.integration.modules.theoneprobe.TheOneProbeText; -import appeng.tile.AEBaseTile; +public class PowerStateInfoProvider implements ITileProbInfoProvider { + @Override + public void addProbeInfo(AEBaseTile tile, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { + if (tile instanceof IPowerChannelState) { + final IPowerChannelState state = (IPowerChannelState) tile; -public class PowerStateInfoProvider implements ITileProbInfoProvider -{ + final boolean isActive = state.isActive(); + final boolean isPowered = state.isPowered(); - @Override - public void addProbeInfo( AEBaseTile tile, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data ) - { - if( tile instanceof IPowerChannelState ) - { - final IPowerChannelState state = (IPowerChannelState) tile; + if (isActive && isPowered) { + probeInfo.text(TheOneProbeText.DEVICE_ONLINE.getLocal()); + } else if (isPowered) { + probeInfo.text(TheOneProbeText.DEVICE_MISSING_CHANNEL.getLocal()); + } else { + probeInfo.text(TheOneProbeText.DEVICE_OFFLINE.getLocal()); + } + } - final boolean isActive = state.isActive(); - final boolean isPowered = state.isPowered(); - - if( isActive && isPowered ) - { - probeInfo.text( TheOneProbeText.DEVICE_ONLINE.getLocal() ); - } - else if( isPowered ) - { - probeInfo.text( TheOneProbeText.DEVICE_MISSING_CHANNEL.getLocal() ); - } - else - { - probeInfo.text( TheOneProbeText.DEVICE_OFFLINE.getLocal() ); - } - } - - } + } } diff --git a/src/main/java/appeng/integration/modules/theoneprobe/tile/PowerStorageInfoProvider.java b/src/main/java/appeng/integration/modules/theoneprobe/tile/PowerStorageInfoProvider.java index d35bae02b..c430daf52 100644 --- a/src/main/java/appeng/integration/modules/theoneprobe/tile/PowerStorageInfoProvider.java +++ b/src/main/java/appeng/integration/modules/theoneprobe/tile/PowerStorageInfoProvider.java @@ -19,48 +19,41 @@ package appeng.integration.modules.theoneprobe.tile; -import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.World; - -import mcjty.theoneprobe.api.IProbeHitData; -import mcjty.theoneprobe.api.IProbeInfo; -import mcjty.theoneprobe.api.ProbeMode; - import appeng.api.networking.energy.IAEPowerStorage; import appeng.integration.modules.theoneprobe.TheOneProbeText; import appeng.tile.AEBaseTile; import appeng.util.Platform; +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeInfo; +import mcjty.theoneprobe.api.ProbeMode; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; -public class PowerStorageInfoProvider implements ITileProbInfoProvider -{ +public class PowerStorageInfoProvider implements ITileProbInfoProvider { - @Override - public void addProbeInfo( AEBaseTile tile, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data ) - { - if( tile instanceof IAEPowerStorage ) - { - final IAEPowerStorage storage = (IAEPowerStorage) tile; - final double maxPower = storage.getAEMaxPower(); + @Override + public void addProbeInfo(AEBaseTile tile, ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { + if (tile instanceof IAEPowerStorage) { + final IAEPowerStorage storage = (IAEPowerStorage) tile; + final double maxPower = storage.getAEMaxPower(); - if( maxPower > 0 ) - { - final long internalCurrentPower = (long) ( storage.getAECurrentPower() * 100 ); + if (maxPower > 0) { + final long internalCurrentPower = (long) (storage.getAECurrentPower() * 100); - if( internalCurrentPower >= 0 ) - { - final long internalMaxPower = (long) ( 100 * maxPower ); + if (internalCurrentPower >= 0) { + final long internalMaxPower = (long) (100 * maxPower); - final String formatCurrentPower = Platform.formatPowerLong( internalCurrentPower, false ); - final String formatMaxPower = Platform.formatPowerLong( internalMaxPower, false ); - final String formattedString = String.format( TheOneProbeText.STORED_ENERGY.getLocal(), formatCurrentPower, formatMaxPower ); + final String formatCurrentPower = Platform.formatPowerLong(internalCurrentPower, false); + final String formatMaxPower = Platform.formatPowerLong(internalMaxPower, false); + final String formattedString = String.format(TheOneProbeText.STORED_ENERGY.getLocal(), formatCurrentPower, formatMaxPower); - probeInfo.text( formattedString ); - } - } - } + probeInfo.text(formattedString); + } + } + } - } + } } diff --git a/src/main/java/appeng/integration/modules/waila/BaseWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/BaseWailaDataProvider.java index 42cb8ec71..92d776dc7 100644 --- a/src/main/java/appeng/integration/modules/waila/BaseWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/BaseWailaDataProvider.java @@ -19,8 +19,9 @@ package appeng.integration.modules.waila; -import java.util.List; - +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; +import mcp.mobius.waila.api.IWailaDataProvider; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -28,9 +29,7 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; -import mcp.mobius.waila.api.IWailaDataProvider; +import java.util.List; /** @@ -40,35 +39,29 @@ import mcp.mobius.waila.api.IWailaDataProvider; * @version rv2 * @since rv2 */ -public abstract class BaseWailaDataProvider implements IWailaDataProvider -{ - @Override - public ItemStack getWailaStack( final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return ItemStack.EMPTY; - } +public abstract class BaseWailaDataProvider implements IWailaDataProvider { + @Override + public ItemStack getWailaStack(final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + return ItemStack.EMPTY; + } - @Override - public List getWailaHead( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaHead(final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + return currentToolTip; + } - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaBody(final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + return currentToolTip; + } - @Override - public List getWailaTail( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaTail(final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + return currentToolTip; + } - @Override - public NBTTagCompound getNBTData( EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, BlockPos pos ) - { - return tag; - } + @Override + public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, BlockPos pos) { + return tag; + } } diff --git a/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java index a7d87d0f0..b21e96b05 100644 --- a/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java @@ -19,11 +19,12 @@ package appeng.integration.modules.waila; -import java.util.List; -import java.util.Optional; - +import appeng.api.parts.IPart; +import appeng.integration.modules.waila.part.*; import com.google.common.collect.Lists; - +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; +import mcp.mobius.waila.api.IWailaDataProvider; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -32,19 +33,8 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; -import mcp.mobius.waila.api.IWailaDataProvider; - -import appeng.api.parts.IPart; -import appeng.integration.modules.waila.part.ChannelWailaDataProvider; -import appeng.integration.modules.waila.part.IPartWailaDataProvider; -import appeng.integration.modules.waila.part.P2PStateWailaDataProvider; -import appeng.integration.modules.waila.part.PartAccessor; -import appeng.integration.modules.waila.part.PartStackWailaDataProvider; -import appeng.integration.modules.waila.part.PowerStateWailaDataProvider; -import appeng.integration.modules.waila.part.StorageMonitorWailaDataProvider; -import appeng.integration.modules.waila.part.Tracer; +import java.util.List; +import java.util.Optional; /** @@ -54,144 +44,126 @@ import appeng.integration.modules.waila.part.Tracer; * @version rv2 * @since rv2 */ -public final class PartWailaDataProvider implements IWailaDataProvider -{ - /** - * Contains all providers - */ - private final List providers; +public final class PartWailaDataProvider implements IWailaDataProvider { + /** + * Contains all providers + */ + private final List providers; - /** - * Can access parts through view-hits - */ - private final PartAccessor accessor = new PartAccessor(); + /** + * Can access parts through view-hits + */ + private final PartAccessor accessor = new PartAccessor(); - /** - * Traces views hit on blocks - */ - private final Tracer tracer = new Tracer(); + /** + * Traces views hit on blocks + */ + private final Tracer tracer = new Tracer(); - /** - * Initializes the provider list with all wanted providers - */ - public PartWailaDataProvider() - { - final IPartWailaDataProvider channel = new ChannelWailaDataProvider(); - final IPartWailaDataProvider storageMonitor = new StorageMonitorWailaDataProvider(); - final IPartWailaDataProvider powerState = new PowerStateWailaDataProvider(); - final IPartWailaDataProvider p2pState = new P2PStateWailaDataProvider(); - final IPartWailaDataProvider partStack = new PartStackWailaDataProvider(); + /** + * Initializes the provider list with all wanted providers + */ + public PartWailaDataProvider() { + final IPartWailaDataProvider channel = new ChannelWailaDataProvider(); + final IPartWailaDataProvider storageMonitor = new StorageMonitorWailaDataProvider(); + final IPartWailaDataProvider powerState = new PowerStateWailaDataProvider(); + final IPartWailaDataProvider p2pState = new P2PStateWailaDataProvider(); + final IPartWailaDataProvider partStack = new PartStackWailaDataProvider(); - this.providers = Lists.newArrayList( channel, storageMonitor, powerState, partStack, p2pState ); - } + this.providers = Lists.newArrayList(channel, storageMonitor, powerState, partStack, p2pState); + } - @Override - public ItemStack getWailaStack( final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - final RayTraceResult mop = accessor.getMOP(); + @Override + public ItemStack getWailaStack(final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); + final RayTraceResult mop = accessor.getMOP(); - final Optional maybePart = this.accessor.getMaybePart( te, mop ); + final Optional maybePart = this.accessor.getMaybePart(te, mop); - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); - ItemStack wailaStack = ItemStack.EMPTY; + ItemStack wailaStack = ItemStack.EMPTY; - for( final IPartWailaDataProvider provider : this.providers ) - { - wailaStack = provider.getWailaStack( part, config, wailaStack ); - } - return wailaStack; - } + for (final IPartWailaDataProvider provider : this.providers) { + wailaStack = provider.getWailaStack(part, config, wailaStack); + } + return wailaStack; + } - return ItemStack.EMPTY; - } + return ItemStack.EMPTY; + } - @Override - public List getWailaHead( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - final RayTraceResult mop = accessor.getMOP(); + @Override + public List getWailaHead(final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); + final RayTraceResult mop = accessor.getMOP(); - final Optional maybePart = this.accessor.getMaybePart( te, mop ); + final Optional maybePart = this.accessor.getMaybePart(te, mop); - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); - for( final IPartWailaDataProvider provider : this.providers ) - { - provider.getWailaHead( part, currentToolTip, accessor, config ); - } - } + for (final IPartWailaDataProvider provider : this.providers) { + provider.getWailaHead(part, currentToolTip, accessor, config); + } + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - final RayTraceResult mop = accessor.getMOP(); + @Override + public List getWailaBody(final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); + final RayTraceResult mop = accessor.getMOP(); - final Optional maybePart = this.accessor.getMaybePart( te, mop ); + final Optional maybePart = this.accessor.getMaybePart(te, mop); - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); - for( final IPartWailaDataProvider provider : this.providers ) - { - provider.getWailaBody( part, currentToolTip, accessor, config ); - } - } + for (final IPartWailaDataProvider provider : this.providers) { + provider.getWailaBody(part, currentToolTip, accessor, config); + } + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public List getWailaTail( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - final RayTraceResult mop = accessor.getMOP(); + @Override + public List getWailaTail(final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); + final RayTraceResult mop = accessor.getMOP(); - final Optional maybePart = this.accessor.getMaybePart( te, mop ); + final Optional maybePart = this.accessor.getMaybePart(te, mop); - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); - for( final IPartWailaDataProvider provider : this.providers ) - { - provider.getWailaTail( part, currentToolTip, accessor, config ); - } - } + for (final IPartWailaDataProvider provider : this.providers) { + provider.getWailaTail(part, currentToolTip, accessor, config); + } + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final TileEntity te, final NBTTagCompound tag, final World world, BlockPos pos ) - { - final RayTraceResult mop = this.tracer.retraceBlock( world, player, pos ); + @Override + public NBTTagCompound getNBTData(final EntityPlayerMP player, final TileEntity te, final NBTTagCompound tag, final World world, BlockPos pos) { + final RayTraceResult mop = this.tracer.retraceBlock(world, player, pos); - if( mop != null ) - { - final Optional maybePart = this.accessor.getMaybePart( te, mop ); + if (mop != null) { + final Optional maybePart = this.accessor.getMaybePart(te, mop); - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); - for( final IPartWailaDataProvider provider : this.providers ) - { - provider.getNBTData( player, part, te, tag, world, pos ); - } - } - } + for (final IPartWailaDataProvider provider : this.providers) { + provider.getNBTData(player, part, te, tag, world, pos); + } + } + } - return tag; - } + return tag; + } } diff --git a/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java index fe3348b8e..1d079f94f 100644 --- a/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java @@ -19,10 +19,14 @@ package appeng.integration.modules.waila; -import java.util.List; - +import appeng.integration.modules.waila.tile.ChargerWailaDataProvider; +import appeng.integration.modules.waila.tile.CraftingMonitorWailaDataProvider; +import appeng.integration.modules.waila.tile.PowerStateWailaDataProvider; +import appeng.integration.modules.waila.tile.PowerStorageWailaDataProvider; import com.google.common.collect.Lists; - +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; +import mcp.mobius.waila.api.IWailaDataProvider; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -30,14 +34,7 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; -import mcp.mobius.waila.api.IWailaDataProvider; - -import appeng.integration.modules.waila.tile.ChargerWailaDataProvider; -import appeng.integration.modules.waila.tile.CraftingMonitorWailaDataProvider; -import appeng.integration.modules.waila.tile.PowerStateWailaDataProvider; -import appeng.integration.modules.waila.tile.PowerStorageWailaDataProvider; +import java.util.List; /** @@ -47,73 +44,62 @@ import appeng.integration.modules.waila.tile.PowerStorageWailaDataProvider; * @version rv2 * @since rv2 */ -public final class TileWailaDataProvider implements IWailaDataProvider -{ - /** - * Contains all providers - */ - private final List providers; +public final class TileWailaDataProvider implements IWailaDataProvider { + /** + * Contains all providers + */ + private final List providers; - /** - * Initializes the provider list with all wanted providers - */ - public TileWailaDataProvider() - { - final IWailaDataProvider charger = new ChargerWailaDataProvider(); - final IWailaDataProvider energyCell = new PowerStorageWailaDataProvider(); - final IWailaDataProvider craftingBlock = new PowerStateWailaDataProvider(); - final IWailaDataProvider craftingMonitor = new CraftingMonitorWailaDataProvider(); + /** + * Initializes the provider list with all wanted providers + */ + public TileWailaDataProvider() { + final IWailaDataProvider charger = new ChargerWailaDataProvider(); + final IWailaDataProvider energyCell = new PowerStorageWailaDataProvider(); + final IWailaDataProvider craftingBlock = new PowerStateWailaDataProvider(); + final IWailaDataProvider craftingMonitor = new CraftingMonitorWailaDataProvider(); - this.providers = Lists.newArrayList( charger, energyCell, craftingBlock, craftingMonitor ); - } + this.providers = Lists.newArrayList(charger, energyCell, craftingBlock, craftingMonitor); + } - @Override - public ItemStack getWailaStack( final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return ItemStack.EMPTY; - } + @Override + public ItemStack getWailaStack(final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + return ItemStack.EMPTY; + } - @Override - public List getWailaHead( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - for( final IWailaDataProvider provider : this.providers ) - { - provider.getWailaHead( itemStack, currentToolTip, accessor, config ); - } + @Override + public List getWailaHead(final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + for (final IWailaDataProvider provider : this.providers) { + provider.getWailaHead(itemStack, currentToolTip, accessor, config); + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - for( final IWailaDataProvider provider : this.providers ) - { - provider.getWailaBody( itemStack, currentToolTip, accessor, config ); - } + @Override + public List getWailaBody(final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + for (final IWailaDataProvider provider : this.providers) { + provider.getWailaBody(itemStack, currentToolTip, accessor, config); + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public List getWailaTail( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - for( final IWailaDataProvider provider : this.providers ) - { - provider.getWailaTail( itemStack, currentToolTip, accessor, config ); - } + @Override + public List getWailaTail(final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + for (final IWailaDataProvider provider : this.providers) { + provider.getWailaTail(itemStack, currentToolTip, accessor, config); + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public NBTTagCompound getNBTData( EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, BlockPos pos ) - { - for( final IWailaDataProvider provider : this.providers ) - { - provider.getNBTData( player, te, tag, world, pos ); - } + @Override + public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, BlockPos pos) { + for (final IWailaDataProvider provider : this.providers) { + provider.getNBTData(player, te, tag, world, pos); + } - return tag; - } + return tag; + } } diff --git a/src/main/java/appeng/integration/modules/waila/WailaModule.java b/src/main/java/appeng/integration/modules/waila/WailaModule.java index efa350f0d..2c210e163 100644 --- a/src/main/java/appeng/integration/modules/waila/WailaModule.java +++ b/src/main/java/appeng/integration/modules/waila/WailaModule.java @@ -19,46 +19,40 @@ package appeng.integration.modules.waila; -import net.minecraftforge.fml.common.event.FMLInterModComms; - -import mcp.mobius.waila.api.IWailaDataProvider; -import mcp.mobius.waila.api.IWailaRegistrar; - import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; import appeng.tile.AEBaseTile; +import mcp.mobius.waila.api.IWailaDataProvider; +import mcp.mobius.waila.api.IWailaRegistrar; +import net.minecraftforge.fml.common.event.FMLInterModComms; -public class WailaModule implements IIntegrationModule -{ +public class WailaModule implements IIntegrationModule { - public WailaModule() - { - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.IWailaDataProvider.class ); - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.IWailaRegistrar.class ); - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.IWailaConfigHandler.class ); - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.IWailaDataAccessor.class ); - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.ITaggedList.class ); - } + public WailaModule() { + IntegrationHelper.testClassExistence(this, mcp.mobius.waila.api.IWailaDataProvider.class); + IntegrationHelper.testClassExistence(this, mcp.mobius.waila.api.IWailaRegistrar.class); + IntegrationHelper.testClassExistence(this, mcp.mobius.waila.api.IWailaConfigHandler.class); + IntegrationHelper.testClassExistence(this, mcp.mobius.waila.api.IWailaDataAccessor.class); + IntegrationHelper.testClassExistence(this, mcp.mobius.waila.api.ITaggedList.class); + } - public static void register( final IWailaRegistrar registrar ) - { - final IWailaDataProvider partHost = new PartWailaDataProvider(); + public static void register(final IWailaRegistrar registrar) { + final IWailaDataProvider partHost = new PartWailaDataProvider(); - registrar.registerStackProvider( partHost, AEBaseTile.class ); - registrar.registerBodyProvider( partHost, AEBaseTile.class ); - registrar.registerNBTProvider( partHost, AEBaseTile.class ); + registrar.registerStackProvider(partHost, AEBaseTile.class); + registrar.registerBodyProvider(partHost, AEBaseTile.class); + registrar.registerNBTProvider(partHost, AEBaseTile.class); - final IWailaDataProvider tile = new TileWailaDataProvider(); + final IWailaDataProvider tile = new TileWailaDataProvider(); - registrar.registerBodyProvider( tile, AEBaseTile.class ); - registrar.registerNBTProvider( tile, AEBaseTile.class ); - } + registrar.registerBodyProvider(tile, AEBaseTile.class); + registrar.registerNBTProvider(tile, AEBaseTile.class); + } - @Override - public void init() throws Throwable - { - FMLInterModComms.sendMessage( "waila", "register", this.getClass().getName() + ".register" ); - } + @Override + public void init() throws Throwable { + FMLInterModComms.sendMessage("waila", "register", this.getClass().getName() + ".register"); + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/BasePartWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/BasePartWailaDataProvider.java index ac51d200c..a9c0d62a9 100644 --- a/src/main/java/appeng/integration/modules/waila/part/BasePartWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/BasePartWailaDataProvider.java @@ -19,8 +19,9 @@ package appeng.integration.modules.waila.part; -import java.util.List; - +import appeng.api.parts.IPart; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -28,10 +29,7 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; - -import appeng.api.parts.IPart; +import java.util.List; /** @@ -41,35 +39,29 @@ import appeng.api.parts.IPart; * @version rv2 * @since rv2 */ -public abstract class BasePartWailaDataProvider implements IPartWailaDataProvider -{ - @Override - public ItemStack getWailaStack( final IPart part, final IWailaConfigHandler config, final ItemStack partStack ) - { - return ItemStack.EMPTY; - } +public abstract class BasePartWailaDataProvider implements IPartWailaDataProvider { + @Override + public ItemStack getWailaStack(final IPart part, final IWailaConfigHandler config, final ItemStack partStack) { + return ItemStack.EMPTY; + } - @Override - public List getWailaHead( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaHead(final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + return currentToolTip; + } - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaBody(final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + return currentToolTip; + } - @Override - public List getWailaTail( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaTail(final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + return currentToolTip; + } - @Override - public NBTTagCompound getNBTData( EntityPlayerMP player, IPart part, TileEntity te, NBTTagCompound tag, World world, BlockPos pos ) - { - return tag; - } + @Override + public NBTTagCompound getNBTData(EntityPlayerMP player, IPart part, TileEntity te, NBTTagCompound tag, World world, BlockPos pos) { + return tag; + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java index 705e64882..1315f58ef 100644 --- a/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java @@ -19,25 +19,23 @@ package appeng.integration.modules.waila.part; -import java.util.List; - +import appeng.api.parts.IPart; import appeng.core.AEConfig; import appeng.core.features.AEFeature; +import appeng.core.localization.WailaText; +import appeng.parts.networking.PartCableSmart; +import appeng.parts.networking.PartDenseCableSmart; +import it.unimi.dsi.fastutil.objects.Object2ByteMap; +import it.unimi.dsi.fastutil.objects.Object2ByteOpenHashMap; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import it.unimi.dsi.fastutil.objects.Object2ByteMap; -import it.unimi.dsi.fastutil.objects.Object2ByteOpenHashMap; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; - -import appeng.api.parts.IPart; -import appeng.core.localization.WailaText; -import appeng.parts.networking.PartCableSmart; -import appeng.parts.networking.PartDenseCableSmart; +import java.util.List; /** @@ -47,120 +45,106 @@ import appeng.parts.networking.PartDenseCableSmart; * @version rv2 * @since rv2 */ -public final class ChannelWailaDataProvider extends BasePartWailaDataProvider -{ - /** - * Channel key used for the transferred {@link net.minecraft.nbt.NBTTagCompound} - */ - private static final String ID_USED_CHANNELS = "usedChannels"; +public final class ChannelWailaDataProvider extends BasePartWailaDataProvider { + /** + * Channel key used for the transferred {@link net.minecraft.nbt.NBTTagCompound} + */ + private static final String ID_USED_CHANNELS = "usedChannels"; - /** - * Used cache for channels if the channel was not transmitted through the server. - *

- * This is useful, when a player just started to look at a tile and thus just requested the new information from the - * server. - *

- * The cache will be updated from the server. - */ - private final Object2ByteMap cache = new Object2ByteOpenHashMap<>(); + /** + * Used cache for channels if the channel was not transmitted through the server. + *

+ * This is useful, when a player just started to look at a tile and thus just requested the new information from the + * server. + *

+ * The cache will be updated from the server. + */ + private final Object2ByteMap cache = new Object2ByteOpenHashMap<>(); - /** - * Adds the used and max channel to the tool tip - * - * @param part being looked at part - * @param currentToolTip current tool tip - * @param accessor wrapper for various world information - * @param config config to react to various settings - * @return modified tool tip - */ - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - if( !AEConfig.instance().isFeatureEnabled( AEFeature.CHANNELS ) ) - { - return currentToolTip; - } - if( part instanceof PartCableSmart || part instanceof PartDenseCableSmart ) - { - final NBTTagCompound tag = accessor.getNBTData(); + /** + * Adds the used and max channel to the tool tip + * + * @param part being looked at part + * @param currentToolTip current tool tip + * @param accessor wrapper for various world information + * @param config config to react to various settings + * @return modified tool tip + */ + @Override + public List getWailaBody(final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + if (!AEConfig.instance().isFeatureEnabled(AEFeature.CHANNELS)) { + return currentToolTip; + } + if (part instanceof PartCableSmart || part instanceof PartDenseCableSmart) { + final NBTTagCompound tag = accessor.getNBTData(); - final byte usedChannels = this.getUsedChannels( part, tag, this.cache ); + final byte usedChannels = this.getUsedChannels(part, tag, this.cache); - if( usedChannels >= 0 ) - { - final byte maxChannels = (byte) ( ( part instanceof PartDenseCableSmart ) ? 32 : 8 ); + if (usedChannels >= 0) { + final byte maxChannels = (byte) ((part instanceof PartDenseCableSmart) ? 32 : 8); - final String formattedToolTip = String.format( WailaText.Channels.getLocal(), usedChannels, maxChannels ); - currentToolTip.add( formattedToolTip ); - } - } + final String formattedToolTip = String.format(WailaText.Channels.getLocal(), usedChannels, maxChannels); + currentToolTip.add(formattedToolTip); + } + } - return currentToolTip; - } + return currentToolTip; + } - /** - * Determines the source of the channel. - *

- * If the client received information of the channels on the server, they are used, else if the cache contains a - * previous stored value, this will be used. Default value is 0. - * - * @param part part to be looked at - * @param tag tag maybe containing the channel information - * @param cache cache with previous knowledge - * @return used channels on the cable - */ - private byte getUsedChannels( final IPart part, final NBTTagCompound tag, final Object2ByteMap cache ) - { - final byte usedChannels; + /** + * Determines the source of the channel. + *

+ * If the client received information of the channels on the server, they are used, else if the cache contains a + * previous stored value, this will be used. Default value is 0. + * + * @param part part to be looked at + * @param tag tag maybe containing the channel information + * @param cache cache with previous knowledge + * @return used channels on the cable + */ + private byte getUsedChannels(final IPart part, final NBTTagCompound tag, final Object2ByteMap cache) { + final byte usedChannels; - if( tag.hasKey( ID_USED_CHANNELS ) ) - { - usedChannels = tag.getByte( ID_USED_CHANNELS ); - this.cache.put( part, usedChannels ); - } - else if( this.cache.containsKey( part ) ) - { - usedChannels = this.cache.get( part ); - } - else - { - usedChannels = -1; - } + if (tag.hasKey(ID_USED_CHANNELS)) { + usedChannels = tag.getByte(ID_USED_CHANNELS); + this.cache.put(part, usedChannels); + } else if (this.cache.containsKey(part)) { + usedChannels = this.cache.get(part); + } else { + usedChannels = -1; + } - return usedChannels; - } + return usedChannels; + } - /** - * Called on server to transfer information from server to client. - *

- * If the part is a cable, it writes the channel information in the {@code #tag} using the {@code ID_USED_CHANNELS} - * key. - * - * @param player player looking at the part - * @param part part being looked at - * @param te host of the part - * @param tag transferred tag which is send to the client - * @param world world of the part - * @param pos pos of the part - * @return tag send to the client - */ - @Override - public NBTTagCompound getNBTData( EntityPlayerMP player, IPart part, TileEntity te, NBTTagCompound tag, World world, BlockPos pos ) - { - if( part instanceof PartCableSmart || part instanceof PartDenseCableSmart ) - { - final NBTTagCompound tempTag = new NBTTagCompound(); + /** + * Called on server to transfer information from server to client. + *

+ * If the part is a cable, it writes the channel information in the {@code #tag} using the {@code ID_USED_CHANNELS} + * key. + * + * @param player player looking at the part + * @param part part being looked at + * @param te host of the part + * @param tag transferred tag which is send to the client + * @param world world of the part + * @param pos pos of the part + * @return tag send to the client + */ + @Override + public NBTTagCompound getNBTData(EntityPlayerMP player, IPart part, TileEntity te, NBTTagCompound tag, World world, BlockPos pos) { + if (part instanceof PartCableSmart || part instanceof PartDenseCableSmart) { + final NBTTagCompound tempTag = new NBTTagCompound(); - part.writeToNBT( tempTag ); + part.writeToNBT(tempTag); - if( tempTag.hasKey( ID_USED_CHANNELS ) ) - { - final byte usedChannels = tempTag.getByte( ID_USED_CHANNELS ); + if (tempTag.hasKey(ID_USED_CHANNELS)) { + final byte usedChannels = tempTag.getByte(ID_USED_CHANNELS); - tag.setByte( ID_USED_CHANNELS, usedChannels ); - } - } + tag.setByte(ID_USED_CHANNELS, usedChannels); + } + } - return tag; - } + return tag; + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java index 51126ea52..a5b2b205c 100644 --- a/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java @@ -19,8 +19,9 @@ package appeng.integration.modules.waila.part; -import java.util.List; - +import appeng.api.parts.IPart; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -28,10 +29,7 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; - -import appeng.api.parts.IPart; +import java.util.List; /** @@ -42,15 +40,14 @@ import appeng.api.parts.IPart; * @version rv2 * @since rv2 */ -public interface IPartWailaDataProvider -{ - ItemStack getWailaStack( IPart part, IWailaConfigHandler config, ItemStack partStack ); +public interface IPartWailaDataProvider { + ItemStack getWailaStack(IPart part, IWailaConfigHandler config, ItemStack partStack); - List getWailaHead( IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ); + List getWailaHead(IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config); - List getWailaBody( IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ); + List getWailaBody(IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config); - List getWailaTail( IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ); + List getWailaTail(IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config); - NBTTagCompound getNBTData( EntityPlayerMP player, IPart part, TileEntity te, NBTTagCompound tag, World world, BlockPos pos ); + NBTTagCompound getNBTData(EntityPlayerMP player, IPart part, TileEntity te, NBTTagCompound tag, World world, BlockPos pos); } diff --git a/src/main/java/appeng/integration/modules/waila/part/P2PStateWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/P2PStateWailaDataProvider.java index ef000ec32..eae1afd71 100644 --- a/src/main/java/appeng/integration/modules/waila/part/P2PStateWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/P2PStateWailaDataProvider.java @@ -19,11 +19,14 @@ package appeng.integration.modules.waila.part; -import java.util.List; - -import appeng.integration.modules.theoneprobe.TheOneProbeText; +import appeng.api.parts.IPart; +import appeng.core.localization.WailaText; +import appeng.me.GridAccessException; +import appeng.parts.p2p.PartP2PTunnel; +import appeng.util.Platform; import com.google.common.collect.Iterators; - +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; @@ -31,170 +34,132 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.translation.I18n; import net.minecraft.world.World; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; - -import appeng.api.parts.IPart; -import appeng.core.localization.WailaText; -import appeng.me.GridAccessException; -import appeng.parts.p2p.PartP2PTunnel; -import appeng.util.Platform; +import java.util.List; /** * Provides information about a P2P tunnel to WAILA. */ -public final class P2PStateWailaDataProvider extends BasePartWailaDataProvider -{ +public final class P2PStateWailaDataProvider extends BasePartWailaDataProvider { - private static final int STATE_UNLINKED = 0; - private static final int STATE_OUTPUT = 1; - private static final int STATE_INPUT = 2; - public static final String TAG_P2P_STATE = "p2p_state"; - public static final String TAG_P2P_FREQUENCY = "p2p_frequency"; + private static final int STATE_UNLINKED = 0; + private static final int STATE_OUTPUT = 1; + private static final int STATE_INPUT = 2; + public static final String TAG_P2P_STATE = "p2p_state"; + public static final String TAG_P2P_FREQUENCY = "p2p_frequency"; - /** - * Adds state to the tooltip - * - * @param part part with state - * @param currentToolTip to be added to tooltip - * @param accessor wrapper for various information - * @param config config settings - * - * @return modified tooltip - */ - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - if( part instanceof PartP2PTunnel ) - { - NBTTagCompound nbtData = accessor.getNBTData(); - if( nbtData.hasKey( TAG_P2P_STATE ) ) - { - int[] stateArr = nbtData.getIntArray( TAG_P2P_STATE ); - if( stateArr.length == 2 ) - { - int state = stateArr[0]; - int outputs = stateArr[1]; + /** + * Adds state to the tooltip + * + * @param part part with state + * @param currentToolTip to be added to tooltip + * @param accessor wrapper for various information + * @param config config settings + * @return modified tooltip + */ + @Override + public List getWailaBody(final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + if (part instanceof PartP2PTunnel) { + NBTTagCompound nbtData = accessor.getNBTData(); + if (nbtData.hasKey(TAG_P2P_STATE)) { + int[] stateArr = nbtData.getIntArray(TAG_P2P_STATE); + if (stateArr.length == 2) { + int state = stateArr[0]; + int outputs = stateArr[1]; - switch( state ) - { - case STATE_UNLINKED: - currentToolTip.add( WailaText.P2PUnlinked.getLocal() ); - break; - case STATE_OUTPUT: - currentToolTip.add( WailaText.P2POutput.getLocal() ); - break; - case STATE_INPUT: - currentToolTip.add( getOutputText( outputs ) ); - break; - } - } + switch (state) { + case STATE_UNLINKED: + currentToolTip.add(WailaText.P2PUnlinked.getLocal()); + break; + case STATE_OUTPUT: + currentToolTip.add(WailaText.P2POutput.getLocal()); + break; + case STATE_INPUT: + currentToolTip.add(getOutputText(outputs)); + break; + } + } - final short freq = nbtData.getShort( TAG_P2P_FREQUENCY ); - final String freqTooltip = Platform.p2p().toHexString( freq ); - currentToolTip.add( I18n.translateToLocalFormatted( "gui.tooltips.appliedenergistics2.P2PFrequency", freqTooltip ) ); - } - } + final short freq = nbtData.getShort(TAG_P2P_FREQUENCY); + final String freqTooltip = Platform.p2p().toHexString(freq); + currentToolTip.add(I18n.translateToLocalFormatted("gui.tooltips.appliedenergistics2.P2PFrequency", freqTooltip)); + } + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public NBTTagCompound getNBTData( EntityPlayerMP player, IPart part, TileEntity te, NBTTagCompound tag, World world, BlockPos pos ) - { - if( part instanceof PartP2PTunnel ) - { - final PartP2PTunnel tunnel = (PartP2PTunnel) part; + @Override + public NBTTagCompound getNBTData(EntityPlayerMP player, IPart part, TileEntity te, NBTTagCompound tag, World world, BlockPos pos) { + if (part instanceof PartP2PTunnel) { + final PartP2PTunnel tunnel = (PartP2PTunnel) part; - if( !tunnel.isPowered() ) - { - return tag; - } + if (!tunnel.isPowered()) { + return tag; + } - // Frquency - final short frequency = tunnel.getFrequency(); - tag.setShort( TAG_P2P_FREQUENCY, frequency ); + // Frquency + final short frequency = tunnel.getFrequency(); + tag.setShort(TAG_P2P_FREQUENCY, frequency); - // The default state - int state = STATE_UNLINKED; - int outputCount = getOutputCount( tunnel ); - int inputCount = getInputCount( tunnel ); + // The default state + int state = STATE_UNLINKED; + int outputCount = getOutputCount(tunnel); + int inputCount = getInputCount(tunnel); - if( !tunnel.isOutput() ) - { - if( outputCount > 0 ) - { - // Only set it to INPUT if we know there are any outputs - state = STATE_INPUT; - } - } - else - { - if( inputCount > 0 ) - { - state = STATE_OUTPUT; - } - } + if (!tunnel.isOutput()) { + if (outputCount > 0) { + // Only set it to INPUT if we know there are any outputs + state = STATE_INPUT; + } + } else { + if (inputCount > 0) { + state = STATE_OUTPUT; + } + } - tag.setIntArray( TAG_P2P_STATE, new int[] { - state, - outputCount - } ); + tag.setIntArray(TAG_P2P_STATE, new int[]{ + state, + outputCount + }); - } + } - return tag; - } + return tag; + } - private static int getOutputCount( PartP2PTunnel tunnel ) - { - try - { - return Iterators.size( tunnel.getOutputs().iterator() ); - } - catch( GridAccessException e ) - { - // Well... unknown size it is! - return 0; - } - } + private static int getOutputCount(PartP2PTunnel tunnel) { + try { + return Iterators.size(tunnel.getOutputs().iterator()); + } catch (GridAccessException e) { + // Well... unknown size it is! + return 0; + } + } - private static int getInputCount( PartP2PTunnel tunnel ) - { - try - { - return Iterators.size( tunnel.getInputs().iterator() ); - } - catch( GridAccessException e ) - { - // Well... unknown size it is! - return 0; - } - } + private static int getInputCount(PartP2PTunnel tunnel) { + try { + return Iterators.size(tunnel.getInputs().iterator()); + } catch (GridAccessException e) { + // Well... unknown size it is! + return 0; + } + } - private static String getOutputText( int outputs ) - { - if( outputs <= 1 ) - { - return WailaText.P2P_INPUT_ONE_OUTPUT.getLocal(); - } - else - { - return String.format( WailaText.P2P_INPUT_MANY_OUTPUTS.getLocal(), outputs ); - } - } + private static String getOutputText(int outputs) { + if (outputs <= 1) { + return WailaText.P2P_INPUT_ONE_OUTPUT.getLocal(); + } else { + return String.format(WailaText.P2P_INPUT_MANY_OUTPUTS.getLocal(), outputs); + } + } - private static String getInputText( int inputs ) - { - if( inputs <= 1 ) - { - return WailaText.P2P_OUTPUT_ONE_INPUT.getLocal(); - } - else - { - return String.format( WailaText.P2P_OUTPUT_MANY_INPUTS.getLocal(), inputs ); - } - } + private static String getInputText(int inputs) { + if (inputs <= 1) { + return WailaText.P2P_OUTPUT_ONE_INPUT.getLocal(); + } else { + return String.format(WailaText.P2P_OUTPUT_MANY_INPUTS.getLocal(), inputs); + } + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java b/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java index 7c1c810d5..b9935e828 100644 --- a/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java +++ b/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java @@ -19,16 +19,15 @@ package appeng.integration.modules.waila.part; -import java.util.Optional; - +import appeng.api.parts.IPart; +import appeng.api.parts.IPartHost; +import appeng.api.parts.SelectedPart; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; -import appeng.api.parts.IPart; -import appeng.api.parts.IPartHost; -import appeng.api.parts.SelectedPart; +import java.util.Optional; /** @@ -38,34 +37,29 @@ import appeng.api.parts.SelectedPart; * @version rv2 * @since rv2 */ -public final class PartAccessor -{ - /** - * Hits a {@link IPartHost} with {@link BlockPos}. - *

- * You can derive the looked at {@link IPart} by doing that. If a facade is being looked at, it is - * defined as being absent. - * - * @param te being looked at {@link TileEntity} - * @param mop type of ray-trace - * - * @return maybe the looked at {@link IPart} - */ - public Optional getMaybePart( final TileEntity te, final RayTraceResult mop ) - { - if( te instanceof IPartHost ) - { - BlockPos pos = mop.getBlockPos(); - final Vec3d position = mop.hitVec.addVector( -pos.getX(), -pos.getY(), -pos.getZ() ); - final IPartHost host = (IPartHost) te; - final SelectedPart sp = host.selectPart( position ); +public final class PartAccessor { + /** + * Hits a {@link IPartHost} with {@link BlockPos}. + *

+ * You can derive the looked at {@link IPart} by doing that. If a facade is being looked at, it is + * defined as being absent. + * + * @param te being looked at {@link TileEntity} + * @param mop type of ray-trace + * @return maybe the looked at {@link IPart} + */ + public Optional getMaybePart(final TileEntity te, final RayTraceResult mop) { + if (te instanceof IPartHost) { + BlockPos pos = mop.getBlockPos(); + final Vec3d position = mop.hitVec.addVector(-pos.getX(), -pos.getY(), -pos.getZ()); + final IPartHost host = (IPartHost) te; + final SelectedPart sp = host.selectPart(position); - if( sp.part != null ) - { - return Optional.of( sp.part ); - } - } + if (sp.part != null) { + return Optional.of(sp.part); + } + } - return Optional.empty(); - } + return Optional.empty(); + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/PartStackWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/PartStackWailaDataProvider.java index 31ab7ddf6..8e0d99570 100644 --- a/src/main/java/appeng/integration/modules/waila/part/PartStackWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/PartStackWailaDataProvider.java @@ -19,12 +19,10 @@ package appeng.integration.modules.waila.part; -import net.minecraft.item.ItemStack; - -import mcp.mobius.waila.api.IWailaConfigHandler; - import appeng.api.parts.IPart; import appeng.api.parts.PartItemStack; +import mcp.mobius.waila.api.IWailaConfigHandler; +import net.minecraft.item.ItemStack; /** @@ -34,14 +32,12 @@ import appeng.api.parts.PartItemStack; * @version rv2 * @since rv2 */ -public class PartStackWailaDataProvider extends BasePartWailaDataProvider -{ +public class PartStackWailaDataProvider extends BasePartWailaDataProvider { - @Override - public ItemStack getWailaStack( final IPart part, final IWailaConfigHandler config, ItemStack partStack ) - { - partStack = part.getItemStack( PartItemStack.PICK ); - return partStack; - } + @Override + public ItemStack getWailaStack(final IPart part, final IWailaConfigHandler config, ItemStack partStack) { + partStack = part.getItemStack(PartItemStack.PICK); + return partStack; + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java index c7e3a8261..9815fa013 100644 --- a/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java @@ -19,14 +19,13 @@ package appeng.integration.modules.waila.part; -import java.util.List; - -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; - import appeng.api.implementations.IPowerChannelState; import appeng.api.parts.IPart; import appeng.core.localization.WailaText; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; + +import java.util.List; /** @@ -36,56 +35,45 @@ import appeng.core.localization.WailaText; * @version rv2 * @since rv2 */ -public final class PowerStateWailaDataProvider extends BasePartWailaDataProvider -{ - /** - * Adds state to the tooltip - * - * @param part part with state - * @param currentToolTip to be added to tooltip - * @param accessor wrapper for various information - * @param config config settings - * - * @return modified tooltip - */ - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - if( part instanceof IPowerChannelState ) - { - final IPowerChannelState state = (IPowerChannelState) part; +public final class PowerStateWailaDataProvider extends BasePartWailaDataProvider { + /** + * Adds state to the tooltip + * + * @param part part with state + * @param currentToolTip to be added to tooltip + * @param accessor wrapper for various information + * @param config config settings + * @return modified tooltip + */ + @Override + public List getWailaBody(final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + if (part instanceof IPowerChannelState) { + final IPowerChannelState state = (IPowerChannelState) part; - currentToolTip.add( this.getToolTip( state.isActive(), state.isPowered() ) ); - } + currentToolTip.add(this.getToolTip(state.isActive(), state.isPowered())); + } - return currentToolTip; - } + return currentToolTip; + } - /** - * Gets the corresponding tool tip for different values of {@code #isActive} and {@code #isPowered} - * - * @param isActive if part is active - * @param isPowered if part is powered - * - * @return tooltip of the state - */ - private String getToolTip( final boolean isActive, final boolean isPowered ) - { - final String result; + /** + * Gets the corresponding tool tip for different values of {@code #isActive} and {@code #isPowered} + * + * @param isActive if part is active + * @param isPowered if part is powered + * @return tooltip of the state + */ + private String getToolTip(final boolean isActive, final boolean isPowered) { + final String result; - if( isActive && isPowered ) - { - result = WailaText.DeviceOnline.getLocal(); - } - else if( isPowered ) - { - result = WailaText.DeviceMissingChannel.getLocal(); - } - else - { - result = WailaText.DeviceOffline.getLocal(); - } + if (isActive && isPowered) { + result = WailaText.DeviceOnline.getLocal(); + } else if (isPowered) { + result = WailaText.DeviceMissingChannel.getLocal(); + } else { + result = WailaText.DeviceOffline.getLocal(); + } - return result; - } + return result; + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java index 30647b6de..7f2ac3f2b 100644 --- a/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java @@ -19,17 +19,16 @@ package appeng.integration.modules.waila.part; -import java.util.List; - -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; - import appeng.api.implementations.parts.IPartStorageMonitor; import appeng.api.parts.IPart; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEStack; import appeng.core.localization.WailaText; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; + +import java.util.List; /** @@ -39,44 +38,37 @@ import appeng.core.localization.WailaText; * @version rv2 * @since rv2 */ -public final class StorageMonitorWailaDataProvider extends BasePartWailaDataProvider -{ - /** - * Displays the stack if present and if the monitor is locked. - * Can handle fluids and items. - * - * @param part maybe storage monitor - * @param currentToolTip to be written to tooltip - * @param accessor information wrapper - * @param config config option - * - * @return modified tooltip - */ - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - if( part instanceof IPartStorageMonitor ) - { - final IPartStorageMonitor monitor = (IPartStorageMonitor) part; +public final class StorageMonitorWailaDataProvider extends BasePartWailaDataProvider { + /** + * Displays the stack if present and if the monitor is locked. + * Can handle fluids and items. + * + * @param part maybe storage monitor + * @param currentToolTip to be written to tooltip + * @param accessor information wrapper + * @param config config option + * @return modified tooltip + */ + @Override + public List getWailaBody(final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + if (part instanceof IPartStorageMonitor) { + final IPartStorageMonitor monitor = (IPartStorageMonitor) part; - final IAEStack displayed = monitor.getDisplayed(); - final boolean isLocked = monitor.isLocked(); + final IAEStack displayed = monitor.getDisplayed(); + final boolean isLocked = monitor.isLocked(); - // TODO: generalize - if( displayed instanceof IAEItemStack ) - { - final IAEItemStack ais = (IAEItemStack) displayed; - currentToolTip.add( WailaText.Showing.getLocal() + ": " + ais.asItemStackRepresentation().getDisplayName() ); - } - else if( displayed instanceof IAEFluidStack ) - { - final IAEFluidStack ais = (IAEFluidStack) displayed; - currentToolTip.add( WailaText.Showing.getLocal() + ": " + ais.getFluid().getLocalizedName( ais.getFluidStack() ) ); - } + // TODO: generalize + if (displayed instanceof IAEItemStack) { + final IAEItemStack ais = (IAEItemStack) displayed; + currentToolTip.add(WailaText.Showing.getLocal() + ": " + ais.asItemStackRepresentation().getDisplayName()); + } else if (displayed instanceof IAEFluidStack) { + final IAEFluidStack ais = (IAEFluidStack) displayed; + currentToolTip.add(WailaText.Showing.getLocal() + ": " + ais.getFluid().getLocalizedName(ais.getFluidStack())); + } - currentToolTip.add( ( isLocked ) ? WailaText.Locked.getLocal() : WailaText.Unlocked.getLocal() ); - } + currentToolTip.add((isLocked) ? WailaText.Locked.getLocal() : WailaText.Unlocked.getLocal()); + } - return currentToolTip; - } + return currentToolTip; + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/Tracer.java b/src/main/java/appeng/integration/modules/waila/part/Tracer.java index 43e6bcd29..0bb456a02 100644 --- a/src/main/java/appeng/integration/modules/waila/part/Tracer.java +++ b/src/main/java/appeng/integration/modules/waila/part/Tracer.java @@ -35,66 +35,55 @@ import net.minecraft.world.World; * @version rv2 * @since rv2 */ -public final class Tracer -{ - /** - * Trace view of players to blocks. - * Ignore all which are out of reach. - * - * @param world word of block - * @param player player viewing block - * @param pos pos of block - * - * @return trace movement. Can be null - */ - public RayTraceResult retraceBlock( final World world, final EntityPlayerMP player, BlockPos pos ) - { - IBlockState blockState = world.getBlockState( pos ); +public final class Tracer { + /** + * Trace view of players to blocks. + * Ignore all which are out of reach. + * + * @param world word of block + * @param player player viewing block + * @param pos pos of block + * @return trace movement. Can be null + */ + public RayTraceResult retraceBlock(final World world, final EntityPlayerMP player, BlockPos pos) { + IBlockState blockState = world.getBlockState(pos); - final Vec3d headVec = this.getCorrectedHeadVec( player ); - final Vec3d lookVec = player.getLook( 1.0F ); - final double reach = this.getBlockReachDistance_server( player ); - final Vec3d endVec = headVec.addVector( lookVec.x * reach, lookVec.y * reach, lookVec.z * reach ); + final Vec3d headVec = this.getCorrectedHeadVec(player); + final Vec3d lookVec = player.getLook(1.0F); + final double reach = this.getBlockReachDistance_server(player); + final Vec3d endVec = headVec.addVector(lookVec.x * reach, lookVec.y * reach, lookVec.z * reach); - return blockState.collisionRayTrace( world, pos, headVec, endVec ); - } + return blockState.collisionRayTrace(world, pos, headVec, endVec); + } - /** - * Gets the view point of a player - * - * @param player player with head - * - * @return view point of player - */ - private Vec3d getCorrectedHeadVec( final EntityPlayer player ) - { - double x = player.posX; - double y = player.posY; - double z = player.posZ; + /** + * Gets the view point of a player + * + * @param player player with head + * @return view point of player + */ + private Vec3d getCorrectedHeadVec(final EntityPlayer player) { + double x = player.posX; + double y = player.posY; + double z = player.posZ; - if( player.world.isRemote ) - { - // compatibility with eye height changing mods - y += player.getEyeHeight() - player.getDefaultEyeHeight(); - } - else - { - y += player.getEyeHeight(); - if( player instanceof EntityPlayerMP && player.isSneaking() ) - { - y -= 0.08; - } - } - return new Vec3d( x, y, z ); - } + if (player.world.isRemote) { + // compatibility with eye height changing mods + y += player.getEyeHeight() - player.getDefaultEyeHeight(); + } else { + y += player.getEyeHeight(); + if (player instanceof EntityPlayerMP && player.isSneaking()) { + y -= 0.08; + } + } + return new Vec3d(x, y, z); + } - /** - * @param player multi-player player - * - * @return block reach distance of player - */ - private double getBlockReachDistance_server( final EntityPlayerMP player ) - { - return player.interactionManager.getBlockReachDistance(); - } + /** + * @param player multi-player player + * @return block reach distance of player + */ + private double getBlockReachDistance_server(final EntityPlayerMP player) { + return player.interactionManager.getBlockReachDistance(); + } } diff --git a/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java index 80ad1da9c..185fbb50c 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java @@ -19,10 +19,11 @@ package appeng.integration.modules.waila.tile; -import java.util.List; - -import javax.annotation.Nonnull; - +import appeng.core.localization.WailaText; +import appeng.integration.modules.waila.BaseWailaDataProvider; +import appeng.tile.misc.TileCharger; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.client.Minecraft; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.EntityPlayer; @@ -30,12 +31,8 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.items.IItemHandler; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; - -import appeng.core.localization.WailaText; -import appeng.integration.modules.waila.BaseWailaDataProvider; -import appeng.tile.misc.TileCharger; +import javax.annotation.Nonnull; +import java.util.List; /** @@ -45,40 +42,35 @@ import appeng.tile.misc.TileCharger; * @version rv2 * @since rv2 */ -public final class ChargerWailaDataProvider extends BaseWailaDataProvider -{ - /** - * Displays the holding item and its tooltip - * - * @param itemStack stack of charger - * @param currentToolTip unmodified tooltip - * @param accessor wrapper information - * @param config config option - * - * @return modified tooltip - */ - @Override - public List getWailaBody( @Nonnull final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - if( te instanceof TileCharger ) - { - final TileCharger charger = (TileCharger) te; - final IItemHandler chargerInventory = charger.getInternalInventory(); - final ItemStack chargingItem = chargerInventory.getStackInSlot( 0 ); +public final class ChargerWailaDataProvider extends BaseWailaDataProvider { + /** + * Displays the holding item and its tooltip + * + * @param itemStack stack of charger + * @param currentToolTip unmodified tooltip + * @param accessor wrapper information + * @param config config option + * @return modified tooltip + */ + @Override + public List getWailaBody(@Nonnull final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); + if (te instanceof TileCharger) { + final TileCharger charger = (TileCharger) te; + final IItemHandler chargerInventory = charger.getInternalInventory(); + final ItemStack chargingItem = chargerInventory.getStackInSlot(0); - if( !chargingItem.isEmpty() ) - { - final String currentInventory = chargingItem.getDisplayName(); - final EntityPlayer player = accessor.getPlayer(); + if (!chargingItem.isEmpty()) { + final String currentInventory = chargingItem.getDisplayName(); + final EntityPlayer player = accessor.getPlayer(); - currentToolTip.add( WailaText.Contains + ": " + currentInventory ); - ITooltipFlag.TooltipFlags tooltipFlag = Minecraft - .getMinecraft().gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL; - chargingItem.getItem().addInformation( chargingItem, player.world, currentToolTip, tooltipFlag ); - } - } + currentToolTip.add(WailaText.Contains + ": " + currentInventory); + ITooltipFlag.TooltipFlags tooltipFlag = Minecraft + .getMinecraft().gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL; + chargingItem.getItem().addInformation(chargingItem, player.world, currentToolTip, tooltipFlag); + } + } - return currentToolTip; - } + return currentToolTip; + } } diff --git a/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java index 0c04718e1..fa514794c 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java @@ -19,18 +19,16 @@ package appeng.integration.modules.waila.tile; -import java.util.List; - -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; - import appeng.api.storage.data.IAEItemStack; import appeng.core.localization.WailaText; import appeng.integration.modules.waila.BaseWailaDataProvider; import appeng.tile.crafting.TileCraftingMonitorTile; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; + +import java.util.List; /** @@ -40,35 +38,30 @@ import appeng.tile.crafting.TileCraftingMonitorTile; * @version rv2 * @since rv2 */ -public final class CraftingMonitorWailaDataProvider extends BaseWailaDataProvider -{ - /** - * Displays the item currently crafted by the CPU cluster - * - * @param itemStack stack of crafting monitor - * @param currentToolTip unmodified tooltip - * @param accessor information wrapper - * @param config config option - * - * @return modified tooltip - */ - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - if( te instanceof TileCraftingMonitorTile ) - { - final TileCraftingMonitorTile monitor = (TileCraftingMonitorTile) te; - final IAEItemStack displayStack = monitor.getJobProgress(); +public final class CraftingMonitorWailaDataProvider extends BaseWailaDataProvider { + /** + * Displays the item currently crafted by the CPU cluster + * + * @param itemStack stack of crafting monitor + * @param currentToolTip unmodified tooltip + * @param accessor information wrapper + * @param config config option + * @return modified tooltip + */ + @Override + public List getWailaBody(final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); + if (te instanceof TileCraftingMonitorTile) { + final TileCraftingMonitorTile monitor = (TileCraftingMonitorTile) te; + final IAEItemStack displayStack = monitor.getJobProgress(); - if( displayStack != null ) - { - final String currentCrafting = displayStack.asItemStackRepresentation().getDisplayName(); + if (displayStack != null) { + final String currentCrafting = displayStack.asItemStackRepresentation().getDisplayName(); - currentToolTip.add( WailaText.Crafting.getLocal() + ": " + currentCrafting ); - } - } + currentToolTip.add(WailaText.Crafting.getLocal() + ": " + currentCrafting); + } + } - return currentToolTip; - } + return currentToolTip; + } } diff --git a/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java index cff256ddf..280a81214 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java @@ -19,17 +19,15 @@ package appeng.integration.modules.waila.tile; -import java.util.List; - -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; - import appeng.api.implementations.IPowerChannelState; import appeng.core.localization.WailaText; import appeng.integration.modules.waila.BaseWailaDataProvider; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; + +import java.util.List; /** @@ -39,44 +37,35 @@ import appeng.integration.modules.waila.BaseWailaDataProvider; * @version rv2 * @since rv2 */ -public final class PowerStateWailaDataProvider extends BaseWailaDataProvider -{ - /** - * Adds state to the tooltip - * - * @param itemStack stack of power state - * @param currentToolTip to be added to tooltip - * @param accessor wrapper for various information - * @param config config settings - * - * @return modified tooltip - */ - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); +public final class PowerStateWailaDataProvider extends BaseWailaDataProvider { + /** + * Adds state to the tooltip + * + * @param itemStack stack of power state + * @param currentToolTip to be added to tooltip + * @param accessor wrapper for various information + * @param config config settings + * @return modified tooltip + */ + @Override + public List getWailaBody(final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); - if( te instanceof IPowerChannelState ) - { - final IPowerChannelState state = (IPowerChannelState) te; + if (te instanceof IPowerChannelState) { + final IPowerChannelState state = (IPowerChannelState) te; - final boolean isActive = state.isActive(); - final boolean isPowered = state.isPowered(); + final boolean isActive = state.isActive(); + final boolean isPowered = state.isPowered(); - if( isActive && isPowered ) - { - currentToolTip.add( WailaText.DeviceOnline.getLocal() ); - } - else if( isPowered ) - { - currentToolTip.add( WailaText.DeviceMissingChannel.getLocal() ); - } - else - { - currentToolTip.add( WailaText.DeviceOffline.getLocal() ); - } - } + if (isActive && isPowered) { + currentToolTip.add(WailaText.DeviceOnline.getLocal()); + } else if (isPowered) { + currentToolTip.add(WailaText.DeviceMissingChannel.getLocal()); + } else { + currentToolTip.add(WailaText.DeviceOffline.getLocal()); + } + } - return currentToolTip; - } + return currentToolTip; + } } \ No newline at end of file diff --git a/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java index d1b0439f7..ce4a461ea 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java @@ -19,8 +19,15 @@ package appeng.integration.modules.waila.tile; -import java.util.List; - +import appeng.api.networking.energy.IAEPowerStorage; +import appeng.core.localization.WailaText; +import appeng.integration.modules.waila.BaseWailaDataProvider; +import appeng.util.Platform; +import it.unimi.dsi.fastutil.objects.Object2LongMap; +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; +import mcp.mobius.waila.api.ITaggedList; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -28,16 +35,7 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import it.unimi.dsi.fastutil.objects.Object2LongMap; -import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; -import mcp.mobius.waila.api.ITaggedList; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; - -import appeng.api.networking.energy.IAEPowerStorage; -import appeng.core.localization.WailaText; -import appeng.integration.modules.waila.BaseWailaDataProvider; -import appeng.util.Platform; +import java.util.List; /** @@ -47,128 +45,111 @@ import appeng.util.Platform; * @version rv2 * @since rv2 */ -public final class PowerStorageWailaDataProvider extends BaseWailaDataProvider -{ - /** - * Power key used for the transferred {@link net.minecraft.nbt.NBTTagCompound} - */ - private static final String ID_CURRENT_POWER = "currentPower"; +public final class PowerStorageWailaDataProvider extends BaseWailaDataProvider { + /** + * Power key used for the transferred {@link net.minecraft.nbt.NBTTagCompound} + */ + private static final String ID_CURRENT_POWER = "currentPower"; - /** - * Used cache for power if the power was not transmitted through the server. - *

- * This is useful, when a player just started to look at a tile and thus just requested the new information from the - * server. - *

- * The cache will be updated from the server. - */ - private final Object2LongMap cache = new Object2LongOpenHashMap<>(); + /** + * Used cache for power if the power was not transmitted through the server. + *

+ * This is useful, when a player just started to look at a tile and thus just requested the new information from the + * server. + *

+ * The cache will be updated from the server. + */ + private final Object2LongMap cache = new Object2LongOpenHashMap<>(); - /** - * Adds the current and max power to the tool tip - * Will ignore if the tile has an energy buffer ( > 0 ) - * - * @param itemStack stack of power storage - * @param currentToolTip current tool tip - * @param accessor wrapper for various world information - * @param config config to react to various settings - * - * @return modified tool tip - */ - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - // Removes RF tooltip on WAILA 1.5.9+ - ( (ITaggedList) currentToolTip ).removeEntries( "RFEnergyStorage" ); + /** + * Adds the current and max power to the tool tip + * Will ignore if the tile has an energy buffer ( > 0 ) + * + * @param itemStack stack of power storage + * @param currentToolTip current tool tip + * @param accessor wrapper for various world information + * @param config config to react to various settings + * @return modified tool tip + */ + @Override + public List getWailaBody(final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + // Removes RF tooltip on WAILA 1.5.9+ + ((ITaggedList) currentToolTip).removeEntries("RFEnergyStorage"); - final TileEntity te = accessor.getTileEntity(); - if( te instanceof IAEPowerStorage ) - { - final IAEPowerStorage storage = (IAEPowerStorage) te; + final TileEntity te = accessor.getTileEntity(); + if (te instanceof IAEPowerStorage) { + final IAEPowerStorage storage = (IAEPowerStorage) te; - final double maxPower = storage.getAEMaxPower(); - if( maxPower > 0 ) - { - final NBTTagCompound tag = accessor.getNBTData(); + final double maxPower = storage.getAEMaxPower(); + if (maxPower > 0) { + final NBTTagCompound tag = accessor.getNBTData(); - final long internalCurrentPower = this.getInternalCurrentPower( tag, te ); + final long internalCurrentPower = this.getInternalCurrentPower(tag, te); - if( internalCurrentPower >= 0 ) - { - final long internalMaxPower = (long) ( 100 * maxPower ); + if (internalCurrentPower >= 0) { + final long internalMaxPower = (long) (100 * maxPower); - final String formatCurrentPower = Platform.formatPowerLong( internalCurrentPower, false ); - final String formatMaxPower = Platform.formatPowerLong( internalMaxPower, false ); + final String formatCurrentPower = Platform.formatPowerLong(internalCurrentPower, false); + final String formatMaxPower = Platform.formatPowerLong(internalMaxPower, false); - currentToolTip.add( WailaText.Contains.getLocal() + ": " + formatCurrentPower + " / " + formatMaxPower ); - } - } - } + currentToolTip.add(WailaText.Contains.getLocal() + ": " + formatCurrentPower + " / " + formatMaxPower); + } + } + } - return currentToolTip; - } + return currentToolTip; + } - /** - * Called on server to transfer information from server to client. - *

- * If the {@link net.minecraft.tileentity.TileEntity} is a {@link appeng.api.networking.energy.IAEPowerStorage}, it - * writes the power information to the {@code #tag} using the {@code #ID_CURRENT_POWER} key. - * - * @param player player looking at the power storage - * @param te power storage - * @param tag transferred tag which is send to the client - * @param world world of the power storage - * @param pos pos of the power storage - * - * @return tag send to the client - */ - @Override - public NBTTagCompound getNBTData( EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, BlockPos pos ) - { - if( te instanceof IAEPowerStorage ) - { - final IAEPowerStorage storage = (IAEPowerStorage) te; + /** + * Called on server to transfer information from server to client. + *

+ * If the {@link net.minecraft.tileentity.TileEntity} is a {@link appeng.api.networking.energy.IAEPowerStorage}, it + * writes the power information to the {@code #tag} using the {@code #ID_CURRENT_POWER} key. + * + * @param player player looking at the power storage + * @param te power storage + * @param tag transferred tag which is send to the client + * @param world world of the power storage + * @param pos pos of the power storage + * @return tag send to the client + */ + @Override + public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, BlockPos pos) { + if (te instanceof IAEPowerStorage) { + final IAEPowerStorage storage = (IAEPowerStorage) te; - if( storage.getAEMaxPower() > 0 ) - { - final long internalCurrentPower = (long) ( 100 * storage.getAECurrentPower() ); + if (storage.getAEMaxPower() > 0) { + final long internalCurrentPower = (long) (100 * storage.getAECurrentPower()); - tag.setLong( ID_CURRENT_POWER, internalCurrentPower ); - } - } + tag.setLong(ID_CURRENT_POWER, internalCurrentPower); + } + } - return tag; - } + return tag; + } - /** - * Determines the current power. - *

- * If the client received power information on the server, they are used, else if the cache contains a previous - * stored value, this will be used. Default value is 0. - * - * @param te te to be looked at - * @param tag tag maybe containing the channel information - * - * @return used channels on the cable - */ - private long getInternalCurrentPower( final NBTTagCompound tag, final TileEntity te ) - { - final long internalCurrentPower; + /** + * Determines the current power. + *

+ * If the client received power information on the server, they are used, else if the cache contains a previous + * stored value, this will be used. Default value is 0. + * + * @param te te to be looked at + * @param tag tag maybe containing the channel information + * @return used channels on the cable + */ + private long getInternalCurrentPower(final NBTTagCompound tag, final TileEntity te) { + final long internalCurrentPower; - if( tag.hasKey( ID_CURRENT_POWER ) ) - { - internalCurrentPower = tag.getLong( ID_CURRENT_POWER ); - this.cache.put( te, internalCurrentPower ); - } - else if( this.cache.containsKey( te ) ) - { - internalCurrentPower = this.cache.get( te ); - } - else - { - internalCurrentPower = -1; - } + if (tag.hasKey(ID_CURRENT_POWER)) { + internalCurrentPower = tag.getLong(ID_CURRENT_POWER); + this.cache.put(te, internalCurrentPower); + } else if (this.cache.containsKey(te)) { + internalCurrentPower = this.cache.get(te); + } else { + internalCurrentPower = -1; + } - return internalCurrentPower; - } + return internalCurrentPower; + } } diff --git a/src/main/java/appeng/items/AEBaseItem.java b/src/main/java/appeng/items/AEBaseItem.java index ca57f7aad..7d5c547d5 100644 --- a/src/main/java/appeng/items/AEBaseItem.java +++ b/src/main/java/appeng/items/AEBaseItem.java @@ -19,8 +19,6 @@ package appeng.items; -import java.util.List; - import net.minecraft.client.util.ITooltipFlag; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; @@ -30,54 +28,47 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import java.util.List; -public abstract class AEBaseItem extends Item -{ - public AEBaseItem() - { - this.setNoRepair(); - } +public abstract class AEBaseItem extends Item { - @Override - public String toString() - { - String regName = this.getRegistryName() != null ? this.getRegistryName().getResourcePath() : "unregistered"; - return this.getClass().getSimpleName() + "[" + regName + "]"; - } + public AEBaseItem() { + this.setNoRepair(); + } - @SideOnly( Side.CLIENT ) - @Override - @SuppressWarnings( "unchecked" ) - public final void addInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - this.addCheckedInformation( stack, world, lines, advancedTooltips ); - } + @Override + public String toString() { + String regName = this.getRegistryName() != null ? this.getRegistryName().getResourcePath() : "unregistered"; + return this.getClass().getSimpleName() + "[" + regName + "]"; + } - @Override - public final void getSubItems( final CreativeTabs creativeTab, final NonNullList itemStacks ) - { - if( this.isInCreativeTab( creativeTab ) ) - { - this.getCheckedSubItems( creativeTab, itemStacks ); - } - } + @SideOnly(Side.CLIENT) + @Override + @SuppressWarnings("unchecked") + public final void addInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + this.addCheckedInformation(stack, world, lines, advancedTooltips); + } - @Override - public boolean isBookEnchantable( final ItemStack itemstack1, final ItemStack itemstack2 ) - { - return false; - } + @Override + public final void getSubItems(final CreativeTabs creativeTab, final NonNullList itemStacks) { + if (this.isInCreativeTab(creativeTab)) { + this.getCheckedSubItems(creativeTab, itemStacks); + } + } - @SideOnly( Side.CLIENT ) - protected void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - super.addInformation( stack, world, lines, advancedTooltips ); - } + @Override + public boolean isBookEnchantable(final ItemStack itemstack1, final ItemStack itemstack2) { + return false; + } - protected void getCheckedSubItems( final CreativeTabs creativeTab, final NonNullList itemStacks ) - { - super.getSubItems( creativeTab, itemStacks ); - } + @SideOnly(Side.CLIENT) + protected void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + super.addInformation(stack, world, lines, advancedTooltips); + } + + protected void getCheckedSubItems(final CreativeTabs creativeTab, final NonNullList itemStacks) { + super.getSubItems(creativeTab, itemStacks); + } } diff --git a/src/main/java/appeng/items/contents/CellConfig.java b/src/main/java/appeng/items/contents/CellConfig.java index a916fd70b..d58fea064 100644 --- a/src/main/java/appeng/items/contents/CellConfig.java +++ b/src/main/java/appeng/items/contents/CellConfig.java @@ -19,27 +19,23 @@ package appeng.items.contents; -import net.minecraft.item.ItemStack; - import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.Platform; +import net.minecraft.item.ItemStack; -public class CellConfig extends AppEngInternalInventory -{ +public class CellConfig extends AppEngInternalInventory { - private final ItemStack is; + private final ItemStack is; - public CellConfig( final ItemStack is ) - { - super( null, 63 ); - this.is = is; - this.readFromNBT( Platform.openNbtData( is ), "list" ); - } + public CellConfig(final ItemStack is) { + super(null, 63); + this.is = is; + this.readFromNBT(Platform.openNbtData(is), "list"); + } - @Override - protected void onContentsChanged( int slot ) - { - this.writeToNBT( Platform.openNbtData( this.is ), "list" ); - } + @Override + protected void onContentsChanged(int slot) { + this.writeToNBT(Platform.openNbtData(this.is), "list"); + } } \ No newline at end of file diff --git a/src/main/java/appeng/items/contents/CellUpgrades.java b/src/main/java/appeng/items/contents/CellUpgrades.java index 5f6dbc99e..53fc124b4 100644 --- a/src/main/java/appeng/items/contents/CellUpgrades.java +++ b/src/main/java/appeng/items/contents/CellUpgrades.java @@ -19,26 +19,22 @@ package appeng.items.contents; -import net.minecraft.item.ItemStack; - import appeng.parts.automation.StackUpgradeInventory; import appeng.util.Platform; +import net.minecraft.item.ItemStack; -public final class CellUpgrades extends StackUpgradeInventory -{ - private final ItemStack is; +public final class CellUpgrades extends StackUpgradeInventory { + private final ItemStack is; - public CellUpgrades( final ItemStack is, final int upgrades ) - { - super( is, null, upgrades ); - this.is = is; - this.readFromNBT( Platform.openNbtData( is ), "upgrades" ); - } + public CellUpgrades(final ItemStack is, final int upgrades) { + super(is, null, upgrades); + this.is = is; + this.readFromNBT(Platform.openNbtData(is), "upgrades"); + } - @Override - protected void onContentsChanged( int slot ) - { - this.writeToNBT( Platform.openNbtData( this.is ), "upgrades" ); - } + @Override + protected void onContentsChanged(int slot) { + this.writeToNBT(Platform.openNbtData(this.is), "upgrades"); + } } \ No newline at end of file diff --git a/src/main/java/appeng/items/contents/NetworkToolViewer.java b/src/main/java/appeng/items/contents/NetworkToolViewer.java index 79a0fa625..1284ec77c 100644 --- a/src/main/java/appeng/items/contents/NetworkToolViewer.java +++ b/src/main/java/appeng/items/contents/NetworkToolViewer.java @@ -19,9 +19,6 @@ package appeng.items.contents; -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandler; - import appeng.api.implementations.guiobjects.INetworkTool; import appeng.api.implementations.items.IUpgradeModule; import appeng.api.networking.IGridHost; @@ -30,73 +27,64 @@ import appeng.util.Platform; import appeng.util.inv.IAEAppEngInventory; import appeng.util.inv.InvOperation; import appeng.util.inv.filter.IAEItemFilter; +import net.minecraft.item.ItemStack; +import net.minecraftforge.items.IItemHandler; -public class NetworkToolViewer implements INetworkTool, IAEAppEngInventory -{ +public class NetworkToolViewer implements INetworkTool, IAEAppEngInventory { - private final AppEngInternalInventory inv; - private final ItemStack is; - private final IGridHost gh; + private final AppEngInternalInventory inv; + private final ItemStack is; + private final IGridHost gh; - public NetworkToolViewer( final ItemStack is, final IGridHost gHost ) - { - this.is = is; - this.gh = gHost; - this.inv = new AppEngInternalInventory( this, 9 ); - this.inv.setFilter( new NetworkToolInventoryFilter() ); - if( is.hasTagCompound() ) // prevent crash when opening network status screen. - { - this.inv.readFromNBT( Platform.openNbtData( is ), "inv" ); - } - } + public NetworkToolViewer(final ItemStack is, final IGridHost gHost) { + this.is = is; + this.gh = gHost; + this.inv = new AppEngInternalInventory(this, 9); + this.inv.setFilter(new NetworkToolInventoryFilter()); + if (is.hasTagCompound()) // prevent crash when opening network status screen. + { + this.inv.readFromNBT(Platform.openNbtData(is), "inv"); + } + } - @Override - public void saveChanges() - { - this.inv.writeToNBT( Platform.openNbtData( this.is ), "inv" ); - } + @Override + public void saveChanges() { + this.inv.writeToNBT(Platform.openNbtData(this.is), "inv"); + } - @Override - public void onChangeInventory( IItemHandler inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) - { - } + @Override + public void onChangeInventory(IItemHandler inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack) { + } - @Override - public ItemStack getItemStack() - { - return this.is; - } + @Override + public ItemStack getItemStack() { + return this.is; + } - @Override - public IGridHost getGridHost() - { - return this.gh; - } + @Override + public IGridHost getGridHost() { + return this.gh; + } - private static class NetworkToolInventoryFilter implements IAEItemFilter - { - @Override - public boolean allowExtract( IItemHandler inv, int slot, int amount ) - { - return true; - } + private static class NetworkToolInventoryFilter implements IAEItemFilter { + @Override + public boolean allowExtract(IItemHandler inv, int slot, int amount) { + return true; + } - @Override - public boolean allowInsert( IItemHandler inv, int slot, ItemStack stack ) - { - return stack.getItem() instanceof IUpgradeModule && ( (IUpgradeModule) stack.getItem() ).getType( stack ) != null; - } - } + @Override + public boolean allowInsert(IItemHandler inv, int slot, ItemStack stack) { + return stack.getItem() instanceof IUpgradeModule && ((IUpgradeModule) stack.getItem()).getType(stack) != null; + } + } - public IItemHandler getInternalInventory() - { - return this.inv; - } + public IItemHandler getInternalInventory() { + return this.inv; + } - @Override - public IItemHandler getInventory() - { - return this.inv; - } + @Override + public IItemHandler getInventory() { + return this.inv; + } } diff --git a/src/main/java/appeng/items/contents/PortableCellViewer.java b/src/main/java/appeng/items/contents/PortableCellViewer.java index 584fbcee9..50249b200 100644 --- a/src/main/java/appeng/items/contents/PortableCellViewer.java +++ b/src/main/java/appeng/items/contents/PortableCellViewer.java @@ -19,19 +19,11 @@ package appeng.items.contents; -import appeng.api.networking.security.IActionSource; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import appeng.api.AEApi; -import appeng.api.config.Actionable; -import appeng.api.config.PowerMultiplier; -import appeng.api.config.Settings; -import appeng.api.config.SortDir; -import appeng.api.config.SortOrder; -import appeng.api.config.ViewItems; +import appeng.api.config.*; import appeng.api.implementations.guiobjects.IPortableCell; import appeng.api.implementations.items.IAEItemPowerStorage; +import appeng.api.networking.security.IActionSource; import appeng.api.storage.IMEMonitor; import appeng.api.storage.IStorageChannel; import appeng.api.storage.channels.IItemStorageChannel; @@ -42,102 +34,91 @@ import appeng.container.interfaces.IInventorySlotAware; import appeng.me.helpers.MEMonitorHandler; import appeng.util.ConfigManager; import appeng.util.Platform; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; import java.util.Collections; -public class PortableCellViewer extends MEMonitorHandler implements IPortableCell, IInventorySlotAware -{ +public class PortableCellViewer extends MEMonitorHandler implements IPortableCell, IInventorySlotAware { - private final ItemStack target; - private final IAEItemPowerStorage ips; - private final int inventorySlot; + private final ItemStack target; + private final IAEItemPowerStorage ips; + private final int inventorySlot; - public PortableCellViewer( final ItemStack is, final int slot ) - { - super( AEApi.instance().registries().cell().getCellInventory( is, null, AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) ); - this.ips = (IAEItemPowerStorage) is.getItem(); - this.target = is; - this.inventorySlot = slot; - } + public PortableCellViewer(final ItemStack is, final int slot) { + super(AEApi.instance().registries().cell().getCellInventory(is, null, AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class))); + this.ips = (IAEItemPowerStorage) is.getItem(); + this.target = is; + this.inventorySlot = slot; + } - @Override - public int getInventorySlot() - { - return this.inventorySlot; - } + @Override + public int getInventorySlot() { + return this.inventorySlot; + } - @Override - public ItemStack getItemStack() - { - return this.target; - } + @Override + public ItemStack getItemStack() { + return this.target; + } - @Override - public double extractAEPower( double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier ) - { - amt = usePowerMultiplier.multiply( amt ); + @Override + public double extractAEPower(double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier) { + amt = usePowerMultiplier.multiply(amt); - if( mode == Actionable.SIMULATE ) - { - return usePowerMultiplier.divide( Math.min( amt, this.ips.getAECurrentPower( this.target ) ) ); - } + if (mode == Actionable.SIMULATE) { + return usePowerMultiplier.divide(Math.min(amt, this.ips.getAECurrentPower(this.target))); + } - return usePowerMultiplier.divide( this.ips.extractAEPower( this.target, amt, Actionable.MODULATE ) ); - } + return usePowerMultiplier.divide(this.ips.extractAEPower(this.target, amt, Actionable.MODULATE)); + } - @Override - public IAEItemStack injectItems( IAEItemStack input, Actionable mode, IActionSource src ) - { - final long size = input.getStackSize(); + @Override + public IAEItemStack injectItems(IAEItemStack input, Actionable mode, IActionSource src) { + final long size = input.getStackSize(); - final IAEItemStack injected = super.injectItems( input, mode, src ); + final IAEItemStack injected = super.injectItems(input, mode, src); - if( mode == Actionable.MODULATE && ( injected == null || injected.getStackSize() != size ) ) - { - this.notifyListenersOfChange( Collections.singletonList( input.copy().setStackSize( input.getStackSize() - ( injected == null ? 0 : injected.getStackSize() ) ) ), null); - } + if (mode == Actionable.MODULATE && (injected == null || injected.getStackSize() != size)) { + this.notifyListenersOfChange(Collections.singletonList(input.copy().setStackSize(input.getStackSize() - (injected == null ? 0 : injected.getStackSize()))), null); + } - return injected; - } + return injected; + } - @Override - public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src ) - { - final IAEItemStack extractable = super.extractItems( request, mode, src ); + @Override + public IAEItemStack extractItems(IAEItemStack request, Actionable mode, IActionSource src) { + final IAEItemStack extractable = super.extractItems(request, mode, src); - if( mode == Actionable.MODULATE && extractable != null ) - { - this.notifyListenersOfChange( Collections.singletonList( request.copy().setStackSize( -extractable.getStackSize() ) ), null ); - } + if (mode == Actionable.MODULATE && extractable != null) { + this.notifyListenersOfChange(Collections.singletonList(request.copy().setStackSize(-extractable.getStackSize())), null); + } - return extractable; - } + return extractable; + } - @Override - public > IMEMonitor getInventory( IStorageChannel channel ) - { - if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - return (IMEMonitor) this; - } - return null; - } + @Override + public > IMEMonitor getInventory(IStorageChannel channel) { + if (channel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + return (IMEMonitor) this; + } + return null; + } - @Override - public IConfigManager getConfigManager() - { - final ConfigManager out = new ConfigManager( ( manager, settingName, newValue ) -> - { - final NBTTagCompound data = Platform.openNbtData( PortableCellViewer.this.target ); - manager.writeToNBT( data ); - } ); + @Override + public IConfigManager getConfigManager() { + final ConfigManager out = new ConfigManager((manager, settingName, newValue) -> + { + final NBTTagCompound data = Platform.openNbtData(PortableCellViewer.this.target); + manager.writeToNBT(data); + }); - out.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - out.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - out.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); + out.registerSetting(Settings.SORT_BY, SortOrder.NAME); + out.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + out.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); - out.readFromNBT( Platform.openNbtData( this.target ).copy() ); - return out; - } + out.readFromNBT(Platform.openNbtData(this.target).copy()); + return out; + } } diff --git a/src/main/java/appeng/items/contents/QuartzKnifeObj.java b/src/main/java/appeng/items/contents/QuartzKnifeObj.java index a06e032d2..19b11a4e9 100644 --- a/src/main/java/appeng/items/contents/QuartzKnifeObj.java +++ b/src/main/java/appeng/items/contents/QuartzKnifeObj.java @@ -19,24 +19,20 @@ package appeng.items.contents; +import appeng.api.implementations.guiobjects.IGuiItemObject; import net.minecraft.item.ItemStack; -import appeng.api.implementations.guiobjects.IGuiItemObject; +public class QuartzKnifeObj implements IGuiItemObject { -public class QuartzKnifeObj implements IGuiItemObject -{ + private final ItemStack is; - private final ItemStack is; + public QuartzKnifeObj(final ItemStack o) { + this.is = o; + } - public QuartzKnifeObj( final ItemStack o ) - { - this.is = o; - } - - @Override - public ItemStack getItemStack() - { - return this.is; - } + @Override + public ItemStack getItemStack() { + return this.is; + } } diff --git a/src/main/java/appeng/items/materials/ItemMaterial.java b/src/main/java/appeng/items/materials/ItemMaterial.java index cca661f20..ed752dc5b 100644 --- a/src/main/java/appeng/items/materials/ItemMaterial.java +++ b/src/main/java/appeng/items/materials/ItemMaterial.java @@ -19,20 +19,24 @@ package appeng.items.materials; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - +import appeng.api.config.Upgrades; +import appeng.api.implementations.IUpgradeableHost; +import appeng.api.implementations.items.IItemGroup; +import appeng.api.implementations.items.IStorageComponent; +import appeng.api.implementations.items.IUpgradeModule; +import appeng.api.implementations.tiles.ISegmentedInventory; +import appeng.api.parts.IPartHost; +import appeng.api.parts.SelectedPart; +import appeng.core.AEConfig; +import appeng.core.features.AEFeature; +import appeng.core.features.IStackSrc; +import appeng.core.features.MaterialStackSrc; +import appeng.items.AEBaseItem; +import appeng.util.InventoryAdaptor; +import appeng.util.Platform; +import appeng.util.inv.AdaptorItemHandler; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; - import net.minecraft.client.util.ITooltipFlag; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; @@ -53,350 +57,280 @@ import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.oredict.OreDictionary; -import appeng.api.config.Upgrades; -import appeng.api.implementations.IUpgradeableHost; -import appeng.api.implementations.items.IItemGroup; -import appeng.api.implementations.items.IStorageComponent; -import appeng.api.implementations.items.IUpgradeModule; -import appeng.api.implementations.tiles.ISegmentedInventory; -import appeng.api.parts.IPartHost; -import appeng.api.parts.SelectedPart; -import appeng.core.AEConfig; -import appeng.core.features.AEFeature; -import appeng.core.features.IStackSrc; -import appeng.core.features.MaterialStackSrc; -import appeng.items.AEBaseItem; -import appeng.util.InventoryAdaptor; -import appeng.util.Platform; -import appeng.util.inv.AdaptorItemHandler; +import java.util.*; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; -public final class ItemMaterial extends AEBaseItem implements IStorageComponent, IUpgradeModule -{ - public static ItemMaterial instance; +public final class ItemMaterial extends AEBaseItem implements IStorageComponent, IUpgradeModule { + public static ItemMaterial instance; - private static final int KILO_SCALAR = 1024; + private static final int KILO_SCALAR = 1024; - private final Map dmgToMaterial = new HashMap<>(); + private final Map dmgToMaterial = new HashMap<>(); - public ItemMaterial() - { - this.setHasSubtypes( true ); - instance = this; - } + public ItemMaterial() { + this.setHasSubtypes(true); + instance = this; + } - @SideOnly( Side.CLIENT ) - @Override - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - super.addCheckedInformation( stack, world, lines, advancedTooltips ); + @SideOnly(Side.CLIENT) + @Override + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + super.addCheckedInformation(stack, world, lines, advancedTooltips); - final MaterialType mt = this.getTypeByStack( stack ); - if( mt == null ) - { - return; - } + final MaterialType mt = this.getTypeByStack(stack); + if (mt == null) { + return; + } - if( mt == MaterialType.NAME_PRESS ) - { - final NBTTagCompound c = Platform.openNbtData( stack ); - lines.add( c.getString( "InscribeName" ) ); - } + if (mt == MaterialType.NAME_PRESS) { + final NBTTagCompound c = Platform.openNbtData(stack); + lines.add(c.getString("InscribeName")); + } - final Upgrades u = this.getType( stack ); - if( u != null ) - { - final List textList = new ArrayList<>(); - for( final Entry j : u.getSupported().entrySet() ) - { - String name = null; + final Upgrades u = this.getType(stack); + if (u != null) { + final List textList = new ArrayList<>(); + for (final Entry j : u.getSupported().entrySet()) { + String name = null; - final int limit = j.getValue(); + final int limit = j.getValue(); - if( j.getKey().getItem() instanceof IItemGroup ) - { - final IItemGroup ig = (IItemGroup) j.getKey().getItem(); - final String str = ig.getUnlocalizedGroupName( u.getSupported().keySet(), j.getKey() ); - if( str != null ) - { - name = Platform.gui_localize( str ) + ( limit > 1 ? " (" + limit + ')' : "" ); - } - } + if (j.getKey().getItem() instanceof IItemGroup) { + final IItemGroup ig = (IItemGroup) j.getKey().getItem(); + final String str = ig.getUnlocalizedGroupName(u.getSupported().keySet(), j.getKey()); + if (str != null) { + name = Platform.gui_localize(str) + (limit > 1 ? " (" + limit + ')' : ""); + } + } - if( name == null ) - { - name = j.getKey().getDisplayName() + ( limit > 1 ? " (" + limit + ')' : "" ); - } + if (name == null) { + name = j.getKey().getDisplayName() + (limit > 1 ? " (" + limit + ')' : ""); + } - if( !textList.contains( name ) ) - { - textList.add( name ); - } - } + if (!textList.contains(name)) { + textList.add(name); + } + } - final Pattern p = Pattern.compile( "(\\d+)[^\\d]" ); - final SlightlyBetterSort s = new SlightlyBetterSort( p ); - Collections.sort( textList, s ); - lines.addAll( textList ); - } - } + final Pattern p = Pattern.compile("(\\d+)[^\\d]"); + final SlightlyBetterSort s = new SlightlyBetterSort(p); + Collections.sort(textList, s); + lines.addAll(textList); + } + } - public MaterialType getTypeByStack( final ItemStack is ) - { - MaterialType type = this.dmgToMaterial.get( is.getItemDamage() ); - return ( type != null ) ? type : MaterialType.INVALID_TYPE; - } + public MaterialType getTypeByStack(final ItemStack is) { + MaterialType type = this.dmgToMaterial.get(is.getItemDamage()); + return (type != null) ? type : MaterialType.INVALID_TYPE; + } - @Override - public Upgrades getType( final ItemStack itemstack ) - { - switch( this.getTypeByStack( itemstack ) ) - { - case CARD_CAPACITY: - return Upgrades.CAPACITY; - case CARD_FUZZY: - return Upgrades.FUZZY; - case CARD_REDSTONE: - return Upgrades.REDSTONE; - case CARD_SPEED: - return Upgrades.SPEED; - case CARD_INVERTER: - return Upgrades.INVERTER; - case CARD_CRAFTING: - return Upgrades.CRAFTING; - case CARD_PATTERN_EXPANSION: - return Upgrades.PATTERN_EXPANSION; - default: - return null; - } - } + @Override + public Upgrades getType(final ItemStack itemstack) { + switch (this.getTypeByStack(itemstack)) { + case CARD_CAPACITY: + return Upgrades.CAPACITY; + case CARD_FUZZY: + return Upgrades.FUZZY; + case CARD_REDSTONE: + return Upgrades.REDSTONE; + case CARD_SPEED: + return Upgrades.SPEED; + case CARD_INVERTER: + return Upgrades.INVERTER; + case CARD_CRAFTING: + return Upgrades.CRAFTING; + case CARD_PATTERN_EXPANSION: + return Upgrades.PATTERN_EXPANSION; + default: + return null; + } + } - public IStackSrc createMaterial( final MaterialType mat ) - { - Preconditions.checkState( !mat.isRegistered(), "Cannot create the same material twice." ); + public IStackSrc createMaterial(final MaterialType mat) { + Preconditions.checkState(!mat.isRegistered(), "Cannot create the same material twice."); - boolean enabled = true; + boolean enabled = true; - for( final AEFeature f : mat.getFeature() ) - { - enabled = enabled && AEConfig.instance().isFeatureEnabled( f ); - } + for (final AEFeature f : mat.getFeature()) { + enabled = enabled && AEConfig.instance().isFeatureEnabled(f); + } - mat.setStackSrc( new MaterialStackSrc( mat, enabled ) ); + mat.setStackSrc(new MaterialStackSrc(mat, enabled)); - if( enabled ) - { - mat.setItemInstance( this ); - mat.markReady(); - final int newMaterialNum = mat.getDamageValue(); + if (enabled) { + mat.setItemInstance(this); + mat.markReady(); + final int newMaterialNum = mat.getDamageValue(); - if( this.dmgToMaterial.get( newMaterialNum ) == null ) - { - this.dmgToMaterial.put( newMaterialNum, mat ); - } - else + if (this.dmgToMaterial.get(newMaterialNum) == null) { + this.dmgToMaterial.put(newMaterialNum, mat); + } else { + throw new IllegalStateException("Meta Overlap detected."); + } + } - { - throw new IllegalStateException( "Meta Overlap detected." ); - } - } + return mat.getStackSrc(); + } - return mat.getStackSrc(); - } + public void registerOredicts() { + for (final MaterialType mt : ImmutableSet.copyOf(this.dmgToMaterial.values())) { + if (mt.getOreName() != null) { + final String[] names = mt.getOreName().split(","); - public void registerOredicts() - { - for( final MaterialType mt : ImmutableSet.copyOf( this.dmgToMaterial.values() ) ) - { - if( mt.getOreName() != null ) - { - final String[] names = mt.getOreName().split( "," ); + for (final String name : names) { + OreDictionary.registerOre(name, mt.stack(1)); + } + } + } + } - for( final String name : names ) - { - OreDictionary.registerOre( name, mt.stack( 1 ) ); - } - } - } - } + @Override + public String getUnlocalizedName(final ItemStack is) { + return "item.appliedenergistics2.material." + this.nameOf(is).toLowerCase(); + } - @Override - public String getUnlocalizedName( final ItemStack is ) - { - return "item.appliedenergistics2.material." + this.nameOf( is ).toLowerCase(); - } + @Override + protected void getCheckedSubItems(final CreativeTabs creativeTab, final NonNullList itemStacks) { + final List types = Arrays.asList(MaterialType.values()); + Collections.sort(types, (o1, o2) -> o1.name().compareTo(o2.name())); - @Override - protected void getCheckedSubItems( final CreativeTabs creativeTab, final NonNullList itemStacks ) - { - final List types = Arrays.asList( MaterialType.values() ); - Collections.sort( types, ( o1, o2 ) -> o1.name().compareTo( o2.name() ) ); + for (final MaterialType mat : types) { + if (mat.getDamageValue() >= 0 && mat.isRegistered() && mat.getItemInstance() == this) { + itemStacks.add(new ItemStack(this, 1, mat.getDamageValue())); + } + } + } - for( final MaterialType mat : types ) - { - if( mat.getDamageValue() >= 0 && mat.isRegistered() && mat.getItemInstance() == this ) - { - itemStacks.add( new ItemStack( this, 1, mat.getDamageValue() ) ); - } - } - } + @Override + public EnumActionResult onItemUseFirst(final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand) { + if (player.isSneaking()) { + final TileEntity te = world.getTileEntity(pos); + IItemHandler upgrades = null; - @Override - public EnumActionResult onItemUseFirst( final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand ) - { - if( player.isSneaking() ) - { - final TileEntity te = world.getTileEntity( pos ); - IItemHandler upgrades = null; + if (te instanceof IPartHost) { + final SelectedPart sp = ((IPartHost) te).selectPart(new Vec3d(hitX, hitY, hitZ)); + if (sp.part instanceof IUpgradeableHost) { + upgrades = ((ISegmentedInventory) sp.part).getInventoryByName("upgrades"); + } + } else if (te instanceof IUpgradeableHost) { + upgrades = ((ISegmentedInventory) te).getInventoryByName("upgrades"); + } - if( te instanceof IPartHost ) - { - final SelectedPart sp = ( (IPartHost) te ).selectPart( new Vec3d( hitX, hitY, hitZ ) ); - if( sp.part instanceof IUpgradeableHost ) - { - upgrades = ( (ISegmentedInventory) sp.part ).getInventoryByName( "upgrades" ); - } - } - else if( te instanceof IUpgradeableHost ) - { - upgrades = ( (ISegmentedInventory) te ).getInventoryByName( "upgrades" ); - } + if (upgrades != null && !player.getHeldItem(hand).isEmpty() && player.getHeldItem(hand).getItem() instanceof IUpgradeModule) { + final IUpgradeModule um = (IUpgradeModule) player.getHeldItem(hand).getItem(); + final Upgrades u = um.getType(player.getHeldItem(hand)); - if( upgrades != null && !player.getHeldItem( hand ).isEmpty() && player.getHeldItem( hand ).getItem() instanceof IUpgradeModule ) - { - final IUpgradeModule um = (IUpgradeModule) player.getHeldItem( hand ).getItem(); - final Upgrades u = um.getType( player.getHeldItem( hand ) ); + if (u != null) { + if (player.world.isRemote) { + return EnumActionResult.PASS; + } - if( u != null ) - { - if( player.world.isRemote ) - { - return EnumActionResult.PASS; - } + final InventoryAdaptor ad = new AdaptorItemHandler(upgrades); + player.setHeldItem(hand, ad.addItems(player.getHeldItem(hand))); + return EnumActionResult.SUCCESS; + } + } + } - final InventoryAdaptor ad = new AdaptorItemHandler( upgrades ); - player.setHeldItem( hand, ad.addItems( player.getHeldItem( hand ) ) ); - return EnumActionResult.SUCCESS; - } - } - } + return super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + } - return super.onItemUseFirst( player, world, pos, side, hitX, hitY, hitZ, hand ); - } + @Override + public boolean hasCustomEntity(final ItemStack is) { + return this.getTypeByStack(is).hasCustomEntity(); + } - @Override - public boolean hasCustomEntity( final ItemStack is ) - { - return this.getTypeByStack( is ).hasCustomEntity(); - } + @Override + public Entity createEntity(final World w, final Entity location, final ItemStack itemstack) { + final Class droppedEntity = this.getTypeByStack(itemstack).getCustomEntityClass(); + final Entity eqi; - @Override - public Entity createEntity( final World w, final Entity location, final ItemStack itemstack ) - { - final Class droppedEntity = this.getTypeByStack( itemstack ).getCustomEntityClass(); - final Entity eqi; + try { + eqi = droppedEntity.getConstructor(World.class, double.class, double.class, double.class, ItemStack.class) + .newInstance(w, location.posX, + location.posY, location.posZ, itemstack); + } catch (final Throwable t) { + throw new IllegalStateException(t); + } - try - { - eqi = droppedEntity.getConstructor( World.class, double.class, double.class, double.class, ItemStack.class ) - .newInstance( w, location.posX, - location.posY, location.posZ, itemstack ); - } - catch( final Throwable t ) - { - throw new IllegalStateException( t ); - } + eqi.motionX = location.motionX; + eqi.motionY = location.motionY; + eqi.motionZ = location.motionZ; - eqi.motionX = location.motionX; - eqi.motionY = location.motionY; - eqi.motionZ = location.motionZ; + if (location instanceof EntityItem && eqi instanceof EntityItem) { + ((EntityItem) eqi).setDefaultPickupDelay(); + } - if( location instanceof EntityItem && eqi instanceof EntityItem ) - { - ( (EntityItem) eqi ).setDefaultPickupDelay(); - } + return eqi; + } - return eqi; - } + private String nameOf(final ItemStack is) { + if (is.isEmpty()) { + return "null"; + } - private String nameOf( final ItemStack is ) - { - if( is.isEmpty() ) - { - return "null"; - } + final MaterialType mt = this.getTypeByStack(is); + if (mt == null) { + return "null"; + } - final MaterialType mt = this.getTypeByStack( is ); - if( mt == null ) - { - return "null"; - } + return mt.name(); + } - return mt.name(); - } + @Override + public int getBytes(final ItemStack is) { + switch (this.getTypeByStack(is)) { + case CELL1K_PART: + return KILO_SCALAR; + case CELL4K_PART: + return KILO_SCALAR * 4; + case CELL16K_PART: + return KILO_SCALAR * 16; + case CELL64K_PART: + return KILO_SCALAR * 64; + default: + } + return 0; + } - @Override - public int getBytes( final ItemStack is ) - { - switch( this.getTypeByStack( is ) ) - { - case CELL1K_PART: - return KILO_SCALAR; - case CELL4K_PART: - return KILO_SCALAR * 4; - case CELL16K_PART: - return KILO_SCALAR * 16; - case CELL64K_PART: - return KILO_SCALAR * 64; - default: - } - return 0; - } + @Override + public boolean isStorageComponent(final ItemStack is) { + switch (this.getTypeByStack(is)) { + case CELL1K_PART: + case CELL4K_PART: + case CELL16K_PART: + case CELL64K_PART: + return true; + default: + } + return false; + } - @Override - public boolean isStorageComponent( final ItemStack is ) - { - switch( this.getTypeByStack( is ) ) - { - case CELL1K_PART: - case CELL4K_PART: - case CELL16K_PART: - case CELL64K_PART: - return true; - default: - } - return false; - } + private static class SlightlyBetterSort implements Comparator { + private final Pattern pattern; - private static class SlightlyBetterSort implements Comparator - { - private final Pattern pattern; + public SlightlyBetterSort(final Pattern pattern) { + this.pattern = pattern; + } - public SlightlyBetterSort( final Pattern pattern ) - { - this.pattern = pattern; - } - - @Override - public int compare( final String o1, final String o2 ) - { - try - { - final Matcher a = this.pattern.matcher( o1 ); - final Matcher b = this.pattern.matcher( o2 ); - if( a.find() && b.find() ) - { - final int ia = Integer.parseInt( a.group( 1 ) ); - final int ib = Integer.parseInt( b.group( 1 ) ); - return Integer.compare( ia, ib ); - } - } - catch( final Throwable t ) - { - // ek! - } - return o1.compareTo( o2 ); - } - } + @Override + public int compare(final String o1, final String o2) { + try { + final Matcher a = this.pattern.matcher(o1); + final Matcher b = this.pattern.matcher(o2); + if (a.find() && b.find()) { + final int ia = Integer.parseInt(a.group(1)); + final int ib = Integer.parseInt(b.group(1)); + return Integer.compare(ia, ib); + } + } catch (final Throwable t) { + // ek! + } + return o1.compareTo(o2); + } + } } diff --git a/src/main/java/appeng/items/materials/MaterialType.java b/src/main/java/appeng/items/materials/MaterialType.java index bc31f9c28..1c0de3f9f 100644 --- a/src/main/java/appeng/items/materials/MaterialType.java +++ b/src/main/java/appeng/items/materials/MaterialType.java @@ -19,219 +19,198 @@ package appeng.items.materials; -import java.util.EnumSet; -import java.util.Set; - +import appeng.core.AppEng; +import appeng.core.features.AEFeature; +import appeng.core.features.MaterialStackSrc; +import appeng.entity.EntityChargedQuartz; +import appeng.entity.EntitySingularity; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.entity.Entity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; -import appeng.core.AppEng; -import appeng.core.features.AEFeature; -import appeng.core.features.MaterialStackSrc; -import appeng.entity.EntityChargedQuartz; -import appeng.entity.EntitySingularity; +import java.util.EnumSet; +import java.util.Set; -public enum MaterialType -{ - INVALID_TYPE( -1, "material_invalid_type" ), +public enum MaterialType { + INVALID_TYPE(-1, "material_invalid_type"), - CERTUS_QUARTZ_CRYSTAL( 0, "material_certus_quartz_crystal", EnumSet.of( AEFeature.CERTUS ), "crystalCertusQuartz" ), - CERTUS_QUARTZ_CRYSTAL_CHARGED( 1, "material_certus_quartz_crystal_charged", EnumSet.of( AEFeature.CERTUS ), EntityChargedQuartz.class ), + CERTUS_QUARTZ_CRYSTAL(0, "material_certus_quartz_crystal", EnumSet.of(AEFeature.CERTUS), "crystalCertusQuartz"), + CERTUS_QUARTZ_CRYSTAL_CHARGED(1, "material_certus_quartz_crystal_charged", EnumSet.of(AEFeature.CERTUS), EntityChargedQuartz.class), - CERTUS_QUARTZ_DUST( 2, "material_certus_quartz_dust", EnumSet.of( AEFeature.DUSTS, AEFeature.CERTUS ), "dustCertusQuartz" ), - NETHER_QUARTZ_DUST( 3, "material_nether_quartz_dust", EnumSet.of( AEFeature.DUSTS ), "dustNetherQuartz,dustQuartz" ), - FLOUR( 4, "material_flour", EnumSet.of( AEFeature.FLOUR ), "dustWheat" ), - GOLD_DUST( 51, "material_gold_dust", EnumSet.of( AEFeature.DUSTS ), "dustGold" ), - IRON_DUST( 49, "material_iron_dust", EnumSet.of( AEFeature.DUSTS ), "dustIron" ), + CERTUS_QUARTZ_DUST(2, "material_certus_quartz_dust", EnumSet.of(AEFeature.DUSTS, AEFeature.CERTUS), "dustCertusQuartz"), + NETHER_QUARTZ_DUST(3, "material_nether_quartz_dust", EnumSet.of(AEFeature.DUSTS), "dustNetherQuartz,dustQuartz"), + FLOUR(4, "material_flour", EnumSet.of(AEFeature.FLOUR), "dustWheat"), + GOLD_DUST(51, "material_gold_dust", EnumSet.of(AEFeature.DUSTS), "dustGold"), + IRON_DUST(49, "material_iron_dust", EnumSet.of(AEFeature.DUSTS), "dustIron"), - SILICON( 5, "material_silicon", EnumSet.of( AEFeature.SILICON ), "itemSilicon" ), - MATTER_BALL( 6, "material_matter_ball", EnumSet.of( AEFeature.MATTER_BALL ) ), + SILICON(5, "material_silicon", EnumSet.of(AEFeature.SILICON), "itemSilicon"), + MATTER_BALL(6, "material_matter_ball", EnumSet.of(AEFeature.MATTER_BALL)), - FLUIX_CRYSTAL( 7, "material_fluix_crystal", EnumSet.of( AEFeature.FLUIX ), "crystalFluix" ), - FLUIX_DUST( 8, "material_fluix_dust", EnumSet.of( AEFeature.FLUIX, AEFeature.DUSTS ), "dustFluix" ), - FLUIX_PEARL( 9, "material_fluix_pearl", EnumSet.of( AEFeature.FLUIX ), "pearlFluix" ), + FLUIX_CRYSTAL(7, "material_fluix_crystal", EnumSet.of(AEFeature.FLUIX), "crystalFluix"), + FLUIX_DUST(8, "material_fluix_dust", EnumSet.of(AEFeature.FLUIX, AEFeature.DUSTS), "dustFluix"), + FLUIX_PEARL(9, "material_fluix_pearl", EnumSet.of(AEFeature.FLUIX), "pearlFluix"), - PURIFIED_CERTUS_QUARTZ_CRYSTAL( 10, "material_purified_certus_quartz_crystal", EnumSet.of( AEFeature.CERTUS, - AEFeature.PURE_CRYSTALS ), "crystalPureCertusQuartz" ), - PURIFIED_NETHER_QUARTZ_CRYSTAL( 11, "material_purified_nether_quartz_crystal", EnumSet.of( AEFeature.PURE_CRYSTALS ), "crystalPureNetherQuartz" ), - PURIFIED_FLUIX_CRYSTAL( 12, "material_purified_fluix_crystal", EnumSet.of( AEFeature.FLUIX, AEFeature.PURE_CRYSTALS ), "crystalPureFluix" ), + PURIFIED_CERTUS_QUARTZ_CRYSTAL(10, "material_purified_certus_quartz_crystal", EnumSet.of(AEFeature.CERTUS, + AEFeature.PURE_CRYSTALS), "crystalPureCertusQuartz"), + PURIFIED_NETHER_QUARTZ_CRYSTAL(11, "material_purified_nether_quartz_crystal", EnumSet.of(AEFeature.PURE_CRYSTALS), "crystalPureNetherQuartz"), + PURIFIED_FLUIX_CRYSTAL(12, "material_purified_fluix_crystal", EnumSet.of(AEFeature.FLUIX, AEFeature.PURE_CRYSTALS), "crystalPureFluix"), - CALCULATION_PROCESSOR_PRESS( 13, "material_calculation_processor_press", EnumSet.of( AEFeature.PRESSES ) ), - ENGINEERING_PROCESSOR_PRESS( 14, "material_engineering_processor_press", EnumSet.of( AEFeature.PRESSES ) ), - LOGIC_PROCESSOR_PRESS( 15, "material_logic_processor_press", EnumSet.of( AEFeature.PRESSES ) ), + CALCULATION_PROCESSOR_PRESS(13, "material_calculation_processor_press", EnumSet.of(AEFeature.PRESSES)), + ENGINEERING_PROCESSOR_PRESS(14, "material_engineering_processor_press", EnumSet.of(AEFeature.PRESSES)), + LOGIC_PROCESSOR_PRESS(15, "material_logic_processor_press", EnumSet.of(AEFeature.PRESSES)), - CALCULATION_PROCESSOR_PRINT( 16, "material_calculation_processor_print", EnumSet.of( AEFeature.PRINTED_CIRCUITS ) ), - ENGINEERING_PROCESSOR_PRINT( 17, "material_engineering_processor_print", EnumSet.of( AEFeature.PRINTED_CIRCUITS ) ), - LOGIC_PROCESSOR_PRINT( 18, "material_logic_processor_print", EnumSet.of( AEFeature.PRINTED_CIRCUITS ) ), + CALCULATION_PROCESSOR_PRINT(16, "material_calculation_processor_print", EnumSet.of(AEFeature.PRINTED_CIRCUITS)), + ENGINEERING_PROCESSOR_PRINT(17, "material_engineering_processor_print", EnumSet.of(AEFeature.PRINTED_CIRCUITS)), + LOGIC_PROCESSOR_PRINT(18, "material_logic_processor_print", EnumSet.of(AEFeature.PRINTED_CIRCUITS)), - SILICON_PRESS( 19, "material_silicon_press", EnumSet.of( AEFeature.PRESSES ) ), - SILICON_PRINT( 20, "material_silicon_print", EnumSet.of( AEFeature.PRINTED_CIRCUITS ) ), + SILICON_PRESS(19, "material_silicon_press", EnumSet.of(AEFeature.PRESSES)), + SILICON_PRINT(20, "material_silicon_print", EnumSet.of(AEFeature.PRINTED_CIRCUITS)), - NAME_PRESS( 21, "material_name_press", EnumSet.of( AEFeature.PRESSES ) ), + NAME_PRESS(21, "material_name_press", EnumSet.of(AEFeature.PRESSES)), - LOGIC_PROCESSOR( 22, "material_logic_processor", EnumSet.of( AEFeature.PROCESSORS ) ), - CALCULATION_PROCESSOR( 23, "material_calculation_processor", EnumSet.of( AEFeature.PROCESSORS ) ), - ENGINEERING_PROCESSOR( 24, "material_engineering_processor", EnumSet.of( AEFeature.PROCESSORS ) ), + LOGIC_PROCESSOR(22, "material_logic_processor", EnumSet.of(AEFeature.PROCESSORS)), + CALCULATION_PROCESSOR(23, "material_calculation_processor", EnumSet.of(AEFeature.PROCESSORS)), + ENGINEERING_PROCESSOR(24, "material_engineering_processor", EnumSet.of(AEFeature.PROCESSORS)), - // Basic Cards - BASIC_CARD( 25, "material_basic_card", EnumSet.of( AEFeature.BASIC_CARDS ) ), - CARD_REDSTONE( 26, "material_card_redstone", EnumSet.of( AEFeature.BASIC_CARDS ) ), - CARD_CAPACITY( 27, "material_card_capacity", EnumSet.of( AEFeature.BASIC_CARDS ) ), + // Basic Cards + BASIC_CARD(25, "material_basic_card", EnumSet.of(AEFeature.BASIC_CARDS)), + CARD_REDSTONE(26, "material_card_redstone", EnumSet.of(AEFeature.BASIC_CARDS)), + CARD_CAPACITY(27, "material_card_capacity", EnumSet.of(AEFeature.BASIC_CARDS)), - // Adv Cards - ADVANCED_CARD( 28, "material_advanced_card", EnumSet.of( AEFeature.ADVANCED_CARDS ) ), - CARD_FUZZY( 29, "material_card_fuzzy", EnumSet.of( AEFeature.ADVANCED_CARDS ) ), - CARD_SPEED( 30, "material_card_speed", EnumSet.of( AEFeature.ADVANCED_CARDS ) ), - CARD_INVERTER( 31, "material_card_inverter", EnumSet.of( AEFeature.ADVANCED_CARDS ) ), + // Adv Cards + ADVANCED_CARD(28, "material_advanced_card", EnumSet.of(AEFeature.ADVANCED_CARDS)), + CARD_FUZZY(29, "material_card_fuzzy", EnumSet.of(AEFeature.ADVANCED_CARDS)), + CARD_SPEED(30, "material_card_speed", EnumSet.of(AEFeature.ADVANCED_CARDS)), + CARD_INVERTER(31, "material_card_inverter", EnumSet.of(AEFeature.ADVANCED_CARDS)), - CELL2_SPATIAL_PART( 32, "material_cell2_spatial_part", EnumSet.of( AEFeature.SPATIAL_IO ) ), - CELL16_SPATIAL_PART( 33, "material_cell16_spatial_part", EnumSet.of( AEFeature.SPATIAL_IO ) ), - CELL128_SPATIAL_PART( 34, "material_cell128_spatial_part", EnumSet.of( AEFeature.SPATIAL_IO ) ), + CELL2_SPATIAL_PART(32, "material_cell2_spatial_part", EnumSet.of(AEFeature.SPATIAL_IO)), + CELL16_SPATIAL_PART(33, "material_cell16_spatial_part", EnumSet.of(AEFeature.SPATIAL_IO)), + CELL128_SPATIAL_PART(34, "material_cell128_spatial_part", EnumSet.of(AEFeature.SPATIAL_IO)), - CELL1K_PART( 35, "material_cell1k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ), - CELL4K_PART( 36, "material_cell4k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ), - CELL16K_PART( 37, "material_cell16k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ), - CELL64K_PART( 38, "material_cell64k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ), - EMPTY_STORAGE_CELL( 39, "material_empty_storage_cell", EnumSet.of( AEFeature.STORAGE_CELLS ) ), + CELL1K_PART(35, "material_cell1k_part", EnumSet.of(AEFeature.STORAGE_CELLS)), + CELL4K_PART(36, "material_cell4k_part", EnumSet.of(AEFeature.STORAGE_CELLS)), + CELL16K_PART(37, "material_cell16k_part", EnumSet.of(AEFeature.STORAGE_CELLS)), + CELL64K_PART(38, "material_cell64k_part", EnumSet.of(AEFeature.STORAGE_CELLS)), + EMPTY_STORAGE_CELL(39, "material_empty_storage_cell", EnumSet.of(AEFeature.STORAGE_CELLS)), - WOODEN_GEAR( 40, "material_wooden_gear", EnumSet.of( AEFeature.GRIND_STONE ), "gearWood" ), + WOODEN_GEAR(40, "material_wooden_gear", EnumSet.of(AEFeature.GRIND_STONE), "gearWood"), - WIRELESS( 41, "material_wireless", EnumSet.of( AEFeature.WIRELESS_ACCESS_TERMINAL ) ), - WIRELESS_BOOSTER( 42, "material_wireless_booster", EnumSet.of( AEFeature.WIRELESS_ACCESS_TERMINAL ) ), + WIRELESS(41, "material_wireless", EnumSet.of(AEFeature.WIRELESS_ACCESS_TERMINAL)), + WIRELESS_BOOSTER(42, "material_wireless_booster", EnumSet.of(AEFeature.WIRELESS_ACCESS_TERMINAL)), - FORMATION_CORE( 43, "material_formation_core", EnumSet.of( AEFeature.CORES ) ), - ANNIHILATION_CORE( 44, "material_annihilation_core", EnumSet.of( AEFeature.CORES ) ), + FORMATION_CORE(43, "material_formation_core", EnumSet.of(AEFeature.CORES)), + ANNIHILATION_CORE(44, "material_annihilation_core", EnumSet.of(AEFeature.CORES)), - SKY_DUST( 45, "material_sky_dust", EnumSet.of( AEFeature.DUSTS ) ), + SKY_DUST(45, "material_sky_dust", EnumSet.of(AEFeature.DUSTS)), - ENDER_DUST( 46, "material_ender_dust", EnumSet.of( AEFeature.QUANTUM_NETWORK_BRIDGE ), "dustEnder,dustEnderPearl", EntitySingularity.class ), - SINGULARITY( 47, "material_singularity", EnumSet.of( AEFeature.QUANTUM_NETWORK_BRIDGE ), EntitySingularity.class ), - QUANTUM_ENTANGLED_SINGULARITY( 48, "material_quantum_entangled_singularity", EnumSet.of( AEFeature.QUANTUM_NETWORK_BRIDGE ), EntitySingularity.class ), + ENDER_DUST(46, "material_ender_dust", EnumSet.of(AEFeature.QUANTUM_NETWORK_BRIDGE), "dustEnder,dustEnderPearl", EntitySingularity.class), + SINGULARITY(47, "material_singularity", EnumSet.of(AEFeature.QUANTUM_NETWORK_BRIDGE), EntitySingularity.class), + QUANTUM_ENTANGLED_SINGULARITY(48, "material_quantum_entangled_singularity", EnumSet.of(AEFeature.QUANTUM_NETWORK_BRIDGE), EntitySingularity.class), - BLANK_PATTERN( 52, "material_blank_pattern", EnumSet.of( AEFeature.PATTERNS ) ), - CARD_CRAFTING( 53, "material_card_crafting", EnumSet.of( AEFeature.ADVANCED_CARDS, AEFeature.CRAFTING_CPU ) ), + BLANK_PATTERN(52, "material_blank_pattern", EnumSet.of(AEFeature.PATTERNS)), + CARD_CRAFTING(53, "material_card_crafting", EnumSet.of(AEFeature.ADVANCED_CARDS, AEFeature.CRAFTING_CPU)), - FLUID_CELL1K_PART( 54, "material_fluid_cell1k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ), - FLUID_CELL4K_PART( 55, "material_fluid_cell4k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ), - FLUID_CELL16K_PART( 56, "material_fluid_cell16k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ), - FLUID_CELL64K_PART( 57, "material_fluid_cell64k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ), + FLUID_CELL1K_PART(54, "material_fluid_cell1k_part", EnumSet.of(AEFeature.STORAGE_CELLS)), + FLUID_CELL4K_PART(55, "material_fluid_cell4k_part", EnumSet.of(AEFeature.STORAGE_CELLS)), + FLUID_CELL16K_PART(56, "material_fluid_cell16k_part", EnumSet.of(AEFeature.STORAGE_CELLS)), + FLUID_CELL64K_PART(57, "material_fluid_cell64k_part", EnumSet.of(AEFeature.STORAGE_CELLS)), - CARD_PATTERN_EXPANSION( 58, "material_card_pattern_expansion", EnumSet.of( AEFeature.ADVANCED_CARDS ) ); + CARD_PATTERN_EXPANSION(58, "material_card_pattern_expansion", EnumSet.of(AEFeature.ADVANCED_CARDS)); - private final Set features; - private final ModelResourceLocation model; - private Item itemInstance; - private int damageValue; - // stack! - private MaterialStackSrc stackSrc; - private String oreName; - private Class droppedEntity; - private boolean isRegistered = false; + private final Set features; + private final ModelResourceLocation model; + private Item itemInstance; + private int damageValue; + // stack! + private MaterialStackSrc stackSrc; + private String oreName; + private Class droppedEntity; + private boolean isRegistered = false; - MaterialType( final int metaValue, String modelName ) - { - this( metaValue, modelName, EnumSet.of( AEFeature.CORE ) ); - } + MaterialType(final int metaValue, String modelName) { + this(metaValue, modelName, EnumSet.of(AEFeature.CORE)); + } - MaterialType( final int metaValue, String modelName, final Set features ) - { - this.setDamageValue( metaValue ); - this.features = features; - this.model = new ModelResourceLocation( new ResourceLocation( AppEng.MOD_ID, modelName ), "inventory" ); - } + MaterialType(final int metaValue, String modelName, final Set features) { + this.setDamageValue(metaValue); + this.features = features; + this.model = new ModelResourceLocation(new ResourceLocation(AppEng.MOD_ID, modelName), "inventory"); + } - MaterialType( final int metaValue, String modelName, final Set features, final Class c ) - { - this( metaValue, modelName, features ); - this.droppedEntity = c; - } + MaterialType(final int metaValue, String modelName, final Set features, final Class c) { + this(metaValue, modelName, features); + this.droppedEntity = c; + } - MaterialType( final int metaValue, String modelName, final Set features, final String oreDictionary, final Class c ) - { - this( metaValue, modelName, features ); - this.oreName = oreDictionary; - this.droppedEntity = c; - } + MaterialType(final int metaValue, String modelName, final Set features, final String oreDictionary, final Class c) { + this(metaValue, modelName, features); + this.oreName = oreDictionary; + this.droppedEntity = c; + } - MaterialType( final int metaValue, String modelName, final Set features, final String oreDictionary ) - { - this( metaValue, modelName, features ); - this.oreName = oreDictionary; - } + MaterialType(final int metaValue, String modelName, final Set features, final String oreDictionary) { + this(metaValue, modelName, features); + this.oreName = oreDictionary; + } - public ItemStack stack( final int size ) - { - return new ItemStack( this.getItemInstance(), size, this.getDamageValue() ); - } + public ItemStack stack(final int size) { + return new ItemStack(this.getItemInstance(), size, this.getDamageValue()); + } - Set getFeature() - { - return this.features; - } + Set getFeature() { + return this.features; + } - public String getOreName() - { - return this.oreName; - } + public String getOreName() { + return this.oreName; + } - boolean hasCustomEntity() - { - return this.droppedEntity != null; - } + boolean hasCustomEntity() { + return this.droppedEntity != null; + } - Class getCustomEntityClass() - { - return this.droppedEntity; - } + Class getCustomEntityClass() { + return this.droppedEntity; + } - public boolean isRegistered() - { - return this.isRegistered; - } + public boolean isRegistered() { + return this.isRegistered; + } - void markReady() - { - this.isRegistered = true; - } + void markReady() { + this.isRegistered = true; + } - public int getDamageValue() - { - return this.damageValue; - } + public int getDamageValue() { + return this.damageValue; + } - void setDamageValue( final int damageValue ) - { - this.damageValue = damageValue; - } + void setDamageValue(final int damageValue) { + this.damageValue = damageValue; + } - public Item getItemInstance() - { - return this.itemInstance; - } + public Item getItemInstance() { + return this.itemInstance; + } - void setItemInstance( final Item itemInstance ) - { - this.itemInstance = itemInstance; - } + void setItemInstance(final Item itemInstance) { + this.itemInstance = itemInstance; + } - MaterialStackSrc getStackSrc() - { - return this.stackSrc; - } + MaterialStackSrc getStackSrc() { + return this.stackSrc; + } - void setStackSrc( final MaterialStackSrc stackSrc ) - { - this.stackSrc = stackSrc; - } + void setStackSrc(final MaterialStackSrc stackSrc) { + this.stackSrc = stackSrc; + } - public ModelResourceLocation getModel() - { - return this.model; - } + public ModelResourceLocation getModel() { + return this.model; + } } diff --git a/src/main/java/appeng/items/misc/ItemCrystalSeed.java b/src/main/java/appeng/items/misc/ItemCrystalSeed.java index 88644e681..00e9459cf 100644 --- a/src/main/java/appeng/items/misc/ItemCrystalSeed.java +++ b/src/main/java/appeng/items/misc/ItemCrystalSeed.java @@ -19,11 +19,14 @@ package appeng.items.misc; -import java.util.List; -import java.util.Optional; - -import javax.annotation.Nullable; - +import appeng.api.AEApi; +import appeng.api.definitions.IMaterials; +import appeng.api.implementations.items.IGrowableCrystal; +import appeng.api.recipes.ResolverResult; +import appeng.core.localization.ButtonToolTips; +import appeng.entity.EntityGrowingCrystal; +import appeng.items.AEBaseItem; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.util.ITooltipFlag; @@ -36,225 +39,190 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.AEApi; -import appeng.api.definitions.IMaterials; -import appeng.api.implementations.items.IGrowableCrystal; -import appeng.api.recipes.ResolverResult; -import appeng.core.localization.ButtonToolTips; -import appeng.entity.EntityGrowingCrystal; -import appeng.items.AEBaseItem; -import appeng.util.Platform; +import javax.annotation.Nullable; +import java.util.List; +import java.util.Optional; -public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal -{ +public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal { - static final int LEVEL_OFFSET = 200; - static final int SINGLE_OFFSET = LEVEL_OFFSET * 3; + static final int LEVEL_OFFSET = 200; + static final int SINGLE_OFFSET = LEVEL_OFFSET * 3; - public static final int CERTUS = 0; - public static final int NETHER = SINGLE_OFFSET; - public static final int FLUIX = SINGLE_OFFSET * 2; - public static final int FINAL_STAGE = SINGLE_OFFSET * 3; + public static final int CERTUS = 0; + public static final int NETHER = SINGLE_OFFSET; + public static final int FLUIX = SINGLE_OFFSET * 2; + public static final int FINAL_STAGE = SINGLE_OFFSET * 3; - public ItemCrystalSeed() - { - this.setHasSubtypes( true ); - } + public ItemCrystalSeed() { + this.setHasSubtypes(true); + } - @Nullable - public static ResolverResult getResolver( final int certus2 ) - { + @Nullable + public static ResolverResult getResolver(final int certus2) { - return AEApi.instance() - .definitions() - .items() - .crystalSeed() - .maybeStack( 1 ) - .map( crystalSeedStack -> - { - crystalSeedStack.setItemDamage( certus2 ); - crystalSeedStack = newStyle( crystalSeedStack ); - String itemName = crystalSeedStack.getItem().getRegistryName().getResourcePath(); - return new ResolverResult( itemName, crystalSeedStack.getItemDamage(), crystalSeedStack.getTagCompound() ); - } ) - .orElse( null ); + return AEApi.instance() + .definitions() + .items() + .crystalSeed() + .maybeStack(1) + .map(crystalSeedStack -> + { + crystalSeedStack.setItemDamage(certus2); + crystalSeedStack = newStyle(crystalSeedStack); + String itemName = crystalSeedStack.getItem().getRegistryName().getResourcePath(); + return new ResolverResult(itemName, crystalSeedStack.getItemDamage(), crystalSeedStack.getTagCompound()); + }) + .orElse(null); - } + } - private static ItemStack newStyle( final ItemStack itemStack ) - { - getProgress( itemStack ); - return itemStack; - } + private static ItemStack newStyle(final ItemStack itemStack) { + getProgress(itemStack); + return itemStack; + } - static int getProgress( final ItemStack is ) - { - if( is.hasTagCompound() ) - { - return is.getTagCompound().getInteger( "progress" ); - } - else - { - final int progress; - final NBTTagCompound comp = Platform.openNbtData( is ); - comp.setInteger( "progress", progress = is.getItemDamage() ); - is.setItemDamage( ( is.getItemDamage() / SINGLE_OFFSET ) * SINGLE_OFFSET ); - return progress; - } - } + static int getProgress(final ItemStack is) { + if (is.hasTagCompound()) { + return is.getTagCompound().getInteger("progress"); + } else { + final int progress; + final NBTTagCompound comp = Platform.openNbtData(is); + comp.setInteger("progress", progress = is.getItemDamage()); + is.setItemDamage((is.getItemDamage() / SINGLE_OFFSET) * SINGLE_OFFSET); + return progress; + } + } - @Nullable - @Override - public ItemStack triggerGrowth( final ItemStack is ) - { - final int newDamage = getProgress( is ) + 1; - final IMaterials materials = AEApi.instance().definitions().materials(); - final int size = is.getCount(); + @Nullable + @Override + public ItemStack triggerGrowth(final ItemStack is) { + final int newDamage = getProgress(is) + 1; + final IMaterials materials = AEApi.instance().definitions().materials(); + final int size = is.getCount(); - if( newDamage == CERTUS + SINGLE_OFFSET ) - { - Optional quartzStack = materials.purifiedCertusQuartzCrystal().maybeStack( size ); - if( quartzStack.isPresent() ) - { - return quartzStack.get(); - } - } - if( newDamage == NETHER + SINGLE_OFFSET ) - { - Optional quartzStack = materials.purifiedNetherQuartzCrystal().maybeStack( size ); - if( quartzStack.isPresent() ) - { - return quartzStack.get(); - } - } - if( newDamage == FLUIX + SINGLE_OFFSET ) - { - Optional quartzStack = materials.purifiedFluixCrystal().maybeStack( size ); - if( quartzStack.isPresent() ) - { - return quartzStack.get(); - } - } - if( newDamage > FINAL_STAGE ) - { - return ItemStack.EMPTY; - } + if (newDamage == CERTUS + SINGLE_OFFSET) { + Optional quartzStack = materials.purifiedCertusQuartzCrystal().maybeStack(size); + if (quartzStack.isPresent()) { + return quartzStack.get(); + } + } + if (newDamage == NETHER + SINGLE_OFFSET) { + Optional quartzStack = materials.purifiedNetherQuartzCrystal().maybeStack(size); + if (quartzStack.isPresent()) { + return quartzStack.get(); + } + } + if (newDamage == FLUIX + SINGLE_OFFSET) { + Optional quartzStack = materials.purifiedFluixCrystal().maybeStack(size); + if (quartzStack.isPresent()) { + return quartzStack.get(); + } + } + if (newDamage > FINAL_STAGE) { + return ItemStack.EMPTY; + } - this.setProgress( is, newDamage ); - return is; - } + this.setProgress(is, newDamage); + return is; + } - private void setProgress( final ItemStack is, final int newDamage ) - { - final NBTTagCompound comp = Platform.openNbtData( is ); - comp.setInteger( "progress", newDamage ); - is.setItemDamage( is.getItemDamage() / LEVEL_OFFSET * LEVEL_OFFSET ); - } + private void setProgress(final ItemStack is, final int newDamage) { + final NBTTagCompound comp = Platform.openNbtData(is); + comp.setInteger("progress", newDamage); + is.setItemDamage(is.getItemDamage() / LEVEL_OFFSET * LEVEL_OFFSET); + } - @Override - public float getMultiplier( final Block blk, final Material mat ) - { - return 0.5f; - } + @Override + public float getMultiplier(final Block blk, final Material mat) { + return 0.5f; + } - @Override - @SideOnly( Side.CLIENT ) - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - lines.add( ButtonToolTips.DoesntDespawn.getLocal() ); - final int progress = getProgress( stack ) % SINGLE_OFFSET; - lines.add( Math.floor( (float) progress / (float) ( SINGLE_OFFSET / 100 ) ) + "%" ); + @Override + @SideOnly(Side.CLIENT) + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + lines.add(ButtonToolTips.DoesntDespawn.getLocal()); + final int progress = getProgress(stack) % SINGLE_OFFSET; + lines.add(Math.floor((float) progress / (float) (SINGLE_OFFSET / 100)) + "%"); - super.addCheckedInformation( stack, world, lines, advancedTooltips ); - } + super.addCheckedInformation(stack, world, lines, advancedTooltips); + } - @Override - public int getEntityLifespan( final ItemStack itemStack, final World world ) - { - return Integer.MAX_VALUE; - } + @Override + public int getEntityLifespan(final ItemStack itemStack, final World world) { + return Integer.MAX_VALUE; + } - @Override - public String getUnlocalizedName( final ItemStack is ) - { - final int damage = getProgress( is ); + @Override + public String getUnlocalizedName(final ItemStack is) { + final int damage = getProgress(is); - if( damage < CERTUS + SINGLE_OFFSET ) - { - return this.getUnlocalizedName() + ".certus"; - } + if (damage < CERTUS + SINGLE_OFFSET) { + return this.getUnlocalizedName() + ".certus"; + } - if( damage < NETHER + SINGLE_OFFSET ) - { - return this.getUnlocalizedName() + ".nether"; - } + if (damage < NETHER + SINGLE_OFFSET) { + return this.getUnlocalizedName() + ".nether"; + } - if( damage < FLUIX + SINGLE_OFFSET ) - { - return this.getUnlocalizedName() + ".fluix"; - } + if (damage < FLUIX + SINGLE_OFFSET) { + return this.getUnlocalizedName() + ".fluix"; + } - return this.getUnlocalizedName(); - } + return this.getUnlocalizedName(); + } - @Override - public boolean isDamageable() - { - return false; - } + @Override + public boolean isDamageable() { + return false; + } - @Override - public boolean isDamaged( final ItemStack stack ) - { - return false; - } + @Override + public boolean isDamaged(final ItemStack stack) { + return false; + } - @Override - public int getMaxDamage( final ItemStack stack ) - { - return FINAL_STAGE; - } + @Override + public int getMaxDamage(final ItemStack stack) { + return FINAL_STAGE; + } - @Override - public boolean hasCustomEntity( final ItemStack stack ) - { - return true; - } + @Override + public boolean hasCustomEntity(final ItemStack stack) { + return true; + } - @Override - public Entity createEntity( final World world, final Entity location, final ItemStack itemstack ) - { - final EntityGrowingCrystal egc = new EntityGrowingCrystal( world, location.posX, location.posY, location.posZ, itemstack ); + @Override + public Entity createEntity(final World world, final Entity location, final ItemStack itemstack) { + final EntityGrowingCrystal egc = new EntityGrowingCrystal(world, location.posX, location.posY, location.posZ, itemstack); - egc.motionX = location.motionX; - egc.motionY = location.motionY; - egc.motionZ = location.motionZ; + egc.motionX = location.motionX; + egc.motionY = location.motionY; + egc.motionZ = location.motionZ; - // Cannot read the pickup delay of the original item, so we - // use the pickup delay used for items dropped by a player instead - egc.setPickupDelay( 40 ); + // Cannot read the pickup delay of the original item, so we + // use the pickup delay used for items dropped by a player instead + egc.setPickupDelay(40); - return egc; - } + return egc; + } - @Override - protected void getCheckedSubItems( final CreativeTabs creativeTab, final NonNullList itemStacks ) - { - // lvl 0 - itemStacks.add( newStyle( new ItemStack( this, 1, CERTUS ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, NETHER ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, FLUIX ) ) ); + @Override + protected void getCheckedSubItems(final CreativeTabs creativeTab, final NonNullList itemStacks) { + // lvl 0 + itemStacks.add(newStyle(new ItemStack(this, 1, CERTUS))); + itemStacks.add(newStyle(new ItemStack(this, 1, NETHER))); + itemStacks.add(newStyle(new ItemStack(this, 1, FLUIX))); - // lvl 1 - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET + CERTUS ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET + NETHER ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET + FLUIX ) ) ); + // lvl 1 + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET + CERTUS))); + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET + NETHER))); + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET + FLUIX))); - // lvl 2 - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET * 2 + CERTUS ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET * 2 + NETHER ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET * 2 + FLUIX ) ) ); - } + // lvl 2 + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET * 2 + CERTUS))); + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET * 2 + NETHER))); + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET * 2 + FLUIX))); + } } diff --git a/src/main/java/appeng/items/misc/ItemCrystalSeedRendering.java b/src/main/java/appeng/items/misc/ItemCrystalSeedRendering.java index d44529829..a8f5e36d0 100644 --- a/src/main/java/appeng/items/misc/ItemCrystalSeedRendering.java +++ b/src/main/java/appeng/items/misc/ItemCrystalSeedRendering.java @@ -19,85 +19,76 @@ package appeng.items.misc; +import appeng.bootstrap.IItemRendering; +import appeng.bootstrap.ItemRenderingCustomizer; import com.google.common.collect.ImmutableList; - import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.bootstrap.IItemRendering; -import appeng.bootstrap.ItemRenderingCustomizer; +public class ItemCrystalSeedRendering extends ItemRenderingCustomizer { -public class ItemCrystalSeedRendering extends ItemRenderingCustomizer -{ + private static final ModelResourceLocation[] MODELS_CERTUS = { + new ModelResourceLocation("appliedenergistics2:crystal_seed_certus"), + new ModelResourceLocation("appliedenergistics2:crystal_seed_certus2"), + new ModelResourceLocation("appliedenergistics2:crystal_seed_certus3") + }; + private static final ModelResourceLocation[] MODELS_FLUIX = { + new ModelResourceLocation("appliedenergistics2:crystal_seed_fluix"), + new ModelResourceLocation("appliedenergistics2:crystal_seed_fluix2"), + new ModelResourceLocation("appliedenergistics2:crystal_seed_fluix3") + }; + private static final ModelResourceLocation[] MODELS_NETHER = { + new ModelResourceLocation("appliedenergistics2:crystal_seed_nether"), + new ModelResourceLocation("appliedenergistics2:crystal_seed_nether2"), + new ModelResourceLocation("appliedenergistics2:crystal_seed_nether3") + }; - private static final ModelResourceLocation[] MODELS_CERTUS = { - new ModelResourceLocation( "appliedenergistics2:crystal_seed_certus" ), - new ModelResourceLocation( "appliedenergistics2:crystal_seed_certus2" ), - new ModelResourceLocation( "appliedenergistics2:crystal_seed_certus3" ) - }; - private static final ModelResourceLocation[] MODELS_FLUIX = { - new ModelResourceLocation( "appliedenergistics2:crystal_seed_fluix" ), - new ModelResourceLocation( "appliedenergistics2:crystal_seed_fluix2" ), - new ModelResourceLocation( "appliedenergistics2:crystal_seed_fluix3" ) - }; - private static final ModelResourceLocation[] MODELS_NETHER = { - new ModelResourceLocation( "appliedenergistics2:crystal_seed_nether" ), - new ModelResourceLocation( "appliedenergistics2:crystal_seed_nether2" ), - new ModelResourceLocation( "appliedenergistics2:crystal_seed_nether3" ) - }; + @Override + @SideOnly(Side.CLIENT) + public void customize(IItemRendering rendering) { + rendering.variants(ImmutableList.builder().add(MODELS_CERTUS).add(MODELS_FLUIX).add(MODELS_NETHER).build()); + rendering.meshDefinition(this.getItemMeshDefinition()); + } - @Override - @SideOnly( Side.CLIENT ) - public void customize( IItemRendering rendering ) - { - rendering.variants( ImmutableList.builder().add( MODELS_CERTUS ).add( MODELS_FLUIX ).add( MODELS_NETHER ).build() ); - rendering.meshDefinition( this.getItemMeshDefinition() ); - } + private ItemMeshDefinition getItemMeshDefinition() { + return is -> + { + int damage = ItemCrystalSeed.getProgress(is); - private ItemMeshDefinition getItemMeshDefinition() - { - return is -> - { - int damage = ItemCrystalSeed.getProgress( is ); + // Split the damage value into crystal type and growth level + int type = damage / ItemCrystalSeed.SINGLE_OFFSET; + int level = (damage % ItemCrystalSeed.SINGLE_OFFSET) / ItemCrystalSeed.LEVEL_OFFSET; - // Split the damage value into crystal type and growth level - int type = damage / ItemCrystalSeed.SINGLE_OFFSET; - int level = ( damage % ItemCrystalSeed.SINGLE_OFFSET ) / ItemCrystalSeed.LEVEL_OFFSET; + // Determine which list of models to use based on the type of crystal + ModelResourceLocation[] models; + switch (type) { + case 0: + models = MODELS_CERTUS; + break; + case 1: + models = MODELS_NETHER; + break; + case 2: + models = MODELS_FLUIX; + break; + default: + // We use this as the fallback for broken items + models = MODELS_CERTUS; + break; + } - // Determine which list of models to use based on the type of crystal - ModelResourceLocation[] models; - switch( type ) - { - case 0: - models = MODELS_CERTUS; - break; - case 1: - models = MODELS_NETHER; - break; - case 2: - models = MODELS_FLUIX; - break; - default: - // We use this as the fallback for broken items - models = MODELS_CERTUS; - break; - } + // Return one of the 3 models based on the level + if (level < 0) { + level = 0; + } else if (level >= models.length) { + level = models.length - 1; + } - // Return one of the 3 models based on the level - if( level < 0 ) - { - level = 0; - } - else if( level >= models.length ) - { - level = models.length - 1; - } - - return models[level]; - }; - } + return models[level]; + }; + } } diff --git a/src/main/java/appeng/items/misc/ItemEncodedPattern.java b/src/main/java/appeng/items/misc/ItemEncodedPattern.java index d91d6015f..71b2baaf6 100644 --- a/src/main/java/appeng/items/misc/ItemEncodedPattern.java +++ b/src/main/java/appeng/items/misc/ItemEncodedPattern.java @@ -19,10 +19,16 @@ package appeng.items.misc; -import java.util.List; -import java.util.Map; -import java.util.WeakHashMap; - +import appeng.api.AEApi; +import appeng.api.implementations.ICraftingPatternItem; +import appeng.api.networking.crafting.ICraftingPatternDetails; +import appeng.api.storage.data.IAEItemStack; +import appeng.core.AppEng; +import appeng.core.localization.GuiText; +import appeng.helpers.InvalidPatternHelper; +import appeng.helpers.PatternHelper; +import appeng.items.AEBaseItem; +import appeng.util.Platform; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; @@ -37,197 +43,161 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.AEApi; -import appeng.api.implementations.ICraftingPatternItem; -import appeng.api.networking.crafting.ICraftingPatternDetails; -import appeng.api.storage.data.IAEItemStack; -import appeng.core.AppEng; -import appeng.core.localization.GuiText; -import appeng.helpers.InvalidPatternHelper; -import appeng.helpers.PatternHelper; -import appeng.items.AEBaseItem; -import appeng.util.Platform; +import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; -public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternItem -{ - // rather simple client side caching. - private static final Map SIMPLE_CACHE = new WeakHashMap<>(); +public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternItem { + // rather simple client side caching. + private static final Map SIMPLE_CACHE = new WeakHashMap<>(); - public ItemEncodedPattern() - { - this.setMaxStackSize( 64 ); - } + public ItemEncodedPattern() { + this.setMaxStackSize(64); + } - @Override - public ActionResult onItemRightClick( final World w, final EntityPlayer player, final EnumHand hand ) - { - this.clearPattern( player.getHeldItem( hand ), player ); + @Override + public ActionResult onItemRightClick(final World w, final EntityPlayer player, final EnumHand hand) { + this.clearPattern(player.getHeldItem(hand), player); - return new ActionResult<>( EnumActionResult.SUCCESS, player.getHeldItem( hand ) ); - } + return new ActionResult<>(EnumActionResult.SUCCESS, player.getHeldItem(hand)); + } - @Override - public EnumActionResult onItemUseFirst( final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand ) - { - return this.clearPattern( player.getHeldItem( hand ), player ) ? EnumActionResult.SUCCESS : EnumActionResult.PASS; - } + @Override + public EnumActionResult onItemUseFirst(final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand) { + return this.clearPattern(player.getHeldItem(hand), player) ? EnumActionResult.SUCCESS : EnumActionResult.PASS; + } - private boolean clearPattern( final ItemStack stack, final EntityPlayer player ) - { - if( player.isSneaking() ) - { - if( Platform.isClient() ) - { - return false; - } + private boolean clearPattern(final ItemStack stack, final EntityPlayer player) { + if (player.isSneaking()) { + if (Platform.isClient()) { + return false; + } - final InventoryPlayer inv = player.inventory; + final InventoryPlayer inv = player.inventory; - ItemStack is = AEApi.instance().definitions().materials().blankPattern().maybeStack( stack.getCount() ).orElse( ItemStack.EMPTY ); - if( !is.isEmpty() ) - { - for( int s = 0; s < player.inventory.getSizeInventory(); s++ ) - { - if( inv.getStackInSlot( s ) == stack ) - { - inv.setInventorySlotContents( s, is ); - return true; - } - } - } - } + ItemStack is = AEApi.instance().definitions().materials().blankPattern().maybeStack(stack.getCount()).orElse(ItemStack.EMPTY); + if (!is.isEmpty()) { + for (int s = 0; s < player.inventory.getSizeInventory(); s++) { + if (inv.getStackInSlot(s) == stack) { + inv.setInventorySlotContents(s, is); + return true; + } + } + } + } - return false; - } + return false; + } - @Override - @SideOnly( Side.CLIENT ) - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - final ICraftingPatternDetails details = this.getPatternForItem( stack, world ); + @Override + @SideOnly(Side.CLIENT) + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + final ICraftingPatternDetails details = this.getPatternForItem(stack, world); - if( details == null ) - { - if( !stack.hasTagCompound() ) - { - return; - } + if (details == null) { + if (!stack.hasTagCompound()) { + return; + } - stack.setStackDisplayName( TextFormatting.RED + GuiText.InvalidPattern.getLocal() ); + stack.setStackDisplayName(TextFormatting.RED + GuiText.InvalidPattern.getLocal()); - InvalidPatternHelper invalid = new InvalidPatternHelper( stack ); + InvalidPatternHelper invalid = new InvalidPatternHelper(stack); - final String label = ( invalid.isCraftable() ? GuiText.Crafts.getLocal() : GuiText.Creates.getLocal() ) + ": "; - final String and = ' ' + GuiText.And.getLocal() + ' '; - final String with = GuiText.With.getLocal() + ": "; + final String label = (invalid.isCraftable() ? GuiText.Crafts.getLocal() : GuiText.Creates.getLocal()) + ": "; + final String and = ' ' + GuiText.And.getLocal() + ' '; + final String with = GuiText.With.getLocal() + ": "; - boolean first = true; - for( final InvalidPatternHelper.PatternIngredient output : invalid.getOutputs() ) - { - lines.add( ( first ? label : and ) + output.getFormattedToolTip() ); - first = false; - } + boolean first = true; + for (final InvalidPatternHelper.PatternIngredient output : invalid.getOutputs()) { + lines.add((first ? label : and) + output.getFormattedToolTip()); + first = false; + } - first = true; - for( final InvalidPatternHelper.PatternIngredient input : invalid.getInputs() ) - { - lines.add( ( first ? with : and ) + input.getFormattedToolTip() ); - first = false; - } + first = true; + for (final InvalidPatternHelper.PatternIngredient input : invalid.getInputs()) { + lines.add((first ? with : and) + input.getFormattedToolTip()); + first = false; + } - if( invalid.isCraftable() ) - { - final String substitutionLabel = GuiText.Substitute.getLocal() + " "; - final String canSubstitute = invalid.canSubstitute() ? GuiText.Yes.getLocal() : GuiText.No.getLocal(); + if (invalid.isCraftable()) { + final String substitutionLabel = GuiText.Substitute.getLocal() + " "; + final String canSubstitute = invalid.canSubstitute() ? GuiText.Yes.getLocal() : GuiText.No.getLocal(); - lines.add( substitutionLabel + canSubstitute ); - } + lines.add(substitutionLabel + canSubstitute); + } - return; - } + return; + } - if( stack.hasDisplayName() ) - { - stack.removeSubCompound( "display" ); - } + if (stack.hasDisplayName()) { + stack.removeSubCompound("display"); + } - final boolean isCrafting = details.isCraftable(); - final boolean substitute = details.canSubstitute(); + final boolean isCrafting = details.isCraftable(); + final boolean substitute = details.canSubstitute(); - final IAEItemStack[] in = details.getCondensedInputs(); - final IAEItemStack[] out = details.getCondensedOutputs(); + final IAEItemStack[] in = details.getCondensedInputs(); + final IAEItemStack[] out = details.getCondensedOutputs(); - final String label = ( isCrafting ? GuiText.Crafts.getLocal() : GuiText.Creates.getLocal() ) + ": "; - final String and = ' ' + GuiText.And.getLocal() + ' '; - final String with = GuiText.With.getLocal() + ": "; + final String label = (isCrafting ? GuiText.Crafts.getLocal() : GuiText.Creates.getLocal()) + ": "; + final String and = ' ' + GuiText.And.getLocal() + ' '; + final String with = GuiText.With.getLocal() + ": "; - boolean first = true; - for( final IAEItemStack anOut : out ) - { - if( anOut == null ) - { - continue; - } + boolean first = true; + for (final IAEItemStack anOut : out) { + if (anOut == null) { + continue; + } - lines.add( ( first ? label : and ) + anOut.getStackSize() + ' ' + Platform.getItemDisplayName( anOut ) ); - first = false; - } + lines.add((first ? label : and) + anOut.getStackSize() + ' ' + Platform.getItemDisplayName(anOut)); + first = false; + } - first = true; - for( final IAEItemStack anIn : in ) - { - if( anIn == null ) - { - continue; - } + first = true; + for (final IAEItemStack anIn : in) { + if (anIn == null) { + continue; + } - lines.add( ( first ? with : and ) + anIn.getStackSize() + ' ' + Platform.getItemDisplayName( anIn ) ); - first = false; - } + lines.add((first ? with : and) + anIn.getStackSize() + ' ' + Platform.getItemDisplayName(anIn)); + first = false; + } - if( isCrafting ) - { - final String substitutionLabel = GuiText.Substitute.getLocal() + " "; - final String canSubstitute = substitute ? GuiText.Yes.getLocal() : GuiText.No.getLocal(); + if (isCrafting) { + final String substitutionLabel = GuiText.Substitute.getLocal() + " "; + final String canSubstitute = substitute ? GuiText.Yes.getLocal() : GuiText.No.getLocal(); - lines.add( substitutionLabel + canSubstitute ); - } - } + lines.add(substitutionLabel + canSubstitute); + } + } - @Override - public ICraftingPatternDetails getPatternForItem( final ItemStack is, final World w ) - { - try - { - return new PatternHelper( is, w ); - } - catch( final Throwable t ) - { - return null; - } - } + @Override + public ICraftingPatternDetails getPatternForItem(final ItemStack is, final World w) { + try { + return new PatternHelper(is, w); + } catch (final Throwable t) { + return null; + } + } - public ItemStack getOutput( final ItemStack item ) - { - ItemStack out = SIMPLE_CACHE.get( item ); + public ItemStack getOutput(final ItemStack item) { + ItemStack out = SIMPLE_CACHE.get(item); - if( out != null ) - { - return out; - } + if (out != null) { + return out; + } - final World w = AppEng.proxy.getWorld(); - if( w == null ) - { - return ItemStack.EMPTY; - } + final World w = AppEng.proxy.getWorld(); + if (w == null) { + return ItemStack.EMPTY; + } - final ICraftingPatternDetails details = this.getPatternForItem( item, w ); + final ICraftingPatternDetails details = this.getPatternForItem(item, w); - out = details != null ? details.getOutputs()[0].createItemStack() : ItemStack.EMPTY; + out = details != null ? details.getOutputs()[0].createItemStack() : ItemStack.EMPTY; - SIMPLE_CACHE.put( item, out ); - return out; - } + SIMPLE_CACHE.put(item, out); + return out; + } } diff --git a/src/main/java/appeng/items/misc/ItemPaintBall.java b/src/main/java/appeng/items/misc/ItemPaintBall.java index 1a87e4388..54c797ee5 100644 --- a/src/main/java/appeng/items/misc/ItemPaintBall.java +++ b/src/main/java/appeng/items/misc/ItemPaintBall.java @@ -19,76 +19,62 @@ package appeng.items.misc; +import appeng.api.util.AEColor; +import appeng.core.localization.GuiText; +import appeng.items.AEBaseItem; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; -import appeng.api.util.AEColor; -import appeng.core.localization.GuiText; -import appeng.items.AEBaseItem; +public class ItemPaintBall extends AEBaseItem { -public class ItemPaintBall extends AEBaseItem -{ + private static final int DAMAGE_THRESHOLD = 20; - private static final int DAMAGE_THRESHOLD = 20; + public ItemPaintBall() { + this.setHasSubtypes(true); + } - public ItemPaintBall() - { - this.setHasSubtypes( true ); - } + @Override + public String getItemStackDisplayName(final ItemStack is) { + return super.getItemStackDisplayName(is) + " - " + this.getExtraName(is); + } - @Override - public String getItemStackDisplayName( final ItemStack is ) - { - return super.getItemStackDisplayName( is ) + " - " + this.getExtraName( is ); - } + private String getExtraName(final ItemStack is) { + return (is.getItemDamage() >= DAMAGE_THRESHOLD ? GuiText.Lumen.getLocal() + ' ' : "") + this.getColor(is); + } - private String getExtraName( final ItemStack is ) - { - return ( is.getItemDamage() >= DAMAGE_THRESHOLD ? GuiText.Lumen.getLocal() + ' ' : "" ) + this.getColor( is ); - } + public AEColor getColor(final ItemStack is) { + int dmg = is.getItemDamage(); + if (dmg >= DAMAGE_THRESHOLD) { + dmg -= DAMAGE_THRESHOLD; + } - public AEColor getColor( final ItemStack is ) - { - int dmg = is.getItemDamage(); - if( dmg >= DAMAGE_THRESHOLD ) - { - dmg -= DAMAGE_THRESHOLD; - } + if (dmg >= AEColor.values().length) { + return AEColor.TRANSPARENT; + } - if( dmg >= AEColor.values().length ) - { - return AEColor.TRANSPARENT; - } + return AEColor.values()[dmg]; + } - return AEColor.values()[dmg]; - } + @Override + protected void getCheckedSubItems(final CreativeTabs creativeTab, final NonNullList itemStacks) { + for (final AEColor c : AEColor.values()) { + if (c != AEColor.TRANSPARENT) { + itemStacks.add(new ItemStack(this, 1, c.ordinal())); + } + } - @Override - protected void getCheckedSubItems( final CreativeTabs creativeTab, final NonNullList itemStacks ) - { - for( final AEColor c : AEColor.values() ) - { - if( c != AEColor.TRANSPARENT ) - { - itemStacks.add( new ItemStack( this, 1, c.ordinal() ) ); - } - } + for (final AEColor c : AEColor.values()) { + if (c != AEColor.TRANSPARENT) { + itemStacks.add(new ItemStack(this, 1, DAMAGE_THRESHOLD + c.ordinal())); + } + } + } - for( final AEColor c : AEColor.values() ) - { - if( c != AEColor.TRANSPARENT ) - { - itemStacks.add( new ItemStack( this, 1, DAMAGE_THRESHOLD + c.ordinal() ) ); - } - } - } - - public static boolean isLumen( final ItemStack is ) - { - final int dmg = is.getItemDamage(); - return dmg >= DAMAGE_THRESHOLD; - } + public static boolean isLumen(final ItemStack is) { + final int dmg = is.getItemDamage(); + return dmg >= DAMAGE_THRESHOLD; + } } diff --git a/src/main/java/appeng/items/misc/ItemPaintBallRendering.java b/src/main/java/appeng/items/misc/ItemPaintBallRendering.java index d84e4426c..a3ceae8f7 100644 --- a/src/main/java/appeng/items/misc/ItemPaintBallRendering.java +++ b/src/main/java/appeng/items/misc/ItemPaintBallRendering.java @@ -19,46 +19,39 @@ package appeng.items.misc; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.item.ItemStack; - import appeng.api.util.AEColor; import appeng.bootstrap.IItemRendering; import appeng.bootstrap.ItemRenderingCustomizer; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.item.ItemStack; -public class ItemPaintBallRendering extends ItemRenderingCustomizer -{ +public class ItemPaintBallRendering extends ItemRenderingCustomizer { - private static final ModelResourceLocation MODEL_NORMAL = new ModelResourceLocation( "appliedenergistics2:paint_ball" ); - private static final ModelResourceLocation MODEL_SHIMMER = new ModelResourceLocation( "appliedenergistics2:paint_ball_shimmer" ); + private static final ModelResourceLocation MODEL_NORMAL = new ModelResourceLocation("appliedenergistics2:paint_ball"); + private static final ModelResourceLocation MODEL_SHIMMER = new ModelResourceLocation("appliedenergistics2:paint_ball_shimmer"); - @Override - public void customize( IItemRendering rendering ) - { - rendering.color( ItemPaintBallRendering::getColorFromItemstack ); - rendering.variants( MODEL_NORMAL, MODEL_SHIMMER ); - rendering.meshDefinition( is -> ItemPaintBall.isLumen( is ) ? MODEL_SHIMMER : MODEL_NORMAL ); - } + @Override + public void customize(IItemRendering rendering) { + rendering.color(ItemPaintBallRendering::getColorFromItemstack); + rendering.variants(MODEL_NORMAL, MODEL_SHIMMER); + rendering.meshDefinition(is -> ItemPaintBall.isLumen(is) ? MODEL_SHIMMER : MODEL_NORMAL); + } - private static int getColorFromItemstack( ItemStack stack, int tintIndex ) - { - final AEColor col = ( (ItemPaintBall) stack.getItem() ).getColor( stack ); + private static int getColorFromItemstack(ItemStack stack, int tintIndex) { + final AEColor col = ((ItemPaintBall) stack.getItem()).getColor(stack); - final int colorValue = stack.getItemDamage() >= 20 ? col.mediumVariant : col.mediumVariant; - final int r = ( colorValue >> 16 ) & 0xff; - final int g = ( colorValue >> 8 ) & 0xff; - final int b = ( colorValue ) & 0xff; + final int colorValue = col.mediumVariant; + final int r = (colorValue >> 16) & 0xff; + final int g = (colorValue >> 8) & 0xff; + final int b = (colorValue) & 0xff; - if( stack.getItemDamage() >= 20 ) - { - final float fail = 0.7f; - final int full = (int) ( 255 * 0.3 ); - return (int) ( full + r * fail ) << 16 | (int) ( full + g * fail ) << 8 | (int) ( full + b * fail ) | 0xff << 24; - } - else - { - return r << 16 | g << 8 | b | 0xff << 24; - } - } + if (stack.getItemDamage() >= 20) { + final float fail = 0.7f; + final int full = (int) (255 * 0.3); + return (int) (full + r * fail) << 16 | (int) (full + g * fail) << 8 | (int) (full + b * fail) | 0xff << 24; + } else { + return r << 16 | g << 8 | b | 0xff << 24; + } + } } diff --git a/src/main/java/appeng/items/parts/FacadeRendering.java b/src/main/java/appeng/items/parts/FacadeRendering.java index 308e107a9..05470d6b8 100644 --- a/src/main/java/appeng/items/parts/FacadeRendering.java +++ b/src/main/java/appeng/items/parts/FacadeRendering.java @@ -28,12 +28,10 @@ import appeng.client.render.FacadeItemModel; * Handles rendering customization for facade items. Please note that this works very differently * from actually rendering a Facade in a cable bus. */ -public class FacadeRendering extends ItemRenderingCustomizer -{ - @Override - public void customize( IItemRendering rendering ) - { - // This actually just uses the path it will look for by default, no custom model redirection needed - rendering.builtInModel( "models/item/facade", new FacadeItemModel() ); - } +public class FacadeRendering extends ItemRenderingCustomizer { + @Override + public void customize(IItemRendering rendering) { + // This actually just uses the path it will look for by default, no custom model redirection needed + rendering.builtInModel("models/item/facade", new FacadeItemModel()); + } } diff --git a/src/main/java/appeng/items/parts/ItemFacade.java b/src/main/java/appeng/items/parts/ItemFacade.java index 70f29cc4e..43e705f80 100644 --- a/src/main/java/appeng/items/parts/ItemFacade.java +++ b/src/main/java/appeng/items/parts/ItemFacade.java @@ -19,29 +19,6 @@ package appeng.items.parts; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.BlockRenderLayer; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumBlockRenderType; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.NonNullList; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.common.property.IExtendedBlockState; - import appeng.api.AEApi; import appeng.api.exceptions.MissingDefinitionException; import appeng.api.parts.IAlphaPassItem; @@ -51,296 +28,261 @@ import appeng.core.FacadeConfig; import appeng.facade.FacadePart; import appeng.facade.IFacadeItem; import appeng.items.AEBaseItem; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.*; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.common.property.IExtendedBlockState; + +import java.util.ArrayList; +import java.util.List; -public class ItemFacade extends AEBaseItem implements IFacadeItem, IAlphaPassItem -{ +public class ItemFacade extends AEBaseItem implements IFacadeItem, IAlphaPassItem { - private static final String TAG_ITEM_ID = "item"; - private static final String TAG_DAMAGE = "damage"; + private static final String TAG_ITEM_ID = "item"; + private static final String TAG_DAMAGE = "damage"; - private List subTypes = null; + private List subTypes = null; - public ItemFacade() - { - this.setHasSubtypes( true ); - } + public ItemFacade() { + this.setHasSubtypes(true); + } - @Override - public EnumActionResult onItemUseFirst( final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand ) - { - return AEApi.instance().partHelper().placeBus( player.getHeldItem( hand ), pos, side, player, hand, world ); - } + @Override + public EnumActionResult onItemUseFirst(final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand) { + return AEApi.instance().partHelper().placeBus(player.getHeldItem(hand), pos, side, player, hand, world); + } - @Override - public String getItemStackDisplayName( final ItemStack is ) - { - try - { - final ItemStack in = this.getTextureItem( is ); - if( !in.isEmpty() ) - { - return super.getItemStackDisplayName( is ) + " - " + in.getDisplayName(); - } - } - catch( final Throwable ignored ) - { + @Override + public String getItemStackDisplayName(final ItemStack is) { + try { + final ItemStack in = this.getTextureItem(is); + if (!in.isEmpty()) { + return super.getItemStackDisplayName(is) + " - " + in.getDisplayName(); + } + } catch (final Throwable ignored) { - } + } - return super.getItemStackDisplayName( is ); - } + return super.getItemStackDisplayName(is); + } - @Override - protected void getCheckedSubItems( final CreativeTabs creativeTab, final NonNullList itemStacks ) - { - this.calculateSubTypes(); - itemStacks.addAll( this.subTypes ); - } + @Override + protected void getCheckedSubItems(final CreativeTabs creativeTab, final NonNullList itemStacks) { + this.calculateSubTypes(); + itemStacks.addAll(this.subTypes); + } - private void calculateSubTypes() - { - if( this.subTypes == null ) - { - this.subTypes = new ArrayList<>( 1000 ); - for( final Object blk : Block.REGISTRY ) - { - final Block b = (Block) blk; - try - { - final Item item = Item.getItemFromBlock( b ); - if( item == Items.AIR ) - { - continue; - } + private void calculateSubTypes() { + if (this.subTypes == null) { + this.subTypes = new ArrayList<>(1000); + for (final Object blk : Block.REGISTRY) { + final Block b = (Block) blk; + try { + final Item item = Item.getItemFromBlock(b); + if (item == Items.AIR) { + continue; + } - final NonNullList tmpList = NonNullList.create(); - b.getSubBlocks( b.getCreativeTabToDisplayOn(), tmpList ); - for( final ItemStack l : tmpList ) - { - final ItemStack facade = this.createFacadeForItem( l, false ); - if( !facade.isEmpty() ) - { - this.subTypes.add( facade ); - } - } - } - catch( final Throwable t ) - { - // just absorb.. - } - } - } - } + final NonNullList tmpList = NonNullList.create(); + b.getSubBlocks(b.getCreativeTabToDisplayOn(), tmpList); + for (final ItemStack l : tmpList) { + final ItemStack facade = this.createFacadeForItem(l, false); + if (!facade.isEmpty()) { + this.subTypes.add(facade); + } + } + } catch (final Throwable t) { + // just absorb.. + } + } + } + } - private static boolean hasSimpleModel( IBlockState blockState ) - { - if( blockState.getRenderType() != EnumBlockRenderType.MODEL || blockState instanceof IExtendedBlockState ) - { - return false; - } + private static boolean hasSimpleModel(IBlockState blockState) { + if (blockState.getRenderType() != EnumBlockRenderType.MODEL || blockState instanceof IExtendedBlockState) { + return false; + } - return blockState.isFullCube(); - } + return blockState.isFullCube(); + } - public ItemStack createFacadeForItem( final ItemStack itemStack, final boolean returnItem ) - { - if( itemStack.isEmpty() ) - { - return ItemStack.EMPTY; - } + public ItemStack createFacadeForItem(final ItemStack itemStack, final boolean returnItem) { + if (itemStack.isEmpty()) { + return ItemStack.EMPTY; + } - final Block block = Block.getBlockFromItem( itemStack.getItem() ); - if( block == Blocks.AIR || itemStack.hasTagCompound() ) - { - return ItemStack.EMPTY; - } + final Block block = Block.getBlockFromItem(itemStack.getItem()); + if (block == Blocks.AIR || itemStack.hasTagCompound()) { + return ItemStack.EMPTY; + } - final int metadata = itemStack.getItem().getMetadata( itemStack.getItemDamage() ); + final int metadata = itemStack.getItem().getMetadata(itemStack.getItemDamage()); - // Try to get the block state based on the item stack's meta. If this fails, don't consider it for a facade - // This for example fails for Pistons because they hardcoded an invalid meta value in vanilla - IBlockState blockState; - try - { - blockState = block.getStateFromMeta( metadata ); - } - catch( Exception e ) - { - AELog.debug( e, "Cannot create a facade for " + block.getRegistryName() ); - return ItemStack.EMPTY; - } + // Try to get the block state based on the item stack's meta. If this fails, don't consider it for a facade + // This for example fails for Pistons because they hardcoded an invalid meta value in vanilla + IBlockState blockState; + try { + blockState = block.getStateFromMeta(metadata); + } catch (Exception e) { + AELog.debug(e, "Cannot create a facade for " + block.getRegistryName()); + return ItemStack.EMPTY; + } - final boolean areTileEntitiesEnabled = FacadeConfig.instance().allowTileEntityFacades(); - final boolean isWhiteListed = FacadeConfig.instance().isWhiteListed( block, metadata ); - final boolean isModel = blockState.getRenderType() == EnumBlockRenderType.MODEL; + final boolean areTileEntitiesEnabled = FacadeConfig.instance().allowTileEntityFacades(); + final boolean isWhiteListed = FacadeConfig.instance().isWhiteListed(block, metadata); + final boolean isModel = blockState.getRenderType() == EnumBlockRenderType.MODEL; - final IBlockState defaultState = block.getDefaultState(); - final boolean isTileEntity = block.hasTileEntity( defaultState ); - final boolean isFullCube = block.isFullCube( defaultState ); + final IBlockState defaultState = block.getDefaultState(); + final boolean isTileEntity = block.hasTileEntity(defaultState); + final boolean isFullCube = block.isFullCube(defaultState); - final boolean isTileEntityAllowed = !isTileEntity || ( areTileEntitiesEnabled && isWhiteListed ); - final boolean isBlockAllowed = isFullCube || isWhiteListed; + final boolean isTileEntityAllowed = !isTileEntity || (areTileEntitiesEnabled && isWhiteListed); + final boolean isBlockAllowed = isFullCube || isWhiteListed; - if( isModel && isTileEntityAllowed && isBlockAllowed ) - { - if( returnItem ) - { - return itemStack; - } + if (isModel && isTileEntityAllowed && isBlockAllowed) { + if (returnItem) { + return itemStack; + } - final ItemStack is = new ItemStack( this ); - final NBTTagCompound data = new NBTTagCompound(); - data.setString( TAG_ITEM_ID, itemStack.getItem().getRegistryName().toString() ); - data.setInteger( TAG_DAMAGE, itemStack.getItemDamage() ); - is.setTagCompound( data ); - return is; - } - return ItemStack.EMPTY; - } + final ItemStack is = new ItemStack(this); + final NBTTagCompound data = new NBTTagCompound(); + data.setString(TAG_ITEM_ID, itemStack.getItem().getRegistryName().toString()); + data.setInteger(TAG_DAMAGE, itemStack.getItemDamage()); + is.setTagCompound(data); + return is; + } + return ItemStack.EMPTY; + } - @Override - public FacadePart createPartFromItemStack( final ItemStack is, final AEPartLocation side ) - { - final ItemStack in = this.getTextureItem( is ); - if( !in.isEmpty() ) - { - return new FacadePart( is, side ); - } - return null; - } + @Override + public FacadePart createPartFromItemStack(final ItemStack is, final AEPartLocation side) { + final ItemStack in = this.getTextureItem(is); + if (!in.isEmpty()) { + return new FacadePart(is, side); + } + return null; + } - @Override - public ItemStack getTextureItem( ItemStack is ) - { + @Override + public ItemStack getTextureItem(ItemStack is) { - NBTTagCompound nbt = is.getTagCompound(); + NBTTagCompound nbt = is.getTagCompound(); - if( nbt == null ) - { - return ItemStack.EMPTY; - } + if (nbt == null) { + return ItemStack.EMPTY; + } - ResourceLocation itemId; - int itemDamage; + ResourceLocation itemId; + int itemDamage; - // Handle legacy facades - if( nbt.hasKey( "x" ) ) - { - int[] data = nbt.getIntArray( "x" ); - if( data.length != 2 ) - { - return ItemStack.EMPTY; - } + // Handle legacy facades + if (nbt.hasKey("x")) { + int[] data = nbt.getIntArray("x"); + if (data.length != 2) { + return ItemStack.EMPTY; + } - Item item = Item.REGISTRY.getObjectById( data[0] ); - if( item == null ) - { - return ItemStack.EMPTY; - } + Item item = Item.REGISTRY.getObjectById(data[0]); + if (item == null) { + return ItemStack.EMPTY; + } - itemId = item.getRegistryName(); - itemDamage = data[1]; - } - else - { - // First item is numeric item id, second is damage - itemId = new ResourceLocation( nbt.getString( TAG_ITEM_ID ) ); - itemDamage = nbt.getInteger( TAG_DAMAGE ); - } + itemId = item.getRegistryName(); + itemDamage = data[1]; + } else { + // First item is numeric item id, second is damage + itemId = new ResourceLocation(nbt.getString(TAG_ITEM_ID)); + itemDamage = nbt.getInteger(TAG_DAMAGE); + } - Item baseItem = Item.REGISTRY.getObject( itemId ); + Item baseItem = Item.REGISTRY.getObject(itemId); - if( baseItem == null ) - { - return ItemStack.EMPTY; - } + if (baseItem == null) { + return ItemStack.EMPTY; + } - return new ItemStack( baseItem, 1, itemDamage ); - } + return new ItemStack(baseItem, 1, itemDamage); + } - @Override - public IBlockState getTextureBlockState( ItemStack is ) - { + @Override + public IBlockState getTextureBlockState(ItemStack is) { - ItemStack baseItemStack = this.getTextureItem( is ); + ItemStack baseItemStack = this.getTextureItem(is); - if( baseItemStack.isEmpty() ) - { - return Blocks.GLASS.getDefaultState(); - } + if (baseItemStack.isEmpty()) { + return Blocks.GLASS.getDefaultState(); + } - Block block = Block.getBlockFromItem( baseItemStack.getItem() ); + Block block = Block.getBlockFromItem(baseItemStack.getItem()); - if( block == Blocks.AIR ) - { - return Blocks.GLASS.getDefaultState(); - } + if (block == Blocks.AIR) { + return Blocks.GLASS.getDefaultState(); + } - int metadata = baseItemStack.getItem().getMetadata( baseItemStack ); + int metadata = baseItemStack.getItem().getMetadata(baseItemStack); - try - { - return block.getStateFromMeta( metadata ); - } - catch( Exception e ) - { - AELog.warn( "Block %s has broken getStateFromMeta method for meta %d", block.getRegistryName().toString(), baseItemStack.getItemDamage() ); - return Blocks.GLASS.getDefaultState(); - } - } + try { + return block.getStateFromMeta(metadata); + } catch (Exception e) { + AELog.warn("Block %s has broken getStateFromMeta method for meta %d", block.getRegistryName().toString(), baseItemStack.getItemDamage()); + return Blocks.GLASS.getDefaultState(); + } + } - public List getFacades() - { - this.calculateSubTypes(); - return this.subTypes; - } + public List getFacades() { + this.calculateSubTypes(); + return this.subTypes; + } - public ItemStack getCreativeTabIcon() - { - this.calculateSubTypes(); - if( this.subTypes.isEmpty() ) - { - return new ItemStack( Items.CAKE ); - } - return this.subTypes.get( 0 ); - } + public ItemStack getCreativeTabIcon() { + this.calculateSubTypes(); + if (this.subTypes.isEmpty()) { + return new ItemStack(Items.CAKE); + } + return this.subTypes.get(0); + } - public ItemStack createFromIDs( final int[] ids ) - { - ItemStack facadeStack = AEApi.instance() - .definitions() - .items() - .facade() - .maybeStack( 1 ) - .orElseThrow( () -> new MissingDefinitionException( "Tried to create a facade, while facades are being deactivated." ) ); + public ItemStack createFromIDs(final int[] ids) { + ItemStack facadeStack = AEApi.instance() + .definitions() + .items() + .facade() + .maybeStack(1) + .orElseThrow(() -> new MissingDefinitionException("Tried to create a facade, while facades are being deactivated.")); - // Convert back to a registry name... - Item item = Item.REGISTRY.getObjectById( ids[0] ); - if( item == null ) - { - return ItemStack.EMPTY; - } + // Convert back to a registry name... + Item item = Item.REGISTRY.getObjectById(ids[0]); + if (item == null) { + return ItemStack.EMPTY; + } - final NBTTagCompound facadeTag = new NBTTagCompound(); - facadeTag.setString( TAG_ITEM_ID, item.getRegistryName().toString() ); - facadeTag.setInteger( TAG_DAMAGE, ids[1] ); - facadeStack.setTagCompound( facadeTag ); + final NBTTagCompound facadeTag = new NBTTagCompound(); + facadeTag.setString(TAG_ITEM_ID, item.getRegistryName().toString()); + facadeTag.setInteger(TAG_DAMAGE, ids[1]); + facadeStack.setTagCompound(facadeTag); - return facadeStack; - } + return facadeStack; + } - @Override - public boolean useAlphaPass( final ItemStack is ) - { - IBlockState blockState = this.getTextureBlockState( is ); + @Override + public boolean useAlphaPass(final ItemStack is) { + IBlockState blockState = this.getTextureBlockState(is); - if( blockState == null ) - { - return false; - } + if (blockState == null) { + return false; + } - Block blk = blockState.getBlock(); - return blk.canRenderInLayer( blockState, BlockRenderLayer.TRANSLUCENT ); - } + Block blk = blockState.getBlock(); + return blk.canRenderInLayer(blockState, BlockRenderLayer.TRANSLUCENT); + } } diff --git a/src/main/java/appeng/items/parts/ItemPart.java b/src/main/java/appeng/items/parts/ItemPart.java index 0024dd2a9..6a9ea4974 100644 --- a/src/main/java/appeng/items/parts/ItemPart.java +++ b/src/main/java/appeng/items/parts/ItemPart.java @@ -19,22 +19,17 @@ package appeng.items.parts; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - +import appeng.api.AEApi; +import appeng.api.implementations.items.IItemGroup; +import appeng.api.parts.IPart; +import appeng.api.parts.IPartItem; +import appeng.api.util.AEColor; +import appeng.core.features.ActivityState; +import appeng.core.features.ItemStackSrc; +import appeng.core.localization.GuiText; +import appeng.items.AEBaseItem; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; - import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -46,352 +41,290 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; -import appeng.api.AEApi; -import appeng.api.implementations.items.IItemGroup; -import appeng.api.parts.IPart; -import appeng.api.parts.IPartItem; -import appeng.api.util.AEColor; -import appeng.core.features.ActivityState; -import appeng.core.features.ItemStackSrc; -import appeng.core.localization.GuiText; -import appeng.items.AEBaseItem; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.reflect.InvocationTargetException; +import java.util.*; +import java.util.Map.Entry; -public final class ItemPart extends AEBaseItem implements IPartItem, IItemGroup -{ - private static final int INITIAL_REGISTERED_CAPACITY = PartType.values().length; - private static final Comparator> REGISTERED_COMPARATOR = new RegisteredComparator(); +public final class ItemPart extends AEBaseItem implements IPartItem, IItemGroup { + private static final int INITIAL_REGISTERED_CAPACITY = PartType.values().length; + private static final Comparator> REGISTERED_COMPARATOR = new RegisteredComparator(); - public static ItemPart instance; - private final Map registered; + public static ItemPart instance; + private final Map registered; - public ItemPart() - { - this.registered = new HashMap<>( INITIAL_REGISTERED_CAPACITY ); + public ItemPart() { + this.registered = new HashMap<>(INITIAL_REGISTERED_CAPACITY); - this.setHasSubtypes( true ); + this.setHasSubtypes(true); - instance = this; - } + instance = this; + } - @Nonnull - public final ItemStackSrc createPart( final PartType mat ) - { - Preconditions.checkNotNull( mat ); + @Nonnull + public final ItemStackSrc createPart(final PartType mat) { + Preconditions.checkNotNull(mat); - return this.createPart( mat, 0 ); - } + return this.createPart(mat, 0); + } - @Nonnull - public ItemStackSrc createPart( final PartType mat, final AEColor color ) - { - Preconditions.checkNotNull( mat ); - Preconditions.checkNotNull( color ); + @Nonnull + public ItemStackSrc createPart(final PartType mat, final AEColor color) { + Preconditions.checkNotNull(mat); + Preconditions.checkNotNull(color); - final int varID = color.ordinal(); + final int varID = color.ordinal(); - return this.createPart( mat, varID ); - } + return this.createPart(mat, varID); + } - @Nonnull - private ItemStackSrc createPart( final PartType mat, final int varID ) - { - assert mat != null; - assert varID >= 0; + @Nonnull + private ItemStackSrc createPart(final PartType mat, final int varID) { + assert mat != null; + assert varID >= 0; - // verify - for( final PartTypeWithVariant p : this.registered.values() ) - { - if( p.part == mat && p.variant == varID ) - { - throw new IllegalStateException( "Cannot create the same material twice..." ); - } - } + // verify + for (final PartTypeWithVariant p : this.registered.values()) { + if (p.part == mat && p.variant == varID) { + throw new IllegalStateException("Cannot create the same material twice..."); + } + } - boolean enabled = mat.isEnabled(); + boolean enabled = mat.isEnabled(); - final int partDamage = mat.getBaseDamage() + varID; - final ActivityState state = ActivityState.from( enabled ); - final ItemStackSrc output = new ItemStackSrc( this, partDamage, state ); + final int partDamage = mat.getBaseDamage() + varID; + final ActivityState state = ActivityState.from(enabled); + final ItemStackSrc output = new ItemStackSrc(this, partDamage, state); - final PartTypeWithVariant pti = new PartTypeWithVariant( mat, varID ); + final PartTypeWithVariant pti = new PartTypeWithVariant(mat, varID); - this.processMetaOverlap( enabled, partDamage, mat, pti ); + this.processMetaOverlap(enabled, partDamage, mat, pti); - return output; - } + return output; + } - private void processMetaOverlap( final boolean enabled, final int partDamage, final PartType mat, final PartTypeWithVariant pti ) - { - assert partDamage >= 0; - assert mat != null; - assert pti != null; + private void processMetaOverlap(final boolean enabled, final int partDamage, final PartType mat, final PartTypeWithVariant pti) { + assert partDamage >= 0; + assert mat != null; + assert pti != null; - final PartTypeWithVariant registeredPartType = this.registered.get( partDamage ); - if( registeredPartType != null ) - { - throw new IllegalStateException( "Meta Overlap detected with type " + mat + " and damage " + partDamage + ". Found " + registeredPartType + " there already." ); - } + final PartTypeWithVariant registeredPartType = this.registered.get(partDamage); + if (registeredPartType != null) { + throw new IllegalStateException("Meta Overlap detected with type " + mat + " and damage " + partDamage + ". Found " + registeredPartType + " there already."); + } - if( enabled ) - { - this.registered.put( partDamage, pti ); - } - } + if (enabled) { + this.registered.put(partDamage, pti); + } + } - public int getDamageByType( final PartType t ) - { - Preconditions.checkNotNull( t ); + public int getDamageByType(final PartType t) { + Preconditions.checkNotNull(t); - for( final Entry pt : this.registered.entrySet() ) - { - if( pt.getValue().part == t ) - { - return pt.getKey(); - } - } - return -1; - } + for (final Entry pt : this.registered.entrySet()) { + if (pt.getValue().part == t) { + return pt.getKey(); + } + } + return -1; + } - @Override - public EnumActionResult onItemUse( final EntityPlayer player, final World w, final BlockPos pos, final EnumHand hand, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( this.getTypeByStack( player.getHeldItem( hand ) ) == PartType.INVALID_TYPE ) - { - return EnumActionResult.FAIL; - } + @Override + public EnumActionResult onItemUse(final EntityPlayer player, final World w, final BlockPos pos, final EnumHand hand, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (this.getTypeByStack(player.getHeldItem(hand)) == PartType.INVALID_TYPE) { + return EnumActionResult.FAIL; + } - return AEApi.instance().partHelper().placeBus( player.getHeldItem( hand ), pos, side, player, hand, w ); - } + return AEApi.instance().partHelper().placeBus(player.getHeldItem(hand), pos, side, player, hand, w); + } - @Override - public String getUnlocalizedName( final ItemStack is ) - { - Preconditions.checkNotNull( is ); - return "item.appliedenergistics2.multi_part." + this.getTypeByStack( is ).getUnlocalizedName().toLowerCase(); - } + @Override + public String getUnlocalizedName(final ItemStack is) { + Preconditions.checkNotNull(is); + return "item.appliedenergistics2.multi_part." + this.getTypeByStack(is).getUnlocalizedName().toLowerCase(); + } - @Override - public String getItemStackDisplayName( final ItemStack is ) - { - final PartType pt = this.getTypeByStack( is ); + @Override + public String getItemStackDisplayName(final ItemStack is) { + final PartType pt = this.getTypeByStack(is); - if( pt.isCable() ) - { - final AEColor[] variants = AEColor.values(); + if (pt.isCable()) { + final AEColor[] variants = AEColor.values(); - final int itemDamage = is.getItemDamage(); - final PartTypeWithVariant registeredPartType = this.registered.get( itemDamage ); - if( registeredPartType != null ) - { - return super.getItemStackDisplayName( is ) + " - " + variants[registeredPartType.variant].toString(); - } - } + final int itemDamage = is.getItemDamage(); + final PartTypeWithVariant registeredPartType = this.registered.get(itemDamage); + if (registeredPartType != null) { + return super.getItemStackDisplayName(is) + " - " + variants[registeredPartType.variant].toString(); + } + } - if( pt.getExtraName() != null ) - { - return super.getItemStackDisplayName( is ) + " - " + pt.getExtraName().getLocal(); - } + if (pt.getExtraName() != null) { + return super.getItemStackDisplayName(is) + " - " + pt.getExtraName().getLocal(); + } - return super.getItemStackDisplayName( is ); - } + return super.getItemStackDisplayName(is); + } - @Override - protected void getCheckedSubItems( final CreativeTabs creativeTab, final NonNullList itemStacks ) - { - final List> types = new ArrayList<>( this.registered.entrySet() ); - Collections.sort( types, REGISTERED_COMPARATOR ); + @Override + protected void getCheckedSubItems(final CreativeTabs creativeTab, final NonNullList itemStacks) { + final List> types = new ArrayList<>(this.registered.entrySet()); + Collections.sort(types, REGISTERED_COMPARATOR); - for( final Entry part : types ) - { - itemStacks.add( new ItemStack( this, 1, part.getKey() ) ); - } - } + for (final Entry part : types) { + itemStacks.add(new ItemStack(this, 1, part.getKey())); + } + } - @Nonnull - public PartType getTypeByStack( final ItemStack is ) - { - Preconditions.checkNotNull( is ); + @Nonnull + public PartType getTypeByStack(final ItemStack is) { + Preconditions.checkNotNull(is); - final PartTypeWithVariant pt = this.registered.get( is.getItemDamage() ); - if( pt != null ) - { - return pt.part; - } + final PartTypeWithVariant pt = this.registered.get(is.getItemDamage()); + if (pt != null) { + return pt.part; + } - return PartType.INVALID_TYPE; - } + return PartType.INVALID_TYPE; + } - @Nullable - @Override - public IPart createPartFromItemStack( final ItemStack is ) - { - final PartType type = this.getTypeByStack( is ); - final Class part = type.getPart(); - if( part == null ) - { - return null; - } + @Nullable + @Override + public IPart createPartFromItemStack(final ItemStack is) { + final PartType type = this.getTypeByStack(is); + final Class part = type.getPart(); + if (part == null) { + return null; + } - try - { - if( type.getConstructor() == null ) - { - type.setConstructor( part.getConstructor( ItemStack.class ) ); - } + try { + if (type.getConstructor() == null) { + type.setConstructor(part.getConstructor(ItemStack.class)); + } - return type.getConstructor().newInstance( is ); - } - catch( final InstantiationException e ) - { - throw new IllegalStateException( "Unable to construct IBusPart from IBusItem : " + part - .getName() + " ; Possibly didn't have correct constructor( ItemStack )", e ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( "Unable to construct IBusPart from IBusItem : " + part - .getName() + " ; Possibly didn't have correct constructor( ItemStack )", e ); - } - catch( final InvocationTargetException e ) - { - throw new IllegalStateException( "Unable to construct IBusPart from IBusItem : " + part - .getName() + " ; Possibly didn't have correct constructor( ItemStack )", e ); - } - catch( final NoSuchMethodException e ) - { - throw new IllegalStateException( "Unable to construct IBusPart from IBusItem : " + part - .getName() + " ; Possibly didn't have correct constructor( ItemStack )", e ); - } - } + return type.getConstructor().newInstance(is); + } catch (final InstantiationException e) { + throw new IllegalStateException("Unable to construct IBusPart from IBusItem : " + part + .getName() + " ; Possibly didn't have correct constructor( ItemStack )", e); + } catch (final IllegalAccessException e) { + throw new IllegalStateException("Unable to construct IBusPart from IBusItem : " + part + .getName() + " ; Possibly didn't have correct constructor( ItemStack )", e); + } catch (final InvocationTargetException e) { + throw new IllegalStateException("Unable to construct IBusPart from IBusItem : " + part + .getName() + " ; Possibly didn't have correct constructor( ItemStack )", e); + } catch (final NoSuchMethodException e) { + throw new IllegalStateException("Unable to construct IBusPart from IBusItem : " + part + .getName() + " ; Possibly didn't have correct constructor( ItemStack )", e); + } + } - public int variantOf( final int itemDamage ) - { - final PartTypeWithVariant registeredPartType = this.registered.get( itemDamage ); - if( registeredPartType != null ) - { - return registeredPartType.variant; - } + public int variantOf(final int itemDamage) { + final PartTypeWithVariant registeredPartType = this.registered.get(itemDamage); + if (registeredPartType != null) { + return registeredPartType.variant; + } - return 0; - } + return 0; + } - @Nullable - @Override - public String getUnlocalizedGroupName( final Set others, final ItemStack is ) - { - boolean importBus = false; - boolean importBusFluids = false; - boolean exportBus = false; - boolean exportBusFluids = false; - boolean group = false; + @Nullable + @Override + public String getUnlocalizedGroupName(final Set others, final ItemStack is) { + boolean importBus = false; + boolean importBusFluids = false; + boolean exportBus = false; + boolean exportBusFluids = false; + boolean group = false; - final PartType u = this.getTypeByStack( is ); + final PartType u = this.getTypeByStack(is); - for( final ItemStack stack : others ) - { - if( stack.getItem() == this ) - { - final PartType pt = this.getTypeByStack( stack ); - switch( pt ) - { - case IMPORT_BUS: - importBus = true; - if( u == pt ) - { - group = true; - } - break; - case FLUID_IMPORT_BUS: - importBusFluids = true; - if( u == pt ) - { - group = true; - } - break; - case EXPORT_BUS: - exportBus = true; - if( u == pt ) - { - group = true; - } - break; - case FLUID_EXPORT_BUS: - exportBusFluids = true; - if( u == pt ) - { - group = true; - } - break; - default: - } - } - } + for (final ItemStack stack : others) { + if (stack.getItem() == this) { + final PartType pt = this.getTypeByStack(stack); + switch (pt) { + case IMPORT_BUS: + importBus = true; + if (u == pt) { + group = true; + } + break; + case FLUID_IMPORT_BUS: + importBusFluids = true; + if (u == pt) { + group = true; + } + break; + case EXPORT_BUS: + exportBus = true; + if (u == pt) { + group = true; + } + break; + case FLUID_EXPORT_BUS: + exportBusFluids = true; + if (u == pt) { + group = true; + } + break; + default: + } + } + } - if( group && importBus && exportBus && ( u == PartType.IMPORT_BUS || u == PartType.EXPORT_BUS ) ) - { - return GuiText.IOBuses.getUnlocalized(); - } - if( group && importBusFluids && exportBusFluids && ( u == PartType.FLUID_IMPORT_BUS || u == PartType.FLUID_EXPORT_BUS ) ) - { - return GuiText.IOBusesFluids.getUnlocalized(); - } + if (group && importBus && exportBus && (u == PartType.IMPORT_BUS || u == PartType.EXPORT_BUS)) { + return GuiText.IOBuses.getUnlocalized(); + } + if (group && importBusFluids && exportBusFluids && (u == PartType.FLUID_IMPORT_BUS || u == PartType.FLUID_EXPORT_BUS)) { + return GuiText.IOBusesFluids.getUnlocalized(); + } - return null; - } + return null; + } - private static final class PartTypeWithVariant - { - private final PartType part; - private final int variant; + private static final class PartTypeWithVariant { + private final PartType part; + private final int variant; - private PartTypeWithVariant( final PartType part, final int variant ) - { - assert part != null; - assert variant >= 0; + private PartTypeWithVariant(final PartType part, final int variant) { + assert part != null; + assert variant >= 0; - this.part = part; - this.variant = variant; - } + this.part = part; + this.variant = variant; + } - @Override - public String toString() - { - return "PartTypeWithVariant{" + "part=" + this.part + ", variant=" + this.variant + '}'; - } - } + @Override + public String toString() { + return "PartTypeWithVariant{" + "part=" + this.part + ", variant=" + this.variant + '}'; + } + } - private static final class RegisteredComparator implements Comparator> - { - @Override - public int compare( final Entry o1, final Entry o2 ) - { - final String string1 = o1.getValue().part.name(); - final String string2 = o2.getValue().part.name(); - final int comparedString = string1.compareTo( string2 ); + private static final class RegisteredComparator implements Comparator> { + @Override + public int compare(final Entry o1, final Entry o2) { + final String string1 = o1.getValue().part.name(); + final String string2 = o2.getValue().part.name(); + final int comparedString = string1.compareTo(string2); - if( comparedString == 0 ) - { - return Integer.compare( o1.getKey(), o2.getKey() ); - } + if (comparedString == 0) { + return Integer.compare(o1.getKey(), o2.getKey()); + } - return comparedString; - } - } + return comparedString; + } + } - public void registerOreDicts() - { - for( final PartTypeWithVariant mt : ImmutableSet.copyOf( this.registered.values() ) ) - { - if( mt.part.getOreName() != null ) - { - final String[] names = mt.part.getOreName().split( "," ); + public void registerOreDicts() { + for (final PartTypeWithVariant mt : ImmutableSet.copyOf(this.registered.values())) { + if (mt.part.getOreName() != null) { + final String[] names = mt.part.getOreName().split(","); - for( final String name : names ) - { - OreDictionary.registerOre( name, new ItemStack( this, 1, mt.part.getBaseDamage() + mt.variant ) ); - } - } - } - } + for (final String name : names) { + OreDictionary.registerOre(name, new ItemStack(this, 1, mt.part.getBaseDamage() + mt.variant)); + } + } + } + } } diff --git a/src/main/java/appeng/items/parts/ItemPartRendering.java b/src/main/java/appeng/items/parts/ItemPartRendering.java index 50f31642d..ef7e6e006 100644 --- a/src/main/java/appeng/items/parts/ItemPartRendering.java +++ b/src/main/java/appeng/items/parts/ItemPartRendering.java @@ -19,17 +19,6 @@ package appeng.items.parts; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.util.AEColor; import appeng.bootstrap.IItemRendering; import appeng.bootstrap.ItemRenderingCustomizer; @@ -39,109 +28,114 @@ import appeng.core.AppEng; import appeng.core.features.registries.PartModels; import appeng.parts.automation.PlaneConnections; import appeng.parts.automation.PlaneModel; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; -public class ItemPartRendering extends ItemRenderingCustomizer -{ +public class ItemPartRendering extends ItemRenderingCustomizer { - private final PartModels partModels; + private final PartModels partModels; - private final ItemPart item; + private final ItemPart item; - public ItemPartRendering( PartModels partModels, ItemPart item ) - { - this.partModels = partModels; - this.item = item; - } + public ItemPartRendering(PartModels partModels, ItemPart item) { + this.partModels = partModels; + this.item = item; + } - @Override - @SideOnly( Side.CLIENT ) - public void customize( IItemRendering rendering ) - { + @Override + @SideOnly(Side.CLIENT) + public void customize(IItemRendering rendering) { - rendering.meshDefinition( this::getItemMeshDefinition ); + rendering.meshDefinition(this::getItemMeshDefinition); - rendering.color( new StaticItemColor( AEColor.TRANSPARENT ) ); + rendering.color(new StaticItemColor(AEColor.TRANSPARENT)); - // Register all item models as variants so they get loaded - rendering.variants( Arrays.stream( PartType.values() ) - .filter( f -> f != PartType.INVALID_TYPE ) - .flatMap( part -> part.getItemModels().stream() ) - .collect( Collectors.toList() ) ); + // Register all item models as variants so they get loaded + rendering.variants(Arrays.stream(PartType.values()) + .filter(f -> f != PartType.INVALID_TYPE) + .flatMap(part -> part.getItemModels().stream()) + .collect(Collectors.toList())); - // Register the built-in models for annihilation planes - ResourceLocation annihilationPlaneTexture = new ResourceLocation( AppEng.MOD_ID, "items/part/annihilation_plane" ); - ResourceLocation annihilationPlaneOnTexture = new ResourceLocation( AppEng.MOD_ID, "parts/annihilation_plane_on" ); - ResourceLocation fluidAnnihilationPlaneTexture = new ResourceLocation( AppEng.MOD_ID, "items/part/fluid_annihilation_plane" ); - ResourceLocation fluidAnnihilationPlaneOnTexture = new ResourceLocation( AppEng.MOD_ID, "parts/fluid_annihilation_plane_on" ); - ResourceLocation identityAnnihilationPlaneTexture = new ResourceLocation( AppEng.MOD_ID, "items/part/identity_annihilation_plane" ); - ResourceLocation identityAnnihilationPlaneOnTexture = new ResourceLocation( AppEng.MOD_ID, "parts/identity_annihilation_plane_on" ); - ResourceLocation formationPlaneTexture = new ResourceLocation( AppEng.MOD_ID, "items/part/formation_plane" ); - ResourceLocation formationPlaneOnTexture = new ResourceLocation( AppEng.MOD_ID, "parts/formation_plane_on" ); - ResourceLocation fluidFormationPlaneTexture = new ResourceLocation( AppEng.MOD_ID, "items/part/fluid_formation_plane" ); - ResourceLocation fluidFormationPlaneOnTexture = new ResourceLocation( AppEng.MOD_ID, "parts/fluid_formation_plane_on" ); - ResourceLocation sidesTexture = new ResourceLocation( AppEng.MOD_ID, "parts/plane_sides" ); - ResourceLocation backTexture = new ResourceLocation( AppEng.MOD_ID, "parts/transition_plane_back" ); + // Register the built-in models for annihilation planes + ResourceLocation annihilationPlaneTexture = new ResourceLocation(AppEng.MOD_ID, "items/part/annihilation_plane"); + ResourceLocation annihilationPlaneOnTexture = new ResourceLocation(AppEng.MOD_ID, "parts/annihilation_plane_on"); + ResourceLocation fluidAnnihilationPlaneTexture = new ResourceLocation(AppEng.MOD_ID, "items/part/fluid_annihilation_plane"); + ResourceLocation fluidAnnihilationPlaneOnTexture = new ResourceLocation(AppEng.MOD_ID, "parts/fluid_annihilation_plane_on"); + ResourceLocation identityAnnihilationPlaneTexture = new ResourceLocation(AppEng.MOD_ID, "items/part/identity_annihilation_plane"); + ResourceLocation identityAnnihilationPlaneOnTexture = new ResourceLocation(AppEng.MOD_ID, "parts/identity_annihilation_plane_on"); + ResourceLocation formationPlaneTexture = new ResourceLocation(AppEng.MOD_ID, "items/part/formation_plane"); + ResourceLocation formationPlaneOnTexture = new ResourceLocation(AppEng.MOD_ID, "parts/formation_plane_on"); + ResourceLocation fluidFormationPlaneTexture = new ResourceLocation(AppEng.MOD_ID, "items/part/fluid_formation_plane"); + ResourceLocation fluidFormationPlaneOnTexture = new ResourceLocation(AppEng.MOD_ID, "parts/fluid_formation_plane_on"); + ResourceLocation sidesTexture = new ResourceLocation(AppEng.MOD_ID, "parts/plane_sides"); + ResourceLocation backTexture = new ResourceLocation(AppEng.MOD_ID, "parts/transition_plane_back"); - List modelNames = new ArrayList<>(); + List modelNames = new ArrayList<>(); - for( PlaneConnections connection : PlaneConnections.PERMUTATIONS ) - { - PlaneModel model = new PlaneModel( annihilationPlaneTexture, sidesTexture, backTexture, connection ); - rendering.builtInModel( "models/part/annihilation_plane_" + connection.getFilenameSuffix(), model ); - modelNames.add( "part/annihilation_plane_" + connection.getFilenameSuffix() ); + for (PlaneConnections connection : PlaneConnections.PERMUTATIONS) { + PlaneModel model = new PlaneModel(annihilationPlaneTexture, sidesTexture, backTexture, connection); + rendering.builtInModel("models/part/annihilation_plane_" + connection.getFilenameSuffix(), model); + modelNames.add("part/annihilation_plane_" + connection.getFilenameSuffix()); - model = new PlaneModel( annihilationPlaneOnTexture, sidesTexture, backTexture, connection ); - rendering.builtInModel( "models/part/annihilation_plane_on_" + connection.getFilenameSuffix(), model ); - modelNames.add( "part/annihilation_plane_on_" + connection.getFilenameSuffix() ); + model = new PlaneModel(annihilationPlaneOnTexture, sidesTexture, backTexture, connection); + rendering.builtInModel("models/part/annihilation_plane_on_" + connection.getFilenameSuffix(), model); + modelNames.add("part/annihilation_plane_on_" + connection.getFilenameSuffix()); - model = new PlaneModel( fluidAnnihilationPlaneTexture, sidesTexture, backTexture, connection ); - rendering.builtInModel( "models/part/fluid_annihilation_plane_" + connection.getFilenameSuffix(), model ); - modelNames.add( "part/fluid_annihilation_plane_" + connection.getFilenameSuffix() ); + model = new PlaneModel(fluidAnnihilationPlaneTexture, sidesTexture, backTexture, connection); + rendering.builtInModel("models/part/fluid_annihilation_plane_" + connection.getFilenameSuffix(), model); + modelNames.add("part/fluid_annihilation_plane_" + connection.getFilenameSuffix()); - model = new PlaneModel( fluidAnnihilationPlaneOnTexture, sidesTexture, backTexture, connection ); - rendering.builtInModel( "models/part/fluid_annihilation_plane_on_" + connection.getFilenameSuffix(), model ); - modelNames.add( "part/fluid_annihilation_plane_on_" + connection.getFilenameSuffix() ); + model = new PlaneModel(fluidAnnihilationPlaneOnTexture, sidesTexture, backTexture, connection); + rendering.builtInModel("models/part/fluid_annihilation_plane_on_" + connection.getFilenameSuffix(), model); + modelNames.add("part/fluid_annihilation_plane_on_" + connection.getFilenameSuffix()); - model = new PlaneModel( identityAnnihilationPlaneTexture, sidesTexture, backTexture, connection ); - rendering.builtInModel( "models/part/identity_annihilation_plane_" + connection.getFilenameSuffix(), model ); - modelNames.add( "part/identity_annihilation_plane_" + connection.getFilenameSuffix() ); + model = new PlaneModel(identityAnnihilationPlaneTexture, sidesTexture, backTexture, connection); + rendering.builtInModel("models/part/identity_annihilation_plane_" + connection.getFilenameSuffix(), model); + modelNames.add("part/identity_annihilation_plane_" + connection.getFilenameSuffix()); - model = new PlaneModel( identityAnnihilationPlaneOnTexture, sidesTexture, backTexture, connection ); - rendering.builtInModel( "models/part/identity_annihilation_plane_on_" + connection.getFilenameSuffix(), model ); - modelNames.add( "part/identity_annihilation_plane_on_" + connection.getFilenameSuffix() ); + model = new PlaneModel(identityAnnihilationPlaneOnTexture, sidesTexture, backTexture, connection); + rendering.builtInModel("models/part/identity_annihilation_plane_on_" + connection.getFilenameSuffix(), model); + modelNames.add("part/identity_annihilation_plane_on_" + connection.getFilenameSuffix()); - model = new PlaneModel( formationPlaneTexture, sidesTexture, backTexture, connection ); - rendering.builtInModel( "models/part/formation_plane_" + connection.getFilenameSuffix(), model ); - modelNames.add( "part/formation_plane_" + connection.getFilenameSuffix() ); + model = new PlaneModel(formationPlaneTexture, sidesTexture, backTexture, connection); + rendering.builtInModel("models/part/formation_plane_" + connection.getFilenameSuffix(), model); + modelNames.add("part/formation_plane_" + connection.getFilenameSuffix()); - model = new PlaneModel( formationPlaneOnTexture, sidesTexture, backTexture, connection ); - rendering.builtInModel( "models/part/formation_plane_on_" + connection.getFilenameSuffix(), model ); - modelNames.add( "part/formation_plane_on_" + connection.getFilenameSuffix() ); + model = new PlaneModel(formationPlaneOnTexture, sidesTexture, backTexture, connection); + rendering.builtInModel("models/part/formation_plane_on_" + connection.getFilenameSuffix(), model); + modelNames.add("part/formation_plane_on_" + connection.getFilenameSuffix()); - model = new PlaneModel( fluidFormationPlaneTexture, sidesTexture, backTexture, connection ); - rendering.builtInModel( "models/part/fluid_formation_plane_" + connection.getFilenameSuffix(), model ); - modelNames.add( "part/fluid_formation_plane_" + connection.getFilenameSuffix() ); + model = new PlaneModel(fluidFormationPlaneTexture, sidesTexture, backTexture, connection); + rendering.builtInModel("models/part/fluid_formation_plane_" + connection.getFilenameSuffix(), model); + modelNames.add("part/fluid_formation_plane_" + connection.getFilenameSuffix()); - model = new PlaneModel( fluidFormationPlaneOnTexture, sidesTexture, backTexture, connection ); - rendering.builtInModel( "models/part/fluid_formation_plane_on_" + connection.getFilenameSuffix(), model ); - modelNames.add( "part/fluid_formation_plane_on_" + connection.getFilenameSuffix() ); + model = new PlaneModel(fluidFormationPlaneOnTexture, sidesTexture, backTexture, connection); + rendering.builtInModel("models/part/fluid_formation_plane_on_" + connection.getFilenameSuffix(), model); + modelNames.add("part/fluid_formation_plane_on_" + connection.getFilenameSuffix()); - } + } - // base p2p model with frequency - rendering.builtInModel( "models/part/builtin/p2p_tunnel_frequency", new P2PTunnelFrequencyModel() ); + // base p2p model with frequency + rendering.builtInModel("models/part/builtin/p2p_tunnel_frequency", new P2PTunnelFrequencyModel()); - List partResourceLocs = modelNames.stream() - .map( name -> new ResourceLocation( AppEng.MOD_ID, name ) ) - .collect( Collectors.toList() ); - this.partModels.registerModels( partResourceLocs ); - } + List partResourceLocs = modelNames.stream() + .map(name -> new ResourceLocation(AppEng.MOD_ID, name)) + .collect(Collectors.toList()); + this.partModels.registerModels(partResourceLocs); + } - private ModelResourceLocation getItemMeshDefinition( ItemStack is ) - { - PartType partType = this.item.getTypeByStack( is ); - int variant = this.item.variantOf( is.getItemDamage() ); - return partType.getItemModels().get( variant ); - } + private ModelResourceLocation getItemMeshDefinition(ItemStack is) { + PartType partType = this.item.getTypeByStack(is); + int variant = this.item.variantOf(is.getItemDamage()); + return partType.getItemModels().get(variant); + } } diff --git a/src/main/java/appeng/items/parts/PartModels.java b/src/main/java/appeng/items/parts/PartModels.java index 2a7fbd1cc..6b5f37ef6 100644 --- a/src/main/java/appeng/items/parts/PartModels.java +++ b/src/main/java/appeng/items/parts/PartModels.java @@ -29,10 +29,10 @@ import java.lang.annotation.Target; * This annotation is used to mark static fields or static methods that return/contain models used * for a part. They are automatically registered as part of the part item registration. */ -@Retention( RetentionPolicy.RUNTIME ) -@Target( { - ElementType.FIELD, - ElementType.METHOD -} ) -public @interface PartModels -{} +@Retention(RetentionPolicy.RUNTIME) +@Target({ + ElementType.FIELD, + ElementType.METHOD +}) +public @interface PartModels { +} diff --git a/src/main/java/appeng/items/parts/PartModelsHelper.java b/src/main/java/appeng/items/parts/PartModelsHelper.java index 83dd00ef9..a6f45b1ba 100644 --- a/src/main/java/appeng/items/parts/PartModelsHelper.java +++ b/src/main/java/appeng/items/parts/PartModelsHelper.java @@ -1,7 +1,10 @@ - package appeng.items.parts; +import appeng.api.parts.IPartModel; +import appeng.core.AELog; +import net.minecraft.util.ResourceLocation; + import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -10,135 +13,104 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import net.minecraft.util.ResourceLocation; - -import appeng.api.parts.IPartModel; -import appeng.core.AELog; - /** * Helps with the reflection magic needed to gather all models for AE2 cable bus parts. */ -class PartModelsHelper -{ +class PartModelsHelper { - static List createModels( Class clazz ) - { - List locations = new ArrayList<>(); + static List createModels(Class clazz) { + List locations = new ArrayList<>(); - // Check all static fields for used models - Field[] fields = clazz.getDeclaredFields(); - for( Field field : fields ) - { - if( field.getAnnotation( PartModels.class ) == null ) - { - continue; - } + // Check all static fields for used models + Field[] fields = clazz.getDeclaredFields(); + for (Field field : fields) { + if (field.getAnnotation(PartModels.class) == null) { + continue; + } - if( !Modifier.isStatic( field.getModifiers() ) ) - { - AELog.error( "The @PartModels annotation can only be used on static fields or methods. Was seen on: " + field ); - continue; - } + if (!Modifier.isStatic(field.getModifiers())) { + AELog.error("The @PartModels annotation can only be used on static fields or methods. Was seen on: " + field); + continue; + } - Object value; - try - { - field.setAccessible( true ); - value = field.get( null ); - } - catch( IllegalAccessException e ) - { - AELog.error( e, "Cannot access field annotated with @PartModels: " + field ); - continue; - } + Object value; + try { + field.setAccessible(true); + value = field.get(null); + } catch (IllegalAccessException e) { + AELog.error(e, "Cannot access field annotated with @PartModels: " + field); + continue; + } - convertAndAddLocation( field, value, locations ); - } + convertAndAddLocation(field, value, locations); + } - // Check all static methods for the annotation - for( Method method : clazz.getDeclaredMethods() ) - { - if( method.getAnnotation( PartModels.class ) == null ) - { - continue; - } + // Check all static methods for the annotation + for (Method method : clazz.getDeclaredMethods()) { + if (method.getAnnotation(PartModels.class) == null) { + continue; + } - if( !Modifier.isStatic( method.getModifiers() ) ) - { - AELog.error( "The @PartModels annotation can only be used on static fields or methods. Was seen on: " + method ); - continue; - } + if (!Modifier.isStatic(method.getModifiers())) { + AELog.error("The @PartModels annotation can only be used on static fields or methods. Was seen on: " + method); + continue; + } - // Check for parameter count - if( method.getParameters().length != 0 ) - { - AELog.error( "The @PartModels annotation can only be used on static methods without parameters. Was seen on: " + method ); - continue; - } + // Check for parameter count + if (method.getParameters().length != 0) { + AELog.error("The @PartModels annotation can only be used on static methods without parameters. Was seen on: " + method); + continue; + } - // Make sure we can handle the return type - Class returnType = method.getReturnType(); - if( !ResourceLocation.class.isAssignableFrom( returnType ) && !Collection.class.isAssignableFrom( returnType ) ) - { - AELog.error( - "The @PartModels annotation can only be used on static methods that return a ResourceLocation or Collection of " + "ResourceLocations. Was seen on: " + method ); - continue; - } + // Make sure we can handle the return type + Class returnType = method.getReturnType(); + if (!ResourceLocation.class.isAssignableFrom(returnType) && !Collection.class.isAssignableFrom(returnType)) { + AELog.error( + "The @PartModels annotation can only be used on static methods that return a ResourceLocation or Collection of " + "ResourceLocations. Was seen on: " + method); + continue; + } - Object value = null; - try - { - method.setAccessible( true ); - value = method.invoke( null ); - } - catch( IllegalAccessException | InvocationTargetException e ) - { - AELog.error( e, "Failed to invoke the @PartModels annotated method " + method ); - continue; - } + Object value = null; + try { + method.setAccessible(true); + value = method.invoke(null); + } catch (IllegalAccessException | InvocationTargetException e) { + AELog.error(e, "Failed to invoke the @PartModels annotated method " + method); + continue; + } - convertAndAddLocation( method, value, locations ); - } + convertAndAddLocation(method, value, locations); + } - if( clazz.getSuperclass() != null ) - { - locations.addAll( createModels( clazz.getSuperclass() ) ); - } + if (clazz.getSuperclass() != null) { + locations.addAll(createModels(clazz.getSuperclass())); + } - return locations; - } + return locations; + } - private static void convertAndAddLocation( Object source, Object value, List locations ) - { - if( value == null ) - { - return; - } + private static void convertAndAddLocation(Object source, Object value, List locations) { + if (value == null) { + return; + } - if( value instanceof ResourceLocation ) - { - locations.add( (ResourceLocation) value ); - } - else if( value instanceof IPartModel ) - { - locations.addAll( ( (IPartModel) value ).getModels() ); - } - else if( value instanceof Collection ) - { - // Check that each object is an IPartModel - Collection values = (Collection) value; - for( Object candidate : values ) - { - if( !( candidate instanceof IPartModel ) ) - { - AELog.error( "List of locations obtained from {} contains a non resource location: {}", source, candidate ); - continue; - } + if (value instanceof ResourceLocation) { + locations.add((ResourceLocation) value); + } else if (value instanceof IPartModel) { + locations.addAll(((IPartModel) value).getModels()); + } else if (value instanceof Collection) { + // Check that each object is an IPartModel + Collection values = (Collection) value; + for (Object candidate : values) { + if (!(candidate instanceof IPartModel)) { + AELog.error("List of locations obtained from {} contains a non resource location: {}", source, candidate); + continue; + } - locations.addAll( ( (IPartModel) candidate ).getModels() ); - } - } - } + locations.addAll(((IPartModel) candidate).getModels()); + } + } + } } diff --git a/src/main/java/appeng/items/parts/PartType.java b/src/main/java/appeng/items/parts/PartType.java index b4fe37eb3..4645103c6 100644 --- a/src/main/java/appeng/items/parts/PartType.java +++ b/src/main/java/appeng/items/parts/PartType.java @@ -19,416 +19,333 @@ package appeng.items.parts; -import java.lang.reflect.Constructor; -import java.util.Arrays; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import appeng.parts.misc.*; -import appeng.parts.p2p.*; -import appeng.parts.reporting.*; -import com.google.common.collect.ImmutableList; - -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.parts.IPart; import appeng.api.util.AEColor; import appeng.core.AEConfig; import appeng.core.AppEng; import appeng.core.features.AEFeature; import appeng.core.localization.GuiText; -import appeng.fluids.parts.PartFluidAnnihilationPlane; -import appeng.fluids.parts.PartFluidExportBus; -import appeng.fluids.parts.PartFluidFormationPlane; -import appeng.fluids.parts.PartFluidImportBus; -import appeng.fluids.parts.PartFluidInterface; -import appeng.fluids.parts.PartFluidLevelEmitter; -import appeng.fluids.parts.PartFluidStorageBus; -import appeng.fluids.parts.PartFluidTerminal; +import appeng.fluids.parts.*; import appeng.integration.IntegrationRegistry; import appeng.integration.IntegrationType; -import appeng.parts.automation.PartAnnihilationPlane; -import appeng.parts.automation.PartExportBus; -import appeng.parts.automation.PartFormationPlane; -import appeng.parts.automation.PartIdentityAnnihilationPlane; -import appeng.parts.automation.PartImportBus; -import appeng.parts.automation.PartLevelEmitter; -import appeng.parts.networking.PartCableCovered; -import appeng.parts.networking.PartCableGlass; -import appeng.parts.networking.PartCableSmart; -import appeng.parts.networking.PartDenseCableCovered; -import appeng.parts.networking.PartDenseCableSmart; -import appeng.parts.networking.PartQuartzFiber; +import appeng.parts.automation.*; +import appeng.parts.misc.*; +import appeng.parts.networking.*; +import appeng.parts.p2p.*; +import appeng.parts.reporting.*; import appeng.util.Platform; +import com.google.common.collect.ImmutableList; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import java.lang.reflect.Constructor; +import java.util.*; +import java.util.stream.Collectors; -public enum PartType -{ - INVALID_TYPE( -1, "invalid", EnumSet.of( AEFeature.CORE ), EnumSet.noneOf( IntegrationType.class ), null ), - - CABLE_GLASS( 0, "cable_glass", EnumSet.of( AEFeature.GLASS_CABLES ), EnumSet.noneOf( IntegrationType.class ), PartCableGlass.class ) - { - @Override - public boolean isCable() - { - return true; - } - - @Override - @SideOnly( Side.CLIENT ) - protected List createItemModels( String baseName ) - { - return Arrays.stream( AEColor.values() ).map( color -> modelFromBaseName( baseName + "_" + color.name().toLowerCase() ) ).collect( Collectors.toList() ); - } - }, - - CABLE_COVERED( 20, "cable_covered", EnumSet.of( AEFeature.COVERED_CABLES ), EnumSet.noneOf( IntegrationType.class ), PartCableCovered.class ) - { - @Override - public boolean isCable() - { - return true; - } - @Override - @SideOnly( Side.CLIENT ) - protected List createItemModels( String baseName ) - { - return Arrays.stream( AEColor.values() ).map( color -> modelFromBaseName( baseName + "_" + color.name().toLowerCase() ) ).collect( Collectors.toList() ); - } - }, +public enum PartType { + INVALID_TYPE(-1, "invalid", EnumSet.of(AEFeature.CORE), EnumSet.noneOf(IntegrationType.class), null), - CABLE_SMART( 40, "cable_smart", EnumSet.of( AEFeature.SMART_CABLES ), EnumSet.noneOf( IntegrationType.class ), PartCableSmart.class ) - { - @Override - public boolean isCable() - { - return true; - } + CABLE_GLASS(0, "cable_glass", EnumSet.of(AEFeature.GLASS_CABLES), EnumSet.noneOf(IntegrationType.class), PartCableGlass.class) { + @Override + public boolean isCable() { + return true; + } - @Override - @SideOnly( Side.CLIENT ) - protected List createItemModels( String baseName ) - { - return Arrays.stream( AEColor.values() ).map( color -> modelFromBaseName( baseName + "_" + color.name().toLowerCase() ) ).collect( Collectors.toList() ); - } - }, + @Override + @SideOnly(Side.CLIENT) + protected List createItemModels(String baseName) { + return Arrays.stream(AEColor.values()).map(color -> modelFromBaseName(baseName + "_" + color.name().toLowerCase())).collect(Collectors.toList()); + } + }, - CABLE_DENSE_SMART( 60, "cable_dense_smart", EnumSet.of( AEFeature.DENSE_CABLES ), EnumSet.noneOf( IntegrationType.class ), PartDenseCableSmart.class ) - { - @Override - public boolean isCable() - { - return true; - } + CABLE_COVERED(20, "cable_covered", EnumSet.of(AEFeature.COVERED_CABLES), EnumSet.noneOf(IntegrationType.class), PartCableCovered.class) { + @Override + public boolean isCable() { + return true; + } - @Override - @SideOnly( Side.CLIENT ) - protected List createItemModels( String baseName ) - { - return Arrays.stream( AEColor.values() ).map( color -> modelFromBaseName( baseName + "_" + color.name().toLowerCase() ) ).collect( Collectors.toList() ); - } - }, - - CABLE_DENSE_COVERED( 500, "cable_dense_covered", EnumSet.of( AEFeature.DENSE_CABLES ), EnumSet.noneOf( IntegrationType.class ), PartDenseCableCovered.class ) - { - @Override - public boolean isCable() - { - return true; - } - - @Override - @SideOnly( Side.CLIENT ) - protected List createItemModels( String baseName ) - { - return Arrays.stream( AEColor.values() ).map( color -> modelFromBaseName( baseName + "_" + color.name().toLowerCase() ) ).collect( Collectors.toList() ); - } - }, - - TOGGLE_BUS( 80, "toggle_bus", EnumSet.of( AEFeature.TOGGLE_BUS ), EnumSet.noneOf( IntegrationType.class ), PartToggleBus.class ), - - INVERTED_TOGGLE_BUS( 100, "inverted_toggle_bus", EnumSet.of( AEFeature.TOGGLE_BUS ), EnumSet.noneOf( IntegrationType.class ), PartInvertedToggleBus.class ), - - CABLE_ANCHOR( 120, "cable_anchor", EnumSet.of( AEFeature.CABLE_ANCHOR ), EnumSet.noneOf( IntegrationType.class ), PartCableAnchor.class ), - - QUARTZ_FIBER( 140, "quartz_fiber", EnumSet.of( AEFeature.QUARTZ_FIBER ), EnumSet.noneOf( IntegrationType.class ), PartQuartzFiber.class ), - - MONITOR( 160, "monitor", EnumSet.of( AEFeature.PANELS ), EnumSet.noneOf( IntegrationType.class ), PartPanel.class, "itemIlluminatedPanel" ), - - SEMI_DARK_MONITOR( 180, "semi_dark_monitor", EnumSet.of( AEFeature.PANELS ), EnumSet.noneOf( IntegrationType.class ), PartSemiDarkPanel.class, "itemIlluminatedPanel" ), - - DARK_MONITOR( 200, "dark_monitor", EnumSet.of( AEFeature.PANELS ), EnumSet.noneOf( IntegrationType.class ), PartDarkPanel.class, "itemIlluminatedPanel" ), - - STORAGE_BUS( 220, "storage_bus", EnumSet.of( AEFeature.STORAGE_BUS ), EnumSet.noneOf( IntegrationType.class ), PartStorageBus.class ), - FLUID_STORAGE_BUS( 221, "fluid_storage_bus", EnumSet.of( AEFeature.FLUID_STORAGE_BUS ), EnumSet.noneOf( IntegrationType.class ), PartFluidStorageBus.class ), - OREDICT_STORAGE_BUS( 222, "oredict_storage_bus", EnumSet.of( AEFeature.STORAGE_BUS ), EnumSet.noneOf( IntegrationType.class ), PartOreDicStorageBus.class ), - - IMPORT_BUS( 240, "import_bus", EnumSet.of( AEFeature.IMPORT_BUS ), EnumSet.noneOf( IntegrationType.class ), PartImportBus.class ), - - FLUID_IMPORT_BUS( 241, "fluid_import_bus", EnumSet.of( AEFeature.FLUID_IMPORT_BUS ), EnumSet.noneOf( IntegrationType.class ), PartFluidImportBus.class ), - - EXPORT_BUS( 260, "export_bus", EnumSet.of( AEFeature.EXPORT_BUS ), EnumSet.noneOf( IntegrationType.class ), PartExportBus.class ), - - FLUID_EXPORT_BUS( 261, "fluid_export_bus", EnumSet.of( AEFeature.FLUID_EXPORT_BUS ), EnumSet.noneOf( IntegrationType.class ), PartFluidExportBus.class ), - - LEVEL_EMITTER( 280, "level_emitter", EnumSet.of( AEFeature.LEVEL_EMITTER ), EnumSet.noneOf( IntegrationType.class ), PartLevelEmitter.class ), - FLUID_LEVEL_EMITTER( 281, "fluid_level_emitter", EnumSet.of( AEFeature.FLUID_LEVEL_EMITTER ), EnumSet.noneOf( IntegrationType.class ), PartFluidLevelEmitter.class ), - - ANNIHILATION_PLANE( 300, "annihilation_plane", EnumSet.of( AEFeature.ANNIHILATION_PLANE ), EnumSet.noneOf( IntegrationType.class ), PartAnnihilationPlane.class ), - - IDENTITY_ANNIHILATION_PLANE( 301, "identity_annihilation_plane", EnumSet.of( AEFeature.ANNIHILATION_PLANE, AEFeature.IDENTITY_ANNIHILATION_PLANE ), EnumSet.noneOf( IntegrationType.class ), PartIdentityAnnihilationPlane.class ), - - FLUID_ANNIHILATION_PLANE( 302, "fluid_annihilation_plane", EnumSet.of( AEFeature.FLUID_ANNIHILATION_PLANE ), EnumSet.noneOf( IntegrationType.class ), PartFluidAnnihilationPlane.class ), - - FORMATION_PLANE( 320, "formation_plane", EnumSet.of( AEFeature.FORMATION_PLANE ), EnumSet.noneOf( IntegrationType.class ), PartFormationPlane.class ), - - FLUID_FORMATION_PLANE( 321, "fluid_formation_plane", EnumSet.of( AEFeature.FLUID_FORMATION_PLANE ), EnumSet.noneOf( IntegrationType.class ), PartFluidFormationPlane.class ), - - PATTERN_TERMINAL( 340, "pattern_terminal", EnumSet.of( AEFeature.PATTERNS ), EnumSet.noneOf( IntegrationType.class ), PartPatternTerminal.class ), - - EXPANDED_PROCESSING_PATTERN_TERMINAL( 341, "expanded_processing_pattern_terminal", EnumSet.of( AEFeature.PATTERNS ), EnumSet.noneOf( IntegrationType.class ), PartExpandedProcessingPatternTerminal.class ), - - CRAFTING_TERMINAL( 360, "crafting_terminal", EnumSet.of( AEFeature.CRAFTING_TERMINAL ), EnumSet.noneOf( IntegrationType.class ), PartCraftingTerminal.class ), - - TERMINAL( 380, "terminal", EnumSet.of( AEFeature.TERMINAL ), EnumSet.noneOf( IntegrationType.class ), PartTerminal.class ), - - STORAGE_MONITOR( 400, "storage_monitor", EnumSet.of( AEFeature.STORAGE_MONITOR ), EnumSet.noneOf( IntegrationType.class ), PartStorageMonitor.class ), - - CONVERSION_MONITOR( 420, "conversion_monitor", EnumSet.of( AEFeature.PART_CONVERSION_MONITOR ), EnumSet.noneOf( IntegrationType.class ), PartConversionMonitor.class ), - - INTERFACE( 440, "interface", EnumSet.of( AEFeature.INTERFACE ), EnumSet.noneOf( IntegrationType.class ), PartInterface.class ), - FLUID_INTERFACE( 441, "fluid_interface", EnumSet.of( AEFeature.FLUID_INTERFACE ), EnumSet.noneOf( IntegrationType.class ), PartFluidInterface.class ), - - P2P_TUNNEL_ME( 460, "p2p_tunnel_me", EnumSet.of( AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_ME ), EnumSet.noneOf( IntegrationType.class ), PartP2PTunnelME.class, GuiText.METunnel ) - { - @Override - String getUnlocalizedName() - { - return "p2p_tunnel"; - } - }, - - P2P_TUNNEL_REDSTONE( 461, "p2p_tunnel_redstone", EnumSet.of( AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_REDSTONE ), EnumSet.noneOf( IntegrationType.class ), PartP2PRedstone.class, GuiText.RedstoneTunnel ) - { - @Override - String getUnlocalizedName() - { - return "p2p_tunnel"; - } - }, - - P2P_TUNNEL_ITEMS( 462, "p2p_tunnel_items", EnumSet.of( AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_ITEMS ), EnumSet.noneOf( IntegrationType.class ), PartP2PItems.class, GuiText.ItemTunnel ) - { - @Override - String getUnlocalizedName() - { - return "p2p_tunnel"; - } - }, - - P2P_TUNNEL_FLUIDS( 463, "p2p_tunnel_fluids", EnumSet.of( AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_FLUIDS ), EnumSet.noneOf( IntegrationType.class ), PartP2PFluids.class, GuiText.FluidTunnel ) - { - @Override - String getUnlocalizedName() - { - return "p2p_tunnel"; - } - }, - - P2P_TUNNEL_IC2( 465, "p2p_tunnel_ic2", EnumSet.of( AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_EU ), EnumSet.of( IntegrationType.IC2 ), PartP2PIC2Power.class, GuiText.EUTunnel ) - { - @Override - String getUnlocalizedName() - { - return "p2p_tunnel"; - } - }, - - P2P_TUNNEL_LIGHT( 467, "p2p_tunnel_light", EnumSet.of( AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_LIGHT ), EnumSet.noneOf( IntegrationType.class ), PartP2PLight.class, GuiText.LightTunnel ) - { - @Override - String getUnlocalizedName() - { - return "p2p_tunnel"; - } - }, - - P2P_TUNNEL_FE( 469, "p2p_tunnel_fe", EnumSet.of( AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_FE ), EnumSet.noneOf( IntegrationType.class ), PartP2PFEPower.class, GuiText.FETunnel ) - { - @Override - String getUnlocalizedName() - { - return "p2p_tunnel"; - } - }, - - P2P_TUNNEL_GTEU( 470, "p2p_tunnel_gteu", EnumSet.of( AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_GTEU ), EnumSet.of( IntegrationType.GTCE ), PartP2PGTCEPower.class, GuiText.GTEUTunnel ) - { - @Override - String getUnlocalizedName() - { - return "p2p_tunnel"; - } - }, - - // P2PTunnelOpenComputers( 468, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelOpenComputers ), EnumSet.of( - // IntegrationType.OpenComputers ), PartP2POpenComputers.class, GuiText.OCTunnel ), - - INTERFACE_TERMINAL( 480, "interface_terminal", EnumSet.of( AEFeature.INTERFACE_TERMINAL ), EnumSet.noneOf( IntegrationType.class ), PartInterfaceTerminal.class ), - - FLUID_TERMINAL( 520, "fluid_terminal", EnumSet.of( AEFeature.FLUID_TERMINAL ), EnumSet.noneOf( IntegrationType.class ), PartFluidTerminal.class ), - INTERFACE_CONFIGURATION_TERMINAL( 521, "interface_configuration_terminal", EnumSet.of( AEFeature.INTERFACE_TERMINAL ), EnumSet.noneOf( IntegrationType.class ), PartInterfaceConfigurationTerminal.class ); - - private final int baseDamage; - private final Set features; - private final Set integrations; - private final Class myPart; - private final GuiText extraName; - @SideOnly( Side.CLIENT ) - private List itemModels; - private final Set models; - private final boolean enabled; - private Constructor constructor; - private final String oreName; - - PartType( final int baseMetaValue, final String itemModel, final Set features, final Set integrations, final Class c ) - { - this( baseMetaValue, itemModel, features, integrations, c, null, null ); - } - - PartType( final int baseMetaValue, final String itemModel, final Set features, final Set integrations, final Class c, final String oreDict ) - { - this( baseMetaValue, itemModel, features, integrations, c, null, oreDict ); - } - - PartType( final int baseMetaValue, final String itemModel, final Set features, final Set integrations, final Class c, final GuiText en ) - { - this( baseMetaValue, itemModel, features, integrations, c, en, null ); - } - - PartType( final int baseMetaValue, final String itemModel, final Set features, final Set integrations, final Class c, final GuiText en, final String oreDict ) - { - this.baseDamage = baseMetaValue; - this.features = Collections.unmodifiableSet( features ); - this.integrations = Collections.unmodifiableSet( integrations ); - this.myPart = c; - this.extraName = en; - this.oreName = oreDict; - - // The part is enabled if all features + integrations it needs are enabled - this.enabled = features.stream().allMatch( AEConfig.instance()::isFeatureEnabled ) && integrations.stream().allMatch( IntegrationRegistry.INSTANCE::isEnabled ); - - if( this.enabled ) - { - // Only load models if the part is enabled, otherwise we also run into class-loading issues while - // scanning for annotations - if( Platform.isClientInstall() ) - { - this.itemModels = this.createItemModels( itemModel ); - } - if( c != null ) - { - this.models = new HashSet<>( PartModelsHelper.createModels( c ) ); - } - else - { - this.models = Collections.emptySet(); - } - } - else - { - if( Platform.isClientInstall() ) - { - this.itemModels = Collections.emptyList(); - } - this.models = Collections.emptySet(); - } - } - - @SideOnly( Side.CLIENT ) - protected List createItemModels( String baseName ) - { - return ImmutableList.of( modelFromBaseName( baseName ) ); - } - - @SideOnly( Side.CLIENT ) - private static ModelResourceLocation modelFromBaseName( String baseName ) - { - return new ModelResourceLocation( new ResourceLocation( AppEng.MOD_ID, "part/" + baseName ), "inventory" ); - } - - public boolean isEnabled() - { - return this.enabled; - } - - int getBaseDamage() - { - return this.baseDamage; - } - - public boolean isCable() - { - return false; - } - - Set getFeature() - { - return this.features; - } - - Set getIntegrations() - { - return this.integrations; - } - - Class getPart() - { - return this.myPart; - } - - String getUnlocalizedName() - { - return this.name().toLowerCase(); - } - - GuiText getExtraName() - { - return this.extraName; - } - - Constructor getConstructor() - { - return this.constructor; - } - - void setConstructor( final Constructor constructor ) - { - this.constructor = constructor; - } - - public String getOreName() - { - return this.oreName; - } - - @SideOnly( Side.CLIENT ) - public List getItemModels() - { - return this.itemModels; - } - - public Set getModels() - { - return this.models; - } + @Override + @SideOnly(Side.CLIENT) + protected List createItemModels(String baseName) { + return Arrays.stream(AEColor.values()).map(color -> modelFromBaseName(baseName + "_" + color.name().toLowerCase())).collect(Collectors.toList()); + } + }, + + CABLE_SMART(40, "cable_smart", EnumSet.of(AEFeature.SMART_CABLES), EnumSet.noneOf(IntegrationType.class), PartCableSmart.class) { + @Override + public boolean isCable() { + return true; + } + + @Override + @SideOnly(Side.CLIENT) + protected List createItemModels(String baseName) { + return Arrays.stream(AEColor.values()).map(color -> modelFromBaseName(baseName + "_" + color.name().toLowerCase())).collect(Collectors.toList()); + } + }, + + CABLE_DENSE_SMART(60, "cable_dense_smart", EnumSet.of(AEFeature.DENSE_CABLES), EnumSet.noneOf(IntegrationType.class), PartDenseCableSmart.class) { + @Override + public boolean isCable() { + return true; + } + + @Override + @SideOnly(Side.CLIENT) + protected List createItemModels(String baseName) { + return Arrays.stream(AEColor.values()).map(color -> modelFromBaseName(baseName + "_" + color.name().toLowerCase())).collect(Collectors.toList()); + } + }, + + CABLE_DENSE_COVERED(500, "cable_dense_covered", EnumSet.of(AEFeature.DENSE_CABLES), EnumSet.noneOf(IntegrationType.class), PartDenseCableCovered.class) { + @Override + public boolean isCable() { + return true; + } + + @Override + @SideOnly(Side.CLIENT) + protected List createItemModels(String baseName) { + return Arrays.stream(AEColor.values()).map(color -> modelFromBaseName(baseName + "_" + color.name().toLowerCase())).collect(Collectors.toList()); + } + }, + + TOGGLE_BUS(80, "toggle_bus", EnumSet.of(AEFeature.TOGGLE_BUS), EnumSet.noneOf(IntegrationType.class), PartToggleBus.class), + + INVERTED_TOGGLE_BUS(100, "inverted_toggle_bus", EnumSet.of(AEFeature.TOGGLE_BUS), EnumSet.noneOf(IntegrationType.class), PartInvertedToggleBus.class), + + CABLE_ANCHOR(120, "cable_anchor", EnumSet.of(AEFeature.CABLE_ANCHOR), EnumSet.noneOf(IntegrationType.class), PartCableAnchor.class), + + QUARTZ_FIBER(140, "quartz_fiber", EnumSet.of(AEFeature.QUARTZ_FIBER), EnumSet.noneOf(IntegrationType.class), PartQuartzFiber.class), + + MONITOR(160, "monitor", EnumSet.of(AEFeature.PANELS), EnumSet.noneOf(IntegrationType.class), PartPanel.class, "itemIlluminatedPanel"), + + SEMI_DARK_MONITOR(180, "semi_dark_monitor", EnumSet.of(AEFeature.PANELS), EnumSet.noneOf(IntegrationType.class), PartSemiDarkPanel.class, "itemIlluminatedPanel"), + + DARK_MONITOR(200, "dark_monitor", EnumSet.of(AEFeature.PANELS), EnumSet.noneOf(IntegrationType.class), PartDarkPanel.class, "itemIlluminatedPanel"), + + STORAGE_BUS(220, "storage_bus", EnumSet.of(AEFeature.STORAGE_BUS), EnumSet.noneOf(IntegrationType.class), PartStorageBus.class), + FLUID_STORAGE_BUS(221, "fluid_storage_bus", EnumSet.of(AEFeature.FLUID_STORAGE_BUS), EnumSet.noneOf(IntegrationType.class), PartFluidStorageBus.class), + OREDICT_STORAGE_BUS(222, "oredict_storage_bus", EnumSet.of(AEFeature.STORAGE_BUS), EnumSet.noneOf(IntegrationType.class), PartOreDicStorageBus.class), + + IMPORT_BUS(240, "import_bus", EnumSet.of(AEFeature.IMPORT_BUS), EnumSet.noneOf(IntegrationType.class), PartImportBus.class), + + FLUID_IMPORT_BUS(241, "fluid_import_bus", EnumSet.of(AEFeature.FLUID_IMPORT_BUS), EnumSet.noneOf(IntegrationType.class), PartFluidImportBus.class), + + EXPORT_BUS(260, "export_bus", EnumSet.of(AEFeature.EXPORT_BUS), EnumSet.noneOf(IntegrationType.class), PartExportBus.class), + + FLUID_EXPORT_BUS(261, "fluid_export_bus", EnumSet.of(AEFeature.FLUID_EXPORT_BUS), EnumSet.noneOf(IntegrationType.class), PartFluidExportBus.class), + + LEVEL_EMITTER(280, "level_emitter", EnumSet.of(AEFeature.LEVEL_EMITTER), EnumSet.noneOf(IntegrationType.class), PartLevelEmitter.class), + FLUID_LEVEL_EMITTER(281, "fluid_level_emitter", EnumSet.of(AEFeature.FLUID_LEVEL_EMITTER), EnumSet.noneOf(IntegrationType.class), PartFluidLevelEmitter.class), + + ANNIHILATION_PLANE(300, "annihilation_plane", EnumSet.of(AEFeature.ANNIHILATION_PLANE), EnumSet.noneOf(IntegrationType.class), PartAnnihilationPlane.class), + + IDENTITY_ANNIHILATION_PLANE(301, "identity_annihilation_plane", EnumSet.of(AEFeature.ANNIHILATION_PLANE, AEFeature.IDENTITY_ANNIHILATION_PLANE), EnumSet.noneOf(IntegrationType.class), PartIdentityAnnihilationPlane.class), + + FLUID_ANNIHILATION_PLANE(302, "fluid_annihilation_plane", EnumSet.of(AEFeature.FLUID_ANNIHILATION_PLANE), EnumSet.noneOf(IntegrationType.class), PartFluidAnnihilationPlane.class), + + FORMATION_PLANE(320, "formation_plane", EnumSet.of(AEFeature.FORMATION_PLANE), EnumSet.noneOf(IntegrationType.class), PartFormationPlane.class), + + FLUID_FORMATION_PLANE(321, "fluid_formation_plane", EnumSet.of(AEFeature.FLUID_FORMATION_PLANE), EnumSet.noneOf(IntegrationType.class), PartFluidFormationPlane.class), + + PATTERN_TERMINAL(340, "pattern_terminal", EnumSet.of(AEFeature.PATTERNS), EnumSet.noneOf(IntegrationType.class), PartPatternTerminal.class), + + EXPANDED_PROCESSING_PATTERN_TERMINAL(341, "expanded_processing_pattern_terminal", EnumSet.of(AEFeature.PATTERNS), EnumSet.noneOf(IntegrationType.class), PartExpandedProcessingPatternTerminal.class), + + CRAFTING_TERMINAL(360, "crafting_terminal", EnumSet.of(AEFeature.CRAFTING_TERMINAL), EnumSet.noneOf(IntegrationType.class), PartCraftingTerminal.class), + + TERMINAL(380, "terminal", EnumSet.of(AEFeature.TERMINAL), EnumSet.noneOf(IntegrationType.class), PartTerminal.class), + + STORAGE_MONITOR(400, "storage_monitor", EnumSet.of(AEFeature.STORAGE_MONITOR), EnumSet.noneOf(IntegrationType.class), PartStorageMonitor.class), + + CONVERSION_MONITOR(420, "conversion_monitor", EnumSet.of(AEFeature.PART_CONVERSION_MONITOR), EnumSet.noneOf(IntegrationType.class), PartConversionMonitor.class), + + INTERFACE(440, "interface", EnumSet.of(AEFeature.INTERFACE), EnumSet.noneOf(IntegrationType.class), PartInterface.class), + FLUID_INTERFACE(441, "fluid_interface", EnumSet.of(AEFeature.FLUID_INTERFACE), EnumSet.noneOf(IntegrationType.class), PartFluidInterface.class), + + P2P_TUNNEL_ME(460, "p2p_tunnel_me", EnumSet.of(AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_ME), EnumSet.noneOf(IntegrationType.class), PartP2PTunnelME.class, GuiText.METunnel) { + @Override + String getUnlocalizedName() { + return "p2p_tunnel"; + } + }, + + P2P_TUNNEL_REDSTONE(461, "p2p_tunnel_redstone", EnumSet.of(AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_REDSTONE), EnumSet.noneOf(IntegrationType.class), PartP2PRedstone.class, GuiText.RedstoneTunnel) { + @Override + String getUnlocalizedName() { + return "p2p_tunnel"; + } + }, + + P2P_TUNNEL_ITEMS(462, "p2p_tunnel_items", EnumSet.of(AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_ITEMS), EnumSet.noneOf(IntegrationType.class), PartP2PItems.class, GuiText.ItemTunnel) { + @Override + String getUnlocalizedName() { + return "p2p_tunnel"; + } + }, + + P2P_TUNNEL_FLUIDS(463, "p2p_tunnel_fluids", EnumSet.of(AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_FLUIDS), EnumSet.noneOf(IntegrationType.class), PartP2PFluids.class, GuiText.FluidTunnel) { + @Override + String getUnlocalizedName() { + return "p2p_tunnel"; + } + }, + + P2P_TUNNEL_IC2(465, "p2p_tunnel_ic2", EnumSet.of(AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_EU), EnumSet.of(IntegrationType.IC2), PartP2PIC2Power.class, GuiText.EUTunnel) { + @Override + String getUnlocalizedName() { + return "p2p_tunnel"; + } + }, + + P2P_TUNNEL_LIGHT(467, "p2p_tunnel_light", EnumSet.of(AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_LIGHT), EnumSet.noneOf(IntegrationType.class), PartP2PLight.class, GuiText.LightTunnel) { + @Override + String getUnlocalizedName() { + return "p2p_tunnel"; + } + }, + + P2P_TUNNEL_FE(469, "p2p_tunnel_fe", EnumSet.of(AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_FE), EnumSet.noneOf(IntegrationType.class), PartP2PFEPower.class, GuiText.FETunnel) { + @Override + String getUnlocalizedName() { + return "p2p_tunnel"; + } + }, + + P2P_TUNNEL_GTEU(470, "p2p_tunnel_gteu", EnumSet.of(AEFeature.P2P_TUNNEL, AEFeature.P2P_TUNNEL_GTEU), EnumSet.of(IntegrationType.GTCE), PartP2PGTCEPower.class, GuiText.GTEUTunnel) { + @Override + String getUnlocalizedName() { + return "p2p_tunnel"; + } + }, + + // P2PTunnelOpenComputers( 468, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelOpenComputers ), EnumSet.of( + // IntegrationType.OpenComputers ), PartP2POpenComputers.class, GuiText.OCTunnel ), + + INTERFACE_TERMINAL(480, "interface_terminal", EnumSet.of(AEFeature.INTERFACE_TERMINAL), EnumSet.noneOf(IntegrationType.class), PartInterfaceTerminal.class), + + FLUID_TERMINAL(520, "fluid_terminal", EnumSet.of(AEFeature.FLUID_TERMINAL), EnumSet.noneOf(IntegrationType.class), PartFluidTerminal.class), + INTERFACE_CONFIGURATION_TERMINAL(521, "interface_configuration_terminal", EnumSet.of(AEFeature.INTERFACE_TERMINAL), EnumSet.noneOf(IntegrationType.class), PartInterfaceConfigurationTerminal.class); + + private final int baseDamage; + private final Set features; + private final Set integrations; + private final Class myPart; + private final GuiText extraName; + @SideOnly(Side.CLIENT) + private List itemModels; + private final Set models; + private final boolean enabled; + private Constructor constructor; + private final String oreName; + + PartType(final int baseMetaValue, final String itemModel, final Set features, final Set integrations, final Class c) { + this(baseMetaValue, itemModel, features, integrations, c, null, null); + } + + PartType(final int baseMetaValue, final String itemModel, final Set features, final Set integrations, final Class c, final String oreDict) { + this(baseMetaValue, itemModel, features, integrations, c, null, oreDict); + } + + PartType(final int baseMetaValue, final String itemModel, final Set features, final Set integrations, final Class c, final GuiText en) { + this(baseMetaValue, itemModel, features, integrations, c, en, null); + } + + PartType(final int baseMetaValue, final String itemModel, final Set features, final Set integrations, final Class c, final GuiText en, final String oreDict) { + this.baseDamage = baseMetaValue; + this.features = Collections.unmodifiableSet(features); + this.integrations = Collections.unmodifiableSet(integrations); + this.myPart = c; + this.extraName = en; + this.oreName = oreDict; + + // The part is enabled if all features + integrations it needs are enabled + this.enabled = features.stream().allMatch(AEConfig.instance()::isFeatureEnabled) && integrations.stream().allMatch(IntegrationRegistry.INSTANCE::isEnabled); + + if (this.enabled) { + // Only load models if the part is enabled, otherwise we also run into class-loading issues while + // scanning for annotations + if (Platform.isClientInstall()) { + this.itemModels = this.createItemModels(itemModel); + } + if (c != null) { + this.models = new HashSet<>(PartModelsHelper.createModels(c)); + } else { + this.models = Collections.emptySet(); + } + } else { + if (Platform.isClientInstall()) { + this.itemModels = Collections.emptyList(); + } + this.models = Collections.emptySet(); + } + } + + @SideOnly(Side.CLIENT) + protected List createItemModels(String baseName) { + return ImmutableList.of(modelFromBaseName(baseName)); + } + + @SideOnly(Side.CLIENT) + private static ModelResourceLocation modelFromBaseName(String baseName) { + return new ModelResourceLocation(new ResourceLocation(AppEng.MOD_ID, "part/" + baseName), "inventory"); + } + + public boolean isEnabled() { + return this.enabled; + } + + int getBaseDamage() { + return this.baseDamage; + } + + public boolean isCable() { + return false; + } + + Set getFeature() { + return this.features; + } + + Set getIntegrations() { + return this.integrations; + } + + Class getPart() { + return this.myPart; + } + + String getUnlocalizedName() { + return this.name().toLowerCase(); + } + + GuiText getExtraName() { + return this.extraName; + } + + Constructor getConstructor() { + return this.constructor; + } + + void setConstructor(final Constructor constructor) { + this.constructor = constructor; + } + + public String getOreName() { + return this.oreName; + } + + @SideOnly(Side.CLIENT) + public List getItemModels() { + return this.itemModels; + } + + public Set getModels() { + return this.models; + } } diff --git a/src/main/java/appeng/items/storage/AbstractStorageCell.java b/src/main/java/appeng/items/storage/AbstractStorageCell.java index 419d4f9eb..05a2d2f32 100644 --- a/src/main/java/appeng/items/storage/AbstractStorageCell.java +++ b/src/main/java/appeng/items/storage/AbstractStorageCell.java @@ -19,23 +19,6 @@ package appeng.items.storage; -import java.util.List; -import java.util.Set; - -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ActionResult; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.FuzzyMode; import appeng.api.exceptions.MissingDefinitionException; @@ -55,6 +38,22 @@ import appeng.items.contents.CellUpgrades; import appeng.items.materials.MaterialType; import appeng.util.InventoryAdaptor; import appeng.util.Platform; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.items.IItemHandler; + +import java.util.List; +import java.util.Set; /** @@ -62,183 +61,153 @@ import appeng.util.Platform; * @version rv6 - 2018-01-17 * @since rv6 2018-01-17 */ -public abstract class AbstractStorageCell> extends AEBaseItem implements IStorageCell, IItemGroup -{ - protected final MaterialType component; - protected final int totalBytes; +public abstract class AbstractStorageCell> extends AEBaseItem implements IStorageCell, IItemGroup { + protected final MaterialType component; + protected final int totalBytes; - public AbstractStorageCell( final MaterialType whichCell, final int kilobytes ) - { - this.setMaxStackSize( 1 ); - this.totalBytes = kilobytes * 1024; - this.component = whichCell; - } + public AbstractStorageCell(final MaterialType whichCell, final int kilobytes) { + this.setMaxStackSize(1); + this.totalBytes = kilobytes * 1024; + this.component = whichCell; + } - @SideOnly( Side.CLIENT ) - @Override - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - AEApi.instance() - .client() - .addCellInformation( AEApi.instance().registries().cell().getCellInventory( stack, null, this.getChannel() ), lines ); - } + @SideOnly(Side.CLIENT) + @Override + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + AEApi.instance() + .client() + .addCellInformation(AEApi.instance().registries().cell().getCellInventory(stack, null, this.getChannel()), lines); + } - @Override - public int getBytes( final ItemStack cellItem ) - { - return this.totalBytes; - } + @Override + public int getBytes(final ItemStack cellItem) { + return this.totalBytes; + } - @Override - public int getTotalTypes( final ItemStack cellItem ) - { - return 63; - } + @Override + public int getTotalTypes(final ItemStack cellItem) { + return 63; + } - @Override - public boolean isBlackListed( final ItemStack cellItem, final T requestedAddition ) - { - return false; - } + @Override + public boolean isBlackListed(final ItemStack cellItem, final T requestedAddition) { + return false; + } - @Override - public boolean storableInStorageCell() - { - return false; - } + @Override + public boolean storableInStorageCell() { + return false; + } - @Override - public boolean isStorageCell( final ItemStack i ) - { - return true; - } + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } - @Override - public String getUnlocalizedGroupName( final Set others, final ItemStack is ) - { - return GuiText.StorageCells.getUnlocalized(); - } + @Override + public String getUnlocalizedGroupName(final Set others, final ItemStack is) { + return GuiText.StorageCells.getUnlocalized(); + } - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } + @Override + public boolean isEditable(final ItemStack is) { + return true; + } - @Override - public IItemHandler getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 2 ); - } + @Override + public IItemHandler getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 2); + } - @Override - public IItemHandler getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } + @Override + public IItemHandler getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } - @Override - public ActionResult onItemRightClick( final World world, final EntityPlayer player, final EnumHand hand ) - { - this.disassembleDrive( player.getHeldItem( hand ), world, player ); - return new ActionResult<>( EnumActionResult.SUCCESS, player.getHeldItem( hand ) ); - } + @Override + public ActionResult onItemRightClick(final World world, final EntityPlayer player, final EnumHand hand) { + this.disassembleDrive(player.getHeldItem(hand), world, player); + return new ActionResult<>(EnumActionResult.SUCCESS, player.getHeldItem(hand)); + } - private boolean disassembleDrive( final ItemStack stack, final World world, final EntityPlayer player ) - { - if( player.isSneaking() ) - { - if( Platform.isClient() ) - { - return false; - } + private boolean disassembleDrive(final ItemStack stack, final World world, final EntityPlayer player) { + if (player.isSneaking()) { + if (Platform.isClient()) { + return false; + } - final InventoryPlayer playerInventory = player.inventory; - final IMEInventoryHandler inv = AEApi.instance().registries().cell().getCellInventory( stack, null, this.getChannel() ); - if( inv != null && playerInventory.getCurrentItem() == stack ) - { - final InventoryAdaptor ia = InventoryAdaptor.getAdaptor( player ); - final IItemList list = inv.getAvailableItems( this.getChannel().createList() ); - if( list.isEmpty() && ia != null ) - { - playerInventory.setInventorySlotContents( playerInventory.currentItem, ItemStack.EMPTY ); + final InventoryPlayer playerInventory = player.inventory; + final IMEInventoryHandler inv = AEApi.instance().registries().cell().getCellInventory(stack, null, this.getChannel()); + if (inv != null && playerInventory.getCurrentItem() == stack) { + final InventoryAdaptor ia = InventoryAdaptor.getAdaptor(player); + final IItemList list = inv.getAvailableItems(this.getChannel().createList()); + if (list.isEmpty() && ia != null) { + playerInventory.setInventorySlotContents(playerInventory.currentItem, ItemStack.EMPTY); - // drop core - final ItemStack extraB = ia.addItems( this.component.stack( 1 ) ); - if( !extraB.isEmpty() ) - { - player.dropItem( extraB, false ); - } + // drop core + final ItemStack extraB = ia.addItems(this.component.stack(1)); + if (!extraB.isEmpty()) { + player.dropItem(extraB, false); + } - // drop upgrades - final IItemHandler upgradesInventory = this.getUpgradesInventory( stack ); - for( int upgradeIndex = 0; upgradeIndex < upgradesInventory.getSlots(); upgradeIndex++ ) - { - final ItemStack upgradeStack = upgradesInventory.getStackInSlot( upgradeIndex ); - final ItemStack leftStack = ia.addItems( upgradeStack ); - if( !leftStack.isEmpty() && upgradeStack.getItem() instanceof IUpgradeModule ) - { - player.dropItem( upgradeStack, false ); - } - } + // drop upgrades + final IItemHandler upgradesInventory = this.getUpgradesInventory(stack); + for (int upgradeIndex = 0; upgradeIndex < upgradesInventory.getSlots(); upgradeIndex++) { + final ItemStack upgradeStack = upgradesInventory.getStackInSlot(upgradeIndex); + final ItemStack leftStack = ia.addItems(upgradeStack); + if (!leftStack.isEmpty() && upgradeStack.getItem() instanceof IUpgradeModule) { + player.dropItem(upgradeStack, false); + } + } - // drop empty storage cell case - this.dropEmptyStorageCellCase( ia, player ); + // drop empty storage cell case + this.dropEmptyStorageCellCase(ia, player); - if( player.inventoryContainer != null ) - { - player.inventoryContainer.detectAndSendChanges(); - } + if (player.inventoryContainer != null) { + player.inventoryContainer.detectAndSendChanges(); + } - return true; - } - } - } - return false; - } + return true; + } + } + } + return false; + } - protected abstract void dropEmptyStorageCellCase( final InventoryAdaptor ia, final EntityPlayer player ); + protected abstract void dropEmptyStorageCellCase(final InventoryAdaptor ia, final EntityPlayer player); - @Override - public EnumActionResult onItemUseFirst( final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand ) - { - return this.disassembleDrive( player.getHeldItem( hand ), world, player ) ? EnumActionResult.SUCCESS : EnumActionResult.PASS; - } + @Override + public EnumActionResult onItemUseFirst(final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand) { + return this.disassembleDrive(player.getHeldItem(hand), world, player) ? EnumActionResult.SUCCESS : EnumActionResult.PASS; + } - @Override - public ItemStack getContainerItem( final ItemStack itemStack ) - { - return AEApi.instance() - .definitions() - .materials() - .emptyStorageCell() - .maybeStack( 1 ) - .orElseThrow( () -> new MissingDefinitionException( "Tried to use empty storage cells while basic storage cells are defined." ) ); - } + @Override + public ItemStack getContainerItem(final ItemStack itemStack) { + return AEApi.instance() + .definitions() + .materials() + .emptyStorageCell() + .maybeStack(1) + .orElseThrow(() -> new MissingDefinitionException("Tried to use empty storage cells while basic storage cells are defined.")); + } - @Override - public boolean hasContainerItem( final ItemStack stack ) - { - return AEConfig.instance().isFeatureEnabled( AEFeature.ENABLE_DISASSEMBLY_CRAFTING ); - } + @Override + public boolean hasContainerItem(final ItemStack stack) { + return AEConfig.instance().isFeatureEnabled(AEFeature.ENABLE_DISASSEMBLY_CRAFTING); + } } diff --git a/src/main/java/appeng/items/storage/BasicItemStorageCell.java b/src/main/java/appeng/items/storage/BasicItemStorageCell.java index 5c6de9811..ba6f3d05d 100644 --- a/src/main/java/appeng/items/storage/BasicItemStorageCell.java +++ b/src/main/java/appeng/items/storage/BasicItemStorageCell.java @@ -19,79 +19,70 @@ package appeng.items.storage; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.api.storage.IStorageChannel; import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEItemStack; import appeng.items.materials.MaterialType; import appeng.util.InventoryAdaptor; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; -public final class BasicItemStorageCell extends AbstractStorageCell -{ +public final class BasicItemStorageCell extends AbstractStorageCell { - protected final int perType; - protected final double idleDrain; + protected final int perType; + protected final double idleDrain; - public BasicItemStorageCell( final MaterialType whichCell, final int kilobytes ) - { - super( whichCell, kilobytes ); - switch( whichCell ) - { - case CELL1K_PART: - this.idleDrain = 0.5; - this.perType = 8; - break; - case CELL4K_PART: - this.idleDrain = 1.0; - this.perType = 32; - break; - case CELL16K_PART: - this.idleDrain = 1.5; - this.perType = 128; - break; - case CELL64K_PART: - this.idleDrain = 2.0; - this.perType = 512; - break; - default: - this.idleDrain = 0.0; - this.perType = 8; - } + public BasicItemStorageCell(final MaterialType whichCell, final int kilobytes) { + super(whichCell, kilobytes); + switch (whichCell) { + case CELL1K_PART: + this.idleDrain = 0.5; + this.perType = 8; + break; + case CELL4K_PART: + this.idleDrain = 1.0; + this.perType = 32; + break; + case CELL16K_PART: + this.idleDrain = 1.5; + this.perType = 128; + break; + case CELL64K_PART: + this.idleDrain = 2.0; + this.perType = 512; + break; + default: + this.idleDrain = 0.0; + this.perType = 8; + } - } + } - @Override - public int getBytesPerType( ItemStack cellItem ) - { - return this.perType; - } + @Override + public int getBytesPerType(ItemStack cellItem) { + return this.perType; + } - @Override - public double getIdleDrain() - { - return this.idleDrain; - } + @Override + public double getIdleDrain() { + return this.idleDrain; + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } - @Override - protected void dropEmptyStorageCellCase( final InventoryAdaptor ia, final EntityPlayer player ) - { - AEApi.instance().definitions().materials().emptyStorageCell().maybeStack( 1 ).ifPresent( is -> - { - final ItemStack extraA = ia.addItems( is ); - if( !extraA.isEmpty() ) - { - player.dropItem( extraA, false ); - } - } ); - } + @Override + protected void dropEmptyStorageCellCase(final InventoryAdaptor ia, final EntityPlayer player) { + AEApi.instance().definitions().materials().emptyStorageCell().maybeStack(1).ifPresent(is -> + { + final ItemStack extraA = ia.addItems(is); + if (!extraA.isEmpty()) { + player.dropItem(extraA, false); + } + }); + } } diff --git a/src/main/java/appeng/items/storage/ItemCreativeStorageCell.java b/src/main/java/appeng/items/storage/ItemCreativeStorageCell.java index f3468bdb6..3e8c22820 100644 --- a/src/main/java/appeng/items/storage/ItemCreativeStorageCell.java +++ b/src/main/java/appeng/items/storage/ItemCreativeStorageCell.java @@ -19,15 +19,6 @@ package appeng.items.storage; -import java.util.List; - -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.FuzzyMode; import appeng.api.storage.ICellInventoryHandler; @@ -36,67 +27,64 @@ import appeng.api.storage.IMEInventoryHandler; import appeng.api.storage.channels.IItemStorageChannel; import appeng.items.AEBaseItem; import appeng.items.contents.CellConfig; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.items.IItemHandler; + +import java.util.List; -public class ItemCreativeStorageCell extends AEBaseItem implements ICellWorkbenchItem -{ +public class ItemCreativeStorageCell extends AEBaseItem implements ICellWorkbenchItem { - public ItemCreativeStorageCell() - { - this.setMaxStackSize( 1 ); - } + public ItemCreativeStorageCell() { + this.setMaxStackSize(1); + } - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } + @Override + public boolean isEditable(final ItemStack is) { + return true; + } - @Override - public IItemHandler getUpgradesInventory( final ItemStack is ) - { - return null; - } + @Override + public IItemHandler getUpgradesInventory(final ItemStack is) { + return null; + } - @Override - public IItemHandler getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } + @Override + public IItemHandler getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - return FuzzyMode.IGNORE_ALL; - } + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + return FuzzyMode.IGNORE_ALL; + } - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { - } + } - @SideOnly( Side.CLIENT ) - @Override - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - final IMEInventoryHandler inventory = AEApi.instance() - .registries() - .cell() - .getCellInventory( stack, null, - AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); + @SideOnly(Side.CLIENT) + @Override + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + final IMEInventoryHandler inventory = AEApi.instance() + .registries() + .cell() + .getCellInventory(stack, null, + AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); - if( inventory instanceof ICellInventoryHandler ) - { - final CellConfig cc = new CellConfig( stack ); + if (inventory instanceof ICellInventoryHandler) { + final CellConfig cc = new CellConfig(stack); - for( final ItemStack is : cc ) - { - if( !is.isEmpty() ) - { - lines.add( is.getDisplayName() ); - } - } - } - } + for (final ItemStack is : cc) { + if (!is.isEmpty()) { + lines.add(is.getDisplayName()); + } + } + } + } } diff --git a/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java b/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java index b2a9e80b8..387b1daab 100644 --- a/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java +++ b/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java @@ -19,17 +19,6 @@ package appeng.items.storage; -import java.util.List; - -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.common.DimensionManager; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.implementations.TransitionResult; import appeng.api.implementations.items.ISpatialStorageCell; import appeng.api.storage.ISpatialDimension; @@ -40,151 +29,137 @@ import appeng.core.localization.GuiText; import appeng.items.AEBaseItem; import appeng.spatial.StorageHelper; import appeng.util.Platform; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.common.DimensionManager; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import java.util.List; -public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorageCell -{ - private static final String NBT_CELL_ID_KEY = "StorageCellID"; - private static final String NBT_SIZE_X_KEY = "sizeX"; - private static final String NBT_SIZE_Y_KEY = "sizeY"; - private static final String NBT_SIZE_Z_KEY = "sizeZ"; +public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorageCell { + private static final String NBT_CELL_ID_KEY = "StorageCellID"; + private static final String NBT_SIZE_X_KEY = "sizeX"; + private static final String NBT_SIZE_Y_KEY = "sizeY"; + private static final String NBT_SIZE_Z_KEY = "sizeZ"; - private final int maxRegion; + private final int maxRegion; - public ItemSpatialStorageCell( final int spatialScale ) - { - this.setMaxStackSize( 1 ); - this.maxRegion = spatialScale; - } + public ItemSpatialStorageCell(final int spatialScale) { + this.setMaxStackSize(1); + this.maxRegion = spatialScale; + } - @SideOnly( Side.CLIENT ) - @Override - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - final int id = this.getStoredDimensionID( stack ); - if( id >= 0 ) - { - lines.add( GuiText.CellId.getLocal() + ": " + id ); - } + @SideOnly(Side.CLIENT) + @Override + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + final int id = this.getStoredDimensionID(stack); + if (id >= 0) { + lines.add(GuiText.CellId.getLocal() + ": " + id); + } - final WorldCoord wc = this.getStoredSize( stack ); - if( wc.x > 0 ) - { - lines.add( GuiText.StoredSize.getLocal() + ": " + wc.x + " x " + wc.y + " x " + wc.z ); - } - } + final WorldCoord wc = this.getStoredSize(stack); + if (wc.x > 0) { + lines.add(GuiText.StoredSize.getLocal() + ": " + wc.x + " x " + wc.y + " x " + wc.z); + } + } - @Override - public boolean isSpatialStorage( final ItemStack is ) - { - return true; - } + @Override + public boolean isSpatialStorage(final ItemStack is) { + return true; + } - @Override - public int getMaxStoredDim( final ItemStack is ) - { - return this.maxRegion; - } + @Override + public int getMaxStoredDim(final ItemStack is) { + return this.maxRegion; + } - @Override - public ISpatialDimension getSpatialDimension() - { - final int id = AppEng.instance().getStorageDimensionID(); - World w = DimensionManager.getWorld( id ); - if( w == null ) - { - DimensionManager.initDimension( id ); - w = DimensionManager.getWorld( id ); - } + @Override + public ISpatialDimension getSpatialDimension() { + final int id = AppEng.instance().getStorageDimensionID(); + World w = DimensionManager.getWorld(id); + if (w == null) { + DimensionManager.initDimension(id); + w = DimensionManager.getWorld(id); + } - if( w != null && w.hasCapability( Capabilities.SPATIAL_DIMENSION, null ) ) - { - return w.getCapability( Capabilities.SPATIAL_DIMENSION, null ); - } - return null; - } + if (w != null && w.hasCapability(Capabilities.SPATIAL_DIMENSION, null)) { + return w.getCapability(Capabilities.SPATIAL_DIMENSION, null); + } + return null; + } - @Override - public WorldCoord getStoredSize( final ItemStack is ) - { - if( is.hasTagCompound() ) - { - final NBTTagCompound c = is.getTagCompound(); - return new WorldCoord( c.getInteger( NBT_SIZE_X_KEY ), c.getInteger( NBT_SIZE_Y_KEY ), c.getInteger( NBT_SIZE_Z_KEY ) ); - } - return new WorldCoord( 0, 0, 0 ); - } + @Override + public WorldCoord getStoredSize(final ItemStack is) { + if (is.hasTagCompound()) { + final NBTTagCompound c = is.getTagCompound(); + return new WorldCoord(c.getInteger(NBT_SIZE_X_KEY), c.getInteger(NBT_SIZE_Y_KEY), c.getInteger(NBT_SIZE_Z_KEY)); + } + return new WorldCoord(0, 0, 0); + } - @Override - public int getStoredDimensionID( final ItemStack is ) - { - if( is.hasTagCompound() ) - { - final NBTTagCompound c = is.getTagCompound(); - return c.getInteger( NBT_CELL_ID_KEY ); - } - return -1; - } + @Override + public int getStoredDimensionID(final ItemStack is) { + if (is.hasTagCompound()) { + final NBTTagCompound c = is.getTagCompound(); + return c.getInteger(NBT_CELL_ID_KEY); + } + return -1; + } - @Override - public TransitionResult doSpatialTransition( final ItemStack is, final World w, final WorldCoord min, final WorldCoord max, int playerId ) - { - final int targetX = max.x - min.x - 1; - final int targetY = max.y - min.y - 1; - final int targetZ = max.z - min.z - 1; - final int maxSize = this.getMaxStoredDim( is ); + @Override + public TransitionResult doSpatialTransition(final ItemStack is, final World w, final WorldCoord min, final WorldCoord max, int playerId) { + final int targetX = max.x - min.x - 1; + final int targetY = max.y - min.y - 1; + final int targetZ = max.z - min.z - 1; + final int maxSize = this.getMaxStoredDim(is); - final BlockPos targetSize = new BlockPos( targetX, targetY, targetZ ); + final BlockPos targetSize = new BlockPos(targetX, targetY, targetZ); - ISpatialDimension manager = this.getSpatialDimension(); + ISpatialDimension manager = this.getSpatialDimension(); - int cellid = this.getStoredDimensionID( is ); - if( cellid < 0 ) - { - cellid = manager.createNewCellDimension( targetSize, playerId ); - } + int cellid = this.getStoredDimensionID(is); + if (cellid < 0) { + cellid = manager.createNewCellDimension(targetSize, playerId); + } - try - { - if( manager.isCellDimension( cellid ) ) - { - BlockPos scale = manager.getCellContentSize( cellid ); + try { + if (manager.isCellDimension(cellid)) { + BlockPos scale = manager.getCellContentSize(cellid); - if( scale.equals( targetSize ) ) - { - if( targetX <= maxSize && targetY <= maxSize && targetZ <= maxSize ) - { - BlockPos offset = manager.getCellDimensionOrigin( cellid ); + if (scale.equals(targetSize)) { + if (targetX <= maxSize && targetY <= maxSize && targetZ <= maxSize) { + BlockPos offset = manager.getCellDimensionOrigin(cellid); - this.setStorageCell( is, cellid, targetSize ); - StorageHelper.getInstance() - .swapRegions( w, min.x + 1, min.y + 1, min.z + 1, manager.getWorld(), offset.getX(), offset.getY(), - offset.getZ(), targetX - 1, targetY - 1, - targetZ - 1 ); + this.setStorageCell(is, cellid, targetSize); + StorageHelper.getInstance() + .swapRegions(w, min.x + 1, min.y + 1, min.z + 1, manager.getWorld(), offset.getX(), offset.getY(), + offset.getZ(), targetX - 1, targetY - 1, + targetZ - 1); - return new TransitionResult( true, 0 ); - } - } - } - return new TransitionResult( false, 0 ); - } - finally - { - // clean up newly created dimensions that failed transfer - if( manager.isCellDimension( cellid ) && this.getStoredDimensionID( is ) < 0 ) - { - manager.deleteCellDimension( cellid ); - } - } - } + return new TransitionResult(true, 0); + } + } + } + return new TransitionResult(false, 0); + } finally { + // clean up newly created dimensions that failed transfer + if (manager.isCellDimension(cellid) && this.getStoredDimensionID(is) < 0) { + manager.deleteCellDimension(cellid); + } + } + } - private void setStorageCell( final ItemStack is, int id, BlockPos size ) - { - final NBTTagCompound c = Platform.openNbtData( is ); + private void setStorageCell(final ItemStack is, int id, BlockPos size) { + final NBTTagCompound c = Platform.openNbtData(is); - c.setInteger( NBT_CELL_ID_KEY, id ); - c.setInteger( NBT_SIZE_X_KEY, size.getX() ); - c.setInteger( NBT_SIZE_Y_KEY, size.getY() ); - c.setInteger( NBT_SIZE_Z_KEY, size.getZ() ); - } + c.setInteger(NBT_CELL_ID_KEY, id); + c.setInteger(NBT_SIZE_X_KEY, size.getX()); + c.setInteger(NBT_SIZE_Y_KEY, size.getY()); + c.setInteger(NBT_SIZE_Z_KEY, size.getZ()); + } } diff --git a/src/main/java/appeng/items/storage/ItemViewCell.java b/src/main/java/appeng/items/storage/ItemViewCell.java index 091f27a94..9a7cf5252 100644 --- a/src/main/java/appeng/items/storage/ItemViewCell.java +++ b/src/main/java/appeng/items/storage/ItemViewCell.java @@ -19,9 +19,6 @@ package appeng.items.storage; -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.FuzzyMode; import appeng.api.config.Upgrades; @@ -39,125 +36,103 @@ import appeng.util.prioritylist.FuzzyPriorityList; import appeng.util.prioritylist.IPartitionList; import appeng.util.prioritylist.MergedPriorityList; import appeng.util.prioritylist.PrecisePriorityList; +import net.minecraft.item.ItemStack; +import net.minecraftforge.items.IItemHandler; -public class ItemViewCell extends AEBaseItem implements ICellWorkbenchItem -{ - public ItemViewCell() - { - this.setMaxStackSize( 1 ); - } +public class ItemViewCell extends AEBaseItem implements ICellWorkbenchItem { + public ItemViewCell() { + this.setMaxStackSize(1); + } - public static IPartitionList createFilter( final ItemStack[] list ) - { - IPartitionList myPartitionList = null; + public static IPartitionList createFilter(final ItemStack[] list) { + IPartitionList myPartitionList = null; - final MergedPriorityList myMergedList = new MergedPriorityList<>(); + final MergedPriorityList myMergedList = new MergedPriorityList<>(); - for( final ItemStack currentViewCell : list ) - { - if( currentViewCell == null ) - { - continue; - } + for (final ItemStack currentViewCell : list) { + if (currentViewCell == null) { + continue; + } - if( ( currentViewCell.getItem() instanceof ItemViewCell ) ) - { - final IItemList priorityList = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); + if ((currentViewCell.getItem() instanceof ItemViewCell)) { + final IItemList priorityList = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); - final ICellWorkbenchItem vc = (ICellWorkbenchItem) currentViewCell.getItem(); - final IItemHandler upgrades = vc.getUpgradesInventory( currentViewCell ); - final IItemHandler config = vc.getConfigInventory( currentViewCell ); - final FuzzyMode fzMode = vc.getFuzzyMode( currentViewCell ); + final ICellWorkbenchItem vc = (ICellWorkbenchItem) currentViewCell.getItem(); + final IItemHandler upgrades = vc.getUpgradesInventory(currentViewCell); + final IItemHandler config = vc.getConfigInventory(currentViewCell); + final FuzzyMode fzMode = vc.getFuzzyMode(currentViewCell); - boolean hasInverter = false; - boolean hasFuzzy = false; + boolean hasInverter = false; + boolean hasFuzzy = false; - for( int x = 0; x < upgrades.getSlots(); x++ ) - { - final ItemStack is = upgrades.getStackInSlot( x ); - if( !is.isEmpty() && is.getItem() instanceof IUpgradeModule ) - { - final Upgrades u = ( (IUpgradeModule) is.getItem() ).getType( is ); - if( u != null ) - { - switch( u ) - { - case FUZZY: - hasFuzzy = true; - break; - case INVERTER: - hasInverter = true; - break; - default: - } - } - } - } + for (int x = 0; x < upgrades.getSlots(); x++) { + final ItemStack is = upgrades.getStackInSlot(x); + if (!is.isEmpty() && is.getItem() instanceof IUpgradeModule) { + final Upgrades u = ((IUpgradeModule) is.getItem()).getType(is); + if (u != null) { + switch (u) { + case FUZZY: + hasFuzzy = true; + break; + case INVERTER: + hasInverter = true; + break; + default: + } + } + } + } - for( int x = 0; x < config.getSlots(); x++ ) - { - final ItemStack is = config.getStackInSlot( x ); - if( !is.isEmpty() ) - { - priorityList.add( AEItemStack.fromItemStack( is ) ); - } - } + for (int x = 0; x < config.getSlots(); x++) { + final ItemStack is = config.getStackInSlot(x); + if (!is.isEmpty()) { + priorityList.add(AEItemStack.fromItemStack(is)); + } + } - if( !priorityList.isEmpty() ) - { - if( hasFuzzy ) - { - myMergedList.addNewList( new FuzzyPriorityList<>( priorityList, fzMode ), !hasInverter ); - } - else - { - myMergedList.addNewList( new PrecisePriorityList<>( priorityList ), !hasInverter ); - } + if (!priorityList.isEmpty()) { + if (hasFuzzy) { + myMergedList.addNewList(new FuzzyPriorityList<>(priorityList, fzMode), !hasInverter); + } else { + myMergedList.addNewList(new PrecisePriorityList<>(priorityList), !hasInverter); + } - myPartitionList = myMergedList; - } - } - } + myPartitionList = myMergedList; + } + } + } - return myPartitionList; - } + return myPartitionList; + } - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } + @Override + public boolean isEditable(final ItemStack is) { + return true; + } - @Override - public IItemHandler getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 2 ); - } + @Override + public IItemHandler getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 2); + } - @Override - public IItemHandler getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } + @Override + public IItemHandler getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } } diff --git a/src/main/java/appeng/items/tools/ToolBiometricCard.java b/src/main/java/appeng/items/tools/ToolBiometricCard.java index 0740090d4..9f2d1134a 100644 --- a/src/main/java/appeng/items/tools/ToolBiometricCard.java +++ b/src/main/java/appeng/items/tools/ToolBiometricCard.java @@ -19,11 +19,14 @@ package appeng.items.tools; -import java.util.EnumSet; -import java.util.List; - +import appeng.api.config.SecurityPermissions; +import appeng.api.features.IPlayerRegistry; +import appeng.api.implementations.items.IBiometricCard; +import appeng.api.networking.security.ISecurityRegistry; +import appeng.core.localization.GuiText; +import appeng.items.AEBaseItem; +import appeng.util.Platform; import com.mojang.authlib.GameProfile; - import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -37,172 +40,133 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.config.SecurityPermissions; -import appeng.api.features.IPlayerRegistry; -import appeng.api.implementations.items.IBiometricCard; -import appeng.api.networking.security.ISecurityRegistry; -import appeng.core.localization.GuiText; -import appeng.items.AEBaseItem; -import appeng.util.Platform; +import java.util.EnumSet; +import java.util.List; -public class ToolBiometricCard extends AEBaseItem implements IBiometricCard -{ - public ToolBiometricCard() - { - this.setMaxStackSize( 1 ); - } +public class ToolBiometricCard extends AEBaseItem implements IBiometricCard { + public ToolBiometricCard() { + this.setMaxStackSize(1); + } - @Override - public ActionResult onItemRightClick( final World w, final EntityPlayer p, final EnumHand hand ) - { - if( p.isSneaking() ) - { - this.encode( p.getHeldItem( hand ), p ); - p.swingArm( hand ); - return new ActionResult<>( EnumActionResult.SUCCESS, p.getHeldItem( hand ) ); - } + @Override + public ActionResult onItemRightClick(final World w, final EntityPlayer p, final EnumHand hand) { + if (p.isSneaking()) { + this.encode(p.getHeldItem(hand), p); + p.swingArm(hand); + return new ActionResult<>(EnumActionResult.SUCCESS, p.getHeldItem(hand)); + } - return new ActionResult<>( EnumActionResult.PASS, p.getHeldItem( hand ) ); - } + return new ActionResult<>(EnumActionResult.PASS, p.getHeldItem(hand)); + } - @Override - public boolean itemInteractionForEntity( ItemStack is, final EntityPlayer player, final EntityLivingBase target, final EnumHand hand ) - { - if( target instanceof EntityPlayer && !player.isSneaking() ) - { - if( player.capabilities.isCreativeMode ) - { - is = player.getHeldItem( hand ); - } - this.encode( is, (EntityPlayer) target ); - player.swingArm( hand ); - return true; - } - return false; - } + @Override + public boolean itemInteractionForEntity(ItemStack is, final EntityPlayer player, final EntityLivingBase target, final EnumHand hand) { + if (target instanceof EntityPlayer && !player.isSneaking()) { + if (player.capabilities.isCreativeMode) { + is = player.getHeldItem(hand); + } + this.encode(is, (EntityPlayer) target); + player.swingArm(hand); + return true; + } + return false; + } - @Override - public String getItemStackDisplayName( final ItemStack is ) - { - final GameProfile username = this.getProfile( is ); - return username != null ? super.getItemStackDisplayName( is ) + " - " + username.getName() : super.getItemStackDisplayName( is ); - } + @Override + public String getItemStackDisplayName(final ItemStack is) { + final GameProfile username = this.getProfile(is); + return username != null ? super.getItemStackDisplayName(is) + " - " + username.getName() : super.getItemStackDisplayName(is); + } - private void encode( final ItemStack is, final EntityPlayer p ) - { - final GameProfile username = this.getProfile( is ); + private void encode(final ItemStack is, final EntityPlayer p) { + final GameProfile username = this.getProfile(is); - if( username != null && username.equals( p.getGameProfile() ) ) - { - this.setProfile( is, null ); - } - else - { - this.setProfile( is, p.getGameProfile() ); - } - } + if (username != null && username.equals(p.getGameProfile())) { + this.setProfile(is, null); + } else { + this.setProfile(is, p.getGameProfile()); + } + } - @Override - public void setProfile( final ItemStack itemStack, final GameProfile profile ) - { - final NBTTagCompound tag = Platform.openNbtData( itemStack ); + @Override + public void setProfile(final ItemStack itemStack, final GameProfile profile) { + final NBTTagCompound tag = Platform.openNbtData(itemStack); - if( profile != null ) - { - final NBTTagCompound pNBT = new NBTTagCompound(); - NBTUtil.writeGameProfile( pNBT, profile ); - tag.setTag( "profile", pNBT ); - } - else - { - tag.removeTag( "profile" ); - } - } + if (profile != null) { + final NBTTagCompound pNBT = new NBTTagCompound(); + NBTUtil.writeGameProfile(pNBT, profile); + tag.setTag("profile", pNBT); + } else { + tag.removeTag("profile"); + } + } - @Override - public GameProfile getProfile( final ItemStack is ) - { - final NBTTagCompound tag = Platform.openNbtData( is ); - if( tag.hasKey( "profile" ) ) - { - return NBTUtil.readGameProfileFromNBT( tag.getCompoundTag( "profile" ) ); - } - return null; - } + @Override + public GameProfile getProfile(final ItemStack is) { + final NBTTagCompound tag = Platform.openNbtData(is); + if (tag.hasKey("profile")) { + return NBTUtil.readGameProfileFromNBT(tag.getCompoundTag("profile")); + } + return null; + } - @Override - public EnumSet getPermissions( final ItemStack is ) - { - final NBTTagCompound tag = Platform.openNbtData( is ); - final EnumSet result = EnumSet.noneOf( SecurityPermissions.class ); + @Override + public EnumSet getPermissions(final ItemStack is) { + final NBTTagCompound tag = Platform.openNbtData(is); + final EnumSet result = EnumSet.noneOf(SecurityPermissions.class); - for( final SecurityPermissions sp : SecurityPermissions.values() ) - { - if( tag.getBoolean( sp.name() ) ) - { - result.add( sp ); - } - } + for (final SecurityPermissions sp : SecurityPermissions.values()) { + if (tag.getBoolean(sp.name())) { + result.add(sp); + } + } - return result; - } + return result; + } - @Override - public boolean hasPermission( final ItemStack is, final SecurityPermissions permission ) - { - final NBTTagCompound tag = Platform.openNbtData( is ); - return tag.getBoolean( permission.name() ); - } + @Override + public boolean hasPermission(final ItemStack is, final SecurityPermissions permission) { + final NBTTagCompound tag = Platform.openNbtData(is); + return tag.getBoolean(permission.name()); + } - @Override - public void removePermission( final ItemStack itemStack, final SecurityPermissions permission ) - { - final NBTTagCompound tag = Platform.openNbtData( itemStack ); - if( tag.hasKey( permission.name() ) ) - { - tag.removeTag( permission.name() ); - } - } + @Override + public void removePermission(final ItemStack itemStack, final SecurityPermissions permission) { + final NBTTagCompound tag = Platform.openNbtData(itemStack); + if (tag.hasKey(permission.name())) { + tag.removeTag(permission.name()); + } + } - @Override - public void addPermission( final ItemStack itemStack, final SecurityPermissions permission ) - { - final NBTTagCompound tag = Platform.openNbtData( itemStack ); - tag.setBoolean( permission.name(), true ); - } + @Override + public void addPermission(final ItemStack itemStack, final SecurityPermissions permission) { + final NBTTagCompound tag = Platform.openNbtData(itemStack); + tag.setBoolean(permission.name(), true); + } - @Override - public void registerPermissions( final ISecurityRegistry register, final IPlayerRegistry pr, final ItemStack is ) - { - register.addPlayer( pr.getID( this.getProfile( is ) ), this.getPermissions( is ) ); - } + @Override + public void registerPermissions(final ISecurityRegistry register, final IPlayerRegistry pr, final ItemStack is) { + register.addPlayer(pr.getID(this.getProfile(is)), this.getPermissions(is)); + } - @Override - @SideOnly( Side.CLIENT ) - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - final EnumSet perms = this.getPermissions( stack ); - if( perms.isEmpty() ) - { - lines.add( GuiText.NoPermissions.getLocal() ); - } - else - { - String msg = null; + @Override + @SideOnly(Side.CLIENT) + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + final EnumSet perms = this.getPermissions(stack); + if (perms.isEmpty()) { + lines.add(GuiText.NoPermissions.getLocal()); + } else { + String msg = null; - for( final SecurityPermissions sp : perms ) - { - if( msg == null ) - { - msg = Platform.gui_localize( sp.getUnlocalizedName() ); - } - else - { - msg = msg + ", " + Platform.gui_localize( sp.getUnlocalizedName() ); - } - } - lines.add( msg ); - } - } + for (final SecurityPermissions sp : perms) { + if (msg == null) { + msg = Platform.gui_localize(sp.getUnlocalizedName()); + } else { + msg = msg + ", " + Platform.gui_localize(sp.getUnlocalizedName()); + } + } + lines.add(msg); + } + } } diff --git a/src/main/java/appeng/items/tools/ToolBiometricCardRendering.java b/src/main/java/appeng/items/tools/ToolBiometricCardRendering.java index 9c167b148..d597752b4 100644 --- a/src/main/java/appeng/items/tools/ToolBiometricCardRendering.java +++ b/src/main/java/appeng/items/tools/ToolBiometricCardRendering.java @@ -1,28 +1,24 @@ - package appeng.items.tools; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.bootstrap.IItemRendering; import appeng.bootstrap.ItemRenderingCustomizer; import appeng.client.render.model.BiometricCardModel; import appeng.core.AppEng; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class ToolBiometricCardRendering extends ItemRenderingCustomizer -{ +public class ToolBiometricCardRendering extends ItemRenderingCustomizer { - private static final ResourceLocation MODEL = new ResourceLocation( AppEng.MOD_ID, "builtin/biometric_card" ); + private static final ResourceLocation MODEL = new ResourceLocation(AppEng.MOD_ID, "builtin/biometric_card"); - @Override - @SideOnly( Side.CLIENT ) - public void customize( IItemRendering rendering ) - { - rendering.builtInModel( "models/item/builtin/biometric_card", new BiometricCardModel() ); - rendering.model( new ModelResourceLocation( MODEL, "inventory" ) ).variants( MODEL ); - } + @Override + @SideOnly(Side.CLIENT) + public void customize(IItemRendering rendering) { + rendering.builtInModel("models/item/builtin/biometric_card", new BiometricCardModel()); + rendering.model(new ModelResourceLocation(MODEL, "inventory")).variants(MODEL); + } } diff --git a/src/main/java/appeng/items/tools/ToolMemoryCard.java b/src/main/java/appeng/items/tools/ToolMemoryCard.java index 75ae60bad..9e4530e53 100644 --- a/src/main/java/appeng/items/tools/ToolMemoryCard.java +++ b/src/main/java/appeng/items/tools/ToolMemoryCard.java @@ -19,8 +19,13 @@ package appeng.items.tools; -import java.util.List; - +import appeng.api.implementations.items.IMemoryCard; +import appeng.api.implementations.items.MemoryCardMessages; +import appeng.api.util.AEColor; +import appeng.core.localization.GuiText; +import appeng.core.localization.PlayerMessages; +import appeng.items.AEBaseItem; +import appeng.util.Platform; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -37,193 +42,158 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.implementations.items.IMemoryCard; -import appeng.api.implementations.items.MemoryCardMessages; -import appeng.api.util.AEColor; -import appeng.core.localization.GuiText; -import appeng.core.localization.PlayerMessages; -import appeng.items.AEBaseItem; -import appeng.util.Platform; +import java.util.List; -public class ToolMemoryCard extends AEBaseItem implements IMemoryCard -{ +public class ToolMemoryCard extends AEBaseItem implements IMemoryCard { - private static final AEColor[] DEFAULT_COLOR_CODE = new AEColor[] { - AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, - AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, - }; + private static final AEColor[] DEFAULT_COLOR_CODE = new AEColor[]{ + AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, + AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, + }; - public ToolMemoryCard() - { - this.setMaxStackSize( 1 ); - } + public ToolMemoryCard() { + this.setMaxStackSize(1); + } - @Override - @SideOnly( Side.CLIENT ) - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - lines.add( this.getLocalizedName( this.getSettingsName( stack ) + ".name", this.getSettingsName( stack ) ) ); + @Override + @SideOnly(Side.CLIENT) + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + lines.add(this.getLocalizedName(this.getSettingsName(stack) + ".name", this.getSettingsName(stack))); - final NBTTagCompound data = this.getData( stack ); - if( data.hasKey( "tooltip" ) ) - { - lines.add( I18n.translateToLocal( this.getLocalizedName( data.getString( "tooltip" ) + ".name", data.getString( "tooltip" ) ) ) ); - } + final NBTTagCompound data = this.getData(stack); + if (data.hasKey("tooltip")) { + lines.add(I18n.translateToLocal(this.getLocalizedName(data.getString("tooltip") + ".name", data.getString("tooltip")))); + } - if( data.hasKey( "freq" ) ) - { - final short freq = data.getShort( "freq" ); - final String freqTooltip = TextFormatting.BOLD + Platform.p2p().toHexString( freq ); + if (data.hasKey("freq")) { + final short freq = data.getShort("freq"); + final String freqTooltip = TextFormatting.BOLD + Platform.p2p().toHexString(freq); - lines.add( I18n.translateToLocalFormatted( "gui.tooltips.appliedenergistics2.P2PFrequency", freqTooltip ) ); - } - } + lines.add(I18n.translateToLocalFormatted("gui.tooltips.appliedenergistics2.P2PFrequency", freqTooltip)); + } + } - /** - * Find the localized string... - * - * @param name possible names for the localized string - * - * @return localized name - */ - private String getLocalizedName( final String... name ) - { - for( final String n : name ) - { - final String l = I18n.translateToLocal( n ); - if( !l.equals( n ) ) - { - return l; - } - } + /** + * Find the localized string... + * + * @param name possible names for the localized string + * @return localized name + */ + private String getLocalizedName(final String... name) { + for (final String n : name) { + final String l = I18n.translateToLocal(n); + if (!l.equals(n)) { + return l; + } + } - for( final String n : name ) - { - return n; - } + for (final String n : name) { + return n; + } - return ""; - } + return ""; + } - @Override - public void setMemoryCardContents( final ItemStack is, final String settingsName, final NBTTagCompound data ) - { - final NBTTagCompound c = Platform.openNbtData( is ); - c.setString( "Config", settingsName ); - c.setTag( "Data", data ); - } + @Override + public void setMemoryCardContents(final ItemStack is, final String settingsName, final NBTTagCompound data) { + final NBTTagCompound c = Platform.openNbtData(is); + c.setString("Config", settingsName); + c.setTag("Data", data); + } - @Override - public String getSettingsName( final ItemStack is ) - { - final NBTTagCompound c = Platform.openNbtData( is ); - final String name = c.getString( "Config" ); - return name == null || name.isEmpty() ? GuiText.Blank.getUnlocalized() : name; - } + @Override + public String getSettingsName(final ItemStack is) { + final NBTTagCompound c = Platform.openNbtData(is); + final String name = c.getString("Config"); + return name == null || name.isEmpty() ? GuiText.Blank.getUnlocalized() : name; + } - @Override - public NBTTagCompound getData( final ItemStack is ) - { - final NBTTagCompound c = Platform.openNbtData( is ); - NBTTagCompound o = c.getCompoundTag( "Data" ); - if( o == null ) - { - o = new NBTTagCompound(); - } - return o.copy(); - } + @Override + public NBTTagCompound getData(final ItemStack is) { + final NBTTagCompound c = Platform.openNbtData(is); + NBTTagCompound o = c.getCompoundTag("Data"); + if (o == null) { + o = new NBTTagCompound(); + } + return o.copy(); + } - @Override - public AEColor[] getColorCode( ItemStack is ) - { - final NBTTagCompound tag = this.getData( is ); + @Override + public AEColor[] getColorCode(ItemStack is) { + final NBTTagCompound tag = this.getData(is); - if( tag.hasKey( "colorCode" ) ) - { - final int[] frequency = tag.getIntArray( "colorCode" ); - final AEColor[] colorArray = AEColor.values(); + if (tag.hasKey("colorCode")) { + final int[] frequency = tag.getIntArray("colorCode"); + final AEColor[] colorArray = AEColor.values(); - return new AEColor[] { - colorArray[frequency[0]], colorArray[frequency[1]], colorArray[frequency[2]], colorArray[frequency[3]], - colorArray[frequency[4]], colorArray[frequency[5]], colorArray[frequency[6]], colorArray[frequency[7]], - }; - } + return new AEColor[]{ + colorArray[frequency[0]], colorArray[frequency[1]], colorArray[frequency[2]], colorArray[frequency[3]], + colorArray[frequency[4]], colorArray[frequency[5]], colorArray[frequency[6]], colorArray[frequency[7]], + }; + } - return DEFAULT_COLOR_CODE; - } + return DEFAULT_COLOR_CODE; + } - @Override - public void notifyUser( final EntityPlayer player, final MemoryCardMessages msg ) - { - if( Platform.isClient() ) - { - return; - } + @Override + public void notifyUser(final EntityPlayer player, final MemoryCardMessages msg) { + if (Platform.isClient()) { + return; + } - switch( msg ) - { - case SETTINGS_CLEARED: - player.sendMessage( PlayerMessages.SettingCleared.get() ); - break; - case INVALID_MACHINE: - player.sendMessage( PlayerMessages.InvalidMachine.get() ); - break; - case SETTINGS_LOADED: - player.sendMessage( PlayerMessages.LoadedSettings.get() ); - break; - case SETTINGS_SAVED: - player.sendMessage( PlayerMessages.SavedSettings.get() ); - break; - case SETTINGS_RESET: - player.sendMessage( PlayerMessages.ResetSettings.get() ); - break; - default: - } - } + switch (msg) { + case SETTINGS_CLEARED: + player.sendMessage(PlayerMessages.SettingCleared.get()); + break; + case INVALID_MACHINE: + player.sendMessage(PlayerMessages.InvalidMachine.get()); + break; + case SETTINGS_LOADED: + player.sendMessage(PlayerMessages.LoadedSettings.get()); + break; + case SETTINGS_SAVED: + player.sendMessage(PlayerMessages.SavedSettings.get()); + break; + case SETTINGS_RESET: + player.sendMessage(PlayerMessages.ResetSettings.get()); + break; + default: + } + } - @Override - public EnumActionResult onItemUse( final EntityPlayer player, final World w, final BlockPos pos, final EnumHand hand, final EnumFacing side, final float hx, final float hy, final float hz ) - { - if( player.isSneaking() ) - { - if( !w.isRemote ) - { - this.clearCard( player, w, hand ); - } - return EnumActionResult.SUCCESS; - } - else - { - return super.onItemUse( player, w, pos, hand, side, hx, hy, hz ); - } - } + @Override + public EnumActionResult onItemUse(final EntityPlayer player, final World w, final BlockPos pos, final EnumHand hand, final EnumFacing side, final float hx, final float hy, final float hz) { + if (player.isSneaking()) { + if (!w.isRemote) { + this.clearCard(player, w, hand); + } + return EnumActionResult.SUCCESS; + } else { + return super.onItemUse(player, w, pos, hand, side, hx, hy, hz); + } + } - @Override - public ActionResult onItemRightClick( World w, EntityPlayer player, EnumHand hand ) - { - if( player.isSneaking() ) - { - if( !w.isRemote ) - { - this.clearCard( player, w, hand ); - } - } + @Override + public ActionResult onItemRightClick(World w, EntityPlayer player, EnumHand hand) { + if (player.isSneaking()) { + if (!w.isRemote) { + this.clearCard(player, w, hand); + } + } - return super.onItemRightClick( w, player, hand ); + return super.onItemRightClick(w, player, hand); - } + } - @Override - public boolean doesSneakBypassUse( final ItemStack itemstack, final IBlockAccess world, final BlockPos pos, final EntityPlayer player ) - { - return true; - } + @Override + public boolean doesSneakBypassUse(final ItemStack itemstack, final IBlockAccess world, final BlockPos pos, final EntityPlayer player) { + return true; + } - private void clearCard( final EntityPlayer player, final World w, final EnumHand hand ) - { - final IMemoryCard mem = (IMemoryCard) player.getHeldItem( hand ).getItem(); - mem.notifyUser( player, MemoryCardMessages.SETTINGS_CLEARED ); - player.getHeldItem( hand ).setTagCompound( null ); - } + private void clearCard(final EntityPlayer player, final World w, final EnumHand hand) { + final IMemoryCard mem = (IMemoryCard) player.getHeldItem(hand).getItem(); + mem.notifyUser(player, MemoryCardMessages.SETTINGS_CLEARED); + player.getHeldItem(hand).setTagCompound(null); + } } diff --git a/src/main/java/appeng/items/tools/ToolMemoryCardRendering.java b/src/main/java/appeng/items/tools/ToolMemoryCardRendering.java index e82548415..e5e37769d 100644 --- a/src/main/java/appeng/items/tools/ToolMemoryCardRendering.java +++ b/src/main/java/appeng/items/tools/ToolMemoryCardRendering.java @@ -1,28 +1,24 @@ - package appeng.items.tools; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.bootstrap.IItemRendering; import appeng.bootstrap.ItemRenderingCustomizer; import appeng.client.render.model.MemoryCardModel; import appeng.core.AppEng; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class ToolMemoryCardRendering extends ItemRenderingCustomizer -{ +public class ToolMemoryCardRendering extends ItemRenderingCustomizer { - private static final ResourceLocation MODEL = new ResourceLocation( AppEng.MOD_ID, "builtin/memory_card" ); + private static final ResourceLocation MODEL = new ResourceLocation(AppEng.MOD_ID, "builtin/memory_card"); - @Override - @SideOnly( Side.CLIENT ) - public void customize( IItemRendering rendering ) - { - rendering.builtInModel( "models/item/builtin/memory_card", new MemoryCardModel() ); - rendering.model( new ModelResourceLocation( MODEL, "inventory" ) ).variants( MODEL ); - } + @Override + @SideOnly(Side.CLIENT) + public void customize(IItemRendering rendering) { + rendering.builtInModel("models/item/builtin/memory_card", new MemoryCardModel()); + rendering.model(new ModelResourceLocation(MODEL, "inventory")).variants(MODEL); + } } diff --git a/src/main/java/appeng/items/tools/ToolNetworkTool.java b/src/main/java/appeng/items/tools/ToolNetworkTool.java index bc8badf94..4e4f95a3f 100644 --- a/src/main/java/appeng/items/tools/ToolNetworkTool.java +++ b/src/main/java/appeng/items/tools/ToolNetworkTool.java @@ -19,25 +19,6 @@ package appeng.items.tools; -import net.minecraft.block.Block; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ActionResult; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; -import net.minecraftforge.fml.common.Optional.Interface; - -import cofh.api.item.IToolHammer; - import appeng.api.implementations.guiobjects.IGuiItem; import appeng.api.implementations.guiobjects.IGuiItemObject; import appeng.api.implementations.items.IAEWrench; @@ -55,171 +36,152 @@ import appeng.core.sync.packets.PacketClick; import appeng.items.AEBaseItem; import appeng.items.contents.NetworkToolViewer; import appeng.util.Platform; +import cofh.api.item.IToolHammer; +import net.minecraft.block.Block; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.fml.common.Optional.Interface; // TODO BC Integration //@Interface( iface = "buildcraft.api.tools.IToolWrench", iname = IntegrationType.BuildCraftCore ) -@Interface( iface = "cofh.api.item.IToolHammer", modid = "cofhcore" ) -public class ToolNetworkTool extends AEBaseItem implements IGuiItem, IAEWrench, IToolHammer /* , IToolWrench */ -{ +@Interface(iface = "cofh.api.item.IToolHammer", modid = "cofhcore") +public class ToolNetworkTool extends AEBaseItem implements IGuiItem, IAEWrench, IToolHammer /* , IToolWrench */ { - public ToolNetworkTool() - { - this.setMaxStackSize( 1 ); - this.setHarvestLevel( "wrench", 0 ); - } + public ToolNetworkTool() { + this.setMaxStackSize(1); + this.setHarvestLevel("wrench", 0); + } - @Override - public IGuiItemObject getGuiObject( final ItemStack is, final World world, final BlockPos pos ) - { - final TileEntity te = world.getTileEntity( pos ); - return new NetworkToolViewer( is, (IGridHost) ( te instanceof IGridHost ? te : null ) ); - } + @Override + public IGuiItemObject getGuiObject(final ItemStack is, final World world, final BlockPos pos) { + final TileEntity te = world.getTileEntity(pos); + return new NetworkToolViewer(is, (IGridHost) (te instanceof IGridHost ? te : null)); + } - @Override - public ActionResult onItemRightClick( final World w, final EntityPlayer p, final EnumHand hand ) - { - if( Platform.isClient() ) - { - final RayTraceResult mop = AppEng.proxy.getRTR(); + @Override + public ActionResult onItemRightClick(final World w, final EntityPlayer p, final EnumHand hand) { + if (Platform.isClient()) { + final RayTraceResult mop = AppEng.proxy.getRTR(); - if( mop == null || mop.typeOfHit == RayTraceResult.Type.MISS ) - { - NetworkHandler.instance().sendToServer( new PacketClick( BlockPos.ORIGIN, null, 0, 0, 0, hand ) ); - } - } + if (mop == null || mop.typeOfHit == RayTraceResult.Type.MISS) { + NetworkHandler.instance().sendToServer(new PacketClick(BlockPos.ORIGIN, null, 0, 0, 0, hand)); + } + } - return new ActionResult<>( EnumActionResult.SUCCESS, p.getHeldItem( hand ) ); - } + return new ActionResult<>(EnumActionResult.SUCCESS, p.getHeldItem(hand)); + } - @Override - public EnumActionResult onItemUseFirst( final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand ) - { - final RayTraceResult mop = new RayTraceResult( new Vec3d( hitX, hitY, hitZ ), side, pos ); - final TileEntity te = world.getTileEntity( pos ); + @Override + public EnumActionResult onItemUseFirst(final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand) { + final RayTraceResult mop = new RayTraceResult(new Vec3d(hitX, hitY, hitZ), side, pos); + final TileEntity te = world.getTileEntity(pos); - if( te instanceof IPartHost ) - { - final SelectedPart part = ( (IPartHost) te ).selectPart( mop.hitVec ); + if (te instanceof IPartHost) { + final SelectedPart part = ((IPartHost) te).selectPart(mop.hitVec); - if( part.part != null || part.facade != null ) - { - if( part.part instanceof INetworkToolAgent && !( (INetworkToolAgent) part.part ).showNetworkInfo( mop ) ) - { - return EnumActionResult.FAIL; - } - else if( player.isSneaking() ) - { - return EnumActionResult.PASS; - } - } - } - else if( te instanceof INetworkToolAgent && !( (INetworkToolAgent) te ).showNetworkInfo( mop ) ) - { - return EnumActionResult.FAIL; - } + if (part.part != null || part.facade != null) { + if (part.part instanceof INetworkToolAgent && !((INetworkToolAgent) part.part).showNetworkInfo(mop)) { + return EnumActionResult.FAIL; + } else if (player.isSneaking()) { + return EnumActionResult.PASS; + } + } + } else if (te instanceof INetworkToolAgent && !((INetworkToolAgent) te).showNetworkInfo(mop)) { + return EnumActionResult.FAIL; + } - if( Platform.isClient() ) - { - NetworkHandler.instance().sendToServer( new PacketClick( pos, side, hitX, hitY, hitZ, hand ) ); - } + if (Platform.isClient()) { + NetworkHandler.instance().sendToServer(new PacketClick(pos, side, hitX, hitY, hitZ, hand)); + } - return EnumActionResult.SUCCESS; - } + return EnumActionResult.SUCCESS; + } - @Override - public boolean doesSneakBypassUse( final ItemStack itemstack, final IBlockAccess world, final BlockPos pos, final EntityPlayer player ) - { - return true; - } + @Override + public boolean doesSneakBypassUse(final ItemStack itemstack, final IBlockAccess world, final BlockPos pos, final EntityPlayer player) { + return true; + } - public boolean serverSideToolLogic( final ItemStack is, final EntityPlayer p, final EnumHand hand, final World w, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( side != null ) - { - if( !Platform.hasPermissions( new DimensionalCoord( w, pos ), p ) ) - { - return false; - } + public boolean serverSideToolLogic(final ItemStack is, final EntityPlayer p, final EnumHand hand, final World w, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (side != null) { + if (!Platform.hasPermissions(new DimensionalCoord(w, pos), p)) { + return false; + } - final Block b = w.getBlockState( pos ).getBlock(); - if( !p.isSneaking() ) - { - final TileEntity te = w.getTileEntity( pos ); - if( !( te instanceof IGridHost ) ) - { - if( b.rotateBlock( w, pos, side ) ) - { - b.neighborChanged( Platform.AIR_BLOCK.getDefaultState(), w, pos, Platform.AIR_BLOCK, null ); - p.swingArm( hand ); - return !w.isRemote; - } - } - } + final Block b = w.getBlockState(pos).getBlock(); + if (!p.isSneaking()) { + final TileEntity te = w.getTileEntity(pos); + if (!(te instanceof IGridHost)) { + if (b.rotateBlock(w, pos, side)) { + b.neighborChanged(Platform.AIR_BLOCK.getDefaultState(), w, pos, Platform.AIR_BLOCK, null); + p.swingArm(hand); + return !w.isRemote; + } + } + } - if( !p.isSneaking() ) - { - if( p.openContainer instanceof AEBaseContainer ) - { - return true; - } + if (!p.isSneaking()) { + if (p.openContainer instanceof AEBaseContainer) { + return true; + } - final TileEntity te = w.getTileEntity( pos ); + final TileEntity te = w.getTileEntity(pos); - if( te instanceof IGridHost ) - { - Platform.openGUI( p, te, AEPartLocation.fromFacing( side ), GuiBridge.GUI_NETWORK_STATUS ); - } - else - { - Platform.openGUI( p, null, AEPartLocation.INTERNAL, GuiBridge.GUI_NETWORK_TOOL ); - } + if (te instanceof IGridHost) { + Platform.openGUI(p, te, AEPartLocation.fromFacing(side), GuiBridge.GUI_NETWORK_STATUS); + } else { + Platform.openGUI(p, null, AEPartLocation.INTERNAL, GuiBridge.GUI_NETWORK_TOOL); + } - return true; - } - else - { - b.onBlockActivated( w, pos, w.getBlockState( pos ), p, hand, side, hitX, hitY, hitZ ); - } - } - else - { - Platform.openGUI( p, null, AEPartLocation.INTERNAL, GuiBridge.GUI_NETWORK_TOOL ); - } + return true; + } else { + b.onBlockActivated(w, pos, w.getBlockState(pos), p, hand, side, hitX, hitY, hitZ); + } + } else { + Platform.openGUI(p, null, AEPartLocation.INTERNAL, GuiBridge.GUI_NETWORK_TOOL); + } - return false; - } + return false; + } - @Override - public boolean canWrench( final ItemStack wrench, final EntityPlayer player, final BlockPos pos ) - { - return true; - } + @Override + public boolean canWrench(final ItemStack wrench, final EntityPlayer player, final BlockPos pos) { + return true; + } - // IToolHammer - start - @Override - public boolean isUsable( ItemStack item, EntityLivingBase user, BlockPos pos ) - { - return true; - } + // IToolHammer - start + @Override + public boolean isUsable(ItemStack item, EntityLivingBase user, BlockPos pos) { + return true; + } - @Override - public boolean isUsable( ItemStack item, EntityLivingBase user, Entity entity ) - { - return true; - } + @Override + public boolean isUsable(ItemStack item, EntityLivingBase user, Entity entity) { + return true; + } - @Override - public void toolUsed( ItemStack item, EntityLivingBase user, BlockPos pos ) - { - } + @Override + public void toolUsed(ItemStack item, EntityLivingBase user, BlockPos pos) { + } - @Override - public void toolUsed( ItemStack item, EntityLivingBase user, Entity entity ) - { - } - // IToolHammer - end + @Override + public void toolUsed(ItemStack item, EntityLivingBase user, Entity entity) { + } + // IToolHammer - end - // TODO: BC WRENCH INTEGRATION + // TODO: BC WRENCH INTEGRATION } diff --git a/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java b/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java index df6efe057..6506c4bed 100644 --- a/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java +++ b/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java @@ -19,48 +19,41 @@ package appeng.items.tools.powered; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.item.ItemStack; -import net.minecraft.util.DamageSource; -import net.minecraft.util.math.AxisAlignedBB; - import appeng.api.config.Actionable; import appeng.core.AEConfig; import appeng.core.AppEng; import appeng.core.sync.packets.PacketLightning; import appeng.items.tools.powered.powersink.AEBasePoweredItem; import appeng.util.Platform; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.item.ItemStack; +import net.minecraft.util.DamageSource; +import net.minecraft.util.math.AxisAlignedBB; -public class ToolChargedStaff extends AEBasePoweredItem -{ +public class ToolChargedStaff extends AEBasePoweredItem { - public ToolChargedStaff() - { - super( AEConfig.instance().getChargedStaffBattery() ); - } + public ToolChargedStaff() { + super(AEConfig.instance().getChargedStaffBattery()); + } - @Override - public boolean hitEntity( final ItemStack item, final EntityLivingBase target, final EntityLivingBase hitter ) - { - if( this.getAECurrentPower( item ) > 300 ) - { - this.extractAEPower( item, 300, Actionable.MODULATE ); - if( Platform.isServer() ) - { - for( int x = 0; x < 2; x++ ) - { - final AxisAlignedBB entityBoundingBox = target.getEntityBoundingBox(); - final float dx = (float) ( Platform.getRandomFloat() * target.width + entityBoundingBox.minX ); - final float dy = (float) ( Platform.getRandomFloat() * target.height + entityBoundingBox.minY ); - final float dz = (float) ( Platform.getRandomFloat() * target.width + entityBoundingBox.minZ ); - AppEng.proxy.sendToAllNearExcept( null, dx, dy, dz, 32.0, target.world, new PacketLightning( dx, dy, dz ) ); - } - } - target.attackEntityFrom( DamageSource.MAGIC, 6 ); - return true; - } + @Override + public boolean hitEntity(final ItemStack item, final EntityLivingBase target, final EntityLivingBase hitter) { + if (this.getAECurrentPower(item) > 300) { + this.extractAEPower(item, 300, Actionable.MODULATE); + if (Platform.isServer()) { + for (int x = 0; x < 2; x++) { + final AxisAlignedBB entityBoundingBox = target.getEntityBoundingBox(); + final float dx = (float) (Platform.getRandomFloat() * target.width + entityBoundingBox.minX); + final float dy = (float) (Platform.getRandomFloat() * target.height + entityBoundingBox.minY); + final float dz = (float) (Platform.getRandomFloat() * target.width + entityBoundingBox.minZ); + AppEng.proxy.sendToAllNearExcept(null, dx, dy, dz, 32.0, target.world, new PacketLightning(dx, dy, dz)); + } + } + target.attackEntityFrom(DamageSource.MAGIC, 6); + return true; + } - return false; - } + return false; + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java b/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java index 766eb9c4c..9ecb0c04d 100644 --- a/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java +++ b/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java @@ -19,38 +19,6 @@ package appeng.items.tools.powered; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang3.text.WordUtils; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockColored; -import net.minecraft.block.BlockStainedGlass; -import net.minecraft.block.BlockStainedGlassPane; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.item.EnumDyeColor; -import net.minecraft.item.ItemSnowball; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.oredict.OreDictionary; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.FuzzyMode; @@ -79,477 +47,413 @@ import appeng.me.helpers.BaseActionSource; import appeng.tile.misc.TilePaint; import appeng.util.Platform; import appeng.util.item.AEItemStack; - - -public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCell, IItemGroup, IBlockTool, IMouseWheelItem -{ - - private static final Map ORE_TO_COLOR = new HashMap<>(); - - static - { - for( final AEColor color : AEColor.VALID_COLORS ) - { - final String dyeName = color.dye.getUnlocalizedName(); - final String oreDictName = "dye" + WordUtils.capitalize( dyeName ); - final int oreDictId = OreDictionary.getOreID( oreDictName ); - - ORE_TO_COLOR.put( oreDictId, color ); - } - } - - public ToolColorApplicator() - { - super( AEConfig.instance().getColorApplicatorBattery() ); - } - - @Override - public EnumActionResult onItemUse( EntityPlayer p, World w, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ ) - { - return this.onItemUse( p.getHeldItem( hand ), p, w, pos, hand, side, hitX, hitY, hitZ ); - } - - @Override - public EnumActionResult onItemUse( ItemStack is, EntityPlayer p, World w, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ ) - { - final Block blk = w.getBlockState( pos ).getBlock(); - - ItemStack paintBall = this.getColor( is ); - - final IMEInventory inv = AEApi.instance() - .registries() - .cell() - .getCellInventory( is, null, - AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - if( inv != null ) - { - final IAEItemStack option = inv.extractItems( AEItemStack.fromItemStack( paintBall ), Actionable.SIMULATE, new BaseActionSource() ); - - if( option != null ) - { - paintBall = option.createItemStack(); - paintBall.setCount( 1 ); - } - else - { - paintBall = ItemStack.EMPTY; - } - - if( !Platform.hasPermissions( new DimensionalCoord( w, pos ), p ) ) - { - return EnumActionResult.FAIL; - } - - final double powerPerUse = 100; - if( !paintBall.isEmpty() && paintBall.getItem() instanceof ItemSnowball ) - { - final TileEntity te = w.getTileEntity( pos ); - // clean cables. - if( te instanceof IColorableTile ) - { - if( this.getAECurrentPower( is ) > powerPerUse && ( (IColorableTile) te ).getColor() != AEColor.TRANSPARENT ) - { - if( ( (IColorableTile) te ).recolourBlock( side, AEColor.TRANSPARENT, p ) ) - { - inv.extractItems( AEItemStack.fromItemStack( paintBall ), Actionable.MODULATE, new BaseActionSource() ); - this.extractAEPower( is, powerPerUse, Actionable.MODULATE ); - return EnumActionResult.SUCCESS; - } - } - } - - // clean paint balls.. - final Block testBlk = w.getBlockState( pos.offset( side ) ).getBlock(); - final TileEntity painted = w.getTileEntity( pos.offset( side ) ); - if( this.getAECurrentPower( is ) > powerPerUse && testBlk instanceof BlockPaint && painted instanceof TilePaint ) - { - inv.extractItems( AEItemStack.fromItemStack( paintBall ), Actionable.MODULATE, new BaseActionSource() ); - this.extractAEPower( is, powerPerUse, Actionable.MODULATE ); - ( (TilePaint) painted ).cleanSide( side.getOpposite() ); - return EnumActionResult.SUCCESS; - } - } - else if( !paintBall.isEmpty() ) - { - final AEColor color = this.getColorFromItem( paintBall ); - - if( color != null && this.getAECurrentPower( is ) > powerPerUse ) - { - if( color != AEColor.TRANSPARENT && this.recolourBlock( blk, side, w, pos, side, color, p ) ) - { - inv.extractItems( AEItemStack.fromItemStack( paintBall ), Actionable.MODULATE, new BaseActionSource() ); - this.extractAEPower( is, powerPerUse, Actionable.MODULATE ); - return EnumActionResult.SUCCESS; - } - } - } - } - - if( p.isSneaking() ) - { - this.cycleColors( is, paintBall, 1 ); - } - - return EnumActionResult.FAIL; - } - - @Override - public String getItemStackDisplayName( final ItemStack par1ItemStack ) - { - String extra = GuiText.Empty.getLocal(); - - final AEColor selected = this.getActiveColor( par1ItemStack ); - - if( selected != null && Platform.isClient() ) - { - extra = Platform.gui_localize( selected.unlocalizedName ); - } - - return super.getItemStackDisplayName( par1ItemStack ) + " - " + extra; - } - - public AEColor getActiveColor( final ItemStack tol ) - { - return this.getColorFromItem( this.getColor( tol ) ); - } - - private AEColor getColorFromItem( final ItemStack paintBall ) - { - if( paintBall.isEmpty() ) - { - return null; - } - - if( paintBall.getItem() instanceof ItemSnowball ) - { - return AEColor.TRANSPARENT; - } - - if( paintBall.getItem() instanceof ItemPaintBall ) - { - final ItemPaintBall ipb = (ItemPaintBall) paintBall.getItem(); - return ipb.getColor( paintBall ); - } - else - { - final int[] id = OreDictionary.getOreIDs( paintBall ); - - for( final int oreID : id ) - { - if( ORE_TO_COLOR.containsKey( oreID ) ) - { - return ORE_TO_COLOR.get( oreID ); - } - } - } - - return null; - } - - public ItemStack getColor( final ItemStack is ) - { - final NBTTagCompound c = is.getTagCompound(); - if( c != null && c.hasKey( "color" ) ) - { - final NBTTagCompound color = c.getCompoundTag( "color" ); - final ItemStack oldColor = new ItemStack( color ); - if( !oldColor.isEmpty() ) - { - return oldColor; - } - } - - return this.findNextColor( is, ItemStack.EMPTY, 0 ); - } - - private ItemStack findNextColor( final ItemStack is, final ItemStack anchor, final int scrollOffset ) - { - ItemStack newColor = ItemStack.EMPTY; - - final IMEInventory inv = AEApi.instance() - .registries() - .cell() - .getCellInventory( is, null, - AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - if( inv != null ) - { - final IItemList itemList = inv - .getAvailableItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList() ); - if( anchor.isEmpty() ) - { - final IAEItemStack firstItem = itemList.getFirstItem(); - if( firstItem != null ) - { - newColor = firstItem.asItemStackRepresentation(); - } - } - else - { - final LinkedList list = new LinkedList<>(); - - for( final IAEItemStack i : itemList ) - { - list.add( i ); - } - - Collections.sort( list, ( a, b ) -> Integer.compare( a.getItemDamage(), b.getItemDamage() ) ); - - if( list.size() <= 0 ) - { - return ItemStack.EMPTY; - } - - IAEItemStack where = list.getFirst(); - int cycles = 1 + list.size(); - - while( cycles > 0 && !where.equals( anchor ) ) - { - list.addLast( list.removeFirst() ); - cycles--; - where = list.getFirst(); - } - - if( scrollOffset > 0 ) - { - list.addLast( list.removeFirst() ); - } - - if( scrollOffset < 0 ) - { - list.addFirst( list.removeLast() ); - } - - return list.get( 0 ).asItemStackRepresentation(); - } - } - - if( !newColor.isEmpty() ) - { - this.setColor( is, newColor ); - } - - return newColor; - } - - private void setColor( final ItemStack is, final ItemStack newColor ) - { - final NBTTagCompound data = Platform.openNbtData( is ); - if( newColor.isEmpty() ) - { - data.removeTag( "color" ); - } - else - { - final NBTTagCompound color = new NBTTagCompound(); - newColor.writeToNBT( color ); - data.setTag( "color", color ); - } - } - - private boolean recolourBlock( final Block blk, final EnumFacing side, final World w, final BlockPos pos, final EnumFacing orientation, final AEColor newColor, final EntityPlayer p ) - { - final IBlockState state = w.getBlockState( pos ); - - if( blk instanceof BlockColored ) - { - final EnumDyeColor color = state.getValue( BlockColored.COLOR ); - - if( newColor.dye == color ) - { - return false; - } - - return w.setBlockState( pos, state.withProperty( BlockColored.COLOR, newColor.dye ) ); - } - - if( blk == Blocks.GLASS ) - { - return w.setBlockState( pos, Blocks.STAINED_GLASS.getDefaultState().withProperty( BlockStainedGlass.COLOR, newColor.dye ) ); - } - - if( blk == Blocks.STAINED_GLASS ) - { - final EnumDyeColor color = state.getValue( BlockStainedGlass.COLOR ); - - if( newColor.dye == color ) - { - return false; - } - - return w.setBlockState( pos, state.withProperty( BlockStainedGlass.COLOR, newColor.dye ) ); - } - - if( blk == Blocks.GLASS_PANE ) - { - return w.setBlockState( pos, Blocks.STAINED_GLASS_PANE.getDefaultState().withProperty( BlockStainedGlassPane.COLOR, newColor.dye ) ); - } - - if( blk == Blocks.STAINED_GLASS_PANE ) - { - final EnumDyeColor color = state.getValue( BlockStainedGlassPane.COLOR ); - - if( newColor.dye == color ) - { - return false; - } - - return w.setBlockState( pos, state.withProperty( BlockStainedGlassPane.COLOR, newColor.dye ) ); - } - - if( blk == Blocks.HARDENED_CLAY ) - { - return w.setBlockState( pos, Blocks.STAINED_HARDENED_CLAY.getDefaultState().withProperty( BlockColored.COLOR, newColor.dye ) ); - } - - if( blk instanceof BlockCableBus ) - { - return ( (BlockCableBus) blk ).recolorBlock( w, pos, side, newColor.dye, p ); - } - - return blk.recolorBlock( w, pos, side, newColor.dye ); - } - - public void cycleColors( final ItemStack is, final ItemStack paintBall, final int i ) - { - if( paintBall.isEmpty() ) - { - this.setColor( is, this.getColor( is ) ); - } - else - { - this.setColor( is, this.findNextColor( is, paintBall, i ) ); - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - super.addCheckedInformation( stack, world, lines, advancedTooltips ); - - final ICellInventoryHandler cdi = AEApi.instance() - .registries() - .cell() - .getCellInventory( stack, null, - AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - - AEApi.instance().client().addCellInformation( cdi, lines ); - } - - @Override - public int getBytes( final ItemStack cellItem ) - { - return 512; - } - - @Override - public int getBytesPerType( final ItemStack cellItem ) - { - return 8; - } - - @Override - public int getTotalTypes( final ItemStack cellItem ) - { - return 27; - } - - @Override - public boolean isBlackListed( final ItemStack cellItem, final IAEItemStack requestedAddition ) - { - if( requestedAddition != null ) - { - final int[] id = OreDictionary.getOreIDs( requestedAddition.getDefinition() ); - - for( final int x : id ) - { - if( ORE_TO_COLOR.containsKey( x ) ) - { - return false; - } - } - - if( requestedAddition.getItem() instanceof ItemSnowball ) - { - return false; - } - - return !( requestedAddition.getItem() instanceof ItemPaintBall && requestedAddition.getItemDamage() < 20 ); - } - return true; - } - - @Override - public boolean storableInStorageCell() - { - return true; - } - - @Override - public boolean isStorageCell( final ItemStack i ) - { - return true; - } - - @Override - public double getIdleDrain() - { - return 0.5; - } - - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } - - @Override - public String getUnlocalizedGroupName( final Set others, final ItemStack is ) - { - return GuiText.StorageCells.getUnlocalized(); - } - - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } - - @Override - public IItemHandler getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 2 ); - } - - @Override - public IItemHandler getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } - - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } - - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } - - @Override - public void onWheel( final ItemStack is, final boolean up ) - { - this.cycleColors( is, this.getColor( is ), up ? 1 : -1 ); - } +import net.minecraft.block.Block; +import net.minecraft.block.BlockColored; +import net.minecraft.block.BlockStainedGlass; +import net.minecraft.block.BlockStainedGlassPane; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.item.EnumDyeColor; +import net.minecraft.item.ItemSnowball; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.oredict.OreDictionary; +import org.apache.commons.lang3.text.WordUtils; + +import java.util.*; + + +public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCell, IItemGroup, IBlockTool, IMouseWheelItem { + + private static final Map ORE_TO_COLOR = new HashMap<>(); + + static { + for (final AEColor color : AEColor.VALID_COLORS) { + final String dyeName = color.dye.getUnlocalizedName(); + final String oreDictName = "dye" + WordUtils.capitalize(dyeName); + final int oreDictId = OreDictionary.getOreID(oreDictName); + + ORE_TO_COLOR.put(oreDictId, color); + } + } + + public ToolColorApplicator() { + super(AEConfig.instance().getColorApplicatorBattery()); + } + + @Override + public EnumActionResult onItemUse(EntityPlayer p, World w, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { + return this.onItemUse(p.getHeldItem(hand), p, w, pos, hand, side, hitX, hitY, hitZ); + } + + @Override + public EnumActionResult onItemUse(ItemStack is, EntityPlayer p, World w, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { + final Block blk = w.getBlockState(pos).getBlock(); + + ItemStack paintBall = this.getColor(is); + + final IMEInventory inv = AEApi.instance() + .registries() + .cell() + .getCellInventory(is, null, + AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + if (inv != null) { + final IAEItemStack option = inv.extractItems(AEItemStack.fromItemStack(paintBall), Actionable.SIMULATE, new BaseActionSource()); + + if (option != null) { + paintBall = option.createItemStack(); + paintBall.setCount(1); + } else { + paintBall = ItemStack.EMPTY; + } + + if (!Platform.hasPermissions(new DimensionalCoord(w, pos), p)) { + return EnumActionResult.FAIL; + } + + final double powerPerUse = 100; + if (!paintBall.isEmpty() && paintBall.getItem() instanceof ItemSnowball) { + final TileEntity te = w.getTileEntity(pos); + // clean cables. + if (te instanceof IColorableTile) { + if (this.getAECurrentPower(is) > powerPerUse && ((IColorableTile) te).getColor() != AEColor.TRANSPARENT) { + if (((IColorableTile) te).recolourBlock(side, AEColor.TRANSPARENT, p)) { + inv.extractItems(AEItemStack.fromItemStack(paintBall), Actionable.MODULATE, new BaseActionSource()); + this.extractAEPower(is, powerPerUse, Actionable.MODULATE); + return EnumActionResult.SUCCESS; + } + } + } + + // clean paint balls.. + final Block testBlk = w.getBlockState(pos.offset(side)).getBlock(); + final TileEntity painted = w.getTileEntity(pos.offset(side)); + if (this.getAECurrentPower(is) > powerPerUse && testBlk instanceof BlockPaint && painted instanceof TilePaint) { + inv.extractItems(AEItemStack.fromItemStack(paintBall), Actionable.MODULATE, new BaseActionSource()); + this.extractAEPower(is, powerPerUse, Actionable.MODULATE); + ((TilePaint) painted).cleanSide(side.getOpposite()); + return EnumActionResult.SUCCESS; + } + } else if (!paintBall.isEmpty()) { + final AEColor color = this.getColorFromItem(paintBall); + + if (color != null && this.getAECurrentPower(is) > powerPerUse) { + if (color != AEColor.TRANSPARENT && this.recolourBlock(blk, side, w, pos, side, color, p)) { + inv.extractItems(AEItemStack.fromItemStack(paintBall), Actionable.MODULATE, new BaseActionSource()); + this.extractAEPower(is, powerPerUse, Actionable.MODULATE); + return EnumActionResult.SUCCESS; + } + } + } + } + + if (p.isSneaking()) { + this.cycleColors(is, paintBall, 1); + } + + return EnumActionResult.FAIL; + } + + @Override + public String getItemStackDisplayName(final ItemStack par1ItemStack) { + String extra = GuiText.Empty.getLocal(); + + final AEColor selected = this.getActiveColor(par1ItemStack); + + if (selected != null && Platform.isClient()) { + extra = Platform.gui_localize(selected.unlocalizedName); + } + + return super.getItemStackDisplayName(par1ItemStack) + " - " + extra; + } + + public AEColor getActiveColor(final ItemStack tol) { + return this.getColorFromItem(this.getColor(tol)); + } + + private AEColor getColorFromItem(final ItemStack paintBall) { + if (paintBall.isEmpty()) { + return null; + } + + if (paintBall.getItem() instanceof ItemSnowball) { + return AEColor.TRANSPARENT; + } + + if (paintBall.getItem() instanceof ItemPaintBall) { + final ItemPaintBall ipb = (ItemPaintBall) paintBall.getItem(); + return ipb.getColor(paintBall); + } else { + final int[] id = OreDictionary.getOreIDs(paintBall); + + for (final int oreID : id) { + if (ORE_TO_COLOR.containsKey(oreID)) { + return ORE_TO_COLOR.get(oreID); + } + } + } + + return null; + } + + public ItemStack getColor(final ItemStack is) { + final NBTTagCompound c = is.getTagCompound(); + if (c != null && c.hasKey("color")) { + final NBTTagCompound color = c.getCompoundTag("color"); + final ItemStack oldColor = new ItemStack(color); + if (!oldColor.isEmpty()) { + return oldColor; + } + } + + return this.findNextColor(is, ItemStack.EMPTY, 0); + } + + private ItemStack findNextColor(final ItemStack is, final ItemStack anchor, final int scrollOffset) { + ItemStack newColor = ItemStack.EMPTY; + + final IMEInventory inv = AEApi.instance() + .registries() + .cell() + .getCellInventory(is, null, + AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + if (inv != null) { + final IItemList itemList = inv + .getAvailableItems(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList()); + if (anchor.isEmpty()) { + final IAEItemStack firstItem = itemList.getFirstItem(); + if (firstItem != null) { + newColor = firstItem.asItemStackRepresentation(); + } + } else { + final LinkedList list = new LinkedList<>(); + + for (final IAEItemStack i : itemList) { + list.add(i); + } + + Collections.sort(list, (a, b) -> Integer.compare(a.getItemDamage(), b.getItemDamage())); + + if (list.size() <= 0) { + return ItemStack.EMPTY; + } + + IAEItemStack where = list.getFirst(); + int cycles = 1 + list.size(); + + while (cycles > 0 && !where.equals(anchor)) { + list.addLast(list.removeFirst()); + cycles--; + where = list.getFirst(); + } + + if (scrollOffset > 0) { + list.addLast(list.removeFirst()); + } + + if (scrollOffset < 0) { + list.addFirst(list.removeLast()); + } + + return list.get(0).asItemStackRepresentation(); + } + } + + if (!newColor.isEmpty()) { + this.setColor(is, newColor); + } + + return newColor; + } + + private void setColor(final ItemStack is, final ItemStack newColor) { + final NBTTagCompound data = Platform.openNbtData(is); + if (newColor.isEmpty()) { + data.removeTag("color"); + } else { + final NBTTagCompound color = new NBTTagCompound(); + newColor.writeToNBT(color); + data.setTag("color", color); + } + } + + private boolean recolourBlock(final Block blk, final EnumFacing side, final World w, final BlockPos pos, final EnumFacing orientation, final AEColor newColor, final EntityPlayer p) { + final IBlockState state = w.getBlockState(pos); + + if (blk instanceof BlockColored) { + final EnumDyeColor color = state.getValue(BlockColored.COLOR); + + if (newColor.dye == color) { + return false; + } + + return w.setBlockState(pos, state.withProperty(BlockColored.COLOR, newColor.dye)); + } + + if (blk == Blocks.GLASS) { + return w.setBlockState(pos, Blocks.STAINED_GLASS.getDefaultState().withProperty(BlockStainedGlass.COLOR, newColor.dye)); + } + + if (blk == Blocks.STAINED_GLASS) { + final EnumDyeColor color = state.getValue(BlockStainedGlass.COLOR); + + if (newColor.dye == color) { + return false; + } + + return w.setBlockState(pos, state.withProperty(BlockStainedGlass.COLOR, newColor.dye)); + } + + if (blk == Blocks.GLASS_PANE) { + return w.setBlockState(pos, Blocks.STAINED_GLASS_PANE.getDefaultState().withProperty(BlockStainedGlassPane.COLOR, newColor.dye)); + } + + if (blk == Blocks.STAINED_GLASS_PANE) { + final EnumDyeColor color = state.getValue(BlockStainedGlassPane.COLOR); + + if (newColor.dye == color) { + return false; + } + + return w.setBlockState(pos, state.withProperty(BlockStainedGlassPane.COLOR, newColor.dye)); + } + + if (blk == Blocks.HARDENED_CLAY) { + return w.setBlockState(pos, Blocks.STAINED_HARDENED_CLAY.getDefaultState().withProperty(BlockColored.COLOR, newColor.dye)); + } + + if (blk instanceof BlockCableBus) { + return ((BlockCableBus) blk).recolorBlock(w, pos, side, newColor.dye, p); + } + + return blk.recolorBlock(w, pos, side, newColor.dye); + } + + public void cycleColors(final ItemStack is, final ItemStack paintBall, final int i) { + if (paintBall.isEmpty()) { + this.setColor(is, this.getColor(is)); + } else { + this.setColor(is, this.findNextColor(is, paintBall, i)); + } + } + + @Override + @SideOnly(Side.CLIENT) + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + super.addCheckedInformation(stack, world, lines, advancedTooltips); + + final ICellInventoryHandler cdi = AEApi.instance() + .registries() + .cell() + .getCellInventory(stack, null, + AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + + AEApi.instance().client().addCellInformation(cdi, lines); + } + + @Override + public int getBytes(final ItemStack cellItem) { + return 512; + } + + @Override + public int getBytesPerType(final ItemStack cellItem) { + return 8; + } + + @Override + public int getTotalTypes(final ItemStack cellItem) { + return 27; + } + + @Override + public boolean isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) { + if (requestedAddition != null) { + final int[] id = OreDictionary.getOreIDs(requestedAddition.getDefinition()); + + for (final int x : id) { + if (ORE_TO_COLOR.containsKey(x)) { + return false; + } + } + + if (requestedAddition.getItem() instanceof ItemSnowball) { + return false; + } + + return !(requestedAddition.getItem() instanceof ItemPaintBall && requestedAddition.getItemDamage() < 20); + } + return true; + } + + @Override + public boolean storableInStorageCell() { + return true; + } + + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } + + @Override + public double getIdleDrain() { + return 0.5; + } + + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } + + @Override + public String getUnlocalizedGroupName(final Set others, final ItemStack is) { + return GuiText.StorageCells.getUnlocalized(); + } + + @Override + public boolean isEditable(final ItemStack is) { + return true; + } + + @Override + public IItemHandler getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 2); + } + + @Override + public IItemHandler getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } + + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } + + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } + + @Override + public void onWheel(final ItemStack is, final boolean up) { + this.cycleColors(is, this.getColor(is), up ? 1 : -1); + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolColorApplicatorRendering.java b/src/main/java/appeng/items/tools/powered/ToolColorApplicatorRendering.java index d3596e012..b2bdda78d 100644 --- a/src/main/java/appeng/items/tools/powered/ToolColorApplicatorRendering.java +++ b/src/main/java/appeng/items/tools/powered/ToolColorApplicatorRendering.java @@ -1,69 +1,60 @@ - package appeng.items.tools.powered; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import appeng.api.util.AEColor; import appeng.bootstrap.IItemRendering; import appeng.bootstrap.ItemRenderingCustomizer; import appeng.client.render.model.ColorApplicatorModel; import appeng.core.AppEng; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class ToolColorApplicatorRendering extends ItemRenderingCustomizer -{ +public class ToolColorApplicatorRendering extends ItemRenderingCustomizer { - private static final ModelResourceLocation MODEL_COLORED = new ModelResourceLocation( new ResourceLocation( AppEng.MOD_ID, "builtin/color_applicator_colored" ), "inventory" ); - private static final ModelResourceLocation MODEL_UNCOLORED = new ModelResourceLocation( new ResourceLocation( AppEng.MOD_ID, "color_applicator_uncolored" ), "inventory" ); + private static final ModelResourceLocation MODEL_COLORED = new ModelResourceLocation(new ResourceLocation(AppEng.MOD_ID, "builtin/color_applicator_colored"), "inventory"); + private static final ModelResourceLocation MODEL_UNCOLORED = new ModelResourceLocation(new ResourceLocation(AppEng.MOD_ID, "color_applicator_uncolored"), "inventory"); - @Override - @SideOnly( Side.CLIENT ) - public void customize( IItemRendering rendering ) - { - rendering.builtInModel( "models/item/builtin/color_applicator_colored", new ColorApplicatorModel() ); - rendering.variants( MODEL_COLORED, MODEL_UNCOLORED ); - rendering.color( this::getColor ); - rendering.meshDefinition( this::getMesh ); - } + @Override + @SideOnly(Side.CLIENT) + public void customize(IItemRendering rendering) { + rendering.builtInModel("models/item/builtin/color_applicator_colored", new ColorApplicatorModel()); + rendering.variants(MODEL_COLORED, MODEL_UNCOLORED); + rendering.color(this::getColor); + rendering.meshDefinition(this::getMesh); + } - private ModelResourceLocation getMesh( ItemStack itemStack ) - { - // If the stack has no color, don't use the colored model since the impact of calling getColor for every quad is - // extremely high, - // if the stack tries to re-search its inventory for a new paintball everytime - AEColor col = ( (ToolColorApplicator) itemStack.getItem() ).getActiveColor( itemStack ); - return ( col != null ) ? MODEL_COLORED : MODEL_UNCOLORED; - } + private ModelResourceLocation getMesh(ItemStack itemStack) { + // If the stack has no color, don't use the colored model since the impact of calling getColor for every quad is + // extremely high, + // if the stack tries to re-search its inventory for a new paintball everytime + AEColor col = ((ToolColorApplicator) itemStack.getItem()).getActiveColor(itemStack); + return (col != null) ? MODEL_COLORED : MODEL_UNCOLORED; + } - private int getColor( ItemStack itemStack, int idx ) - { - if( idx == 0 ) - { - return -1; - } + private int getColor(ItemStack itemStack, int idx) { + if (idx == 0) { + return -1; + } - final AEColor col = ( (ToolColorApplicator) itemStack.getItem() ).getActiveColor( itemStack ); + final AEColor col = ((ToolColorApplicator) itemStack.getItem()).getActiveColor(itemStack); - if( col == null ) - { - return -1; - } + if (col == null) { + return -1; + } - switch( idx ) - { - case 1: - return col.blackVariant; - case 2: - return col.mediumVariant; - case 3: - return col.whiteVariant; - default: - return -1; - } - } + switch (idx) { + case 1: + return col.blackVariant; + case 2: + return col.mediumVariant; + case 3: + return col.whiteVariant; + default: + return -1; + } + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java b/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java index f45e151e6..ada1424ac 100644 --- a/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java +++ b/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java @@ -19,11 +19,14 @@ package appeng.items.tools.powered; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import appeng.api.config.Actionable; +import appeng.api.util.DimensionalCoord; +import appeng.block.misc.BlockTinyTNT; +import appeng.core.AEConfig; +import appeng.hooks.IBlockTool; +import appeng.items.tools.powered.powersink.AEBasePoweredItem; +import appeng.util.InWorldToolOperationResult; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.BlockTNT; import net.minecraft.block.material.Material; @@ -36,333 +39,265 @@ import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; -import net.minecraft.util.ActionResult; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.SoundCategory; +import net.minecraft.util.*; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; -import appeng.api.config.Actionable; -import appeng.api.util.DimensionalCoord; -import appeng.block.misc.BlockTinyTNT; -import appeng.core.AEConfig; -import appeng.hooks.IBlockTool; -import appeng.items.tools.powered.powersink.AEBasePoweredItem; -import appeng.util.InWorldToolOperationResult; -import appeng.util.Platform; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; -public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockTool -{ - private final Map heatUp; - private final Map coolDown; +public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockTool { + private final Map heatUp; + private final Map coolDown; - public ToolEntropyManipulator() - { - super( AEConfig.instance().getEntropyManipulatorBattery() ); + public ToolEntropyManipulator() { + super(AEConfig.instance().getEntropyManipulatorBattery()); - this.heatUp = new HashMap<>(); - this.coolDown = new HashMap<>(); + this.heatUp = new HashMap<>(); + this.coolDown = new HashMap<>(); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.STONE.getDefaultState() ), - new InWorldToolOperationResult( Blocks.COBBLESTONE.getDefaultState() ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.STONEBRICK.getDefaultState() ), - new InWorldToolOperationResult( Blocks.STONEBRICK.getStateFromMeta( 2 ) ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.LAVA, true ), new InWorldToolOperationResult( Blocks.OBSIDIAN.getDefaultState() ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.FLOWING_LAVA, true ), - new InWorldToolOperationResult( Blocks.OBSIDIAN.getDefaultState() ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.GRASS, true ), new InWorldToolOperationResult( Blocks.DIRT.getDefaultState() ) ); + this.coolDown.put(new InWorldToolOperationIngredient(Blocks.STONE.getDefaultState()), + new InWorldToolOperationResult(Blocks.COBBLESTONE.getDefaultState())); + this.coolDown.put(new InWorldToolOperationIngredient(Blocks.STONEBRICK.getDefaultState()), + new InWorldToolOperationResult(Blocks.STONEBRICK.getStateFromMeta(2))); + this.coolDown.put(new InWorldToolOperationIngredient(Blocks.LAVA, true), new InWorldToolOperationResult(Blocks.OBSIDIAN.getDefaultState())); + this.coolDown.put(new InWorldToolOperationIngredient(Blocks.FLOWING_LAVA, true), + new InWorldToolOperationResult(Blocks.OBSIDIAN.getDefaultState())); + this.coolDown.put(new InWorldToolOperationIngredient(Blocks.GRASS, true), new InWorldToolOperationResult(Blocks.DIRT.getDefaultState())); - final List snowBalls = new ArrayList<>(); - snowBalls.add( new ItemStack( Items.SNOWBALL ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.FLOWING_WATER, true ), new InWorldToolOperationResult( null, snowBalls ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.WATER, true ), new InWorldToolOperationResult( Blocks.ICE.getDefaultState() ) ); + final List snowBalls = new ArrayList<>(); + snowBalls.add(new ItemStack(Items.SNOWBALL)); + this.coolDown.put(new InWorldToolOperationIngredient(Blocks.FLOWING_WATER, true), new InWorldToolOperationResult(null, snowBalls)); + this.coolDown.put(new InWorldToolOperationIngredient(Blocks.WATER, true), new InWorldToolOperationResult(Blocks.ICE.getDefaultState())); - this.heatUp.put( new InWorldToolOperationIngredient( Blocks.ICE.getDefaultState() ), new InWorldToolOperationResult( Blocks.WATER.getDefaultState() ) ); - this.heatUp.put( new InWorldToolOperationIngredient( Blocks.FLOWING_WATER, true ), new InWorldToolOperationResult() ); - this.heatUp.put( new InWorldToolOperationIngredient( Blocks.WATER, true ), new InWorldToolOperationResult() ); - this.heatUp.put( new InWorldToolOperationIngredient( Blocks.SNOW, true ), - new InWorldToolOperationResult( Blocks.FLOWING_WATER.getStateFromMeta( 7 ) ) ); - } + this.heatUp.put(new InWorldToolOperationIngredient(Blocks.ICE.getDefaultState()), new InWorldToolOperationResult(Blocks.WATER.getDefaultState())); + this.heatUp.put(new InWorldToolOperationIngredient(Blocks.FLOWING_WATER, true), new InWorldToolOperationResult()); + this.heatUp.put(new InWorldToolOperationIngredient(Blocks.WATER, true), new InWorldToolOperationResult()); + this.heatUp.put(new InWorldToolOperationIngredient(Blocks.SNOW, true), + new InWorldToolOperationResult(Blocks.FLOWING_WATER.getStateFromMeta(7))); + } - private static class InWorldToolOperationIngredient - { - private final IBlockState state; - private final boolean blockOnly; + private static class InWorldToolOperationIngredient { + private final IBlockState state; + private final boolean blockOnly; - public InWorldToolOperationIngredient( final IBlockState state ) - { - this.state = state; - this.blockOnly = false; - } + public InWorldToolOperationIngredient(final IBlockState state) { + this.state = state; + this.blockOnly = false; + } - public InWorldToolOperationIngredient( final Block blk, final boolean b ) - { - this.state = blk.getDefaultState(); - this.blockOnly = b; - } + public InWorldToolOperationIngredient(final Block blk, final boolean b) { + this.state = blk.getDefaultState(); + this.blockOnly = b; + } - @Override - public int hashCode() - { - return this.state.getBlock().hashCode(); - } + @Override + public int hashCode() { + return this.state.getBlock().hashCode(); + } - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final InWorldToolOperationIngredient other = (InWorldToolOperationIngredient) obj; - return this.state == other.state && ( this.blockOnly && this.state.getBlock() == other.state.getBlock() ); - } - } + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final InWorldToolOperationIngredient other = (InWorldToolOperationIngredient) obj; + return this.state == other.state && (this.blockOnly && this.state.getBlock() == other.state.getBlock()); + } + } - private void heat( final IBlockState state, final World w, final BlockPos pos ) - { - InWorldToolOperationResult r = this.heatUp.get( new InWorldToolOperationIngredient( state ) ); + private void heat(final IBlockState state, final World w, final BlockPos pos) { + InWorldToolOperationResult r = this.heatUp.get(new InWorldToolOperationIngredient(state)); - if( r == null ) - { - r = this.heatUp.get( new InWorldToolOperationIngredient( state.getBlock(), true ) ); - } + if (r == null) { + r = this.heatUp.get(new InWorldToolOperationIngredient(state.getBlock(), true)); + } - if( r.getBlockState() != null ) - { - w.setBlockState( pos, r.getBlockState(), 3 ); - } - else - { - w.setBlockToAir( pos ); - } + if (r.getBlockState() != null) { + w.setBlockState(pos, r.getBlockState(), 3); + } else { + w.setBlockToAir(pos); + } - if( r.getDrops() != null ) - { - Platform.spawnDrops( w, pos, r.getDrops() ); - } - } + if (r.getDrops() != null) { + Platform.spawnDrops(w, pos, r.getDrops()); + } + } - private boolean canHeat( final IBlockState state ) - { - InWorldToolOperationResult r = this.heatUp.get( new InWorldToolOperationIngredient( state ) ); + private boolean canHeat(final IBlockState state) { + InWorldToolOperationResult r = this.heatUp.get(new InWorldToolOperationIngredient(state)); - if( r == null ) - { - r = this.heatUp.get( new InWorldToolOperationIngredient( state.getBlock(), true ) ); - } + if (r == null) { + r = this.heatUp.get(new InWorldToolOperationIngredient(state.getBlock(), true)); + } - return r != null; - } + return r != null; + } - private void cool( final IBlockState state, final World w, final BlockPos pos ) - { - InWorldToolOperationResult r = this.coolDown.get( new InWorldToolOperationIngredient( state ) ); + private void cool(final IBlockState state, final World w, final BlockPos pos) { + InWorldToolOperationResult r = this.coolDown.get(new InWorldToolOperationIngredient(state)); - if( r == null ) - { - r = this.coolDown.get( new InWorldToolOperationIngredient( state.getBlock(), true ) ); - } + if (r == null) { + r = this.coolDown.get(new InWorldToolOperationIngredient(state.getBlock(), true)); + } - if( r.getBlockState() != null ) - { - w.setBlockState( pos, r.getBlockState(), 3 ); - } - else - { - w.setBlockToAir( pos ); - } + if (r.getBlockState() != null) { + w.setBlockState(pos, r.getBlockState(), 3); + } else { + w.setBlockToAir(pos); + } - if( r.getDrops() != null ) - { - Platform.spawnDrops( w, pos, r.getDrops() ); - } - } + if (r.getDrops() != null) { + Platform.spawnDrops(w, pos, r.getDrops()); + } + } - private boolean canCool( final IBlockState state ) - { - InWorldToolOperationResult r = this.coolDown.get( new InWorldToolOperationIngredient( state ) ); + private boolean canCool(final IBlockState state) { + InWorldToolOperationResult r = this.coolDown.get(new InWorldToolOperationIngredient(state)); - if( r == null ) - { - r = this.coolDown.get( new InWorldToolOperationIngredient( state.getBlock(), true ) ); - } + if (r == null) { + r = this.coolDown.get(new InWorldToolOperationIngredient(state.getBlock(), true)); + } - return r != null; - } + return r != null; + } - @Override - public boolean hitEntity( final ItemStack item, final EntityLivingBase target, final EntityLivingBase hitter ) - { - if( this.getAECurrentPower( item ) > 1600 ) - { - this.extractAEPower( item, 1600, Actionable.MODULATE ); - target.setFire( 8 ); - } + @Override + public boolean hitEntity(final ItemStack item, final EntityLivingBase target, final EntityLivingBase hitter) { + if (this.getAECurrentPower(item) > 1600) { + this.extractAEPower(item, 1600, Actionable.MODULATE); + target.setFire(8); + } - return false; - } + return false; + } - @Override - public ActionResult onItemRightClick( final World w, final EntityPlayer p, final EnumHand hand ) - { - final RayTraceResult target = this.rayTrace( w, p, true ); + @Override + public ActionResult onItemRightClick(final World w, final EntityPlayer p, final EnumHand hand) { + final RayTraceResult target = this.rayTrace(w, p, true); - if( target == null ) - { - return new ActionResult<>( EnumActionResult.FAIL, p.getHeldItem( hand ) ); - } - else - { - if( target.typeOfHit == RayTraceResult.Type.BLOCK ) - { - final IBlockState state = w.getBlockState( target.getBlockPos() ); - if( state.getMaterial() == Material.LAVA || state.getMaterial() == Material.WATER ) - { - if( Platform.hasPermissions( new DimensionalCoord( w, target.getBlockPos() ), p ) ) - { - this.onItemUse( p, w, target.getBlockPos(), hand, EnumFacing.UP, 0.0F, 0.0F, 0.0F ); - } - } - } - } + if (target == null) { + return new ActionResult<>(EnumActionResult.FAIL, p.getHeldItem(hand)); + } else { + if (target.typeOfHit == RayTraceResult.Type.BLOCK) { + final IBlockState state = w.getBlockState(target.getBlockPos()); + if (state.getMaterial() == Material.LAVA || state.getMaterial() == Material.WATER) { + if (Platform.hasPermissions(new DimensionalCoord(w, target.getBlockPos()), p)) { + this.onItemUse(p, w, target.getBlockPos(), hand, EnumFacing.UP, 0.0F, 0.0F, 0.0F); + } + } + } + } - return new ActionResult<>( EnumActionResult.SUCCESS, p.getHeldItem( hand ) ); - } + return new ActionResult<>(EnumActionResult.SUCCESS, p.getHeldItem(hand)); + } - @Override - public EnumActionResult onItemUse( EntityPlayer p, World w, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ ) - { - return this.onItemUse( p.getHeldItem( hand ), p, w, pos, hand, side, hitX, hitY, hitZ ); - } + @Override + public EnumActionResult onItemUse(EntityPlayer p, World w, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { + return this.onItemUse(p.getHeldItem(hand), p, w, pos, hand, side, hitX, hitY, hitZ); + } - @Override - public EnumActionResult onItemUse( ItemStack item, EntityPlayer p, World w, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ ) - { - if( this.getAECurrentPower( item ) > 1600 ) - { - if( !p.canPlayerEdit( pos, side, item ) ) - { - return EnumActionResult.FAIL; - } + @Override + public EnumActionResult onItemUse(ItemStack item, EntityPlayer p, World w, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { + if (this.getAECurrentPower(item) > 1600) { + if (!p.canPlayerEdit(pos, side, item)) { + return EnumActionResult.FAIL; + } - final IBlockState state = w.getBlockState( pos ); - final Block blockID = state.getBlock(); + final IBlockState state = w.getBlockState(pos); + final Block blockID = state.getBlock(); - if( p.isSneaking() ) - { - if( this.canCool( state ) ) - { - this.extractAEPower( item, 1600, Actionable.MODULATE ); - this.cool( state, w, pos ); - return EnumActionResult.SUCCESS; - } - } - else - { - if( blockID instanceof BlockTNT ) - { - w.setBlockToAir( pos ); - ( (BlockTNT) blockID ).explode( w, pos, state, p ); - return EnumActionResult.SUCCESS; - } + if (p.isSneaking()) { + if (this.canCool(state)) { + this.extractAEPower(item, 1600, Actionable.MODULATE); + this.cool(state, w, pos); + return EnumActionResult.SUCCESS; + } + } else { + if (blockID instanceof BlockTNT) { + w.setBlockToAir(pos); + ((BlockTNT) blockID).explode(w, pos, state, p); + return EnumActionResult.SUCCESS; + } - if( blockID instanceof BlockTinyTNT ) - { - w.setBlockToAir( pos ); - ( (BlockTinyTNT) blockID ).startFuse( w, pos, p ); - return EnumActionResult.SUCCESS; - } + if (blockID instanceof BlockTinyTNT) { + w.setBlockToAir(pos); + ((BlockTinyTNT) blockID).startFuse(w, pos, p); + return EnumActionResult.SUCCESS; + } - if( this.canHeat( state ) ) - { - this.extractAEPower( item, 1600, Actionable.MODULATE ); - this.heat( state, w, pos ); - return EnumActionResult.SUCCESS; - } + if (this.canHeat(state)) { + this.extractAEPower(item, 1600, Actionable.MODULATE); + this.heat(state, w, pos); + return EnumActionResult.SUCCESS; + } - final ItemStack[] stack = Platform.getBlockDrops( w, pos ); - final List out = new ArrayList<>(); - boolean hasFurnaceable = false; - boolean canFurnaceable = true; + final ItemStack[] stack = Platform.getBlockDrops(w, pos); + final List out = new ArrayList<>(); + boolean hasFurnaceable = false; + boolean canFurnaceable = true; - for( final ItemStack i : stack ) - { - final ItemStack result = FurnaceRecipes.instance().getSmeltingResult( i ); + for (final ItemStack i : stack) { + final ItemStack result = FurnaceRecipes.instance().getSmeltingResult(i); - if( !result.isEmpty() ) - { - if( result.getItem() instanceof ItemBlock ) - { - if( Block.getBlockFromItem( result.getItem() ) == blockID && result.getItem().getDamage( result ) == blockID - .getMetaFromState( state ) ) - { - canFurnaceable = false; - } - } - hasFurnaceable = true; - out.add( result ); - } - else - { - canFurnaceable = false; - out.add( i ); - } - } + if (!result.isEmpty()) { + if (result.getItem() instanceof ItemBlock) { + if (Block.getBlockFromItem(result.getItem()) == blockID && result.getItem().getDamage(result) == blockID + .getMetaFromState(state)) { + canFurnaceable = false; + } + } + hasFurnaceable = true; + out.add(result); + } else { + canFurnaceable = false; + out.add(i); + } + } - if( hasFurnaceable && canFurnaceable ) - { - this.extractAEPower( item, 1600, Actionable.MODULATE ); - final InWorldToolOperationResult or = InWorldToolOperationResult.getBlockOperationResult( out.toArray( new ItemStack[out.size()] ) ); - w.playSound( p, pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5D, SoundEvents.ITEM_FLINTANDSTEEL_USE, SoundCategory.PLAYERS, 1.0F, - itemRand.nextFloat() * 0.4F + 0.8F ); + if (hasFurnaceable && canFurnaceable) { + this.extractAEPower(item, 1600, Actionable.MODULATE); + final InWorldToolOperationResult or = InWorldToolOperationResult.getBlockOperationResult(out.toArray(new ItemStack[out.size()])); + w.playSound(p, pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5D, SoundEvents.ITEM_FLINTANDSTEEL_USE, SoundCategory.PLAYERS, 1.0F, + itemRand.nextFloat() * 0.4F + 0.8F); - if( or.getBlockState() == null ) - { - w.setBlockState( pos, Platform.AIR_BLOCK.getDefaultState(), 3 ); - } - else - { - w.setBlockState( pos, or.getBlockState(), 3 ); - } + if (or.getBlockState() == null) { + w.setBlockState(pos, Platform.AIR_BLOCK.getDefaultState(), 3); + } else { + w.setBlockState(pos, or.getBlockState(), 3); + } - if( or.getDrops() != null ) - { - Platform.spawnDrops( w, pos, or.getDrops() ); - } + if (or.getDrops() != null) { + Platform.spawnDrops(w, pos, or.getDrops()); + } - return EnumActionResult.SUCCESS; - } - else - { - final BlockPos offsetPos = pos.offset( side ); + return EnumActionResult.SUCCESS; + } else { + final BlockPos offsetPos = pos.offset(side); - if( !p.canPlayerEdit( offsetPos, side, item ) ) - { - return EnumActionResult.FAIL; - } + if (!p.canPlayerEdit(offsetPos, side, item)) { + return EnumActionResult.FAIL; + } - if( w.isAirBlock( offsetPos ) ) - { - this.extractAEPower( item, 1600, Actionable.MODULATE ); - w.playSound( p, offsetPos.getX() + 0.5D, offsetPos.getY() + 0.5D, offsetPos.getZ() + 0.5D, SoundEvents.ITEM_FLINTANDSTEEL_USE, - SoundCategory.PLAYERS, 1.0F, itemRand.nextFloat() * 0.4F + 0.8F ); - w.setBlockState( offsetPos, Blocks.FIRE.getDefaultState() ); - } + if (w.isAirBlock(offsetPos)) { + this.extractAEPower(item, 1600, Actionable.MODULATE); + w.playSound(p, offsetPos.getX() + 0.5D, offsetPos.getY() + 0.5D, offsetPos.getZ() + 0.5D, SoundEvents.ITEM_FLINTANDSTEEL_USE, + SoundCategory.PLAYERS, 1.0F, itemRand.nextFloat() * 0.4F + 0.8F); + w.setBlockState(offsetPos, Blocks.FIRE.getDefaultState()); + } - return EnumActionResult.SUCCESS; - } - } - } + return EnumActionResult.SUCCESS; + } + } + } - return EnumActionResult.PASS; - } + return EnumActionResult.PASS; + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolMatterCannon.java b/src/main/java/appeng/items/tools/powered/ToolMatterCannon.java index 9d019e808..aceb377e2 100644 --- a/src/main/java/appeng/items/tools/powered/ToolMatterCannon.java +++ b/src/main/java/appeng/items/tools/powered/ToolMatterCannon.java @@ -19,34 +19,6 @@ package appeng.items.tools.powered; -import java.util.List; - -import javax.annotation.Nullable; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.passive.EntitySheep; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ActionResult; -import net.minecraft.util.DamageSource; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.FuzzyMode; @@ -76,459 +48,390 @@ import appeng.me.helpers.PlayerSource; import appeng.tile.misc.TilePaint; import appeng.util.LookDirection; import appeng.util.Platform; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.passive.EntitySheep; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.*; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.items.IItemHandler; + +import javax.annotation.Nullable; +import java.util.List; -public class ToolMatterCannon extends AEBasePoweredItem implements IStorageCell -{ +public class ToolMatterCannon extends AEBasePoweredItem implements IStorageCell { - public ToolMatterCannon() - { - super( AEConfig.instance().getMatterCannonBattery() ); - } + public ToolMatterCannon() { + super(AEConfig.instance().getMatterCannonBattery()); + } - @SideOnly( Side.CLIENT ) - @Override - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - super.addCheckedInformation( stack, world, lines, advancedTooltips ); + @SideOnly(Side.CLIENT) + @Override + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + super.addCheckedInformation(stack, world, lines, advancedTooltips); - final ICellInventoryHandler cdi = AEApi.instance() - .registries() - .cell() - .getCellInventory( stack, null, - AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); + final ICellInventoryHandler cdi = AEApi.instance() + .registries() + .cell() + .getCellInventory(stack, null, + AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); - AEApi.instance().client().addCellInformation( cdi, lines ); - } + AEApi.instance().client().addCellInformation(cdi, lines); + } - @Override - public ActionResult onItemRightClick( final World w, final EntityPlayer p, final @Nullable EnumHand hand ) - { - if( this.getAECurrentPower( p.getHeldItem( hand ) ) > 1600 ) - { - int shots = 1; + @Override + public ActionResult onItemRightClick(final World w, final EntityPlayer p, final @Nullable EnumHand hand) { + if (this.getAECurrentPower(p.getHeldItem(hand)) > 1600) { + int shots = 1; - final CellUpgrades cu = (CellUpgrades) this.getUpgradesInventory( p.getHeldItem( hand ) ); - if( cu != null ) - { - shots += cu.getInstalledUpgrades( Upgrades.SPEED ); - } + final CellUpgrades cu = (CellUpgrades) this.getUpgradesInventory(p.getHeldItem(hand)); + if (cu != null) { + shots += cu.getInstalledUpgrades(Upgrades.SPEED); + } - final ICellInventoryHandler inv = AEApi.instance() - .registries() - .cell() - .getCellInventory( p.getHeldItem( hand ), null, - AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - if( inv != null ) - { - final IItemList itemList = inv - .getAvailableItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList() ); - IAEItemStack req = itemList.getFirstItem(); - if( req instanceof IAEItemStack ) - { - shots = Math.min( shots, (int) req.getStackSize() ); - for( int sh = 0; sh < shots; sh++ ) - { - IAEItemStack aeAmmo = req.copy(); - this.extractAEPower( p.getHeldItem( hand ), 1600, Actionable.MODULATE ); + final ICellInventoryHandler inv = AEApi.instance() + .registries() + .cell() + .getCellInventory(p.getHeldItem(hand), null, + AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + if (inv != null) { + final IItemList itemList = inv + .getAvailableItems(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList()); + IAEItemStack req = itemList.getFirstItem(); + if (req instanceof IAEItemStack) { + shots = Math.min(shots, (int) req.getStackSize()); + for (int sh = 0; sh < shots; sh++) { + IAEItemStack aeAmmo = req.copy(); + this.extractAEPower(p.getHeldItem(hand), 1600, Actionable.MODULATE); - if( Platform.isClient() ) - { - return new ActionResult<>( EnumActionResult.SUCCESS, p.getHeldItem( hand ) ); - } + if (Platform.isClient()) { + return new ActionResult<>(EnumActionResult.SUCCESS, p.getHeldItem(hand)); + } - aeAmmo.setStackSize( 1 ); - final ItemStack ammo = aeAmmo.createItemStack(); - if( ammo == null ) - { - return new ActionResult<>( EnumActionResult.SUCCESS, p.getHeldItem( hand ) ); - } + aeAmmo.setStackSize(1); + final ItemStack ammo = aeAmmo.createItemStack(); + if (ammo == null) { + return new ActionResult<>(EnumActionResult.SUCCESS, p.getHeldItem(hand)); + } - aeAmmo = inv.extractItems( aeAmmo, Actionable.MODULATE, new PlayerSource( p, null ) ); - if( aeAmmo == null ) - { - return new ActionResult<>( EnumActionResult.SUCCESS, p.getHeldItem( hand ) ); - } + aeAmmo = inv.extractItems(aeAmmo, Actionable.MODULATE, new PlayerSource(p, null)); + if (aeAmmo == null) { + return new ActionResult<>(EnumActionResult.SUCCESS, p.getHeldItem(hand)); + } - final LookDirection dir = Platform.getPlayerRay( p, p.getEyeHeight() ); + final LookDirection dir = Platform.getPlayerRay(p, p.getEyeHeight()); - final Vec3d Vec3d = dir.getA(); - final Vec3d Vec3d1 = dir.getB(); - final Vec3d direction = Vec3d1.subtract( Vec3d ); - direction.normalize(); + final Vec3d Vec3d = dir.getA(); + final Vec3d Vec3d1 = dir.getB(); + final Vec3d direction = Vec3d1.subtract(Vec3d); + direction.normalize(); - final double d0 = Vec3d.x; - final double d1 = Vec3d.y; - final double d2 = Vec3d.z; + final double d0 = Vec3d.x; + final double d1 = Vec3d.y; + final double d2 = Vec3d.z; - final float penetration = AEApi.instance().registries().matterCannon().getPenetration( ammo ); // 196.96655f; - if( penetration <= 0 ) - { - final ItemStack type = aeAmmo.asItemStackRepresentation(); - if( type.getItem() instanceof ItemPaintBall ) - { - this.shootPaintBalls( type, w, p, Vec3d, Vec3d1, direction, d0, d1, d2 ); - } - return new ActionResult<>( EnumActionResult.SUCCESS, p.getHeldItem( hand ) ); - } - else - { - this.standardAmmo( penetration, w, p, Vec3d, Vec3d1, direction, d0, d1, d2 ); - } - } - } - else - { - if( Platform.isServer() ) - { - p.sendMessage( PlayerMessages.AmmoDepleted.get() ); - } - return new ActionResult<>( EnumActionResult.SUCCESS, p.getHeldItem( hand ) ); - } - } - } - return new ActionResult<>( EnumActionResult.FAIL, p.getHeldItem( hand ) ); - } + final float penetration = AEApi.instance().registries().matterCannon().getPenetration(ammo); // 196.96655f; + if (penetration <= 0) { + final ItemStack type = aeAmmo.asItemStackRepresentation(); + if (type.getItem() instanceof ItemPaintBall) { + this.shootPaintBalls(type, w, p, Vec3d, Vec3d1, direction, d0, d1, d2); + } + return new ActionResult<>(EnumActionResult.SUCCESS, p.getHeldItem(hand)); + } else { + this.standardAmmo(penetration, w, p, Vec3d, Vec3d1, direction, d0, d1, d2); + } + } + } else { + if (Platform.isServer()) { + p.sendMessage(PlayerMessages.AmmoDepleted.get()); + } + return new ActionResult<>(EnumActionResult.SUCCESS, p.getHeldItem(hand)); + } + } + } + return new ActionResult<>(EnumActionResult.FAIL, p.getHeldItem(hand)); + } - private void shootPaintBalls( final ItemStack type, final World w, final EntityPlayer p, final Vec3d Vec3d, final Vec3d Vec3d1, final Vec3d direction, final double d0, final double d1, final double d2 ) - { - final AxisAlignedBB bb = new AxisAlignedBB( Math.min( Vec3d.x, Vec3d1.x ), Math.min( Vec3d.y, Vec3d1.y ), Math.min( Vec3d.z, Vec3d1.z ), Math - .max( Vec3d.x, Vec3d1.x ), Math.max( Vec3d.y, Vec3d1.y ), Math.max( Vec3d.z, Vec3d1.z ) ).grow( 16, 16, 16 ); + private void shootPaintBalls(final ItemStack type, final World w, final EntityPlayer p, final Vec3d Vec3d, final Vec3d Vec3d1, final Vec3d direction, final double d0, final double d1, final double d2) { + final AxisAlignedBB bb = new AxisAlignedBB(Math.min(Vec3d.x, Vec3d1.x), Math.min(Vec3d.y, Vec3d1.y), Math.min(Vec3d.z, Vec3d1.z), Math + .max(Vec3d.x, Vec3d1.x), Math.max(Vec3d.y, Vec3d1.y), Math.max(Vec3d.z, Vec3d1.z)).grow(16, 16, 16); - Entity entity = null; - final List list = w.getEntitiesWithinAABBExcludingEntity( p, bb ); - double closest = 9999999.0D; + Entity entity = null; + final List list = w.getEntitiesWithinAABBExcludingEntity(p, bb); + double closest = 9999999.0D; - for( int l = 0; l < list.size(); ++l ) - { - final Entity entity1 = (Entity) list.get( l ); + for (int l = 0; l < list.size(); ++l) { + final Entity entity1 = (Entity) list.get(l); - if( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) - { - if( entity1.isEntityAlive() ) - { - // prevent killing / flying of mounts. - if( entity1.isRidingOrBeingRiddenBy( p ) ) - { - continue; - } + if (!entity1.isDead && entity1 != p && !(entity1 instanceof EntityItem)) { + if (entity1.isEntityAlive()) { + // prevent killing / flying of mounts. + if (entity1.isRidingOrBeingRiddenBy(p)) { + continue; + } - final float f1 = 0.3F; + final float f1 = 0.3F; - final AxisAlignedBB boundingBox = entity1.getEntityBoundingBox().grow( f1, f1, f1 ); - final RayTraceResult RayTraceResult = boundingBox.calculateIntercept( Vec3d, Vec3d1 ); + final AxisAlignedBB boundingBox = entity1.getEntityBoundingBox().grow(f1, f1, f1); + final RayTraceResult RayTraceResult = boundingBox.calculateIntercept(Vec3d, Vec3d1); - if( RayTraceResult != null ) - { - final double nd = Vec3d.squareDistanceTo( RayTraceResult.hitVec ); + if (RayTraceResult != null) { + final double nd = Vec3d.squareDistanceTo(RayTraceResult.hitVec); - if( nd < closest ) - { - entity = entity1; - closest = nd; - } - } - } - } - } + if (nd < closest) { + entity = entity1; + closest = nd; + } + } + } + } + } - RayTraceResult pos = w.rayTraceBlocks( Vec3d, Vec3d1, false ); + RayTraceResult pos = w.rayTraceBlocks(Vec3d, Vec3d1, false); - final Vec3d vec = new Vec3d( d0, d1, d2 ); - if( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) - { - pos = new RayTraceResult( entity ); - } - else if( entity != null && pos == null ) - { - pos = new RayTraceResult( entity ); - } + final Vec3d vec = new Vec3d(d0, d1, d2); + if (entity != null && pos != null && pos.hitVec.squareDistanceTo(vec) > closest) { + pos = new RayTraceResult(entity); + } else if (entity != null && pos == null) { + pos = new RayTraceResult(entity); + } - try - { - AppEng.proxy.sendToAllNearExcept( null, d0, d1, d2, 128, w, - new PacketMatterCannon( d0, d1, d2, (float) direction.x, (float) direction.y, (float) direction.z, (byte) ( pos == null ? 32 : pos.hitVec - .squareDistanceTo( vec ) + 1 ) ) ); - } - catch( final Exception err ) - { - AELog.debug( err ); - } + try { + AppEng.proxy.sendToAllNearExcept(null, d0, d1, d2, 128, w, + new PacketMatterCannon(d0, d1, d2, (float) direction.x, (float) direction.y, (float) direction.z, (byte) (pos == null ? 32 : pos.hitVec + .squareDistanceTo(vec) + 1))); + } catch (final Exception err) { + AELog.debug(err); + } - if( pos != null && type != null && type.getItem() instanceof ItemPaintBall ) - { - final ItemPaintBall ipb = (ItemPaintBall) type.getItem(); + if (pos != null && type != null && type.getItem() instanceof ItemPaintBall) { + final ItemPaintBall ipb = (ItemPaintBall) type.getItem(); - final AEColor col = ipb.getColor( type ); - // boolean lit = ipb.isLumen( type ); + final AEColor col = ipb.getColor(type); + // boolean lit = ipb.isLumen( type ); - if( pos.typeOfHit == RayTraceResult.Type.ENTITY ) - { - final int id = pos.entityHit.getEntityId(); - final PlayerColor marker = new PlayerColor( id, col, 20 * 30 ); - TickHandler.INSTANCE.getPlayerColors().put( id, marker ); + if (pos.typeOfHit == RayTraceResult.Type.ENTITY) { + final int id = pos.entityHit.getEntityId(); + final PlayerColor marker = new PlayerColor(id, col, 20 * 30); + TickHandler.INSTANCE.getPlayerColors().put(id, marker); - if( pos.entityHit instanceof EntitySheep ) - { - final EntitySheep sh = (EntitySheep) pos.entityHit; - sh.setFleeceColor( col.dye ); - } + if (pos.entityHit instanceof EntitySheep) { + final EntitySheep sh = (EntitySheep) pos.entityHit; + sh.setFleeceColor(col.dye); + } - pos.entityHit.attackEntityFrom( DamageSource.causePlayerDamage( p ), 0 ); - NetworkHandler.instance().sendToAll( marker.getPacket() ); - } - else if( pos.typeOfHit == RayTraceResult.Type.BLOCK ) - { - final EnumFacing side = pos.sideHit; - final BlockPos hitPos = pos.getBlockPos().offset( side ); + pos.entityHit.attackEntityFrom(DamageSource.causePlayerDamage(p), 0); + NetworkHandler.instance().sendToAll(marker.getPacket()); + } else if (pos.typeOfHit == RayTraceResult.Type.BLOCK) { + final EnumFacing side = pos.sideHit; + final BlockPos hitPos = pos.getBlockPos().offset(side); - if( !Platform.hasPermissions( new DimensionalCoord( w, hitPos ), p ) ) - { - return; - } + if (!Platform.hasPermissions(new DimensionalCoord(w, hitPos), p)) { + return; + } - final Block whatsThere = w.getBlockState( hitPos ).getBlock(); - if( whatsThere.isReplaceable( w, hitPos ) && w.isAirBlock( hitPos ) ) - { - AEApi.instance().definitions().blocks().paint().maybeBlock().ifPresent( paintBlock -> - { - w.setBlockState( hitPos, paintBlock.getDefaultState(), 3 ); - } ); - } + final Block whatsThere = w.getBlockState(hitPos).getBlock(); + if (whatsThere.isReplaceable(w, hitPos) && w.isAirBlock(hitPos)) { + AEApi.instance().definitions().blocks().paint().maybeBlock().ifPresent(paintBlock -> + { + w.setBlockState(hitPos, paintBlock.getDefaultState(), 3); + }); + } - final TileEntity te = w.getTileEntity( hitPos ); - if( te instanceof TilePaint ) - { - final Vec3d hp = pos.hitVec.subtract( hitPos.getX(), hitPos.getY(), hitPos.getZ() ); - ( (TilePaint) te ).addBlot( type, side.getOpposite(), hp ); - } - } - } - } + final TileEntity te = w.getTileEntity(hitPos); + if (te instanceof TilePaint) { + final Vec3d hp = pos.hitVec.subtract(hitPos.getX(), hitPos.getY(), hitPos.getZ()); + ((TilePaint) te).addBlot(type, side.getOpposite(), hp); + } + } + } + } - private void standardAmmo( float penetration, final World w, final EntityPlayer p, final Vec3d Vec3d, final Vec3d Vec3d1, final Vec3d direction, final double d0, final double d1, final double d2 ) - { - boolean hasDestroyed = true; - while( penetration > 0 && hasDestroyed ) - { - hasDestroyed = false; + private void standardAmmo(float penetration, final World w, final EntityPlayer p, final Vec3d Vec3d, final Vec3d Vec3d1, final Vec3d direction, final double d0, final double d1, final double d2) { + boolean hasDestroyed = true; + while (penetration > 0 && hasDestroyed) { + hasDestroyed = false; - final AxisAlignedBB bb = new AxisAlignedBB( Math.min( Vec3d.x, Vec3d1.x ), Math.min( Vec3d.y, Vec3d1.y ), Math.min( Vec3d.z, Vec3d1.z ), Math - .max( Vec3d.x, Vec3d1.x ), Math.max( Vec3d.y, Vec3d1.y ), Math.max( Vec3d.z, Vec3d1.z ) ).grow( 16, 16, 16 ); + final AxisAlignedBB bb = new AxisAlignedBB(Math.min(Vec3d.x, Vec3d1.x), Math.min(Vec3d.y, Vec3d1.y), Math.min(Vec3d.z, Vec3d1.z), Math + .max(Vec3d.x, Vec3d1.x), Math.max(Vec3d.y, Vec3d1.y), Math.max(Vec3d.z, Vec3d1.z)).grow(16, 16, 16); - Entity entity = null; - final List list = w.getEntitiesWithinAABBExcludingEntity( p, bb ); - double closest = 9999999.0D; + Entity entity = null; + final List list = w.getEntitiesWithinAABBExcludingEntity(p, bb); + double closest = 9999999.0D; - for( int l = 0; l < list.size(); ++l ) - { - final Entity entity1 = (Entity) list.get( l ); + for (int l = 0; l < list.size(); ++l) { + final Entity entity1 = (Entity) list.get(l); - if( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) - { - if( entity1.isEntityAlive() ) - { - // prevent killing / flying of mounts. - if( entity1.isRidingOrBeingRiddenBy( p ) ) - { - continue; - } + if (!entity1.isDead && entity1 != p && !(entity1 instanceof EntityItem)) { + if (entity1.isEntityAlive()) { + // prevent killing / flying of mounts. + if (entity1.isRidingOrBeingRiddenBy(p)) { + continue; + } - final float f1 = 0.3F; + final float f1 = 0.3F; - final AxisAlignedBB boundingBox = entity1.getEntityBoundingBox().grow( f1, f1, f1 ); - final RayTraceResult RayTraceResult = boundingBox.calculateIntercept( Vec3d, Vec3d1 ); + final AxisAlignedBB boundingBox = entity1.getEntityBoundingBox().grow(f1, f1, f1); + final RayTraceResult RayTraceResult = boundingBox.calculateIntercept(Vec3d, Vec3d1); - if( RayTraceResult != null ) - { - final double nd = Vec3d.squareDistanceTo( RayTraceResult.hitVec ); + if (RayTraceResult != null) { + final double nd = Vec3d.squareDistanceTo(RayTraceResult.hitVec); - if( nd < closest ) - { - entity = entity1; - closest = nd; - } - } - } - } - } + if (nd < closest) { + entity = entity1; + closest = nd; + } + } + } + } + } - final Vec3d vec = new Vec3d( d0, d1, d2 ); - RayTraceResult pos = w.rayTraceBlocks( Vec3d, Vec3d1, true ); - if( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) - { - pos = new RayTraceResult( entity ); - } - else if( entity != null && pos == null ) - { - pos = new RayTraceResult( entity ); - } + final Vec3d vec = new Vec3d(d0, d1, d2); + RayTraceResult pos = w.rayTraceBlocks(Vec3d, Vec3d1, true); + if (entity != null && pos != null && pos.hitVec.squareDistanceTo(vec) > closest) { + pos = new RayTraceResult(entity); + } else if (entity != null && pos == null) { + pos = new RayTraceResult(entity); + } - try - { - AppEng.proxy.sendToAllNearExcept( null, d0, d1, d2, 128, w, - new PacketMatterCannon( d0, d1, d2, (float) direction.x, (float) direction.y, (float) direction.z, (byte) ( pos == null ? 32 : pos.hitVec - .squareDistanceTo( vec ) + 1 ) ) ); - } - catch( final Exception err ) - { - AELog.debug( err ); - } + try { + AppEng.proxy.sendToAllNearExcept(null, d0, d1, d2, 128, w, + new PacketMatterCannon(d0, d1, d2, (float) direction.x, (float) direction.y, (float) direction.z, (byte) (pos == null ? 32 : pos.hitVec + .squareDistanceTo(vec) + 1))); + } catch (final Exception err) { + AELog.debug(err); + } - if( pos != null ) - { - final DamageSource dmgSrc = DamageSource.causePlayerDamage( p ); - dmgSrc.damageType = "matter_cannon"; + if (pos != null) { + final DamageSource dmgSrc = DamageSource.causePlayerDamage(p); + dmgSrc.damageType = "matter_cannon"; - if( pos.typeOfHit == RayTraceResult.Type.ENTITY ) - { - final int dmg = (int) Math.ceil( penetration / 20.0f ); - if( pos.entityHit instanceof EntityLivingBase ) - { - final EntityLivingBase el = (EntityLivingBase) pos.entityHit; - penetration -= dmg; - el.knockBack( p, 0, -direction.x, -direction.z ); - // el.knockBack( p, 0, Vec3d.x, - // Vec3d.z ); - el.attackEntityFrom( dmgSrc, dmg ); - if( !el.isEntityAlive() ) - { - hasDestroyed = true; - } - } - else if( pos.entityHit instanceof EntityItem ) - { - hasDestroyed = true; - pos.entityHit.setDead(); - } - else if( pos.entityHit.attackEntityFrom( dmgSrc, dmg ) ) - { - hasDestroyed = pos.entityHit.isEntityAlive(); - } - } - else if( pos.typeOfHit == RayTraceResult.Type.BLOCK ) - { - if( !AEConfig.instance().isFeatureEnabled( AEFeature.MASS_CANNON_BLOCK_DAMAGE ) ) - { - penetration = 0; - } - else - { - final IBlockState bs = w.getBlockState( pos.getBlockPos() ); - // int meta = w.getBlockMetadata( - // pos.blockX, pos.blockY, pos.blockZ ); + if (pos.typeOfHit == RayTraceResult.Type.ENTITY) { + final int dmg = (int) Math.ceil(penetration / 20.0f); + if (pos.entityHit instanceof EntityLivingBase) { + final EntityLivingBase el = (EntityLivingBase) pos.entityHit; + penetration -= dmg; + el.knockBack(p, 0, -direction.x, -direction.z); + // el.knockBack( p, 0, Vec3d.x, + // Vec3d.z ); + el.attackEntityFrom(dmgSrc, dmg); + if (!el.isEntityAlive()) { + hasDestroyed = true; + } + } else if (pos.entityHit instanceof EntityItem) { + hasDestroyed = true; + pos.entityHit.setDead(); + } else if (pos.entityHit.attackEntityFrom(dmgSrc, dmg)) { + hasDestroyed = pos.entityHit.isEntityAlive(); + } + } else if (pos.typeOfHit == RayTraceResult.Type.BLOCK) { + if (!AEConfig.instance().isFeatureEnabled(AEFeature.MASS_CANNON_BLOCK_DAMAGE)) { + penetration = 0; + } else { + final IBlockState bs = w.getBlockState(pos.getBlockPos()); + // int meta = w.getBlockMetadata( + // pos.blockX, pos.blockY, pos.blockZ ); - final float hardness = bs.getBlockHardness( w, pos.getBlockPos() ) * 9.0f; - if( hardness >= 0.0 ) - { - if( penetration > hardness && Platform.hasPermissions( new DimensionalCoord( w, pos.getBlockPos() ), p ) ) - { - hasDestroyed = true; - penetration -= hardness; - penetration *= 0.60; - w.destroyBlock( pos.getBlockPos(), true ); - } - } - } - } - } - } - } + final float hardness = bs.getBlockHardness(w, pos.getBlockPos()) * 9.0f; + if (hardness >= 0.0) { + if (penetration > hardness && Platform.hasPermissions(new DimensionalCoord(w, pos.getBlockPos()), p)) { + hasDestroyed = true; + penetration -= hardness; + penetration *= 0.60; + w.destroyBlock(pos.getBlockPos(), true); + } + } + } + } + } + } + } - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } + @Override + public boolean isEditable(final ItemStack is) { + return true; + } - @Override - public IItemHandler getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 4 ); - } + @Override + public IItemHandler getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 4); + } - @Override - public IItemHandler getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } + @Override + public IItemHandler getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } - @Override - public int getBytes( final ItemStack cellItem ) - { - return 512; - } + @Override + public int getBytes(final ItemStack cellItem) { + return 512; + } - @Override - public int getBytesPerType( final ItemStack cellItem ) - { - return 8; - } + @Override + public int getBytesPerType(final ItemStack cellItem) { + return 8; + } - @Override - public int getTotalTypes( final ItemStack cellItem ) - { - return 1; - } + @Override + public int getTotalTypes(final ItemStack cellItem) { + return 1; + } - @Override - public boolean isBlackListed( final ItemStack cellItem, final IAEItemStack requestedAddition ) - { - final float pen = AEApi.instance().registries().matterCannon().getPenetration( requestedAddition.createItemStack() ); - if( pen > 0 ) - { - return false; - } + @Override + public boolean isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) { + final float pen = AEApi.instance().registries().matterCannon().getPenetration(requestedAddition.createItemStack()); + if (pen > 0) { + return false; + } - if( requestedAddition.getItem() instanceof ItemPaintBall ) - { - return false; - } + return !(requestedAddition.getItem() instanceof ItemPaintBall); + } - return true; - } + @Override + public boolean storableInStorageCell() { + return true; + } - @Override - public boolean storableInStorageCell() - { - return true; - } + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } - @Override - public boolean isStorageCell( final ItemStack i ) - { - return true; - } + @Override + public double getIdleDrain() { + return 0.5; + } - @Override - public double getIdleDrain() - { - return 0.5; - } - - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolPortableCell.java b/src/main/java/appeng/items/tools/powered/ToolPortableCell.java index 1adbe42ef..7100b2f62 100644 --- a/src/main/java/appeng/items/tools/powered/ToolPortableCell.java +++ b/src/main/java/appeng/items/tools/powered/ToolPortableCell.java @@ -19,21 +19,6 @@ package appeng.items.tools.powered; -import java.util.List; -import java.util.Set; - -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ActionResult; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.FuzzyMode; import appeng.api.implementations.guiobjects.IGuiItem; @@ -53,145 +38,135 @@ import appeng.items.contents.CellUpgrades; import appeng.items.contents.PortableCellViewer; import appeng.items.tools.powered.powersink.AEBasePoweredItem; import appeng.util.Platform; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.items.IItemHandler; + +import java.util.List; +import java.util.Set; -public class ToolPortableCell extends AEBasePoweredItem implements IStorageCell, IGuiItem, IItemGroup -{ - public ToolPortableCell() - { - super( AEConfig.instance().getPortableCellBattery() ); - } +public class ToolPortableCell extends AEBasePoweredItem implements IStorageCell, IGuiItem, IItemGroup { + public ToolPortableCell() { + super(AEConfig.instance().getPortableCellBattery()); + } - @Override - public ActionResult onItemRightClick( final World w, final EntityPlayer player, final EnumHand hand ) - { - Platform.openGUI( player, null, AEPartLocation.INTERNAL, GuiBridge.GUI_PORTABLE_CELL ); - return new ActionResult<>( EnumActionResult.SUCCESS, player.getHeldItem( hand ) ); - } + @Override + public ActionResult onItemRightClick(final World w, final EntityPlayer player, final EnumHand hand) { + Platform.openGUI(player, null, AEPartLocation.INTERNAL, GuiBridge.GUI_PORTABLE_CELL); + return new ActionResult<>(EnumActionResult.SUCCESS, player.getHeldItem(hand)); + } - @SideOnly( Side.CLIENT ) - @Override - public boolean isFull3D() - { - return false; - } + @SideOnly(Side.CLIENT) + @Override + public boolean isFull3D() { + return false; + } - @Override - @SideOnly( Side.CLIENT ) - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - super.addCheckedInformation( stack, world, lines, advancedTooltips ); + @Override + @SideOnly(Side.CLIENT) + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + super.addCheckedInformation(stack, world, lines, advancedTooltips); - final ICellInventoryHandler cdi = AEApi.instance() - .registries() - .cell() - .getCellInventory( stack, null, - AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); + final ICellInventoryHandler cdi = AEApi.instance() + .registries() + .cell() + .getCellInventory(stack, null, + AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); - AEApi.instance().client().addCellInformation( cdi, lines ); - } + AEApi.instance().client().addCellInformation(cdi, lines); + } - @Override - public int getBytes( final ItemStack cellItem ) - { - return 512; - } + @Override + public int getBytes(final ItemStack cellItem) { + return 512; + } - @Override - public int getBytesPerType( final ItemStack cellItem ) - { - return 8; - } + @Override + public int getBytesPerType(final ItemStack cellItem) { + return 8; + } - @Override - public int getTotalTypes( final ItemStack cellItem ) - { - return 27; - } + @Override + public int getTotalTypes(final ItemStack cellItem) { + return 27; + } - @Override - public boolean isBlackListed( final ItemStack cellItem, final IAEItemStack requestedAddition ) - { - return false; - } + @Override + public boolean isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) { + return false; + } - @Override - public boolean storableInStorageCell() - { - return false; - } + @Override + public boolean storableInStorageCell() { + return false; + } - @Override - public boolean isStorageCell( final ItemStack i ) - { - return true; - } + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } - @Override - public double getIdleDrain() - { - return 0.5; - } + @Override + public double getIdleDrain() { + return 0.5; + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } - @Override - public String getUnlocalizedGroupName( final Set others, final ItemStack is ) - { - return GuiText.StorageCells.getUnlocalized(); - } + @Override + public String getUnlocalizedGroupName(final Set others, final ItemStack is) { + return GuiText.StorageCells.getUnlocalized(); + } - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } + @Override + public boolean isEditable(final ItemStack is) { + return true; + } - @Override - public IItemHandler getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 2 ); - } + @Override + public IItemHandler getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 2); + } - @Override - public IItemHandler getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } + @Override + public IItemHandler getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } - @Override - public IGuiItemObject getGuiObject( final ItemStack is, final World w, final BlockPos pos ) - { - return new PortableCellViewer( is, pos.getX() ); - } + @Override + public IGuiItemObject getGuiObject(final ItemStack is, final World w, final BlockPos pos) { + return new PortableCellViewer(is, pos.getX()); + } - @Override - public boolean shouldCauseReequipAnimation( ItemStack oldStack, ItemStack newStack, boolean slotChanged ) - { - return slotChanged; - } + @Override + public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) { + return slotChanged; + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java b/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java index 062ef6961..d341dbc63 100644 --- a/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java +++ b/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java @@ -19,8 +19,15 @@ package appeng.items.tools.powered; -import java.util.List; - +import appeng.api.AEApi; +import appeng.api.config.*; +import appeng.api.features.IWirelessTermHandler; +import appeng.api.util.IConfigManager; +import appeng.core.AEConfig; +import appeng.core.localization.GuiText; +import appeng.items.tools.powered.powersink.AEBasePoweredItem; +import appeng.util.ConfigManager; +import appeng.util.Platform; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -33,125 +40,94 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.AEApi; -import appeng.api.config.Actionable; -import appeng.api.config.Settings; -import appeng.api.config.SortDir; -import appeng.api.config.SortOrder; -import appeng.api.config.ViewItems; -import appeng.api.features.IWirelessTermHandler; -import appeng.api.util.IConfigManager; -import appeng.core.AEConfig; -import appeng.core.localization.GuiText; -import appeng.items.tools.powered.powersink.AEBasePoweredItem; -import appeng.util.ConfigManager; -import appeng.util.Platform; +import java.util.List; -public class ToolWirelessTerminal extends AEBasePoweredItem implements IWirelessTermHandler -{ +public class ToolWirelessTerminal extends AEBasePoweredItem implements IWirelessTermHandler { - public ToolWirelessTerminal() - { - super( AEConfig.instance().getWirelessTerminalBattery() ); - } + public ToolWirelessTerminal() { + super(AEConfig.instance().getWirelessTerminalBattery()); + } - @Override - public ActionResult onItemRightClick( final World w, final EntityPlayer player, final EnumHand hand ) - { - AEApi.instance().registries().wireless().openWirelessTerminalGui( player.getHeldItem( hand ), w, player ); - return new ActionResult<>( EnumActionResult.SUCCESS, player.getHeldItem( hand ) ); - } + @Override + public ActionResult onItemRightClick(final World w, final EntityPlayer player, final EnumHand hand) { + AEApi.instance().registries().wireless().openWirelessTerminalGui(player.getHeldItem(hand), w, player); + return new ActionResult<>(EnumActionResult.SUCCESS, player.getHeldItem(hand)); + } - @SideOnly( Side.CLIENT ) - @Override - public boolean isFull3D() - { - return false; - } + @SideOnly(Side.CLIENT) + @Override + public boolean isFull3D() { + return false; + } - @Override - @SideOnly( Side.CLIENT ) - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - super.addCheckedInformation( stack, world, lines, advancedTooltips ); + @Override + @SideOnly(Side.CLIENT) + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + super.addCheckedInformation(stack, world, lines, advancedTooltips); - if( stack.hasTagCompound() ) - { - final NBTTagCompound tag = Platform.openNbtData( stack ); - if( tag != null ) - { - final String encKey = tag.getString( "encryptionKey" ); + if (stack.hasTagCompound()) { + final NBTTagCompound tag = Platform.openNbtData(stack); + if (tag != null) { + final String encKey = tag.getString("encryptionKey"); - if( encKey == null || encKey.isEmpty() ) - { - lines.add( GuiText.Unlinked.getLocal() ); - } - else - { - lines.add( GuiText.Linked.getLocal() ); - } - } - } - else - { - lines.add( I18n.translateToLocal( "AppEng.GuiITooltip.Unlinked" ) ); - } - } + if (encKey == null || encKey.isEmpty()) { + lines.add(GuiText.Unlinked.getLocal()); + } else { + lines.add(GuiText.Linked.getLocal()); + } + } + } else { + lines.add(I18n.translateToLocal("AppEng.GuiITooltip.Unlinked")); + } + } - @Override - public boolean canHandle( final ItemStack is ) - { - return AEApi.instance().definitions().items().wirelessTerminal().isSameAs( is ); - } + @Override + public boolean canHandle(final ItemStack is) { + return AEApi.instance().definitions().items().wirelessTerminal().isSameAs(is); + } - @Override - public boolean usePower( final EntityPlayer player, final double amount, final ItemStack is ) - { - return this.extractAEPower( is, amount, Actionable.MODULATE ) >= amount - 0.5; - } + @Override + public boolean usePower(final EntityPlayer player, final double amount, final ItemStack is) { + return this.extractAEPower(is, amount, Actionable.MODULATE) >= amount - 0.5; + } - @Override - public boolean hasPower( final EntityPlayer player, final double amt, final ItemStack is ) - { - return this.getAECurrentPower( is ) >= amt; - } + @Override + public boolean hasPower(final EntityPlayer player, final double amt, final ItemStack is) { + return this.getAECurrentPower(is) >= amt; + } - @Override - public IConfigManager getConfigManager( final ItemStack target ) - { - final ConfigManager out = new ConfigManager( ( manager, settingName, newValue ) -> - { - final NBTTagCompound data = Platform.openNbtData( target ); - manager.writeToNBT( data ); - } ); + @Override + public IConfigManager getConfigManager(final ItemStack target) { + final ConfigManager out = new ConfigManager((manager, settingName, newValue) -> + { + final NBTTagCompound data = Platform.openNbtData(target); + manager.writeToNBT(data); + }); - out.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - out.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - out.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); + out.registerSetting(Settings.SORT_BY, SortOrder.NAME); + out.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + out.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); - out.readFromNBT( Platform.openNbtData( target ).copy() ); - return out; - } + out.readFromNBT(Platform.openNbtData(target).copy()); + return out; + } - @Override - public String getEncryptionKey( final ItemStack item ) - { - final NBTTagCompound tag = Platform.openNbtData( item ); - return tag.getString( "encryptionKey" ); - } + @Override + public String getEncryptionKey(final ItemStack item) { + final NBTTagCompound tag = Platform.openNbtData(item); + return tag.getString("encryptionKey"); + } - @Override - public void setEncryptionKey( final ItemStack item, final String encKey, final String name ) - { - final NBTTagCompound tag = Platform.openNbtData( item ); - tag.setString( "encryptionKey", encKey ); - tag.setString( "name", name ); - } + @Override + public void setEncryptionKey(final ItemStack item, final String encKey, final String name) { + final NBTTagCompound tag = Platform.openNbtData(item); + tag.setString("encryptionKey", encKey); + tag.setString("name", name); + } - @Override - public boolean shouldCauseReequipAnimation( ItemStack oldStack, ItemStack newStack, boolean slotChanged ) - { - return slotChanged; - } + @Override + public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) { + return slotChanged; + } } diff --git a/src/main/java/appeng/items/tools/powered/powersink/AEBasePoweredItem.java b/src/main/java/appeng/items/tools/powered/powersink/AEBasePoweredItem.java index 0283eb1cb..cf80f0430 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/AEBasePoweredItem.java +++ b/src/main/java/appeng/items/tools/powered/powersink/AEBasePoweredItem.java @@ -19,9 +19,13 @@ package appeng.items.tools.powered.powersink; -import java.text.MessageFormat; -import java.util.List; - +import appeng.api.config.AccessRestriction; +import appeng.api.config.Actionable; +import appeng.api.config.PowerUnits; +import appeng.api.implementations.items.IAEItemPowerStorage; +import appeng.core.localization.GuiText; +import appeng.items.AEBaseItem; +import appeng.util.Platform; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; @@ -32,151 +36,128 @@ import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.config.AccessRestriction; -import appeng.api.config.Actionable; -import appeng.api.config.PowerUnits; -import appeng.api.implementations.items.IAEItemPowerStorage; -import appeng.core.localization.GuiText; -import appeng.items.AEBaseItem; -import appeng.util.Platform; +import java.text.MessageFormat; +import java.util.List; -public abstract class AEBasePoweredItem extends AEBaseItem implements IAEItemPowerStorage -{ - private static final String CURRENT_POWER_NBT_KEY = "internalCurrentPower"; - private static final String MAX_POWER_NBT_KEY = "internalMaxPower"; - private final double powerCapacity; +public abstract class AEBasePoweredItem extends AEBaseItem implements IAEItemPowerStorage { + private static final String CURRENT_POWER_NBT_KEY = "internalCurrentPower"; + private static final String MAX_POWER_NBT_KEY = "internalMaxPower"; + private final double powerCapacity; - public AEBasePoweredItem( final double powerCapacity ) - { - this.setMaxStackSize( 1 ); - this.setMaxDamage( 32 ); - this.hasSubtypes = false; - this.setFull3D(); + public AEBasePoweredItem(final double powerCapacity) { + this.setMaxStackSize(1); + this.setMaxDamage(32); + this.hasSubtypes = false; + this.setFull3D(); - this.powerCapacity = powerCapacity; - } + this.powerCapacity = powerCapacity; + } - @SideOnly( Side.CLIENT ) - @Override - public void addCheckedInformation( final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips ) - { - final NBTTagCompound tag = stack.getTagCompound(); - double internalCurrentPower = 0; - final double internalMaxPower = this.getAEMaxPower( stack ); + @SideOnly(Side.CLIENT) + @Override + public void addCheckedInformation(final ItemStack stack, final World world, final List lines, final ITooltipFlag advancedTooltips) { + final NBTTagCompound tag = stack.getTagCompound(); + double internalCurrentPower = 0; + final double internalMaxPower = this.getAEMaxPower(stack); - if( tag != null ) - { - internalCurrentPower = tag.getDouble( CURRENT_POWER_NBT_KEY ); - } + if (tag != null) { + internalCurrentPower = tag.getDouble(CURRENT_POWER_NBT_KEY); + } - final double percent = internalCurrentPower / internalMaxPower; + final double percent = internalCurrentPower / internalMaxPower; - lines.add( GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format( " {0,number,#} ", internalCurrentPower ) + Platform - .gui_localize( PowerUnits.AE.unlocalizedName ) + " - " + MessageFormat.format( " {0,number,#.##%} ", percent ) ); - } + lines.add(GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format(" {0,number,#} ", internalCurrentPower) + Platform + .gui_localize(PowerUnits.AE.unlocalizedName) + " - " + MessageFormat.format(" {0,number,#.##%} ", percent)); + } - @Override - public boolean isDamageable() - { - return true; - } + @Override + public boolean isDamageable() { + return true; + } - @Override - protected void getCheckedSubItems( final CreativeTabs creativeTab, final NonNullList itemStacks ) - { - super.getCheckedSubItems( creativeTab, itemStacks ); + @Override + protected void getCheckedSubItems(final CreativeTabs creativeTab, final NonNullList itemStacks) { + super.getCheckedSubItems(creativeTab, itemStacks); - final ItemStack charged = new ItemStack( this, 1 ); - final NBTTagCompound tag = Platform.openNbtData( charged ); - tag.setDouble( CURRENT_POWER_NBT_KEY, this.getAEMaxPower( charged ) ); - tag.setDouble( MAX_POWER_NBT_KEY, this.getAEMaxPower( charged ) ); + final ItemStack charged = new ItemStack(this, 1); + final NBTTagCompound tag = Platform.openNbtData(charged); + tag.setDouble(CURRENT_POWER_NBT_KEY, this.getAEMaxPower(charged)); + tag.setDouble(MAX_POWER_NBT_KEY, this.getAEMaxPower(charged)); - itemStacks.add( charged ); - } + itemStacks.add(charged); + } - @Override - public boolean isRepairable() - { - return false; - } + @Override + public boolean isRepairable() { + return false; + } - @Override - public double getDurabilityForDisplay( final ItemStack is ) - { - return 1 - this.getAECurrentPower( is ) / this.getAEMaxPower( is ); - } + @Override + public double getDurabilityForDisplay(final ItemStack is) { + return 1 - this.getAECurrentPower(is) / this.getAEMaxPower(is); + } - @Override - public boolean isDamaged( final ItemStack stack ) - { - return true; - } + @Override + public boolean isDamaged(final ItemStack stack) { + return true; + } - @Override - public void setDamage( final ItemStack stack, final int damage ) - { + @Override + public void setDamage(final ItemStack stack, final int damage) { - } + } - @Override - public double injectAEPower( final ItemStack is, final double amount, Actionable mode ) - { - final double maxStorage = this.getAEMaxPower( is ); - final double currentStorage = this.getAECurrentPower( is ); - final double required = maxStorage - currentStorage; - final double overflow = amount - required; + @Override + public double injectAEPower(final ItemStack is, final double amount, Actionable mode) { + final double maxStorage = this.getAEMaxPower(is); + final double currentStorage = this.getAECurrentPower(is); + final double required = maxStorage - currentStorage; + final double overflow = amount - required; - if( mode == Actionable.MODULATE ) - { - final NBTTagCompound data = Platform.openNbtData( is ); - final double toAdd = Math.min( amount, required ); + if (mode == Actionable.MODULATE) { + final NBTTagCompound data = Platform.openNbtData(is); + final double toAdd = Math.min(amount, required); - data.setDouble( CURRENT_POWER_NBT_KEY, currentStorage + toAdd ); - } + data.setDouble(CURRENT_POWER_NBT_KEY, currentStorage + toAdd); + } - return Math.max( 0, overflow ); - } + return Math.max(0, overflow); + } - @Override - public double extractAEPower( final ItemStack is, final double amount, Actionable mode ) - { - final double currentStorage = this.getAECurrentPower( is ); - final double fulfillable = Math.min( amount, currentStorage ); + @Override + public double extractAEPower(final ItemStack is, final double amount, Actionable mode) { + final double currentStorage = this.getAECurrentPower(is); + final double fulfillable = Math.min(amount, currentStorage); - if( mode == Actionable.MODULATE ) - { - final NBTTagCompound data = Platform.openNbtData( is ); + if (mode == Actionable.MODULATE) { + final NBTTagCompound data = Platform.openNbtData(is); - data.setDouble( CURRENT_POWER_NBT_KEY, currentStorage - fulfillable ); - } + data.setDouble(CURRENT_POWER_NBT_KEY, currentStorage - fulfillable); + } - return fulfillable; - } + return fulfillable; + } - @Override - public double getAEMaxPower( final ItemStack is ) - { - return this.powerCapacity; - } + @Override + public double getAEMaxPower(final ItemStack is) { + return this.powerCapacity; + } - @Override - public double getAECurrentPower( final ItemStack is ) - { - final NBTTagCompound data = Platform.openNbtData( is ); + @Override + public double getAECurrentPower(final ItemStack is) { + final NBTTagCompound data = Platform.openNbtData(is); - return data.getDouble( CURRENT_POWER_NBT_KEY ); - } + return data.getDouble(CURRENT_POWER_NBT_KEY); + } - @Override - public AccessRestriction getPowerFlow( final ItemStack is ) - { - return AccessRestriction.WRITE; - } + @Override + public AccessRestriction getPowerFlow(final ItemStack is) { + return AccessRestriction.WRITE; + } - @Override - public ICapabilityProvider initCapabilities( ItemStack stack, NBTTagCompound nbt ) - { - return new PoweredItemCapabilities( stack, this ); - } + @Override + public ICapabilityProvider initCapabilities(ItemStack stack, NBTTagCompound nbt) { + return new PoweredItemCapabilities(stack, this); + } } diff --git a/src/main/java/appeng/items/tools/powered/powersink/PoweredItemCapabilities.java b/src/main/java/appeng/items/tools/powered/powersink/PoweredItemCapabilities.java index c28f0738c..5f397d59a 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/PoweredItemCapabilities.java +++ b/src/main/java/appeng/items/tools/powered/powersink/PoweredItemCapabilities.java @@ -19,8 +19,10 @@ package appeng.items.tools.powered.powersink; -import javax.annotation.Nullable; - +import appeng.api.config.Actionable; +import appeng.api.config.PowerUnits; +import appeng.api.implementations.items.IAEItemPowerStorage; +import appeng.capabilities.Capabilities; import net.darkhax.tesla.api.ITeslaConsumer; import net.darkhax.tesla.api.ITeslaHolder; import net.minecraft.item.ItemStack; @@ -29,117 +31,94 @@ import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.energy.IEnergyStorage; -import appeng.api.config.Actionable; -import appeng.api.config.PowerUnits; -import appeng.api.implementations.items.IAEItemPowerStorage; -import appeng.capabilities.Capabilities; +import javax.annotation.Nullable; /** * The capability provider to expose chargable items to other mods. */ -class PoweredItemCapabilities implements ICapabilityProvider, IEnergyStorage -{ +class PoweredItemCapabilities implements ICapabilityProvider, IEnergyStorage { - private final ItemStack is; + private final ItemStack is; - private final IAEItemPowerStorage item; + private final IAEItemPowerStorage item; - private final Object teslaAdapter; + private final Object teslaAdapter; - PoweredItemCapabilities( ItemStack is, IAEItemPowerStorage item ) - { - this.is = is; - this.item = item; - if( Capabilities.TESLA_CONSUMER != null || Capabilities.TESLA_HOLDER != null ) - { - this.teslaAdapter = new TeslaAdapter(); - } - else - { - this.teslaAdapter = null; - } - } + PoweredItemCapabilities(ItemStack is, IAEItemPowerStorage item) { + this.is = is; + this.item = item; + if (Capabilities.TESLA_CONSUMER != null || Capabilities.TESLA_HOLDER != null) { + this.teslaAdapter = new TeslaAdapter(); + } else { + this.teslaAdapter = null; + } + } - @Override - public boolean hasCapability( Capability capability, @Nullable EnumFacing facing ) - { - return capability == Capabilities.FORGE_ENERGY || capability == Capabilities.TESLA_CONSUMER || capability == Capabilities.TESLA_HOLDER; - } + @Override + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { + return capability == Capabilities.FORGE_ENERGY || capability == Capabilities.TESLA_CONSUMER || capability == Capabilities.TESLA_HOLDER; + } - @SuppressWarnings( "unchecked" ) - @Override - public T getCapability( Capability capability, @Nullable EnumFacing facing ) - { - if( capability == Capabilities.FORGE_ENERGY ) - { - return (T) this; - } - else if( capability == Capabilities.TESLA_CONSUMER || capability == Capabilities.TESLA_HOLDER ) - { - return (T) this.teslaAdapter; - } - return null; - } + @SuppressWarnings("unchecked") + @Override + public T getCapability(Capability capability, @Nullable EnumFacing facing) { + if (capability == Capabilities.FORGE_ENERGY) { + return (T) this; + } else if (capability == Capabilities.TESLA_CONSUMER || capability == Capabilities.TESLA_HOLDER) { + return (T) this.teslaAdapter; + } + return null; + } - @Override - public int receiveEnergy( int maxReceive, boolean simulate ) - { - final double convertedOffer = PowerUnits.RF.convertTo( PowerUnits.AE, maxReceive ); - final double overflow = this.item.injectAEPower( this.is, convertedOffer, simulate ? Actionable.SIMULATE : Actionable.MODULATE ); + @Override + public int receiveEnergy(int maxReceive, boolean simulate) { + final double convertedOffer = PowerUnits.RF.convertTo(PowerUnits.AE, maxReceive); + final double overflow = this.item.injectAEPower(this.is, convertedOffer, simulate ? Actionable.SIMULATE : Actionable.MODULATE); - return maxReceive - (int) PowerUnits.AE.convertTo( PowerUnits.RF, overflow ); - } + return maxReceive - (int) PowerUnits.AE.convertTo(PowerUnits.RF, overflow); + } - @Override - public int extractEnergy( int maxExtract, boolean simulate ) - { - return 0; - } + @Override + public int extractEnergy(int maxExtract, boolean simulate) { + return 0; + } - @Override - public int getEnergyStored() - { - return (int) PowerUnits.AE.convertTo( PowerUnits.RF, this.item.getAECurrentPower( this.is ) ); - } + @Override + public int getEnergyStored() { + return (int) PowerUnits.AE.convertTo(PowerUnits.RF, this.item.getAECurrentPower(this.is)); + } - @Override - public int getMaxEnergyStored() - { - return (int) PowerUnits.AE.convertTo( PowerUnits.RF, this.item.getAEMaxPower( this.is ) ); - } + @Override + public int getMaxEnergyStored() { + return (int) PowerUnits.AE.convertTo(PowerUnits.RF, this.item.getAEMaxPower(this.is)); + } - @Override - public boolean canExtract() - { - return false; - } + @Override + public boolean canExtract() { + return false; + } - @Override - public boolean canReceive() - { - return true; - } + @Override + public boolean canReceive() { + return true; + } - private class TeslaAdapter implements ITeslaConsumer, ITeslaHolder - { + private class TeslaAdapter implements ITeslaConsumer, ITeslaHolder { - @Override - public long givePower( long power, boolean simulated ) - { - return PoweredItemCapabilities.this.receiveEnergy( (int) power, simulated ); - } + @Override + public long givePower(long power, boolean simulated) { + return PoweredItemCapabilities.this.receiveEnergy((int) power, simulated); + } - @Override - public long getStoredPower() - { - return PoweredItemCapabilities.this.getEnergyStored(); - } + @Override + public long getStoredPower() { + return PoweredItemCapabilities.this.getEnergyStored(); + } - @Override - public long getCapacity() - { - return PoweredItemCapabilities.this.getMaxEnergyStored(); - } - } + @Override + public long getCapacity() { + return PoweredItemCapabilities.this.getMaxEnergyStored(); + } + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java index 0438e4d23..12867c00b 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java @@ -19,26 +19,22 @@ package appeng.items.tools.quartz; +import appeng.core.features.AEFeature; +import appeng.util.Platform; import net.minecraft.item.ItemAxe; import net.minecraft.item.ItemStack; -import appeng.core.features.AEFeature; -import appeng.util.Platform; +public class ToolQuartzAxe extends ItemAxe { + private final AEFeature type; -public class ToolQuartzAxe extends ItemAxe -{ - private final AEFeature type; + public ToolQuartzAxe(final AEFeature type) { + super(ToolMaterial.IRON); + this.type = type; + } - public ToolQuartzAxe( final AEFeature type ) - { - super( ToolMaterial.IRON ); - this.type = type; - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java index 0fd8fb449..40b97f978 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java @@ -19,6 +19,14 @@ package appeng.items.tools.quartz; +import appeng.api.implementations.guiobjects.IGuiItem; +import appeng.api.implementations.guiobjects.IGuiItemObject; +import appeng.api.util.AEPartLocation; +import appeng.core.features.AEFeature; +import appeng.core.sync.GuiBridge; +import appeng.items.AEBaseItem; +import appeng.items.contents.QuartzKnifeObj; +import appeng.util.Platform; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ActionResult; @@ -28,78 +36,58 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.api.implementations.guiobjects.IGuiItem; -import appeng.api.implementations.guiobjects.IGuiItemObject; -import appeng.api.util.AEPartLocation; -import appeng.core.features.AEFeature; -import appeng.core.sync.GuiBridge; -import appeng.items.AEBaseItem; -import appeng.items.contents.QuartzKnifeObj; -import appeng.util.Platform; +public class ToolQuartzCuttingKnife extends AEBaseItem implements IGuiItem { + private final AEFeature type; -public class ToolQuartzCuttingKnife extends AEBaseItem implements IGuiItem -{ - private final AEFeature type; + public ToolQuartzCuttingKnife(final AEFeature type) { + this.type = type; + this.setMaxDamage(50); + this.setMaxStackSize(1); + } - public ToolQuartzCuttingKnife( final AEFeature type ) - { - this.type = type; - this.setMaxDamage( 50 ); - this.setMaxStackSize( 1 ); - } + @Override + public EnumActionResult onItemUse(final EntityPlayer p, final World worldIn, final BlockPos pos, final EnumHand hand, final EnumFacing side, final float hitX, final float hitY, final float hitZ) { + if (Platform.isServer()) { + Platform.openGUI(p, null, AEPartLocation.INTERNAL, GuiBridge.GUI_QUARTZ_KNIFE); + } + return EnumActionResult.SUCCESS; + } - @Override - public EnumActionResult onItemUse( final EntityPlayer p, final World worldIn, final BlockPos pos, final EnumHand hand, final EnumFacing side, final float hitX, final float hitY, final float hitZ ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, null, AEPartLocation.INTERNAL, GuiBridge.GUI_QUARTZ_KNIFE ); - } - return EnumActionResult.SUCCESS; - } + @Override + public ActionResult onItemRightClick(final World w, final EntityPlayer p, final EnumHand hand) { + if (Platform.isServer()) { + Platform.openGUI(p, null, AEPartLocation.INTERNAL, GuiBridge.GUI_QUARTZ_KNIFE); + } + p.swingArm(hand); + return new ActionResult<>(EnumActionResult.SUCCESS, p.getHeldItem(hand)); + } - @Override - public ActionResult onItemRightClick( final World w, final EntityPlayer p, final EnumHand hand ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, null, AEPartLocation.INTERNAL, GuiBridge.GUI_QUARTZ_KNIFE ); - } - p.swingArm( hand ); - return new ActionResult<>( EnumActionResult.SUCCESS, p.getHeldItem( hand ) ); - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } + @Override + public boolean isRepairable() { + return false; + } - @Override - public boolean isRepairable() - { - return false; - } + @Override + public ItemStack getContainerItem(final ItemStack itemStack) { + ItemStack copy = itemStack.copy(); + copy.setItemDamage(itemStack.getItemDamage() + 1); - @Override - public ItemStack getContainerItem( final ItemStack itemStack ) - { - ItemStack copy = itemStack.copy(); - copy.setItemDamage( itemStack.getItemDamage() + 1 ); + return copy; + } - return copy; - } + @Override + public boolean hasContainerItem(final ItemStack stack) { + return true; + } - @Override - public boolean hasContainerItem( final ItemStack stack ) - { - return true; - } - - @Override - public IGuiItemObject getGuiObject( final ItemStack is, final World world, final BlockPos pos ) - { - return new QuartzKnifeObj( is ); - } + @Override + public IGuiItemObject getGuiObject(final ItemStack is, final World world, final BlockPos pos) { + return new QuartzKnifeObj(is); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java index c1376824a..8acdad49e 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java @@ -19,27 +19,23 @@ package appeng.items.tools.quartz; +import appeng.core.features.AEFeature; +import appeng.util.Platform; import net.minecraft.item.ItemHoe; import net.minecraft.item.ItemStack; -import appeng.core.features.AEFeature; -import appeng.util.Platform; +public class ToolQuartzHoe extends ItemHoe { + private final AEFeature type; -public class ToolQuartzHoe extends ItemHoe -{ - private final AEFeature type; + public ToolQuartzHoe(final AEFeature type) { + super(ToolMaterial.IRON); + this.type = type; + } - public ToolQuartzHoe( final AEFeature type ) - { - super( ToolMaterial.IRON ); - this.type = type; - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } } \ No newline at end of file diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java index 3b5bfbf6e..f2438dc12 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java @@ -19,26 +19,22 @@ package appeng.items.tools.quartz; +import appeng.core.features.AEFeature; +import appeng.util.Platform; import net.minecraft.item.ItemPickaxe; import net.minecraft.item.ItemStack; -import appeng.core.features.AEFeature; -import appeng.util.Platform; +public class ToolQuartzPickaxe extends ItemPickaxe { + private final AEFeature type; -public class ToolQuartzPickaxe extends ItemPickaxe -{ - private final AEFeature type; + public ToolQuartzPickaxe(final AEFeature type) { + super(ToolMaterial.IRON); + this.type = type; + } - public ToolQuartzPickaxe( final AEFeature type ) - { - super( ToolMaterial.IRON ); - this.type = type; - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java index ffcb6ec18..e3a418e85 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java @@ -19,26 +19,22 @@ package appeng.items.tools.quartz; +import appeng.core.features.AEFeature; +import appeng.util.Platform; import net.minecraft.item.ItemSpade; import net.minecraft.item.ItemStack; -import appeng.core.features.AEFeature; -import appeng.util.Platform; +public class ToolQuartzSpade extends ItemSpade { + private final AEFeature type; -public class ToolQuartzSpade extends ItemSpade -{ - private final AEFeature type; + public ToolQuartzSpade(final AEFeature type) { + super(ToolMaterial.IRON); + this.type = type; + } - public ToolQuartzSpade( final AEFeature type ) - { - super( ToolMaterial.IRON ); - this.type = type; - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java index 6cd0901e6..605426b20 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java @@ -19,26 +19,22 @@ package appeng.items.tools.quartz; +import appeng.core.features.AEFeature; +import appeng.util.Platform; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; -import appeng.core.features.AEFeature; -import appeng.util.Platform; +public class ToolQuartzSword extends ItemSword { + private final AEFeature type; -public class ToolQuartzSword extends ItemSword -{ - private final AEFeature type; + public ToolQuartzSword(AEFeature type) { + super(ToolMaterial.IRON); + this.type = type; + } - public ToolQuartzSword( AEFeature type ) - { - super( ToolMaterial.IRON ); - this.type = type; - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java index 8e28002ed..22dcd25a6 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java @@ -19,6 +19,11 @@ package appeng.items.tools.quartz; +import appeng.api.implementations.items.IAEWrench; +import appeng.api.util.DimensionalCoord; +import appeng.items.AEBaseItem; +import appeng.util.Platform; +import cofh.api.item.IToolHammer; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -32,96 +37,77 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.common.Optional.Interface; -import cofh.api.item.IToolHammer; - -import appeng.api.implementations.items.IAEWrench; -import appeng.api.util.DimensionalCoord; -import appeng.items.AEBaseItem; -import appeng.util.Platform; - // TODO BC Integration //@Interface( iface = "buildcraft.api.tools.IToolWrench", iname = IntegrationType.BuildCraftCore ) -@Interface( iface = "cofh.api.item.IToolHammer", modid = "cofhcore" ) -public class ToolQuartzWrench extends AEBaseItem implements IAEWrench, IToolHammer /* , IToolWrench */ -{ +@Interface(iface = "cofh.api.item.IToolHammer", modid = "cofhcore") +public class ToolQuartzWrench extends AEBaseItem implements IAEWrench, IToolHammer /* , IToolWrench */ { - public ToolQuartzWrench() - { - this.setMaxStackSize( 1 ); - this.setHarvestLevel( "wrench", 0 ); - } + public ToolQuartzWrench() { + this.setMaxStackSize(1); + this.setHarvestLevel("wrench", 0); + } - @Override - public EnumActionResult onItemUseFirst( final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand ) - { - final Block b = world.getBlockState( pos ).getBlock(); - if( b != null && !player.isSneaking() && Platform.hasPermissions( new DimensionalCoord( world, pos ), player ) ) - { - if( Platform.isClient() ) - { - // TODO 1.10-R - if we return FAIL on client, action will not be sent to server. Fix that in all - // Block#onItemUseFirst overrides. - return !world.isRemote ? EnumActionResult.SUCCESS : EnumActionResult.PASS; - } + @Override + public EnumActionResult onItemUseFirst(final EntityPlayer player, final World world, final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, final EnumHand hand) { + final Block b = world.getBlockState(pos).getBlock(); + if (b != null && !player.isSneaking() && Platform.hasPermissions(new DimensionalCoord(world, pos), player)) { + if (Platform.isClient()) { + // TODO 1.10-R - if we return FAIL on client, action will not be sent to server. Fix that in all + // Block#onItemUseFirst overrides. + return !world.isRemote ? EnumActionResult.SUCCESS : EnumActionResult.PASS; + } - if( b.rotateBlock( world, pos, side ) ) - { - player.swingArm( hand ); - return !world.isRemote ? EnumActionResult.SUCCESS : EnumActionResult.FAIL; - } - } - return EnumActionResult.PASS; - } + if (b.rotateBlock(world, pos, side)) { + player.swingArm(hand); + return !world.isRemote ? EnumActionResult.SUCCESS : EnumActionResult.FAIL; + } + } + return EnumActionResult.PASS; + } - @Override - public boolean doesSneakBypassUse( final ItemStack itemstack, final IBlockAccess world, final BlockPos pos, final EntityPlayer player ) - { - return true; - } + @Override + public boolean doesSneakBypassUse(final ItemStack itemstack, final IBlockAccess world, final BlockPos pos, final EntityPlayer player) { + return true; + } - @Override - public boolean canWrench( final ItemStack wrench, final EntityPlayer player, final BlockPos pos ) - { - return true; - } + @Override + public boolean canWrench(final ItemStack wrench, final EntityPlayer player, final BlockPos pos) { + return true; + } - // IToolHammer - start - @Override - public boolean isUsable( ItemStack item, EntityLivingBase user, BlockPos pos ) - { - return true; - } + // IToolHammer - start + @Override + public boolean isUsable(ItemStack item, EntityLivingBase user, BlockPos pos) { + return true; + } - @Override - public boolean isUsable( ItemStack item, EntityLivingBase user, Entity entity ) - { - return true; - } + @Override + public boolean isUsable(ItemStack item, EntityLivingBase user, Entity entity) { + return true; + } - @Override - public void toolUsed( ItemStack item, EntityLivingBase user, BlockPos pos ) - { - } + @Override + public void toolUsed(ItemStack item, EntityLivingBase user, BlockPos pos) { + } - @Override - public void toolUsed( ItemStack item, EntityLivingBase user, Entity entity ) - { - } + @Override + public void toolUsed(ItemStack item, EntityLivingBase user, Entity entity) { + } - // IToolHammer - end + // IToolHammer - end - // TODO: BC Wrench Integration - /* - * @Override - * public boolean canWrench( EntityPlayer player, int x, int y, int z ) - * { - * return true; - * } - * @Override - * public void wrenchUsed( EntityPlayer player, int x, int y, int z ) - * { - * player.swingItem(); - * } - */ + // TODO: BC Wrench Integration + /* + * @Override + * public boolean canWrench( EntityPlayer player, int x, int y, int z ) + * { + * return true; + * } + * @Override + * public void wrenchUsed( EntityPlayer player, int x, int y, int z ) + * { + * player.swingItem(); + * } + */ } diff --git a/src/main/java/appeng/loot/ChestLoot.java b/src/main/java/appeng/loot/ChestLoot.java index f7422cf02..4593a4840 100644 --- a/src/main/java/appeng/loot/ChestLoot.java +++ b/src/main/java/appeng/loot/ChestLoot.java @@ -19,11 +19,9 @@ package appeng.loot; -import net.minecraft.world.storage.loot.LootEntry; -import net.minecraft.world.storage.loot.LootEntryItem; -import net.minecraft.world.storage.loot.LootPool; -import net.minecraft.world.storage.loot.LootTableList; -import net.minecraft.world.storage.loot.RandomValueRange; +import appeng.api.AEApi; +import appeng.api.definitions.IMaterials; +import net.minecraft.world.storage.loot.*; import net.minecraft.world.storage.loot.conditions.LootCondition; import net.minecraft.world.storage.loot.conditions.RandomChance; import net.minecraft.world.storage.loot.functions.LootFunction; @@ -31,41 +29,35 @@ import net.minecraft.world.storage.loot.functions.SetMetadata; import net.minecraftforge.event.LootTableLoadEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import appeng.api.AEApi; -import appeng.api.definitions.IMaterials; +public class ChestLoot { -public class ChestLoot -{ + @SubscribeEvent + public void loadLootTable(LootTableLoadEvent event) { + if (event.getName() == LootTableList.CHESTS_ABANDONED_MINESHAFT) { + // TODO 1.9.4 aftermath - All these loot quality, pools and stuff. Figure it out and balance it. + final IMaterials materials = AEApi.instance().definitions().materials(); + materials.certusQuartzCrystal().maybeStack(1).ifPresent(is -> + { + event.getTable() + .addPool(new LootPool(new LootEntry[]{ + new LootEntryItem(is.getItem(), 2, 3, new LootFunction[]{ + new SetMetadata(null, new RandomValueRange(is.getItemDamage()))}, new LootCondition[]{ + new RandomChance(1)}, "AE2 Crystal_" + is.getItemDamage()) + }, new LootCondition[0], new RandomValueRange(1, 4), new RandomValueRange(0, 2), "AE2 Crystals")); + }); - @SubscribeEvent - public void loadLootTable( LootTableLoadEvent event ) - { - if( event.getName() == LootTableList.CHESTS_ABANDONED_MINESHAFT ) - { - // TODO 1.9.4 aftermath - All these loot quality, pools and stuff. Figure it out and balance it. - final IMaterials materials = AEApi.instance().definitions().materials(); - materials.certusQuartzCrystal().maybeStack( 1 ).ifPresent( is -> - { - event.getTable() - .addPool( new LootPool( new LootEntry[] { - new LootEntryItem( is.getItem(), 2, 3, new LootFunction[] { - new SetMetadata( null, new RandomValueRange( is.getItemDamage() ) ) }, new LootCondition[] { - new RandomChance( 1 ) }, "AE2 Crystal_" + is.getItemDamage() ) - }, new LootCondition[0], new RandomValueRange( 1, 4 ), new RandomValueRange( 0, 2 ), "AE2 Crystals" ) ); - } ); + materials.certusQuartzDust().maybeStack(1).ifPresent(is -> + { + event.getTable() + .addPool(new LootPool(new LootEntryItem[]{ + new LootEntryItem(is.getItem(), 2, 3, new LootFunction[]{ + new SetMetadata(null, new RandomValueRange(is.getItemDamage()))}, new LootCondition[]{ + new RandomChance(1)}, "AE2 Dust_" + is.getItemDamage()) + }, new LootCondition[0], new RandomValueRange(1, 4), new RandomValueRange(0, 2), "AE2 DUSTS")); + }); - materials.certusQuartzDust().maybeStack( 1 ).ifPresent( is -> - { - event.getTable() - .addPool( new LootPool( new LootEntryItem[] { - new LootEntryItem( is.getItem(), 2, 3, new LootFunction[] { - new SetMetadata( null, new RandomValueRange( is.getItemDamage() ) ) }, new LootCondition[] { - new RandomChance( 1 ) }, "AE2 Dust_" + is.getItemDamage() ) - }, new LootCondition[0], new RandomValueRange( 1, 4 ), new RandomValueRange( 0, 2 ), "AE2 DUSTS" ) ); - } ); - - } - } + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/me/Grid.java b/src/main/java/appeng/me/Grid.java index 6155c884f..9cea186c2 100644 --- a/src/main/java/appeng/me/Grid.java +++ b/src/main/java/appeng/me/Grid.java @@ -19,278 +19,226 @@ package appeng.me; -import java.util.*; -import java.util.Map.Entry; - import appeng.api.AEApi; -import appeng.api.networking.IGrid; -import appeng.api.networking.IGridCache; -import appeng.api.networking.IGridHost; -import appeng.api.networking.IGridNode; -import appeng.api.networking.IGridStorage; -import appeng.api.networking.IMachineSet; +import appeng.api.networking.*; import appeng.api.networking.events.MENetworkEvent; import appeng.api.networking.events.MENetworkPostCacheConstruction; import appeng.api.util.IReadOnlyCollection; import appeng.core.worlddata.WorldData; import appeng.hooks.TickHandler; import appeng.util.ReadOnlyCollection; -import appeng.me.cache.CraftingGridCache; + +import java.util.*; +import java.util.Map.Entry; -public class Grid implements IGrid -{ - private final NetworkEventBus eventBus = new NetworkEventBus(); - private final Map, MachineSet> machines = new HashMap<>(); - private final Map, GridCacheWrapper> caches = new HashMap<>(); - private GridNode pivot; - private int priority; // how import is this network? - private GridStorage myStorage; +public class Grid implements IGrid { + private final NetworkEventBus eventBus = new NetworkEventBus(); + private final Map, MachineSet> machines = new HashMap<>(); + private final Map, GridCacheWrapper> caches = new HashMap<>(); + private GridNode pivot; + private int priority; // how import is this network? + private GridStorage myStorage; - public Grid( final GridNode center ) - { - this.pivot = center; + public Grid(final GridNode center) { + this.pivot = center; - final Map, IGridCache> myCaches = AEApi.instance().registries().gridCache().createCacheInstance( this ); - for( final Entry, IGridCache> c : myCaches.entrySet() ) - { - final Class key = c.getKey(); - final IGridCache value = c.getValue(); - final Class valueClass = value.getClass(); + final Map, IGridCache> myCaches = AEApi.instance().registries().gridCache().createCacheInstance(this); + for (final Entry, IGridCache> c : myCaches.entrySet()) { + final Class key = c.getKey(); + final IGridCache value = c.getValue(); + final Class valueClass = value.getClass(); - this.eventBus.readClass( key, valueClass ); - this.caches.put( key, new GridCacheWrapper( value ) ); - } + this.eventBus.readClass(key, valueClass); + this.caches.put(key, new GridCacheWrapper(value)); + } - this.postEvent( new MENetworkPostCacheConstruction() ); + this.postEvent(new MENetworkPostCacheConstruction()); - TickHandler.INSTANCE.addNetwork( this ); - center.setGrid( this ); - } + TickHandler.INSTANCE.addNetwork(this); + center.setGrid(this); + } - int getPriority() - { - return this.priority; - } + int getPriority() { + return this.priority; + } - IGridStorage getMyStorage() - { - return this.myStorage; - } + IGridStorage getMyStorage() { + return this.myStorage; + } - Map, GridCacheWrapper> getCaches() - { - return this.caches; - } + Map, GridCacheWrapper> getCaches() { + return this.caches; + } - public Iterable> getMachineClasses() - { - return this.machines.keySet(); - } + public Iterable> getMachineClasses() { + return this.machines.keySet(); + } - int size() - { - int out = 0; - for( final Collection x : this.machines.values() ) - { - out += x.size(); - } - return out; - } + int size() { + int out = 0; + for (final Collection x : this.machines.values()) { + out += x.size(); + } + return out; + } - void remove( final GridNode gridNode ) - { - for( final IGridCache c : this.caches.values() ) - { - final IGridHost machine = gridNode.getMachine(); - c.removeNode( gridNode, machine ); - } + void remove(final GridNode gridNode) { + for (final IGridCache c : this.caches.values()) { + final IGridHost machine = gridNode.getMachine(); + c.removeNode(gridNode, machine); + } - final Class machineClass = gridNode.getMachineClass(); - final Set nodes = this.machines.get( machineClass ); - if( nodes != null ) - { - nodes.remove( gridNode ); - } + final Class machineClass = gridNode.getMachineClass(); + final Set nodes = this.machines.get(machineClass); + if (nodes != null) { + nodes.remove(gridNode); + } - gridNode.setGridStorage( null ); + gridNode.setGridStorage(null); - if( this.pivot == gridNode ) - { - final Iterator n = this.getNodes().iterator(); - if( n.hasNext() ) - { - this.pivot = (GridNode) n.next(); - } - else - { - this.pivot = null; - TickHandler.INSTANCE.removeNetwork( this ); - this.myStorage.remove(); - } - } - } + if (this.pivot == gridNode) { + final Iterator n = this.getNodes().iterator(); + if (n.hasNext()) { + this.pivot = (GridNode) n.next(); + } else { + this.pivot = null; + TickHandler.INSTANCE.removeNetwork(this); + this.myStorage.remove(); + } + } + } - void add( final GridNode gridNode ) - { - final Class mClass = gridNode.getMachineClass(); + void add(final GridNode gridNode) { + final Class mClass = gridNode.getMachineClass(); - MachineSet nodes = this.machines.get( mClass ); - if( nodes == null ) - { - nodes = new MachineSet( mClass ); - this.machines.put( mClass, nodes ); - this.eventBus.readClass( mClass, mClass ); - } + MachineSet nodes = this.machines.get(mClass); + if (nodes == null) { + nodes = new MachineSet(mClass); + this.machines.put(mClass, nodes); + this.eventBus.readClass(mClass, mClass); + } - // handle loading grid storages. - if( gridNode.getGridStorage() != null ) - { - final GridStorage gs = gridNode.getGridStorage(); - final IGrid grid = gs.getGrid(); + // handle loading grid storages. + if (gridNode.getGridStorage() != null) { + final GridStorage gs = gridNode.getGridStorage(); + final IGrid grid = gs.getGrid(); - if( grid == null ) - { - this.myStorage = gs; - this.myStorage.setGrid( this ); + if (grid == null) { + this.myStorage = gs; + this.myStorage.setGrid(this); - for( final IGridCache gc : this.caches.values() ) - { - gc.onJoin( this.myStorage ); - } - } - else if( grid != this ) - { - if( this.myStorage == null ) - { - this.myStorage = WorldData.instance().storageData().getNewGridStorage(); - this.myStorage.setGrid( this ); - } + for (final IGridCache gc : this.caches.values()) { + gc.onJoin(this.myStorage); + } + } else if (grid != this) { + if (this.myStorage == null) { + this.myStorage = WorldData.instance().storageData().getNewGridStorage(); + this.myStorage.setGrid(this); + } - final IGridStorage tmp = new GridStorage(); - if( !gs.hasDivided( this.myStorage ) ) - { - gs.addDivided( this.myStorage ); + final IGridStorage tmp = new GridStorage(); + if (!gs.hasDivided(this.myStorage)) { + gs.addDivided(this.myStorage); - for( final IGridCache gc : ( (Grid) grid ).caches.values() ) - { - gc.onSplit( tmp ); - } + for (final IGridCache gc : ((Grid) grid).caches.values()) { + gc.onSplit(tmp); + } - for( final IGridCache gc : this.caches.values() ) - { - gc.onJoin( tmp ); - } - } - } - } - else if( this.myStorage == null ) - { - this.myStorage = WorldData.instance().storageData().getNewGridStorage(); - this.myStorage.setGrid( this ); - } + for (final IGridCache gc : this.caches.values()) { + gc.onJoin(tmp); + } + } + } + } else if (this.myStorage == null) { + this.myStorage = WorldData.instance().storageData().getNewGridStorage(); + this.myStorage.setGrid(this); + } - // update grid node... - gridNode.setGridStorage( this.myStorage ); + // update grid node... + gridNode.setGridStorage(this.myStorage); - // track node. - nodes.add( gridNode ); + // track node. + nodes.add(gridNode); - for( final IGridCache cache : this.caches.values() ) - { - final IGridHost machine = gridNode.getMachine(); - cache.addNode( gridNode, machine ); - } + for (final IGridCache cache : this.caches.values()) { + final IGridHost machine = gridNode.getMachine(); + cache.addNode(gridNode, machine); + } - gridNode.getGridProxy().gridChanged(); - // postEventTo( gridNode, networkChanged ); - } + gridNode.getGridProxy().gridChanged(); + // postEventTo( gridNode, networkChanged ); + } - @Override - @SuppressWarnings( "unchecked" ) - public C getCache( final Class iface ) - { - return (C) this.caches.get( iface ).getCache(); - } + @Override + @SuppressWarnings("unchecked") + public C getCache(final Class iface) { + return (C) this.caches.get(iface).getCache(); + } - @Override - public MENetworkEvent postEvent( final MENetworkEvent ev ) - { - final MENetworkEvent ret = this.eventBus.postEvent( this, ev ); - return ret; - } + @Override + public MENetworkEvent postEvent(final MENetworkEvent ev) { + final MENetworkEvent ret = this.eventBus.postEvent(this, ev); + return ret; + } - @Override - public MENetworkEvent postEventTo( final IGridNode node, final MENetworkEvent ev ) - { - return this.eventBus.postEventTo( this, (GridNode) node, ev ); - } + @Override + public MENetworkEvent postEventTo(final IGridNode node, final MENetworkEvent ev) { + return this.eventBus.postEventTo(this, (GridNode) node, ev); + } - @Override - public IReadOnlyCollection> getMachinesClasses() - { - final Set> machineKeys = this.machines.keySet(); + @Override + public IReadOnlyCollection> getMachinesClasses() { + final Set> machineKeys = this.machines.keySet(); - return new ReadOnlyCollection<>( machineKeys ); - } + return new ReadOnlyCollection<>(machineKeys); + } - @Override - public IMachineSet getMachines( final Class c ) - { - final MachineSet s = this.machines.get( c ); - if( s == null ) - { - return new MachineSet( c ); - } - return s; - } + @Override + public IMachineSet getMachines(final Class c) { + final MachineSet s = this.machines.get(c); + if (s == null) { + return new MachineSet(c); + } + return s; + } - @Override - public IReadOnlyCollection getNodes() - { - return new GridNodeCollection( this.machines ); - } + @Override + public IReadOnlyCollection getNodes() { + return new GridNodeCollection(this.machines); + } - @Override - public boolean isEmpty() - { - return this.pivot == null; - } + @Override + public boolean isEmpty() { + return this.pivot == null; + } - @Override - public IGridNode getPivot() - { - return this.pivot; - } + @Override + public IGridNode getPivot() { + return this.pivot; + } - void setPivot( final GridNode pivot ) - { - this.pivot = pivot; - } + void setPivot(final GridNode pivot) { + this.pivot = pivot; + } - public void update() - { - for( final IGridCache gc : this.caches.values() ) - { - // are there any nodes left? - if( this.pivot != null ) - { - gc.onUpdateTick(); - } - } - } + public void update() { + for (final IGridCache gc : this.caches.values()) { + // are there any nodes left? + if (this.pivot != null) { + gc.onUpdateTick(); + } + } + } - void saveState() - { - for( final IGridCache c : this.caches.values() ) - { - c.populateGridStorage( this.myStorage ); - } - } + void saveState() { + for (final IGridCache c : this.caches.values()) { + c.populateGridStorage(this.myStorage); + } + } - public void setImportantFlag( final int i, final boolean publicHasPower ) - { - final int flag = 1 << i; - this.priority = ( this.priority & ~flag ) | ( publicHasPower ? flag : 0 ); - } + public void setImportantFlag(final int i, final boolean publicHasPower) { + final int flag = 1 << i; + this.priority = (this.priority & ~flag) | (publicHasPower ? flag : 0); + } } diff --git a/src/main/java/appeng/me/GridAccessException.java b/src/main/java/appeng/me/GridAccessException.java index 6877e2176..9a2b59ae1 100644 --- a/src/main/java/appeng/me/GridAccessException.java +++ b/src/main/java/appeng/me/GridAccessException.java @@ -19,8 +19,7 @@ package appeng.me; -public class GridAccessException extends Exception -{ +public class GridAccessException extends Exception { - private static final long serialVersionUID = 3914554394866375300L; + private static final long serialVersionUID = 3914554394866375300L; } diff --git a/src/main/java/appeng/me/GridCacheWrapper.java b/src/main/java/appeng/me/GridCacheWrapper.java index 2825faa45..8fe591b6b 100644 --- a/src/main/java/appeng/me/GridCacheWrapper.java +++ b/src/main/java/appeng/me/GridCacheWrapper.java @@ -25,61 +25,51 @@ import appeng.api.networking.IGridNode; import appeng.api.networking.IGridStorage; -public class GridCacheWrapper implements IGridCache -{ +public class GridCacheWrapper implements IGridCache { - private final IGridCache myCache; - private final String name; + private final IGridCache myCache; + private final String name; - public GridCacheWrapper( final IGridCache gc ) - { - this.myCache = gc; - this.name = this.getCache().getClass().getName(); - } + public GridCacheWrapper(final IGridCache gc) { + this.myCache = gc; + this.name = this.getCache().getClass().getName(); + } - @Override - public void onUpdateTick() - { - this.getCache().onUpdateTick(); - } + @Override + public void onUpdateTick() { + this.getCache().onUpdateTick(); + } - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - this.getCache().removeNode( gridNode, machine ); - } + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + this.getCache().removeNode(gridNode, machine); + } - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - this.getCache().addNode( gridNode, machine ); - } + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + this.getCache().addNode(gridNode, machine); + } - @Override - public void onSplit( final IGridStorage storageB ) - { - this.getCache().onSplit( storageB ); - } + @Override + public void onSplit(final IGridStorage storageB) { + this.getCache().onSplit(storageB); + } - @Override - public void onJoin( final IGridStorage storageB ) - { - this.getCache().onJoin( storageB ); - } + @Override + public void onJoin(final IGridStorage storageB) { + this.getCache().onJoin(storageB); + } - @Override - public void populateGridStorage( final IGridStorage storage ) - { - this.getCache().populateGridStorage( storage ); - } + @Override + public void populateGridStorage(final IGridStorage storage) { + this.getCache().populateGridStorage(storage); + } - public String getName() - { - return this.name; - } + public String getName() { + return this.name; + } - IGridCache getCache() - { - return this.myCache; - } + IGridCache getCache() { + return this.myCache; + } } diff --git a/src/main/java/appeng/me/GridConnection.java b/src/main/java/appeng/me/GridConnection.java index 5c4330cdc..f7208f518 100644 --- a/src/main/java/appeng/me/GridConnection.java +++ b/src/main/java/appeng/me/GridConnection.java @@ -19,9 +19,6 @@ package appeng.me; -import java.util.Arrays; -import java.util.EnumSet; - import appeng.api.exceptions.ExistingConnectionException; import appeng.api.exceptions.FailedConnectionException; import appeng.api.exceptions.NullNodeConnectionException; @@ -41,262 +38,218 @@ import appeng.me.pathfinding.IPathItem; import appeng.util.Platform; import appeng.util.ReadOnlyCollection; +import java.util.Arrays; +import java.util.EnumSet; -public class GridConnection implements IGridConnection, IPathItem -{ - private static final String EXISTING_CONNECTION_MESSAGE = "Connection between node [machine=%s, %s] and [machine=%s, %s] on [%s] already exists."; +public class GridConnection implements IGridConnection, IPathItem { - private static final MENetworkChannelsChanged EVENT = new MENetworkChannelsChanged(); - private int channelData = 0; - private Object visitorIterationNumber = null; - private GridNode sideA; - private AEPartLocation fromAtoB; - private GridNode sideB; + private static final String EXISTING_CONNECTION_MESSAGE = "Connection between node [machine=%s, %s] and [machine=%s, %s] on [%s] already exists."; - private GridConnection( final GridNode aNode, final GridNode bNode, final AEPartLocation fromAtoB ) - { - this.sideA = aNode; - this.fromAtoB = fromAtoB; - this.sideB = bNode; - } + private static final MENetworkChannelsChanged EVENT = new MENetworkChannelsChanged(); + private int channelData = 0; + private Object visitorIterationNumber = null; + private GridNode sideA; + private AEPartLocation fromAtoB; + private GridNode sideB; - private boolean isNetworkABetter( final GridNode a, final GridNode b ) - { - return a.getMyGrid().getPriority() > b.getMyGrid().getPriority() || a.getMyGrid().size() > b.getMyGrid().size(); - } + private GridConnection(final GridNode aNode, final GridNode bNode, final AEPartLocation fromAtoB) { + this.sideA = aNode; + this.fromAtoB = fromAtoB; + this.sideB = bNode; + } - @Override - public IGridNode getOtherSide( final IGridNode gridNode ) - { - if( gridNode == this.sideA ) - { - return this.sideB; - } - if( gridNode == this.sideB ) - { - return this.sideA; - } + private boolean isNetworkABetter(final GridNode a, final GridNode b) { + return a.getMyGrid().getPriority() > b.getMyGrid().getPriority() || a.getMyGrid().size() > b.getMyGrid().size(); + } - throw new GridException( "Invalid Side of Connection" ); - } + @Override + public IGridNode getOtherSide(final IGridNode gridNode) { + if (gridNode == this.sideA) { + return this.sideB; + } + if (gridNode == this.sideB) { + return this.sideA; + } - @Override - public AEPartLocation getDirection( final IGridNode side ) - { - if( this.fromAtoB == AEPartLocation.INTERNAL ) - { - return this.fromAtoB; - } + throw new GridException("Invalid Side of Connection"); + } - if( this.sideA == side ) - { - return this.fromAtoB; - } - else - { - return this.fromAtoB.getOpposite(); - } - } + @Override + public AEPartLocation getDirection(final IGridNode side) { + if (this.fromAtoB == AEPartLocation.INTERNAL) { + return this.fromAtoB; + } - @Override - public void destroy() - { - // a connection was destroyed RE-PATH!! - final IPathingGrid p = this.sideA.getInternalGrid().getCache( IPathingGrid.class ); - p.repath(); + if (this.sideA == side) { + return this.fromAtoB; + } else { + return this.fromAtoB.getOpposite(); + } + } - this.sideA.removeConnection( this ); - this.sideB.removeConnection( this ); + @Override + public void destroy() { + // a connection was destroyed RE-PATH!! + final IPathingGrid p = this.sideA.getInternalGrid().getCache(IPathingGrid.class); + p.repath(); - this.sideA.validateGrid(); - this.sideB.validateGrid(); - } + this.sideA.removeConnection(this); + this.sideB.removeConnection(this); - @Override - public IGridNode a() - { - return this.sideA; - } + this.sideA.validateGrid(); + this.sideB.validateGrid(); + } - @Override - public IGridNode b() - { - return this.sideB; - } + @Override + public IGridNode a() { + return this.sideA; + } - @Override - public boolean hasDirection() - { - return this.fromAtoB != AEPartLocation.INTERNAL; - } + @Override + public IGridNode b() { + return this.sideB; + } - @Override - public int getUsedChannels() - { - return ( this.channelData >> 8 ) & 0xff; - } + @Override + public boolean hasDirection() { + return this.fromAtoB != AEPartLocation.INTERNAL; + } - @Override - public IPathItem getControllerRoute() - { - if( this.sideA.getFlags().contains( GridFlags.CANNOT_CARRY ) ) - { - return null; - } - return this.sideA; - } + @Override + public int getUsedChannels() { + return (this.channelData >> 8) & 0xff; + } - @Override - public void setControllerRoute( final IPathItem fast, final boolean zeroOut ) - { - if( zeroOut ) - { - this.channelData &= ~0xff; - } + @Override + public IPathItem getControllerRoute() { + if (this.sideA.getFlags().contains(GridFlags.CANNOT_CARRY)) { + return null; + } + return this.sideA; + } - if( this.sideB == fast ) - { - final GridNode tmp = this.sideA; - this.sideA = this.sideB; - this.sideB = tmp; - this.fromAtoB = this.fromAtoB.getOpposite(); - } - } + @Override + public void setControllerRoute(final IPathItem fast, final boolean zeroOut) { + if (zeroOut) { + this.channelData &= ~0xff; + } - @Override - public boolean canSupportMoreChannels() - { - return this.getLastUsedChannels() < 32; // max, PERIOD. - } + if (this.sideB == fast) { + final GridNode tmp = this.sideA; + this.sideA = this.sideB; + this.sideB = tmp; + this.fromAtoB = this.fromAtoB.getOpposite(); + } + } - @Override - public IReadOnlyCollection getPossibleOptions() - { - return new ReadOnlyCollection<>( Arrays.asList( (IPathItem) this.a(), (IPathItem) this.b() ) ); - } + @Override + public boolean canSupportMoreChannels() { + return this.getLastUsedChannels() < 32; // max, PERIOD. + } - @Override - public void incrementChannelCount( final int usedChannels ) - { - this.channelData += usedChannels; - } + @Override + public IReadOnlyCollection getPossibleOptions() { + return new ReadOnlyCollection<>(Arrays.asList((IPathItem) this.a(), (IPathItem) this.b())); + } - @Override - public EnumSet getFlags() - { - return EnumSet.noneOf( GridFlags.class ); - } + @Override + public void incrementChannelCount(final int usedChannels) { + this.channelData += usedChannels; + } - @Override - public void finalizeChannels() - { - if( this.getUsedChannels() != this.getLastUsedChannels() ) - { - this.channelData &= 0xff; - this.channelData |= this.channelData << 8; + @Override + public EnumSet getFlags() { + return EnumSet.noneOf(GridFlags.class); + } - if( this.sideA.getInternalGrid() != null ) - { - this.sideA.getInternalGrid().postEventTo( this.sideA, EVENT ); - } + @Override + public void finalizeChannels() { + if (this.getUsedChannels() != this.getLastUsedChannels()) { + this.channelData &= 0xff; + this.channelData |= this.channelData << 8; - if( this.sideB.getInternalGrid() != null ) - { - this.sideB.getInternalGrid().postEventTo( this.sideB, EVENT ); - } - } - } + if (this.sideA.getInternalGrid() != null) { + this.sideA.getInternalGrid().postEventTo(this.sideA, EVENT); + } - private int getLastUsedChannels() - { - return this.channelData & 0xff; - } + if (this.sideB.getInternalGrid() != null) { + this.sideB.getInternalGrid().postEventTo(this.sideB, EVENT); + } + } + } - Object getVisitorIterationNumber() - { - return this.visitorIterationNumber; - } + private int getLastUsedChannels() { + return this.channelData & 0xff; + } - void setVisitorIterationNumber( final Object visitorIterationNumber ) - { - this.visitorIterationNumber = visitorIterationNumber; - } + Object getVisitorIterationNumber() { + return this.visitorIterationNumber; + } - public static GridConnection create( final IGridNode aNode, final IGridNode bNode, final AEPartLocation fromAtoB ) throws FailedConnectionException - { - if( aNode == null || bNode == null ) - { - throw new NullNodeConnectionException(); - } + void setVisitorIterationNumber(final Object visitorIterationNumber) { + this.visitorIterationNumber = visitorIterationNumber; + } - final GridNode a = (GridNode) aNode; - final GridNode b = (GridNode) bNode; + public static GridConnection create(final IGridNode aNode, final IGridNode bNode, final AEPartLocation fromAtoB) throws FailedConnectionException { + if (aNode == null || bNode == null) { + throw new NullNodeConnectionException(); + } - if( a.hasConnection( b ) || b.hasConnection( a ) ) - { - final String aMachineClass = a.getGridBlock().getMachine().getClass().getSimpleName(); - final String bMachineClass = b.getGridBlock().getMachine().getClass().getSimpleName(); - final String aCoordinates = a.getGridBlock().getLocation().toString(); - final String bCoordinates = b.getGridBlock().getLocation().toString(); + final GridNode a = (GridNode) aNode; + final GridNode b = (GridNode) bNode; - throw new ExistingConnectionException( String.format( EXISTING_CONNECTION_MESSAGE, aMachineClass, aCoordinates, bMachineClass, bCoordinates, - fromAtoB ) ); - } + if (a.hasConnection(b) || b.hasConnection(a)) { + final String aMachineClass = a.getGridBlock().getMachine().getClass().getSimpleName(); + final String bMachineClass = b.getGridBlock().getMachine().getClass().getSimpleName(); + final String aCoordinates = a.getGridBlock().getLocation().toString(); + final String bCoordinates = b.getGridBlock().getLocation().toString(); - if( !Platform.securityCheck( a, b ) ) - { - if( AEConfig.instance().isFeatureEnabled( AEFeature.LOG_SECURITY_AUDITS ) ) - { - final DimensionalCoord aCoordinates = a.getGridBlock().getLocation(); - final DimensionalCoord bCoordinates = b.getGridBlock().getLocation(); + throw new ExistingConnectionException(String.format(EXISTING_CONNECTION_MESSAGE, aMachineClass, aCoordinates, bMachineClass, bCoordinates, + fromAtoB)); + } - AELog.info( "Security audit 1 failed at [%s] belonging to player [id=%d]", aCoordinates.toString(), a.getPlayerID() ); - AELog.info( "Security audit 2 failed at [%s] belonging to player [id=%d]", bCoordinates.toString(), b.getPlayerID() ); - } + if (!Platform.securityCheck(a, b)) { + if (AEConfig.instance().isFeatureEnabled(AEFeature.LOG_SECURITY_AUDITS)) { + final DimensionalCoord aCoordinates = a.getGridBlock().getLocation(); + final DimensionalCoord bCoordinates = b.getGridBlock().getLocation(); - throw new SecurityConnectionException(); - } + AELog.info("Security audit 1 failed at [%s] belonging to player [id=%d]", aCoordinates.toString(), a.getPlayerID()); + AELog.info("Security audit 2 failed at [%s] belonging to player [id=%d]", bCoordinates.toString(), b.getPlayerID()); + } - // Create the actual connection - final GridConnection connection = new GridConnection( a, b, fromAtoB ); + throw new SecurityConnectionException(); + } - // Update both nodes with the new connection. - if( a.getMyGrid() == null ) - { - b.setGrid( a.getInternalGrid() ); - } - else - { - if( a.getMyGrid() == null ) - { - final GridPropagator gp = new GridPropagator( b.getInternalGrid() ); - aNode.beginVisit( gp ); - } - else if( b.getMyGrid() == null ) - { - final GridPropagator gp = new GridPropagator( a.getInternalGrid() ); - bNode.beginVisit( gp ); - } - else if( connection.isNetworkABetter( a, b ) ) - { - final GridPropagator gp = new GridPropagator( a.getInternalGrid() ); - b.beginVisit( gp ); - } - else - { - final GridPropagator gp = new GridPropagator( b.getInternalGrid() ); - a.beginVisit( gp ); - } - } + // Create the actual connection + final GridConnection connection = new GridConnection(a, b, fromAtoB); - // a connection was destroyed RE-PATH!! - final IPathingGrid p = connection.sideA.getInternalGrid().getCache( IPathingGrid.class ); - p.repath(); + // Update both nodes with the new connection. + if (a.getMyGrid() == null) { + b.setGrid(a.getInternalGrid()); + } else { + if (a.getMyGrid() == null) { + final GridPropagator gp = new GridPropagator(b.getInternalGrid()); + aNode.beginVisit(gp); + } else if (b.getMyGrid() == null) { + final GridPropagator gp = new GridPropagator(a.getInternalGrid()); + bNode.beginVisit(gp); + } else if (connection.isNetworkABetter(a, b)) { + final GridPropagator gp = new GridPropagator(a.getInternalGrid()); + b.beginVisit(gp); + } else { + final GridPropagator gp = new GridPropagator(b.getInternalGrid()); + a.beginVisit(gp); + } + } - connection.sideA.addConnection( connection ); - connection.sideB.addConnection( connection ); + // a connection was destroyed RE-PATH!! + final IPathingGrid p = connection.sideA.getInternalGrid().getCache(IPathingGrid.class); + p.repath(); - return connection; - } + connection.sideA.addConnection(connection); + connection.sideB.addConnection(connection); + + return connection; + } } diff --git a/src/main/java/appeng/me/GridException.java b/src/main/java/appeng/me/GridException.java index 5a3f418b7..6b4902782 100644 --- a/src/main/java/appeng/me/GridException.java +++ b/src/main/java/appeng/me/GridException.java @@ -19,14 +19,12 @@ package appeng.me; -public class GridException extends RuntimeException -{ +public class GridException extends RuntimeException { - private static final long serialVersionUID = -8110077032108243076L; + private static final long serialVersionUID = -8110077032108243076L; - public GridException( final String s ) - { + public GridException(final String s) { - super( s ); - } + super(s); + } } diff --git a/src/main/java/appeng/me/GridNode.java b/src/main/java/appeng/me/GridNode.java index 168d9b4a0..bbeedf120 100644 --- a/src/main/java/appeng/me/GridNode.java +++ b/src/main/java/appeng/me/GridNode.java @@ -19,34 +19,9 @@ package appeng.me; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Deque; -import java.util.EnumSet; -import java.util.List; - -import appeng.core.AEConfig; -import appeng.core.features.AEFeature; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import appeng.api.exceptions.FailedConnectionException; import appeng.api.exceptions.SecurityConnectionException; -import appeng.api.networking.GridFlags; -import appeng.api.networking.GridNotification; -import appeng.api.networking.IGrid; -import appeng.api.networking.IGridBlock; -import appeng.api.networking.IGridCache; -import appeng.api.networking.IGridConnection; -import appeng.api.networking.IGridConnectionVisitor; -import appeng.api.networking.IGridHost; -import appeng.api.networking.IGridNode; -import appeng.api.networking.IGridVisitor; +import appeng.api.networking.*; import appeng.api.networking.energy.IEnergyGrid; import appeng.api.networking.events.MENetworkChannelsChanged; import appeng.api.networking.pathing.IPathingGrid; @@ -54,713 +29,579 @@ import appeng.api.util.AEColor; import appeng.api.util.AEPartLocation; import appeng.api.util.DimensionalCoord; import appeng.api.util.IReadOnlyCollection; +import appeng.core.AEConfig; import appeng.core.AELog; +import appeng.core.features.AEFeature; import appeng.core.worlddata.WorldData; import appeng.hooks.TickHandler; -import appeng.me.cache.CraftingGridCache; import appeng.me.pathfinding.IPathItem; import appeng.util.IWorldCallable; import appeng.util.ReadOnlyCollection; -import net.minecraftforge.common.util.Constants; - - -public class GridNode implements IGridNode, IPathItem -{ - private static final MENetworkChannelsChanged EVENT = new MENetworkChannelsChanged(); - private static final int[] CHANNEL_COUNT = {0, 8, 32}; - - private final List connections = new ArrayList<>(); - private final IGridBlock gridProxy; - // old power draw, used to diff - private double previousDraw = 0.0; - private long lastSecurityKey = -1; - private int playerID = -1; - private GridStorage myStorage = null; - private Grid myGrid; - private Object visitorIterationNumber = null; - // connection criteria - private int compressedData = 0; - private int usedChannels = 0; - private int lastUsedChannels = 0; - - public GridNode( final IGridBlock what ) - { - this.gridProxy = what; - } - - IGridBlock getGridProxy() - { - return this.gridProxy; - } - - Grid getMyGrid() - { - return this.myGrid; - } - - public int usedChannels() - { - return this.lastUsedChannels; - } - - Class getMachineClass() - { - return this.getMachine().getClass(); - } - - void addConnection( final IGridConnection gridConnection ) - { - this.connections.add( gridConnection ); - if( gridConnection.hasDirection() ) - { - this.gridProxy.onGridNotification( GridNotification.CONNECTIONS_CHANGED ); - } - - final IGridNode gn = this; - - Collections.sort( this.connections, new ConnectionComparator( gn ) ); - } - - void removeConnection( final IGridConnection gridConnection ) - { - this.connections.remove( gridConnection ); - if( gridConnection.hasDirection() ) - { - this.gridProxy.onGridNotification( GridNotification.CONNECTIONS_CHANGED ); - } - } - - boolean hasConnection( final IGridNode otherSide ) - { - for( final IGridConnection gc : this.connections ) - { - if( gc.a() == otherSide || gc.b() == otherSide ) - { - return true; - } - } - return false; - } - - void validateGrid() - { - final GridSplitDetector gsd = new GridSplitDetector( this.getInternalGrid().getPivot() ); - this.beginVisit( gsd ); - if( !gsd.isPivotFound() ) - { - final IGridVisitor gp = new GridPropagator( new Grid( this ) ); - this.beginVisit( gp ); - } - } - - public Grid getInternalGrid() - { - if( this.myGrid == null ) - { - this.myGrid = new Grid( this ); - } - - return this.myGrid; - } - - @Override - public void beginVisit( final IGridVisitor g ) - { - final Object tracker = new Object(); - - Deque nextRun = new ArrayDeque<>(); - nextRun.add( this ); - - this.visitorIterationNumber = tracker; - - if( g instanceof IGridConnectionVisitor ) - { - final Deque nextConn = new ArrayDeque<>(); - final IGridConnectionVisitor gcv = (IGridConnectionVisitor) g; - - while ( !nextRun.isEmpty() ) - { - while ( !nextConn.isEmpty() ) - { - gcv.visitConnection( nextConn.poll() ); - } - - final Iterable thisRun = nextRun; - nextRun = new ArrayDeque<>(); - - for( final GridNode n : thisRun ) - { - n.visitorConnection( tracker, g, nextRun, nextConn ); - } - } - } - else - { - while ( !nextRun.isEmpty() ) - { - final Iterable thisRun = nextRun; - nextRun = new ArrayDeque<>(); - - for( final GridNode n : thisRun ) - { - n.visitorNode( tracker, g, nextRun ); - } - } - } - } - - @Override - public void updateState() - { - final EnumSet set = this.gridProxy.getFlags(); - - this.compressedData = set.contains( GridFlags.CANNOT_CARRY ) ? 0 : ( set.contains( GridFlags.DENSE_CAPACITY ) ? 2 : 1 ); - - this.compressedData |= ( this.gridProxy.getGridColor().ordinal() << 3 ); - - for( final EnumFacing dir : this.gridProxy.getConnectableSides() ) - { - this.compressedData |= ( 1 << ( dir.ordinal() + 8 ) ); - } - - this.findConnections(); - this.getInternalGrid(); - } - - @Override - public IGridHost getMachine() - { - return this.gridProxy.getMachine(); - } - - @Override - public IGrid getGrid() - { - return this.myGrid; - } - - void setGrid( final Grid grid ) - { - if( this.myGrid == grid ) - { - return; - } - - if( this.myGrid != null ) - { - this.myGrid.remove( this ); - - if( this.myGrid.isEmpty() ) - { - this.myGrid.saveState(); - - for( final IGridCache c : grid.getCaches().values() ) - { - c.onJoin( this.myGrid.getMyStorage() ); - } - } - } - - this.myGrid = grid; - this.myGrid.add( this ); - } - - @Override - public void destroy() - { - while ( !this.connections.isEmpty() ) - { - // not part of this network for real anymore. - if( this.connections.size() == 1 ) - { - this.setGridStorage( null ); - } - - final IGridConnection c = this.connections.listIterator().next(); - final GridNode otherSide = (GridNode) c.getOtherSide( this ); - otherSide.getInternalGrid().setPivot( otherSide ); - c.destroy(); - } - - if( this.myGrid != null ) - { - this.myGrid.remove( this ); - } - } - - @Override - public World getWorld() - { - return this.gridProxy.getLocation().getWorld(); - } - - @Override - public EnumSet getConnectedSides() - { - final EnumSet set = EnumSet.noneOf( AEPartLocation.class ); - for( final IGridConnection gc : this.connections ) - { - set.add( gc.getDirection( this ) ); - } - return set; - } - - @Override - public IReadOnlyCollection getConnections() - { - return new ReadOnlyCollection<>( this.connections ); - } - - @Override - public IGridBlock getGridBlock() - { - return this.gridProxy; - } - - @Override - public boolean isActive() - { - final IGrid g = this.getGrid(); - if( g != null ) - { - final IPathingGrid pg = g.getCache( IPathingGrid.class ); - final IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - return eg.isNetworkPowered() && !pg.isNetworkBooting() && this.meetsChannelRequirements(); - } - return false; - } - - @Override - public void loadFromNBT( final String name, final NBTTagCompound nodeData ) - { - if( this.myGrid != null ) - { - throw new IllegalStateException( "Loading data after part of a grid, this is invalid." ); - } - if( nodeData.hasKey( name, 10 ) ) - { - final NBTTagCompound node = nodeData.getCompoundTag( name ); - this.playerID = node.getInteger( "p" ); - this.setLastSecurityKey( node.getLong( "k" ) ); - - final long storageID = node.getLong( "g" ); - final GridStorage gridStorage = WorldData.instance().storageData().getGridStorage( storageID ); - this.setGridStorage( gridStorage ); - } - else - { - this.playerID = -1; // Unknown owner - setLastSecurityKey( -1 ); - setGridStorage( null ); - } - } - - @Override - public void saveToNBT( final String name, final NBTTagCompound nodeData ) - { - if( this.myStorage != null ) - { - final NBTTagCompound node = new NBTTagCompound(); - - node.setInteger( "p", this.playerID ); - node.setLong( "k", this.getLastSecurityKey() ); - node.setLong( "g", this.myStorage.getID() ); - - nodeData.setTag( name, node ); - } - else - { - nodeData.removeTag( name ); - } - } - - @Override - public boolean meetsChannelRequirements() - { - if( this.gridProxy.getFlags().contains( GridFlags.REQUIRE_CHANNEL ) ) - { - if( AEConfig.instance().isFeatureEnabled( AEFeature.CHANNELS ) ) - { - return this.getUsedChannels() > 0; - } - } - return true; - } - - @Override - public boolean hasFlag( final GridFlags flag ) - { - return this.gridProxy.getFlags().contains( flag ); - } - - @Override - public int getPlayerID() - { - return this.playerID; - } - - @Override - public void setPlayerID( final int playerID ) - { - if( playerID >= 0 ) - { - this.playerID = playerID; - } - } - - private int getUsedChannels() - { - return this.usedChannels; - } - - private void findConnections() - { - if( !this.gridProxy.isWorldAccessible() ) - { - return; - } - - final EnumSet newSecurityConnections = EnumSet.noneOf( AEPartLocation.class ); - - final DimensionalCoord dc = this.gridProxy.getLocation(); - for( final AEPartLocation f : AEPartLocation.SIDE_LOCATIONS ) - { - final IGridHost te = this.findGridHost( dc.getWorld(), dc.x + f.xOffset, dc.y + f.yOffset, dc.z + f.zOffset ); - if( te != null ) - { - final GridNode node = (GridNode) te.getGridNode( f.getOpposite() ); - if( node == null ) - { - continue; - } - - final boolean isValidConnection = this.canConnect( node, f ) && node.canConnect( this, f.getOpposite() ); - - IGridConnection con = null; // find the connection for this - // direction.. - for( final IGridConnection c : this.getConnections() ) - { - if( c.getDirection( this ) == f ) - { - con = c; - break; - } - } - - if( con != null ) - { - final IGridNode os = con.getOtherSide( this ); - if( os == node ) - { - // if this connection is no longer valid, destroy it. - if( !isValidConnection ) - { - con.destroy(); - } - } - else - { - con.destroy(); - // throw new GridException( "invalid state found, encountered connection to phantom block." ); - } - } - else if( isValidConnection ) - { - if( node.getLastSecurityKey() != -1 ) - { - newSecurityConnections.add( f ); - } - else - { - // construct a new connection between these two nodes. - try - { - GridConnection.create( node, this, f.getOpposite() ); - } - catch( SecurityConnectionException e ) - { - AELog.debug( e ); - TickHandler.INSTANCE.addCallable( node.getWorld(), new MachineSecurityBreak( this ) ); - - return; - } - catch( final FailedConnectionException e ) - { - AELog.debug( e ); - - return; - } - } - } - } - } - - for( final AEPartLocation f : newSecurityConnections ) - { - final IGridHost te = this.findGridHost( dc.getWorld(), dc.x + f.xOffset, dc.y + f.yOffset, dc.z + f.zOffset ); - if( te != null ) - { - final GridNode node = (GridNode) te.getGridNode( f.getOpposite() ); - if( node == null ) - { - continue; - } - - // construct a new connection between these two nodes. - try - { - GridConnection.create( node, this, f.getOpposite() ); - } - catch( SecurityConnectionException e ) - { - AELog.debug( e ); - - TickHandler.INSTANCE.addCallable( node.getWorld(), new MachineSecurityBreak( this ) ); - - return; - } - catch( final FailedConnectionException e ) - { - AELog.debug( e ); - - return; - } - } - } - } - - private IGridHost findGridHost( final World world, final int x, final int y, final int z ) - { - final BlockPos pos = new BlockPos( x, y, z ); - if( world.isBlockLoaded( pos ) ) - { - final TileEntity te = world.getTileEntity( pos ); - if( te instanceof IGridHost ) - { - return (IGridHost) te; - } - } - return null; - } - - private boolean canConnect( final GridNode from, final AEPartLocation dir ) - { - if( !this.isValidDirection( dir ) ) - { - return false; - } - - if( !from.getColor().matches( this.getColor() ) ) - { - return false; - } - - return true; - } - - private boolean isValidDirection( final AEPartLocation dir ) - { - return ( this.compressedData & ( 1 << ( 8 + dir.ordinal() ) ) ) > 0; - } - - private AEColor getColor() - { - return AEColor.values()[( this.compressedData >> 3 ) & 0x1F]; - } - - private void visitorConnection( final Object tracker, final IGridVisitor g, final Deque nextRun, final Deque nextConnections ) - { - if( g.visitNode( this ) ) - { - for( final IGridConnection gc : this.getConnections() ) - { - final GridNode gn = (GridNode) gc.getOtherSide( this ); - final GridConnection gcc = (GridConnection) gc; - - if( gcc.getVisitorIterationNumber() != tracker ) - { - gcc.setVisitorIterationNumber( tracker ); - nextConnections.add( gc ); - } - - if( tracker == gn.visitorIterationNumber ) - { - continue; - } - - gn.visitorIterationNumber = tracker; - - nextRun.add( gn ); - } - } - } - - private void visitorNode( final Object tracker, final IGridVisitor g, final Deque nextRun ) - { - if( g.visitNode( this ) ) - { - for( final IGridConnection gc : this.getConnections() ) - { - final GridNode gn = (GridNode) gc.getOtherSide( this ); - - if( tracker == gn.visitorIterationNumber ) - { - continue; - } - - gn.visitorIterationNumber = tracker; - - nextRun.add( gn ); - } - } - } - - GridStorage getGridStorage() - { - return this.myStorage; - } - - void setGridStorage( final GridStorage s ) - { - this.myStorage = s; - this.usedChannels = 0; - this.lastUsedChannels = 0; - } - - @Override - public IPathItem getControllerRoute() - { - if( this.connections.isEmpty() || this.getFlags().contains( GridFlags.CANNOT_CARRY ) ) - { - return null; - } - - return (IPathItem) this.connections.get( 0 ); - } - - @Override - public void setControllerRoute( final IPathItem fast, final boolean zeroOut ) - { - if( zeroOut ) - { - this.usedChannels = 0; - } - - final int idx = this.connections.indexOf( (IGridConnection) fast ); - if( idx > 0 ) - { - this.connections.remove( (IGridConnection) fast ); - this.connections.add( 0, (IGridConnection) fast ); - } - } - - @Override - public boolean canSupportMoreChannels() - { - return this.getUsedChannels() < this.getMaxChannels(); - } - - private int getMaxChannels() - { - return CHANNEL_COUNT[this.compressedData & 0x03]; - } - - @Override - public IReadOnlyCollection getPossibleOptions() - { - return (IReadOnlyCollection) this.getConnections(); - } - - @Override - public void incrementChannelCount( final int usedChannels ) - { - this.usedChannels += usedChannels; - } - - @Override - public EnumSet getFlags() - { - return this.gridProxy.getFlags(); - } - - @Override - public void finalizeChannels() - { - if( this.getFlags().contains( GridFlags.CANNOT_CARRY ) ) - { - return; - } - - if( this.getLastUsedChannels() != this.getUsedChannels() ) - { - this.lastUsedChannels = this.usedChannels; - - if( this.getInternalGrid() != null ) - { - this.getInternalGrid().postEventTo( this, EVENT ); - } - } - } - - private int getLastUsedChannels() - { - return this.lastUsedChannels; - } - - public long getLastSecurityKey() - { - return this.lastSecurityKey; - } - - public void setLastSecurityKey( final long lastSecurityKey ) - { - this.lastSecurityKey = lastSecurityKey; - } - - public double getPreviousDraw() - { - return this.previousDraw; - } - - public void setPreviousDraw( final double previousDraw ) - { - this.previousDraw = previousDraw; - } - - private static class MachineSecurityBreak implements IWorldCallable - { - private final GridNode node; - - public MachineSecurityBreak( final GridNode node ) - { - this.node = node; - } - - @Override - public Void call( final World world ) throws Exception - { - this.node.getMachine().securityBreak(); - - return null; - } - } - - private static class ConnectionComparator implements Comparator - { - private final IGridNode gn; - - public ConnectionComparator( final IGridNode gn ) - { - this.gn = gn; - } - - @Override - public int compare( final IGridConnection o1, final IGridConnection o2 ) - { - final boolean preferredA = o1.getOtherSide( this.gn ).hasFlag( GridFlags.PREFERRED ); - final boolean preferredB = o2.getOtherSide( this.gn ).hasFlag( GridFlags.PREFERRED ); - - return preferredA == preferredB ? 0 : ( preferredA ? -1 : 1 ); - } - } +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +import java.util.*; + + +public class GridNode implements IGridNode, IPathItem { + private static final MENetworkChannelsChanged EVENT = new MENetworkChannelsChanged(); + private static final int[] CHANNEL_COUNT = {0, 8, 32}; + + private final List connections = new ArrayList<>(); + private final IGridBlock gridProxy; + // old power draw, used to diff + private double previousDraw = 0.0; + private long lastSecurityKey = -1; + private int playerID = -1; + private GridStorage myStorage = null; + private Grid myGrid; + private Object visitorIterationNumber = null; + // connection criteria + private int compressedData = 0; + private int usedChannels = 0; + private int lastUsedChannels = 0; + + public GridNode(final IGridBlock what) { + this.gridProxy = what; + } + + IGridBlock getGridProxy() { + return this.gridProxy; + } + + Grid getMyGrid() { + return this.myGrid; + } + + public int usedChannels() { + return this.lastUsedChannels; + } + + Class getMachineClass() { + return this.getMachine().getClass(); + } + + void addConnection(final IGridConnection gridConnection) { + this.connections.add(gridConnection); + if (gridConnection.hasDirection()) { + this.gridProxy.onGridNotification(GridNotification.CONNECTIONS_CHANGED); + } + + final IGridNode gn = this; + + Collections.sort(this.connections, new ConnectionComparator(gn)); + } + + void removeConnection(final IGridConnection gridConnection) { + this.connections.remove(gridConnection); + if (gridConnection.hasDirection()) { + this.gridProxy.onGridNotification(GridNotification.CONNECTIONS_CHANGED); + } + } + + boolean hasConnection(final IGridNode otherSide) { + for (final IGridConnection gc : this.connections) { + if (gc.a() == otherSide || gc.b() == otherSide) { + return true; + } + } + return false; + } + + void validateGrid() { + final GridSplitDetector gsd = new GridSplitDetector(this.getInternalGrid().getPivot()); + this.beginVisit(gsd); + if (!gsd.isPivotFound()) { + final IGridVisitor gp = new GridPropagator(new Grid(this)); + this.beginVisit(gp); + } + } + + public Grid getInternalGrid() { + if (this.myGrid == null) { + this.myGrid = new Grid(this); + } + + return this.myGrid; + } + + @Override + public void beginVisit(final IGridVisitor g) { + final Object tracker = new Object(); + + Deque nextRun = new ArrayDeque<>(); + nextRun.add(this); + + this.visitorIterationNumber = tracker; + + if (g instanceof IGridConnectionVisitor) { + final Deque nextConn = new ArrayDeque<>(); + final IGridConnectionVisitor gcv = (IGridConnectionVisitor) g; + + while (!nextRun.isEmpty()) { + while (!nextConn.isEmpty()) { + gcv.visitConnection(nextConn.poll()); + } + + final Iterable thisRun = nextRun; + nextRun = new ArrayDeque<>(); + + for (final GridNode n : thisRun) { + n.visitorConnection(tracker, g, nextRun, nextConn); + } + } + } else { + while (!nextRun.isEmpty()) { + final Iterable thisRun = nextRun; + nextRun = new ArrayDeque<>(); + + for (final GridNode n : thisRun) { + n.visitorNode(tracker, g, nextRun); + } + } + } + } + + @Override + public void updateState() { + final EnumSet set = this.gridProxy.getFlags(); + + this.compressedData = set.contains(GridFlags.CANNOT_CARRY) ? 0 : (set.contains(GridFlags.DENSE_CAPACITY) ? 2 : 1); + + this.compressedData |= (this.gridProxy.getGridColor().ordinal() << 3); + + for (final EnumFacing dir : this.gridProxy.getConnectableSides()) { + this.compressedData |= (1 << (dir.ordinal() + 8)); + } + + this.findConnections(); + this.getInternalGrid(); + } + + @Override + public IGridHost getMachine() { + return this.gridProxy.getMachine(); + } + + @Override + public IGrid getGrid() { + return this.myGrid; + } + + void setGrid(final Grid grid) { + if (this.myGrid == grid) { + return; + } + + if (this.myGrid != null) { + this.myGrid.remove(this); + + if (this.myGrid.isEmpty()) { + this.myGrid.saveState(); + + for (final IGridCache c : grid.getCaches().values()) { + c.onJoin(this.myGrid.getMyStorage()); + } + } + } + + this.myGrid = grid; + this.myGrid.add(this); + } + + @Override + public void destroy() { + while (!this.connections.isEmpty()) { + // not part of this network for real anymore. + if (this.connections.size() == 1) { + this.setGridStorage(null); + } + + final IGridConnection c = this.connections.listIterator().next(); + final GridNode otherSide = (GridNode) c.getOtherSide(this); + otherSide.getInternalGrid().setPivot(otherSide); + c.destroy(); + } + + if (this.myGrid != null) { + this.myGrid.remove(this); + } + } + + @Override + public World getWorld() { + return this.gridProxy.getLocation().getWorld(); + } + + @Override + public EnumSet getConnectedSides() { + final EnumSet set = EnumSet.noneOf(AEPartLocation.class); + for (final IGridConnection gc : this.connections) { + set.add(gc.getDirection(this)); + } + return set; + } + + @Override + public IReadOnlyCollection getConnections() { + return new ReadOnlyCollection<>(this.connections); + } + + @Override + public IGridBlock getGridBlock() { + return this.gridProxy; + } + + @Override + public boolean isActive() { + final IGrid g = this.getGrid(); + if (g != null) { + final IPathingGrid pg = g.getCache(IPathingGrid.class); + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + return eg.isNetworkPowered() && !pg.isNetworkBooting() && this.meetsChannelRequirements(); + } + return false; + } + + @Override + public void loadFromNBT(final String name, final NBTTagCompound nodeData) { + if (this.myGrid != null) { + throw new IllegalStateException("Loading data after part of a grid, this is invalid."); + } + if (nodeData.hasKey(name, 10)) { + final NBTTagCompound node = nodeData.getCompoundTag(name); + this.playerID = node.getInteger("p"); + this.setLastSecurityKey(node.getLong("k")); + + final long storageID = node.getLong("g"); + final GridStorage gridStorage = WorldData.instance().storageData().getGridStorage(storageID); + this.setGridStorage(gridStorage); + } else { + this.playerID = -1; // Unknown owner + setLastSecurityKey(-1); + setGridStorage(null); + } + } + + @Override + public void saveToNBT(final String name, final NBTTagCompound nodeData) { + if (this.myStorage != null) { + final NBTTagCompound node = new NBTTagCompound(); + + node.setInteger("p", this.playerID); + node.setLong("k", this.getLastSecurityKey()); + node.setLong("g", this.myStorage.getID()); + + nodeData.setTag(name, node); + } else { + nodeData.removeTag(name); + } + } + + @Override + public boolean meetsChannelRequirements() { + if (this.gridProxy.getFlags().contains(GridFlags.REQUIRE_CHANNEL)) { + if (AEConfig.instance().isFeatureEnabled(AEFeature.CHANNELS)) { + return this.getUsedChannels() > 0; + } + } + return true; + } + + @Override + public boolean hasFlag(final GridFlags flag) { + return this.gridProxy.getFlags().contains(flag); + } + + @Override + public int getPlayerID() { + return this.playerID; + } + + @Override + public void setPlayerID(final int playerID) { + if (playerID >= 0) { + this.playerID = playerID; + } + } + + private int getUsedChannels() { + return this.usedChannels; + } + + private void findConnections() { + if (!this.gridProxy.isWorldAccessible()) { + return; + } + + final EnumSet newSecurityConnections = EnumSet.noneOf(AEPartLocation.class); + + final DimensionalCoord dc = this.gridProxy.getLocation(); + for (final AEPartLocation f : AEPartLocation.SIDE_LOCATIONS) { + final IGridHost te = this.findGridHost(dc.getWorld(), dc.x + f.xOffset, dc.y + f.yOffset, dc.z + f.zOffset); + if (te != null) { + final GridNode node = (GridNode) te.getGridNode(f.getOpposite()); + if (node == null) { + continue; + } + + final boolean isValidConnection = this.canConnect(node, f) && node.canConnect(this, f.getOpposite()); + + IGridConnection con = null; // find the connection for this + // direction.. + for (final IGridConnection c : this.getConnections()) { + if (c.getDirection(this) == f) { + con = c; + break; + } + } + + if (con != null) { + final IGridNode os = con.getOtherSide(this); + if (os == node) { + // if this connection is no longer valid, destroy it. + if (!isValidConnection) { + con.destroy(); + } + } else { + con.destroy(); + // throw new GridException( "invalid state found, encountered connection to phantom block." ); + } + } else if (isValidConnection) { + if (node.getLastSecurityKey() != -1) { + newSecurityConnections.add(f); + } else { + // construct a new connection between these two nodes. + try { + GridConnection.create(node, this, f.getOpposite()); + } catch (SecurityConnectionException e) { + AELog.debug(e); + TickHandler.INSTANCE.addCallable(node.getWorld(), new MachineSecurityBreak(this)); + + return; + } catch (final FailedConnectionException e) { + AELog.debug(e); + + return; + } + } + } + } + } + + for (final AEPartLocation f : newSecurityConnections) { + final IGridHost te = this.findGridHost(dc.getWorld(), dc.x + f.xOffset, dc.y + f.yOffset, dc.z + f.zOffset); + if (te != null) { + final GridNode node = (GridNode) te.getGridNode(f.getOpposite()); + if (node == null) { + continue; + } + + // construct a new connection between these two nodes. + try { + GridConnection.create(node, this, f.getOpposite()); + } catch (SecurityConnectionException e) { + AELog.debug(e); + + TickHandler.INSTANCE.addCallable(node.getWorld(), new MachineSecurityBreak(this)); + + return; + } catch (final FailedConnectionException e) { + AELog.debug(e); + + return; + } + } + } + } + + private IGridHost findGridHost(final World world, final int x, final int y, final int z) { + final BlockPos pos = new BlockPos(x, y, z); + if (world.isBlockLoaded(pos)) { + final TileEntity te = world.getTileEntity(pos); + if (te instanceof IGridHost) { + return (IGridHost) te; + } + } + return null; + } + + private boolean canConnect(final GridNode from, final AEPartLocation dir) { + if (!this.isValidDirection(dir)) { + return false; + } + + return from.getColor().matches(this.getColor()); + } + + private boolean isValidDirection(final AEPartLocation dir) { + return (this.compressedData & (1 << (8 + dir.ordinal()))) > 0; + } + + private AEColor getColor() { + return AEColor.values()[(this.compressedData >> 3) & 0x1F]; + } + + private void visitorConnection(final Object tracker, final IGridVisitor g, final Deque nextRun, final Deque nextConnections) { + if (g.visitNode(this)) { + for (final IGridConnection gc : this.getConnections()) { + final GridNode gn = (GridNode) gc.getOtherSide(this); + final GridConnection gcc = (GridConnection) gc; + + if (gcc.getVisitorIterationNumber() != tracker) { + gcc.setVisitorIterationNumber(tracker); + nextConnections.add(gc); + } + + if (tracker == gn.visitorIterationNumber) { + continue; + } + + gn.visitorIterationNumber = tracker; + + nextRun.add(gn); + } + } + } + + private void visitorNode(final Object tracker, final IGridVisitor g, final Deque nextRun) { + if (g.visitNode(this)) { + for (final IGridConnection gc : this.getConnections()) { + final GridNode gn = (GridNode) gc.getOtherSide(this); + + if (tracker == gn.visitorIterationNumber) { + continue; + } + + gn.visitorIterationNumber = tracker; + + nextRun.add(gn); + } + } + } + + GridStorage getGridStorage() { + return this.myStorage; + } + + void setGridStorage(final GridStorage s) { + this.myStorage = s; + this.usedChannels = 0; + this.lastUsedChannels = 0; + } + + @Override + public IPathItem getControllerRoute() { + if (this.connections.isEmpty() || this.getFlags().contains(GridFlags.CANNOT_CARRY)) { + return null; + } + + return (IPathItem) this.connections.get(0); + } + + @Override + public void setControllerRoute(final IPathItem fast, final boolean zeroOut) { + if (zeroOut) { + this.usedChannels = 0; + } + + final int idx = this.connections.indexOf((IGridConnection) fast); + if (idx > 0) { + this.connections.remove((IGridConnection) fast); + this.connections.add(0, (IGridConnection) fast); + } + } + + @Override + public boolean canSupportMoreChannels() { + return this.getUsedChannels() < this.getMaxChannels(); + } + + private int getMaxChannels() { + return CHANNEL_COUNT[this.compressedData & 0x03]; + } + + @Override + public IReadOnlyCollection getPossibleOptions() { + return (IReadOnlyCollection) this.getConnections(); + } + + @Override + public void incrementChannelCount(final int usedChannels) { + this.usedChannels += usedChannels; + } + + @Override + public EnumSet getFlags() { + return this.gridProxy.getFlags(); + } + + @Override + public void finalizeChannels() { + if (this.getFlags().contains(GridFlags.CANNOT_CARRY)) { + return; + } + + if (this.getLastUsedChannels() != this.getUsedChannels()) { + this.lastUsedChannels = this.usedChannels; + + if (this.getInternalGrid() != null) { + this.getInternalGrid().postEventTo(this, EVENT); + } + } + } + + private int getLastUsedChannels() { + return this.lastUsedChannels; + } + + public long getLastSecurityKey() { + return this.lastSecurityKey; + } + + public void setLastSecurityKey(final long lastSecurityKey) { + this.lastSecurityKey = lastSecurityKey; + } + + public double getPreviousDraw() { + return this.previousDraw; + } + + public void setPreviousDraw(final double previousDraw) { + this.previousDraw = previousDraw; + } + + private static class MachineSecurityBreak implements IWorldCallable { + private final GridNode node; + + public MachineSecurityBreak(final GridNode node) { + this.node = node; + } + + @Override + public Void call(final World world) throws Exception { + this.node.getMachine().securityBreak(); + + return null; + } + } + + private static class ConnectionComparator implements Comparator { + private final IGridNode gn; + + public ConnectionComparator(final IGridNode gn) { + this.gn = gn; + } + + @Override + public int compare(final IGridConnection o1, final IGridConnection o2) { + final boolean preferredA = o1.getOtherSide(this.gn).hasFlag(GridFlags.PREFERRED); + final boolean preferredB = o2.getOtherSide(this.gn).hasFlag(GridFlags.PREFERRED); + + return preferredA == preferredB ? 0 : (preferredA ? -1 : 1); + } + } } diff --git a/src/main/java/appeng/me/GridNodeCollection.java b/src/main/java/appeng/me/GridNodeCollection.java index e0a8515bd..da2dbb3b4 100644 --- a/src/main/java/appeng/me/GridNodeCollection.java +++ b/src/main/java/appeng/me/GridNodeCollection.java @@ -19,77 +19,65 @@ package appeng.me; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.util.IReadOnlyCollection; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; -public class GridNodeCollection implements IReadOnlyCollection -{ - private final Map, MachineSet> machines; - public GridNodeCollection( final Map, MachineSet> machines ) - { - this.machines = machines; - } +public class GridNodeCollection implements IReadOnlyCollection { + private final Map, MachineSet> machines; - @Override - public Iterator iterator() - { - return new GridNodeIterator( this.machines ); - } + public GridNodeCollection(final Map, MachineSet> machines) { + this.machines = machines; + } - @Override - public int size() - { - int size = 0; + @Override + public Iterator iterator() { + return new GridNodeIterator(this.machines); + } - for( final Set o : this.machines.values() ) - { - size += o.size(); - } + @Override + public int size() { + int size = 0; - return size; - } + for (final Set o : this.machines.values()) { + size += o.size(); + } - @Override - public boolean isEmpty() - { - for( final Set o : this.machines.values() ) - { - if( !o.isEmpty() ) - { - return false; - } - } + return size; + } - return true; - } + @Override + public boolean isEmpty() { + for (final Set o : this.machines.values()) { + if (!o.isEmpty()) { + return false; + } + } - @Override - public boolean contains( final Object maybeGridNode ) - { - final boolean doesContainNode; + return true; + } - if( maybeGridNode instanceof IGridNode ) - { - final IGridNode node = (IGridNode) maybeGridNode; - final IGridHost machine = node.getMachine(); - final Class machineClass = machine.getClass(); + @Override + public boolean contains(final Object maybeGridNode) { + final boolean doesContainNode; - final MachineSet machineSet = this.machines.get( machineClass ); + if (maybeGridNode instanceof IGridNode) { + final IGridNode node = (IGridNode) maybeGridNode; + final IGridHost machine = node.getMachine(); + final Class machineClass = machine.getClass(); - doesContainNode = machineSet != null && machineSet.contains( maybeGridNode ); - } - else - { - doesContainNode = false; - } + final MachineSet machineSet = this.machines.get(machineClass); - return doesContainNode; - } + doesContainNode = machineSet != null && machineSet.contains(maybeGridNode); + } else { + doesContainNode = false; + } + + return doesContainNode; + } } diff --git a/src/main/java/appeng/me/GridNodeIterator.java b/src/main/java/appeng/me/GridNodeIterator.java index e441aeb09..fb225af4e 100644 --- a/src/main/java/appeng/me/GridNodeIterator.java +++ b/src/main/java/appeng/me/GridNodeIterator.java @@ -19,68 +19,57 @@ package appeng.me; -import java.util.Iterator; -import java.util.Map; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; +import java.util.Iterator; +import java.util.Map; + /** * Nested iterator for {@link appeng.me.MachineSet} - * + *

* Traverses first over the {@link appeng.me.MachineSet} and then over every containing * {@link appeng.api.networking.IGridNode} */ -public class GridNodeIterator implements Iterator -{ - private final Iterator outerIterator; - private Iterator innerIterator; +public class GridNodeIterator implements Iterator { + private final Iterator outerIterator; + private Iterator innerIterator; - public GridNodeIterator( final Map, MachineSet> machines ) - { - this.outerIterator = machines.values().iterator(); - this.innerHasNext(); - } + public GridNodeIterator(final Map, MachineSet> machines) { + this.outerIterator = machines.values().iterator(); + this.innerHasNext(); + } - private boolean innerHasNext() - { - final boolean hasNext = this.outerIterator.hasNext(); + private boolean innerHasNext() { + final boolean hasNext = this.outerIterator.hasNext(); - if( hasNext ) - { - final MachineSet nextElem = this.outerIterator.next(); - this.innerIterator = nextElem.iterator(); - } + if (hasNext) { + final MachineSet nextElem = this.outerIterator.next(); + this.innerIterator = nextElem.iterator(); + } - return hasNext; - } + return hasNext; + } - @Override - public boolean hasNext() - { - while( true ) - { - if( this.innerIterator.hasNext() ) - { - return true; - } - else if( !this.innerHasNext() ) - { - return false; - } - } - } + @Override + public boolean hasNext() { + while (true) { + if (this.innerIterator.hasNext()) { + return true; + } else if (!this.innerHasNext()) { + return false; + } + } + } - @Override - public IGridNode next() - { - return this.innerIterator.next(); - } + @Override + public IGridNode next() { + return this.innerIterator.next(); + } - @Override - public void remove() - { - this.innerIterator.remove(); - } + @Override + public void remove() { + this.innerIterator.remove(); + } } diff --git a/src/main/java/appeng/me/GridPropagator.java b/src/main/java/appeng/me/GridPropagator.java index 4bc6c99fb..3ecec6b94 100644 --- a/src/main/java/appeng/me/GridPropagator.java +++ b/src/main/java/appeng/me/GridPropagator.java @@ -23,25 +23,21 @@ import appeng.api.networking.IGridNode; import appeng.api.networking.IGridVisitor; -public class GridPropagator implements IGridVisitor -{ - private final Grid g; +public class GridPropagator implements IGridVisitor { + private final Grid g; - public GridPropagator( final Grid g ) - { - this.g = g; - } + public GridPropagator(final Grid g) { + this.g = g; + } - @Override - public boolean visitNode( final IGridNode n ) - { - final GridNode gn = (GridNode) n; - if( gn.getMyGrid() != this.g || this.g.getPivot() == n ) - { - gn.setGrid( this.g ); + @Override + public boolean visitNode(final IGridNode n) { + final GridNode gn = (GridNode) n; + if (gn.getMyGrid() != this.g || this.g.getPivot() == n) { + gn.setGrid(this.g); - return true; - } - return false; - } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/me/GridSplitDetector.java b/src/main/java/appeng/me/GridSplitDetector.java index ac0b98c7a..a321b7118 100644 --- a/src/main/java/appeng/me/GridSplitDetector.java +++ b/src/main/java/appeng/me/GridSplitDetector.java @@ -23,35 +23,29 @@ import appeng.api.networking.IGridNode; import appeng.api.networking.IGridVisitor; -class GridSplitDetector implements IGridVisitor -{ +class GridSplitDetector implements IGridVisitor { - private final IGridNode pivot; - private boolean pivotFound; + private final IGridNode pivot; + private boolean pivotFound; - public GridSplitDetector( final IGridNode pivot ) - { - this.pivot = pivot; - } + public GridSplitDetector(final IGridNode pivot) { + this.pivot = pivot; + } - @Override - public boolean visitNode( final IGridNode n ) - { - if( n == this.pivot ) - { - this.setPivotFound( true ); - } + @Override + public boolean visitNode(final IGridNode n) { + if (n == this.pivot) { + this.setPivotFound(true); + } - return !this.isPivotFound(); - } + return !this.isPivotFound(); + } - public boolean isPivotFound() - { - return this.pivotFound; - } + public boolean isPivotFound() { + return this.pivotFound; + } - private void setPivotFound( final boolean pivotFound ) - { - this.pivotFound = pivotFound; - } + private void setPivotFound(final boolean pivotFound) { + this.pivotFound = pivotFound; + } } diff --git a/src/main/java/appeng/me/GridStorage.java b/src/main/java/appeng/me/GridStorage.java index 65b91e41e..0eb34a3f9 100644 --- a/src/main/java/appeng/me/GridStorage.java +++ b/src/main/java/appeng/me/GridStorage.java @@ -19,137 +19,117 @@ package appeng.me; +import appeng.api.networking.IGrid; +import appeng.api.networking.IGridStorage; +import appeng.core.AELog; +import appeng.core.worlddata.WorldData; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.WeakHashMap; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; -import appeng.api.networking.IGrid; -import appeng.api.networking.IGridStorage; -import appeng.core.AELog; -import appeng.core.worlddata.WorldData; +public class GridStorage implements IGridStorage { + private final long myID; + private final NBTTagCompound data; + private final GridStorageSearch mySearchEntry; // keep myself in the list until I'm + private final WeakHashMap divided = new WeakHashMap<>(); + private WeakReference internalGrid = null; -public class GridStorage implements IGridStorage -{ + // lost... - private final long myID; - private final NBTTagCompound data; - private final GridStorageSearch mySearchEntry; // keep myself in the list until I'm - private final WeakHashMap divided = new WeakHashMap<>(); - private WeakReference internalGrid = null; + /** + * for use with world settings + * + * @param id ID of grid storage + * @param gss grid storage search + */ + public GridStorage(final long id, final GridStorageSearch gss) { + this.myID = id; + this.mySearchEntry = gss; + this.data = new NBTTagCompound(); + } - // lost... + /** + * for use with world settings + * + * @param input array of bytes string + * @param id ID of grid storage + * @param gss grid storage search + */ + public GridStorage(final String input, final long id, final GridStorageSearch gss) { + this.myID = id; + this.mySearchEntry = gss; + NBTTagCompound myTag = null; - /** - * for use with world settings - * - * @param id ID of grid storage - * @param gss grid storage search - */ - public GridStorage( final long id, final GridStorageSearch gss ) - { - this.myID = id; - this.mySearchEntry = gss; - this.data = new NBTTagCompound(); - } + try { + final byte[] byteData = javax.xml.bind.DatatypeConverter.parseBase64Binary(input); + myTag = CompressedStreamTools.readCompressed(new ByteArrayInputStream(byteData)); + } catch (final Throwable t) { + myTag = new NBTTagCompound(); + } - /** - * for use with world settings - * - * @param input array of bytes string - * @param id ID of grid storage - * @param gss grid storage search - */ - public GridStorage( final String input, final long id, final GridStorageSearch gss ) - { - this.myID = id; - this.mySearchEntry = gss; - NBTTagCompound myTag = null; + this.data = myTag; + } - try - { - final byte[] byteData = javax.xml.bind.DatatypeConverter.parseBase64Binary( input ); - myTag = CompressedStreamTools.readCompressed( new ByteArrayInputStream( byteData ) ); - } - catch( final Throwable t ) - { - myTag = new NBTTagCompound(); - } + /** + * fake storage. + */ + public GridStorage() { + this.myID = 0; + this.mySearchEntry = null; + this.data = new NBTTagCompound(); + } - this.data = myTag; - } + public String getValue() { + final Grid currentGrid = (Grid) this.getGrid(); + if (currentGrid != null) { + currentGrid.saveState(); + } - /** - * fake storage. - */ - public GridStorage() - { - this.myID = 0; - this.mySearchEntry = null; - this.data = new NBTTagCompound(); - } + try { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + CompressedStreamTools.writeCompressed(this.data, out); + return javax.xml.bind.DatatypeConverter.printBase64Binary(out.toByteArray()); + } catch (final IOException e) { + AELog.debug(e); + } - public String getValue() - { - final Grid currentGrid = (Grid) this.getGrid(); - if( currentGrid != null ) - { - currentGrid.saveState(); - } + return ""; + } - try - { - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - CompressedStreamTools.writeCompressed( this.data, out ); - return javax.xml.bind.DatatypeConverter.printBase64Binary( out.toByteArray() ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } + public IGrid getGrid() { + return this.internalGrid == null ? null : this.internalGrid.get(); + } - return ""; - } + void setGrid(final Grid grid) { + this.internalGrid = new WeakReference<>(grid); + } - public IGrid getGrid() - { - return this.internalGrid == null ? null : this.internalGrid.get(); - } + @Override + public NBTTagCompound dataObject() { + return this.data; + } - void setGrid( final Grid grid ) - { - this.internalGrid = new WeakReference<>( grid ); - } + @Override + public long getID() { + return this.myID; + } - @Override - public NBTTagCompound dataObject() - { - return this.data; - } + void addDivided(final GridStorage gs) { + this.divided.put(gs, true); + } - @Override - public long getID() - { - return this.myID; - } + boolean hasDivided(final GridStorage myStorage) { + return this.divided.containsKey(myStorage); + } - void addDivided( final GridStorage gs ) - { - this.divided.put( gs, true ); - } - - boolean hasDivided( final GridStorage myStorage ) - { - return this.divided.containsKey( myStorage ); - } - - void remove() - { - WorldData.instance().storageData().destroyGridStorage( this.myID ); - } + void remove() { + WorldData.instance().storageData().destroyGridStorage(this.myID); + } } diff --git a/src/main/java/appeng/me/GridStorageSearch.java b/src/main/java/appeng/me/GridStorageSearch.java index cd8875ca2..c7dbd3c41 100644 --- a/src/main/java/appeng/me/GridStorageSearch.java +++ b/src/main/java/appeng/me/GridStorageSearch.java @@ -22,56 +22,43 @@ package appeng.me; import java.lang.ref.WeakReference; -public class GridStorageSearch -{ +public class GridStorageSearch { - private final long id; - private WeakReference gridStorage; + private final long id; + private WeakReference gridStorage; - /** - * for use with the world settings - * - * @param id ID of grid storage search - */ - public GridStorageSearch( final long id ) - { - this.id = id; - } + /** + * for use with the world settings + * + * @param id ID of grid storage search + */ + public GridStorageSearch(final long id) { + this.id = id; + } - @Override - public int hashCode() - { - return ( (Long) this.id ).hashCode(); - } + @Override + public int hashCode() { + return ((Long) this.id).hashCode(); + } - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } - final GridStorageSearch other = (GridStorageSearch) obj; - if( this.id == other.id ) - { - return true; - } + final GridStorageSearch other = (GridStorageSearch) obj; + return this.id == other.id; + } - return false; - } + public WeakReference getGridStorage() { + return this.gridStorage; + } - public WeakReference getGridStorage() - { - return this.gridStorage; - } - - public void setGridStorage( final WeakReference gridStorage ) - { - this.gridStorage = gridStorage; - } + public void setGridStorage(final WeakReference gridStorage) { + this.gridStorage = gridStorage; + } } diff --git a/src/main/java/appeng/me/MachineSet.java b/src/main/java/appeng/me/MachineSet.java index f35209c53..b2353b1ba 100644 --- a/src/main/java/appeng/me/MachineSet.java +++ b/src/main/java/appeng/me/MachineSet.java @@ -19,28 +19,25 @@ package appeng.me; -import java.util.HashSet; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.networking.IMachineSet; +import java.util.HashSet; -public class MachineSet extends HashSet implements IMachineSet -{ - private static final long serialVersionUID = 3224660708327386933L; +public class MachineSet extends HashSet implements IMachineSet { - private final Class machine; + private static final long serialVersionUID = 3224660708327386933L; - MachineSet( final Class m ) - { - this.machine = m; - } + private final Class machine; - @Override - public Class getMachineClass() - { - return this.machine; - } + MachineSet(final Class m) { + this.machine = m; + } + + @Override + public Class getMachineClass() { + return this.machine; + } } diff --git a/src/main/java/appeng/me/NetworkEventBus.java b/src/main/java/appeng/me/NetworkEventBus.java index 55519baa9..dc167d276 100644 --- a/src/main/java/appeng/me/NetworkEventBus.java +++ b/src/main/java/appeng/me/NetworkEventBus.java @@ -19,211 +19,163 @@ package appeng.me; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - import appeng.api.networking.IGridNode; import appeng.api.networking.IMachineSet; import appeng.api.networking.events.MENetworkEvent; import appeng.api.networking.events.MENetworkEventSubscribe; import appeng.core.AELog; +import java.lang.reflect.Method; +import java.util.*; +import java.util.Map.Entry; -public class NetworkEventBus -{ - private static final Collection READ_CLASSES = new HashSet<>(); - private static final Map, Map> EVENTS = new HashMap<>(); - void readClass( final Class listAs, final Class c ) - { - if( READ_CLASSES.contains( c ) ) - { - return; - } - READ_CLASSES.add( c ); +public class NetworkEventBus { + private static final Collection READ_CLASSES = new HashSet<>(); + private static final Map, Map> EVENTS = new HashMap<>(); - try - { - for( final Method m : c.getMethods() ) - { - final MENetworkEventSubscribe s = m.getAnnotation( MENetworkEventSubscribe.class ); - if( s != null ) - { - final Class[] types = m.getParameterTypes(); - if( types.length == 1 ) - { - if( MENetworkEvent.class.isAssignableFrom( types[0] ) ) - { + void readClass(final Class listAs, final Class c) { + if (READ_CLASSES.contains(c)) { + return; + } + READ_CLASSES.add(c); - Map classEvents = EVENTS.get( types[0] ); - if( classEvents == null ) - { - EVENTS.put( types[0], classEvents = new HashMap<>() ); - } + try { + for (final Method m : c.getMethods()) { + final MENetworkEventSubscribe s = m.getAnnotation(MENetworkEventSubscribe.class); + if (s != null) { + final Class[] types = m.getParameterTypes(); + if (types.length == 1) { + if (MENetworkEvent.class.isAssignableFrom(types[0])) { - MENetworkEventInfo thisEvent = classEvents.get( listAs ); - if( thisEvent == null ) - { - thisEvent = new MENetworkEventInfo(); - } + Map classEvents = EVENTS.get(types[0]); + if (classEvents == null) { + EVENTS.put(types[0], classEvents = new HashMap<>()); + } - thisEvent.Add( types[0], c, m ); + MENetworkEventInfo thisEvent = classEvents.get(listAs); + if (thisEvent == null) { + thisEvent = new MENetworkEventInfo(); + } - classEvents.put( listAs, thisEvent ); - } - else - { - throw new IllegalStateException( "Invalid ME Network Event Subscriber, " + m - .getName() + "s Parameter must extend MENetworkEvent." ); - } - } - else - { - throw new IllegalStateException( "Invalid ME Network Event Subscriber, " + m.getName() + " must have exactly 1 parameter." ); - } - } - } - } - catch( final Throwable t ) - { - throw new IllegalStateException( "Error while adding " + c.getName() + " to event bus", t ); - } - } + thisEvent.Add(types[0], c, m); - MENetworkEvent postEvent( final Grid g, final MENetworkEvent e ) - { - final Map subscribers = EVENTS.get( e.getClass() ); - int x = 0; + classEvents.put(listAs, thisEvent); + } else { + throw new IllegalStateException("Invalid ME Network Event Subscriber, " + m + .getName() + "s Parameter must extend MENetworkEvent."); + } + } else { + throw new IllegalStateException("Invalid ME Network Event Subscriber, " + m.getName() + " must have exactly 1 parameter."); + } + } + } + } catch (final Throwable t) { + throw new IllegalStateException("Error while adding " + c.getName() + " to event bus", t); + } + } - try - { - if( subscribers != null ) - { - for( final Entry subscriber : subscribers.entrySet() ) - { - final MENetworkEventInfo target = subscriber.getValue(); - final GridCacheWrapper cache = g.getCaches().get( subscriber.getKey() ); - if( cache != null ) - { - x++; - target.invoke( cache.getCache(), e ); - } + MENetworkEvent postEvent(final Grid g, final MENetworkEvent e) { + final Map subscribers = EVENTS.get(e.getClass()); + int x = 0; - // events may create or remove grid nodes in rare cases - final IMachineSet machines = g.getMachines( subscriber.getKey() ); - final List work = new ArrayList<>( machines.size() ); - machines.forEach( work::add ); + try { + if (subscribers != null) { + for (final Entry subscriber : subscribers.entrySet()) { + final MENetworkEventInfo target = subscriber.getValue(); + final GridCacheWrapper cache = g.getCaches().get(subscriber.getKey()); + if (cache != null) { + x++; + target.invoke(cache.getCache(), e); + } - for( final IGridNode obj : work ) - { - // stil part of grid? - if( machines.contains( obj ) ) - { - x++; - target.invoke( obj.getMachine(), e ); - } - } - } - } - } - catch( final NetworkEventDone done ) - { - // Early out. - } + // events may create or remove grid nodes in rare cases + final IMachineSet machines = g.getMachines(subscriber.getKey()); + final List work = new ArrayList<>(machines.size()); + machines.forEach(work::add); - e.setVisitedObjects( x ); - return e; - } + for (final IGridNode obj : work) { + // stil part of grid? + if (machines.contains(obj)) { + x++; + target.invoke(obj.getMachine(), e); + } + } + } + } + } catch (final NetworkEventDone done) { + // Early out. + } - MENetworkEvent postEventTo( final Grid grid, final GridNode node, final MENetworkEvent e ) - { - final Map subscribers = EVENTS.get( e.getClass() ); - int x = 0; + e.setVisitedObjects(x); + return e; + } - try - { - if( subscribers != null ) - { - final MENetworkEventInfo target = subscribers.get( node.getMachineClass() ); - if( target != null ) - { - x++; - target.invoke( node.getMachine(), e ); - } - } - } - catch( final NetworkEventDone done ) - { - // Early out. - } + MENetworkEvent postEventTo(final Grid grid, final GridNode node, final MENetworkEvent e) { + final Map subscribers = EVENTS.get(e.getClass()); + int x = 0; - e.setVisitedObjects( x ); - return e; - } + try { + if (subscribers != null) { + final MENetworkEventInfo target = subscribers.get(node.getMachineClass()); + if (target != null) { + x++; + target.invoke(node.getMachine(), e); + } + } + } catch (final NetworkEventDone done) { + // Early out. + } - private static class NetworkEventDone extends Throwable - { + e.setVisitedObjects(x); + return e; + } - private static final long serialVersionUID = -3079021487019171205L; - } + private static class NetworkEventDone extends Throwable { - private class EventMethod - { + private static final long serialVersionUID = -3079021487019171205L; + } - private final Class objClass; - private final Method objMethod; - private final Class objEvent; + private class EventMethod { - public EventMethod( final Class Event, final Class ObjClass, final Method ObjMethod ) - { - this.objClass = ObjClass; - this.objMethod = ObjMethod; - this.objEvent = Event; - } + private final Class objClass; + private final Method objMethod; + private final Class objEvent; - private void invoke( final Object obj, final MENetworkEvent e ) throws NetworkEventDone - { - try - { - this.objMethod.invoke( obj, e ); - } - catch( final Throwable e1 ) - { - AELog.error( "[AppEng] Network Event caused exception:" ); - AELog.error( "Class: %1s, Object: %2s", obj.getClass().getName(), obj.toString() ); - AELog.info( e1 ); - throw new IllegalStateException( e1 ); - } + public EventMethod(final Class Event, final Class ObjClass, final Method ObjMethod) { + this.objClass = ObjClass; + this.objMethod = ObjMethod; + this.objEvent = Event; + } - if( e.isCanceled() ) - { - throw new NetworkEventDone(); - } - } - } + private void invoke(final Object obj, final MENetworkEvent e) throws NetworkEventDone { + try { + this.objMethod.invoke(obj, e); + } catch (final Throwable e1) { + AELog.error("[AppEng] Network Event caused exception:"); + AELog.error("Class: %1s, Object: %2s", obj.getClass().getName(), obj.toString()); + AELog.info(e1); + throw new IllegalStateException(e1); + } - private class MENetworkEventInfo - { + if (e.isCanceled()) { + throw new NetworkEventDone(); + } + } + } - private final List methods = new ArrayList<>(); + private class MENetworkEventInfo { - private void Add( final Class Event, final Class ObjClass, final Method ObjMethod ) - { - this.methods.add( new EventMethod( Event, ObjClass, ObjMethod ) ); - } + private final List methods = new ArrayList<>(); - private void invoke( final Object obj, final MENetworkEvent e ) throws NetworkEventDone - { - for( final EventMethod em : this.methods ) - { - em.invoke( obj, e ); - } - } - } + private void Add(final Class Event, final Class ObjClass, final Method ObjMethod) { + this.methods.add(new EventMethod(Event, ObjClass, ObjMethod)); + } + + private void invoke(final Object obj, final MENetworkEvent e) throws NetworkEventDone { + for (final EventMethod em : this.methods) { + em.invoke(obj, e); + } + } + } } diff --git a/src/main/java/appeng/me/cache/CraftingGridCache.java b/src/main/java/appeng/me/cache/CraftingGridCache.java index de7374bd9..ccf475119 100644 --- a/src/main/java/appeng/me/cache/CraftingGridCache.java +++ b/src/main/java/appeng/me/cache/CraftingGridCache.java @@ -19,31 +19,6 @@ package appeng.me.cache; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ThreadFactory; - -import com.google.common.collect.HashMultimap; -import com.google.common.collect.ImmutableCollection; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Multimap; - -import it.unimi.dsi.fastutil.objects.*; -import net.minecraft.world.World; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -51,18 +26,7 @@ import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.networking.IGridStorage; -import appeng.api.networking.crafting.ICraftingCPU; -import appeng.api.networking.crafting.ICraftingCallback; -import appeng.api.networking.crafting.ICraftingGrid; -import appeng.api.networking.crafting.ICraftingJob; -import appeng.api.networking.crafting.ICraftingLink; -import appeng.api.networking.crafting.ICraftingMedium; -import appeng.api.networking.crafting.ICraftingPatternDetails; -import appeng.api.networking.crafting.ICraftingProvider; -import appeng.api.networking.crafting.ICraftingProviderHelper; -import appeng.api.networking.crafting.ICraftingRequester; -import appeng.api.networking.crafting.ICraftingWatcher; -import appeng.api.networking.crafting.ICraftingWatcherHost; +import appeng.api.networking.crafting.*; import appeng.api.networking.energy.IEnergyGrid; import appeng.api.networking.events.MENetworkCraftingCpuChange; import appeng.api.networking.events.MENetworkCraftingPatternChange; @@ -86,624 +50,530 @@ import appeng.me.helpers.BaseActionSource; import appeng.me.helpers.GenericInterestManager; import appeng.tile.crafting.TileCraftingStorageTile; import appeng.tile.crafting.TileCraftingTile; - - -public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper, ICellProvider, IMEInventoryHandler -{ - - private static final ExecutorService CRAFTING_POOL; - private static final Comparator COMPARATOR = ( firstDetail, nextDetail ) -> nextDetail.getPriority() - firstDetail.getPriority(); - - static - { - final ThreadFactory factory = ar -> new Thread( ar, "AE Crafting Calculator" ); - - CRAFTING_POOL = Executors.newCachedThreadPool( factory ); - } - - private final Set craftingCPUClusters = new HashSet<>(); - private final Set craftingProviders = new HashSet<>(); - private final Map craftingWatchers = new HashMap<>(); - private final IGrid grid; - private final Object2ObjectMap> craftingMethods = new Object2ObjectOpenHashMap<>(); - private final Object2ObjectMap> craftableItems = new Object2ObjectOpenHashMap<>(); - private final Set emitableItems = new HashSet<>(); - private final Map craftingLinks = new HashMap<>(); - private final Multimap interests = HashMultimap.create(); - private final GenericInterestManager interestManager = new GenericInterestManager<>( this.interests ); - private IStorageGrid storageGrid; - private IEnergyGrid energyGrid; - int i; - private boolean updateList = false; - private boolean updatePatterns = false; - - public CraftingGridCache( final IGrid grid ) - { - this.grid = grid; - } - - @MENetworkEventSubscribe - public void afterCacheConstruction( final MENetworkPostCacheConstruction cacheConstruction ) - { - this.storageGrid = this.grid.getCache( IStorageGrid.class ); - this.energyGrid = this.grid.getCache( IEnergyGrid.class ); - - this.storageGrid.registerCellProvider( this ); - } - - @Override - public void onUpdateTick() - { - if( this.updateList ) - { - this.updateList = false; - this.updateCPUClusters(); - } - - if( updatePatterns ) - { - this.recalculateCraftingPatterns(); - this.updatePatterns = false; - } - - final Iterator craftingLinkIterator = this.craftingLinks.values().iterator(); - while ( craftingLinkIterator.hasNext() ) - { - if( craftingLinkIterator.next().isDead( this.grid, this ) ) - { - craftingLinkIterator.remove(); - } - } - - for( final CraftingCPUCluster cpu : this.craftingCPUClusters ) - { - cpu.updateCraftingLogic( this.grid, this.energyGrid, this ); - } - } - - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof ICraftingWatcherHost ) - { - final ICraftingWatcher craftingWatcher = this.craftingWatchers.get( gridNode ); - if( craftingWatcher != null ) - { - craftingWatcher.reset(); - this.craftingWatchers.remove( gridNode ); - } - } - - if( machine instanceof ICraftingRequester ) - { - for( final CraftingLinkNexus link : this.craftingLinks.values() ) - { - if( link.isMachine( machine ) ) - { - link.removeNode(); - } - } - } - - if( machine instanceof TileCraftingTile ) - { - this.updateList = true; - } - - if( machine instanceof ICraftingProvider ) - { - this.craftingProviders.remove( machine ); - this.updatePatterns = true; - } - } - - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof ICraftingWatcherHost ) - { - final ICraftingWatcherHost watcherHost = (ICraftingWatcherHost) machine; - final CraftingWatcher watcher = new CraftingWatcher( this, watcherHost ); - this.craftingWatchers.put( gridNode, watcher ); - watcherHost.updateWatcher( watcher ); - } - - if( machine instanceof ICraftingRequester ) - { - for( final ICraftingLink link : ( (ICraftingRequester) machine ).getRequestedJobs() ) - { - if( link instanceof CraftingLink ) - { - this.addLink( (CraftingLink) link ); - } - } - } - - if( machine instanceof TileCraftingTile ) - { - this.updateList = true; - } - - if( machine instanceof ICraftingProvider ) - { - this.craftingProviders.add( (ICraftingProvider) machine ); - this.updatePatterns = true; - } - } - - @Override - public void onSplit( final IGridStorage destinationStorage ) - { // nothing! - } - - @Override - public void onJoin( final IGridStorage sourceStorage ) - { - // nothing! - } - - @Override - public void populateGridStorage( final IGridStorage destinationStorage ) - { - // nothing! - } - - private void updatePatterns() - { - this.updatePatterns = true; - } - - private void recalculateCraftingPatterns() - { - final Object2ObjectMap> oldItems = new Object2ObjectOpenHashMap<>( this.craftableItems ); - final Set oldEmitableItems = new HashSet<>( this.emitableItems ); - - // erase list. - this.craftingMethods.clear(); - this.craftableItems.clear(); - this.emitableItems.clear(); - - // re-create list.. - for( final ICraftingProvider provider : this.craftingProviders ) - { - provider.provideCrafting( this ); - } - - final Object2ObjectMap> tmpCraft = new Object2ObjectOpenHashMap<>(); - - // new craftables! - for( final ICraftingPatternDetails details : this.craftingMethods.keySet() ) - { - for( IAEItemStack out : details.getOutputs() ) - { - out = out.copy(); - out.reset(); - out.setCraftable( true ); - - ObjectSet methods = tmpCraft.get( out ); - - if( methods == null ) - { - tmpCraft.put( out, methods = new ObjectRBTreeSet<>( COMPARATOR ) ); - } - - methods.add( details ); - } - } - - // make them immutable - for( final Entry> e : tmpCraft.entrySet() ) - { - this.craftableItems.put( e.getKey(), ImmutableList.copyOf( e.getValue() ) ); - } - - List craftablesChanged = new ArrayList<>(); - - ObjectSet>> i = oldItems.entrySet(); - for( Entry> ais : i ) - { - if( !this.craftableItems.containsKey( ais.getKey() ) ) - { - IAEItemStack changedStack = ais.getKey().copy(); - changedStack.reset(); - changedStack.setCraftable( false ); - craftablesChanged.add( changedStack ); - } - } - - ObjectSet>> j = this.craftableItems.entrySet(); - for( Entry> ais : j ) - { - if( !oldItems.containsKey( ais ) ) - { - IAEItemStack changedStack = ais.getKey().copy(); - changedStack.reset(); - changedStack.setCraftable( true ); - craftablesChanged.add( changedStack ); - } - } - - for( final IAEItemStack st : oldEmitableItems ) - { - if( !emitableItems.contains( st ) ) - { - IAEItemStack changedStack = st.copy(); - changedStack.reset(); - changedStack.setCraftable( false ); - craftablesChanged.add( changedStack ); - } - } - - for( final IAEItemStack st : this.emitableItems ) - { - if( !oldEmitableItems.contains( st ) ) - { - IAEItemStack changedStack = st.copy(); - changedStack.reset(); - changedStack.setCraftable( true ); - craftablesChanged.add( changedStack ); - } - } - - this.storageGrid.postCraftablesChanges( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), craftablesChanged, new BaseActionSource() ); - } - - private void updateCPUClusters() - { - this.craftingCPUClusters.clear(); - - for( final IGridNode cst : this.grid.getMachines( TileCraftingStorageTile.class ) ) - { - final TileCraftingStorageTile tile = (TileCraftingStorageTile) cst.getMachine(); - final CraftingCPUCluster cluster = (CraftingCPUCluster) tile.getCluster(); - if( cluster != null ) - { - this.craftingCPUClusters.add( cluster ); - - if( cluster.getLastCraftingLink() != null ) - { - this.addLink( (CraftingLink) cluster.getLastCraftingLink() ); - } - } - } - - } - - public void addLink( final CraftingLink link ) - { - if( link.isStandalone() ) - { - return; - } - - CraftingLinkNexus nexus = this.craftingLinks.get( link.getCraftingID() ); - if( nexus == null ) - { - this.craftingLinks.put( link.getCraftingID(), nexus = new CraftingLinkNexus( link.getCraftingID() ) ); - } - - link.setNexus( nexus ); - } - - @MENetworkEventSubscribe - public void updateCPUClusters( final MENetworkCraftingCpuChange c ) - { - this.updateList = true; - } - - @MENetworkEventSubscribe - public void updateCPUClusters( final MENetworkCraftingPatternChange c ) - { - this.updatePatterns(); - } - - @Override - public void addCraftingOption( final ICraftingMedium medium, final ICraftingPatternDetails api ) - { - List details = this.craftingMethods.get( api ); - if( details == null ) - { - details = new ArrayList<>(); - details.add( medium ); - this.craftingMethods.put( api, details ); - } - else - { - details.add( medium ); - } - } - - @Override - public void setEmitable( final IAEItemStack someItem ) - { - this.emitableItems.add( someItem.copy() ); - } - - @Override - public List getCellArray( final IStorageChannel channel ) - { - final List list = new ArrayList<>( 1 ); - - if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - list.add( this ); - } - - return list; - } - - @Override - public int getPriority() - { - return Integer.MAX_VALUE; - } - - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.WRITE; - } - - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - return true; - } - - @Override - public boolean canAccept( final IAEItemStack input ) - { - for( final CraftingCPUCluster cpu : this.craftingCPUClusters ) - { - if( cpu.canAccept( input ) ) - { - return true; - } - } - - return false; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return i == 1; - } - - @Override - public IAEItemStack injectItems( IAEItemStack input, final Actionable type, final IActionSource src ) - { - for( final CraftingCPUCluster cpu : this.craftingCPUClusters ) - { - input = cpu.injectItems( input, type, src ); - } - - return input; - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final IActionSource src ) - { - return null; - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - // add craftable items! - for( final IAEItemStack stack : this.craftableItems.keySet() ) - { - out.addCrafting( stack ); - } - - for( final IAEItemStack st : this.emitableItems ) - { - out.addCrafting( st ); - } - - return out; - } - - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } - - @Override - public ImmutableCollection getCraftingFor( final IAEItemStack whatToCraft, final ICraftingPatternDetails details, final int slotIndex, final World world ) - { - final ImmutableList res = this.craftableItems.get( whatToCraft ); - - if( res == null ) - { - return ImmutableSet.of(); - } - - return res; - } - - @Override - public Future beginCraftingJob( final World world, final IGrid grid, final IActionSource actionSrc, final IAEItemStack slotItem, final ICraftingCallback cb ) - { - if( world == null || grid == null || actionSrc == null || slotItem == null ) - { - throw new IllegalArgumentException( "Invalid Crafting Job Request" ); - } - - final CraftingJob job = new CraftingJob( world, grid, actionSrc, slotItem, cb ); - - return CRAFTING_POOL.submit( job, (ICraftingJob) job ); - } - - @Override - public ICraftingLink submitJob( final ICraftingJob job, final ICraftingRequester requestingMachine, final ICraftingCPU target, final boolean prioritizePower, final IActionSource src ) - { - if( job.isSimulation() ) - { - return null; - } - - CraftingCPUCluster cpuCluster = null; - - if( target instanceof CraftingCPUCluster ) - { - cpuCluster = (CraftingCPUCluster) target; - } - - if( target == null ) - { - final List validCpusClusters = new ArrayList<>(); - for( final CraftingCPUCluster cpu : this.craftingCPUClusters ) - { - if( cpu.isActive() && !cpu.isBusy() && cpu.getAvailableStorage() >= job.getByteTotal() ) - { - validCpusClusters.add( cpu ); - } - } - - Collections.sort( validCpusClusters, ( firstCluster, nextCluster ) -> { - if( prioritizePower ) - { - final int comparison1 = Long.compare( nextCluster.getCoProcessors(), firstCluster.getCoProcessors() ); - if( comparison1 != 0 ) - { - return comparison1; - } - return Long.compare( nextCluster.getAvailableStorage(), firstCluster.getAvailableStorage() ); - } - - final int comparison2 = Long.compare( firstCluster.getCoProcessors(), nextCluster.getCoProcessors() ); - if( comparison2 != 0 ) - { - return comparison2; - } - return Long.compare( firstCluster.getAvailableStorage(), nextCluster.getAvailableStorage() ); - } ); - - if( !validCpusClusters.isEmpty() ) - { - cpuCluster = validCpusClusters.get( 0 ); - } - } - - if( cpuCluster != null ) - { - return cpuCluster.submitJob( this.grid, job, src, requestingMachine ); - } - - return null; - } - - @Override - public ImmutableSet getCpus() - { - return ImmutableSet.copyOf( new ActiveCpuIterator( this.craftingCPUClusters ) ); - } - - @Override - public boolean canEmitFor( final IAEItemStack someItem ) - { - return this.emitableItems.contains( someItem ); - } - - @Override - public boolean isRequesting( final IAEItemStack what ) - { - return this.requesting( what ) > 0; - } - - @Override - public long requesting( IAEItemStack what ) - { - long requested = 0; - - for( final CraftingCPUCluster cluster : this.craftingCPUClusters ) - { - final IAEItemStack stack = cluster.making( what ); - requested += stack != null ? stack.getStackSize() : 0; - } - - return requested; - } - - public List getMediums( final ICraftingPatternDetails key ) - { - List mediums = this.craftingMethods.get( key ); - - if( mediums == null ) - { - mediums = ImmutableList.of(); - } - - return mediums; - } - - public boolean hasCpu( final ICraftingCPU cpu ) - { - if( cpu instanceof CraftingCPUCluster ) - { - return this.craftingCPUClusters.contains( (CraftingCPUCluster) cpu ); - } - return false; - } - - public GenericInterestManager getInterestManager() - { - return this.interestManager; - } - - private static class ActiveCpuIterator implements Iterator - { - - private final Iterator iterator; - private CraftingCPUCluster cpuCluster; - - public ActiveCpuIterator( final Collection o ) - { - this.iterator = o.iterator(); - this.cpuCluster = null; - } - - @Override - public boolean hasNext() - { - this.findNext(); - - return this.cpuCluster != null; - } - - private void findNext() - { - while ( this.iterator.hasNext() && this.cpuCluster == null ) - { - this.cpuCluster = this.iterator.next(); - if( !this.cpuCluster.isActive() || this.cpuCluster.isDestroyed() ) - { - this.cpuCluster = null; - } - } - } - - @Override - public ICraftingCPU next() - { - final ICraftingCPU o = this.cpuCluster; - this.cpuCluster = null; - - return o; - } - - @Override - public void remove() - { - // no.. - } - } +import com.google.common.collect.*; +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectRBTreeSet; +import it.unimi.dsi.fastutil.objects.ObjectSet; +import net.minecraft.world.World; + +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadFactory; + + +public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper, ICellProvider, IMEInventoryHandler { + + private static final ExecutorService CRAFTING_POOL; + private static final Comparator COMPARATOR = (firstDetail, nextDetail) -> nextDetail.getPriority() - firstDetail.getPriority(); + + static { + final ThreadFactory factory = ar -> new Thread(ar, "AE Crafting Calculator"); + + CRAFTING_POOL = Executors.newCachedThreadPool(factory); + } + + private final Set craftingCPUClusters = new HashSet<>(); + private final Set craftingProviders = new HashSet<>(); + private final Map craftingWatchers = new HashMap<>(); + private final IGrid grid; + private final Object2ObjectMap> craftingMethods = new Object2ObjectOpenHashMap<>(); + private final Object2ObjectMap> craftableItems = new Object2ObjectOpenHashMap<>(); + private final Set emitableItems = new HashSet<>(); + private final Map craftingLinks = new HashMap<>(); + private final Multimap interests = HashMultimap.create(); + private final GenericInterestManager interestManager = new GenericInterestManager<>(this.interests); + private IStorageGrid storageGrid; + private IEnergyGrid energyGrid; + int i; + private boolean updateList = false; + private boolean updatePatterns = false; + + public CraftingGridCache(final IGrid grid) { + this.grid = grid; + } + + @MENetworkEventSubscribe + public void afterCacheConstruction(final MENetworkPostCacheConstruction cacheConstruction) { + this.storageGrid = this.grid.getCache(IStorageGrid.class); + this.energyGrid = this.grid.getCache(IEnergyGrid.class); + + this.storageGrid.registerCellProvider(this); + } + + @Override + public void onUpdateTick() { + if (this.updateList) { + this.updateList = false; + this.updateCPUClusters(); + } + + if (updatePatterns) { + this.recalculateCraftingPatterns(); + this.updatePatterns = false; + } + + final Iterator craftingLinkIterator = this.craftingLinks.values().iterator(); + while (craftingLinkIterator.hasNext()) { + if (craftingLinkIterator.next().isDead(this.grid, this)) { + craftingLinkIterator.remove(); + } + } + + for (final CraftingCPUCluster cpu : this.craftingCPUClusters) { + cpu.updateCraftingLogic(this.grid, this.energyGrid, this); + } + } + + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof ICraftingWatcherHost) { + final ICraftingWatcher craftingWatcher = this.craftingWatchers.get(gridNode); + if (craftingWatcher != null) { + craftingWatcher.reset(); + this.craftingWatchers.remove(gridNode); + } + } + + if (machine instanceof ICraftingRequester) { + for (final CraftingLinkNexus link : this.craftingLinks.values()) { + if (link.isMachine(machine)) { + link.removeNode(); + } + } + } + + if (machine instanceof TileCraftingTile) { + this.updateList = true; + } + + if (machine instanceof ICraftingProvider) { + this.craftingProviders.remove(machine); + this.updatePatterns = true; + } + } + + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof ICraftingWatcherHost) { + final ICraftingWatcherHost watcherHost = (ICraftingWatcherHost) machine; + final CraftingWatcher watcher = new CraftingWatcher(this, watcherHost); + this.craftingWatchers.put(gridNode, watcher); + watcherHost.updateWatcher(watcher); + } + + if (machine instanceof ICraftingRequester) { + for (final ICraftingLink link : ((ICraftingRequester) machine).getRequestedJobs()) { + if (link instanceof CraftingLink) { + this.addLink((CraftingLink) link); + } + } + } + + if (machine instanceof TileCraftingTile) { + this.updateList = true; + } + + if (machine instanceof ICraftingProvider) { + this.craftingProviders.add((ICraftingProvider) machine); + this.updatePatterns = true; + } + } + + @Override + public void onSplit(final IGridStorage destinationStorage) { // nothing! + } + + @Override + public void onJoin(final IGridStorage sourceStorage) { + // nothing! + } + + @Override + public void populateGridStorage(final IGridStorage destinationStorage) { + // nothing! + } + + private void updatePatterns() { + this.updatePatterns = true; + } + + private void recalculateCraftingPatterns() { + final Object2ObjectMap> oldItems = new Object2ObjectOpenHashMap<>(this.craftableItems); + final Set oldEmitableItems = new HashSet<>(this.emitableItems); + + // erase list. + this.craftingMethods.clear(); + this.craftableItems.clear(); + this.emitableItems.clear(); + + // re-create list.. + for (final ICraftingProvider provider : this.craftingProviders) { + provider.provideCrafting(this); + } + + final Object2ObjectMap> tmpCraft = new Object2ObjectOpenHashMap<>(); + + // new craftables! + for (final ICraftingPatternDetails details : this.craftingMethods.keySet()) { + for (IAEItemStack out : details.getOutputs()) { + out = out.copy(); + out.reset(); + out.setCraftable(true); + + ObjectSet methods = tmpCraft.get(out); + + if (methods == null) { + tmpCraft.put(out, methods = new ObjectRBTreeSet<>(COMPARATOR)); + } + + methods.add(details); + } + } + + // make them immutable + for (final Entry> e : tmpCraft.entrySet()) { + this.craftableItems.put(e.getKey(), ImmutableList.copyOf(e.getValue())); + } + + List craftablesChanged = new ArrayList<>(); + + ObjectSet>> i = oldItems.entrySet(); + for (Entry> ais : i) { + if (!this.craftableItems.containsKey(ais.getKey())) { + IAEItemStack changedStack = ais.getKey().copy(); + changedStack.reset(); + changedStack.setCraftable(false); + craftablesChanged.add(changedStack); + } + } + + ObjectSet>> j = this.craftableItems.entrySet(); + for (Entry> ais : j) { + if (!oldItems.containsKey(ais)) { + IAEItemStack changedStack = ais.getKey().copy(); + changedStack.reset(); + changedStack.setCraftable(true); + craftablesChanged.add(changedStack); + } + } + + for (final IAEItemStack st : oldEmitableItems) { + if (!emitableItems.contains(st)) { + IAEItemStack changedStack = st.copy(); + changedStack.reset(); + changedStack.setCraftable(false); + craftablesChanged.add(changedStack); + } + } + + for (final IAEItemStack st : this.emitableItems) { + if (!oldEmitableItems.contains(st)) { + IAEItemStack changedStack = st.copy(); + changedStack.reset(); + changedStack.setCraftable(true); + craftablesChanged.add(changedStack); + } + } + + this.storageGrid.postCraftablesChanges(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class), craftablesChanged, new BaseActionSource()); + } + + private void updateCPUClusters() { + this.craftingCPUClusters.clear(); + + for (final IGridNode cst : this.grid.getMachines(TileCraftingStorageTile.class)) { + final TileCraftingStorageTile tile = (TileCraftingStorageTile) cst.getMachine(); + final CraftingCPUCluster cluster = (CraftingCPUCluster) tile.getCluster(); + if (cluster != null) { + this.craftingCPUClusters.add(cluster); + + if (cluster.getLastCraftingLink() != null) { + this.addLink((CraftingLink) cluster.getLastCraftingLink()); + } + } + } + + } + + public void addLink(final CraftingLink link) { + if (link.isStandalone()) { + return; + } + + CraftingLinkNexus nexus = this.craftingLinks.get(link.getCraftingID()); + if (nexus == null) { + this.craftingLinks.put(link.getCraftingID(), nexus = new CraftingLinkNexus(link.getCraftingID())); + } + + link.setNexus(nexus); + } + + @MENetworkEventSubscribe + public void updateCPUClusters(final MENetworkCraftingCpuChange c) { + this.updateList = true; + } + + @MENetworkEventSubscribe + public void updateCPUClusters(final MENetworkCraftingPatternChange c) { + this.updatePatterns(); + } + + @Override + public void addCraftingOption(final ICraftingMedium medium, final ICraftingPatternDetails api) { + List details = this.craftingMethods.get(api); + if (details == null) { + details = new ArrayList<>(); + details.add(medium); + this.craftingMethods.put(api, details); + } else { + details.add(medium); + } + } + + @Override + public void setEmitable(final IAEItemStack someItem) { + this.emitableItems.add(someItem.copy()); + } + + @Override + public List getCellArray(final IStorageChannel channel) { + final List list = new ArrayList<>(1); + + if (channel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + list.add(this); + } + + return list; + } + + @Override + public int getPriority() { + return Integer.MAX_VALUE; + } + + @Override + public AccessRestriction getAccess() { + return AccessRestriction.WRITE; + } + + @Override + public boolean isPrioritized(final IAEItemStack input) { + return true; + } + + @Override + public boolean canAccept(final IAEItemStack input) { + for (final CraftingCPUCluster cpu : this.craftingCPUClusters) { + if (cpu.canAccept(input)) { + return true; + } + } + + return false; + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public boolean validForPass(final int i) { + return i == 1; + } + + @Override + public IAEItemStack injectItems(IAEItemStack input, final Actionable type, final IActionSource src) { + for (final CraftingCPUCluster cpu : this.craftingCPUClusters) { + input = cpu.injectItems(input, type, src); + } + + return input; + } + + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final IActionSource src) { + return null; + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + // add craftable items! + for (final IAEItemStack stack : this.craftableItems.keySet()) { + out.addCrafting(stack); + } + + for (final IAEItemStack st : this.emitableItems) { + out.addCrafting(st); + } + + return out; + } + + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } + + @Override + public ImmutableCollection getCraftingFor(final IAEItemStack whatToCraft, final ICraftingPatternDetails details, final int slotIndex, final World world) { + final ImmutableList res = this.craftableItems.get(whatToCraft); + + if (res == null) { + return ImmutableSet.of(); + } + + return res; + } + + @Override + public Future beginCraftingJob(final World world, final IGrid grid, final IActionSource actionSrc, final IAEItemStack slotItem, final ICraftingCallback cb) { + if (world == null || grid == null || actionSrc == null || slotItem == null) { + throw new IllegalArgumentException("Invalid Crafting Job Request"); + } + + final CraftingJob job = new CraftingJob(world, grid, actionSrc, slotItem, cb); + + return CRAFTING_POOL.submit(job, job); + } + + @Override + public ICraftingLink submitJob(final ICraftingJob job, final ICraftingRequester requestingMachine, final ICraftingCPU target, final boolean prioritizePower, final IActionSource src) { + if (job.isSimulation()) { + return null; + } + + CraftingCPUCluster cpuCluster = null; + + if (target instanceof CraftingCPUCluster) { + cpuCluster = (CraftingCPUCluster) target; + } + + if (target == null) { + final List validCpusClusters = new ArrayList<>(); + for (final CraftingCPUCluster cpu : this.craftingCPUClusters) { + if (cpu.isActive() && !cpu.isBusy() && cpu.getAvailableStorage() >= job.getByteTotal()) { + validCpusClusters.add(cpu); + } + } + + Collections.sort(validCpusClusters, (firstCluster, nextCluster) -> { + if (prioritizePower) { + final int comparison1 = Long.compare(nextCluster.getCoProcessors(), firstCluster.getCoProcessors()); + if (comparison1 != 0) { + return comparison1; + } + return Long.compare(nextCluster.getAvailableStorage(), firstCluster.getAvailableStorage()); + } + + final int comparison2 = Long.compare(firstCluster.getCoProcessors(), nextCluster.getCoProcessors()); + if (comparison2 != 0) { + return comparison2; + } + return Long.compare(firstCluster.getAvailableStorage(), nextCluster.getAvailableStorage()); + }); + + if (!validCpusClusters.isEmpty()) { + cpuCluster = validCpusClusters.get(0); + } + } + + if (cpuCluster != null) { + return cpuCluster.submitJob(this.grid, job, src, requestingMachine); + } + + return null; + } + + @Override + public ImmutableSet getCpus() { + return ImmutableSet.copyOf(new ActiveCpuIterator(this.craftingCPUClusters)); + } + + @Override + public boolean canEmitFor(final IAEItemStack someItem) { + return this.emitableItems.contains(someItem); + } + + @Override + public boolean isRequesting(final IAEItemStack what) { + return this.requesting(what) > 0; + } + + @Override + public long requesting(IAEItemStack what) { + long requested = 0; + + for (final CraftingCPUCluster cluster : this.craftingCPUClusters) { + final IAEItemStack stack = cluster.making(what); + requested += stack != null ? stack.getStackSize() : 0; + } + + return requested; + } + + public List getMediums(final ICraftingPatternDetails key) { + List mediums = this.craftingMethods.get(key); + + if (mediums == null) { + mediums = ImmutableList.of(); + } + + return mediums; + } + + public boolean hasCpu(final ICraftingCPU cpu) { + if (cpu instanceof CraftingCPUCluster) { + return this.craftingCPUClusters.contains((CraftingCPUCluster) cpu); + } + return false; + } + + public GenericInterestManager getInterestManager() { + return this.interestManager; + } + + private static class ActiveCpuIterator implements Iterator { + + private final Iterator iterator; + private CraftingCPUCluster cpuCluster; + + public ActiveCpuIterator(final Collection o) { + this.iterator = o.iterator(); + this.cpuCluster = null; + } + + @Override + public boolean hasNext() { + this.findNext(); + + return this.cpuCluster != null; + } + + private void findNext() { + while (this.iterator.hasNext() && this.cpuCluster == null) { + this.cpuCluster = this.iterator.next(); + if (!this.cpuCluster.isActive() || this.cpuCluster.isDestroyed()) { + this.cpuCluster = null; + } + } + } + + @Override + public ICraftingCPU next() { + final ICraftingCPU o = this.cpuCluster; + this.cpuCluster = null; + + return o; + } + + @Override + public void remove() { + // no.. + } + } } diff --git a/src/main/java/appeng/me/cache/EnergyGridCache.java b/src/main/java/appeng/me/cache/EnergyGridCache.java index 1d0adb668..bf1f7766f 100644 --- a/src/main/java/appeng/me/cache/EnergyGridCache.java +++ b/src/main/java/appeng/me/cache/EnergyGridCache.java @@ -19,807 +19,654 @@ package appeng.me.cache; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.NavigableSet; -import java.util.PriorityQueue; -import java.util.Queue; -import java.util.Set; - -import com.google.common.base.Preconditions; -import com.google.common.collect.HashMultiset; -import com.google.common.collect.Multiset; -import com.google.common.collect.Sets; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; -import appeng.api.networking.IGrid; -import appeng.api.networking.IGridBlock; -import appeng.api.networking.IGridHost; -import appeng.api.networking.IGridNode; -import appeng.api.networking.IGridStorage; -import appeng.api.networking.energy.IAEPowerStorage; -import appeng.api.networking.energy.IEnergyGrid; -import appeng.api.networking.energy.IEnergyGridProvider; -import appeng.api.networking.energy.IEnergyWatcher; -import appeng.api.networking.energy.IEnergyWatcherHost; -import appeng.api.networking.events.MENetworkEventSubscribe; -import appeng.api.networking.events.MENetworkPostCacheConstruction; -import appeng.api.networking.events.MENetworkPowerIdleChange; -import appeng.api.networking.events.MENetworkPowerStatusChange; -import appeng.api.networking.events.MENetworkPowerStorage; +import appeng.api.networking.*; +import appeng.api.networking.energy.*; +import appeng.api.networking.events.*; import appeng.api.networking.events.MENetworkPowerStorage.PowerEventType; import appeng.api.networking.pathing.IPathingGrid; import appeng.me.Grid; import appeng.me.GridNode; import appeng.me.energy.EnergyThreshold; import appeng.me.energy.EnergyWatcher; - - -public class EnergyGridCache implements IEnergyGrid -{ - - private static final double MAX_BUFFER_STORAGE = 800; - private static final Comparator COMPARATOR_HIGHEST_AMOUNT_STORED_FIRST = ( o1, o2 ) -> Double.compare( o2.getProviderStoredEnergy(), o1.getProviderStoredEnergy() ); - - private static final Comparator COMPARATOR_LOWEST_PERCENTAGE_FIRST = ( o1, o2 ) -> { - final double percent1 = ( o1.getProviderStoredEnergy() + 1 ) / ( o1.getProviderMaxEnergy() + 1 ); - final double percent2 = ( o2.getProviderStoredEnergy() + 1 ) / ( o2.getProviderMaxEnergy() + 1 ); - - return Double.compare( percent1, percent2 ); - }; - - private final NavigableSet interests = Sets.newTreeSet(); - - // Should only be modified from the add/remove methods below to guard against - // concurrent modifications - private final double averageLength = 40.0; - private final Set providers = new LinkedHashSet<>(); - // Used to track whether an extraction is currently in progress, to fail fast - // when something externally - // modifies the energy grid. - private boolean ongoingExtractOperation = false; - - // Should only be modified from the add/remove methods below to guard against - // concurrent modifications - private final Set requesters = new LinkedHashSet<>(); - // Used to track whether an injection is currently in progress, to fail fast - // when something externally - // modifies the energy grid. - private boolean ongoingInjectOperation = false; - - private final Multiset energyGridProviders = HashMultiset.create(); - private final IGrid myGrid; - private final HashMap watchers = new HashMap<>(); - - /** - * estimated power available. - */ - private int availableTicksSinceUpdate = 0; - private double globalAvailablePower = 0; - private double globalMaxPower = MAX_BUFFER_STORAGE; - - /** - * idle draw. - */ - private double drainPerTick = 0; - private double avgDrainPerTick = 0; - private double avgInjectionPerTick = 0; - private double tickDrainPerTick = 0; - private double tickInjectionPerTick = 0; - - /** - * power status - */ - private boolean publicHasPower = false; - private boolean hasPower = true; - private long ticksSinceHasPowerChange = 900; - - private PathGridCache pgc; - private double lastStoredPower = -1; - - private final GridPowerStorage localStorage = new GridPowerStorage(); - private Set providerToRemove = new HashSet<>(); - private Set requesterToRemove = new HashSet<>(); - private Set providersToAdd = new HashSet<>(); - private Set requesterToAdd = new HashSet<>(); - - public EnergyGridCache( final IGrid g ) - { - this.myGrid = g; - this.requesters.add( this.localStorage ); - this.providers.add( this.localStorage ); - } - - @MENetworkEventSubscribe - public void postInit( final MENetworkPostCacheConstruction pcc ) - { - this.pgc = this.myGrid.getCache( IPathingGrid.class ); - } - - @MENetworkEventSubscribe - public void nodeIdlePowerChangeHandler( final MENetworkPowerIdleChange ev ) - { - // update power usage based on event. - final GridNode node = (GridNode) ev.node; - final IGridBlock gb = node.getGridBlock(); - - final double newDraw = gb.getIdlePowerUsage(); - final double diffDraw = newDraw - node.getPreviousDraw(); - node.setPreviousDraw( newDraw ); - - this.drainPerTick += diffDraw; - } - - @MENetworkEventSubscribe - public void storagePowerChangeHandler( final MENetworkPowerStorage ev ) - { - if( ev.storage.isAEPublicPowerStorage() ) - { - if( ev.type == PowerEventType.PROVIDE_POWER ) - { - if( ev.storage.getPowerFlow() != AccessRestriction.WRITE ) - { - if( !ongoingExtractOperation ) - { - addProvider( ev.storage ); - } - else - { - this.providersToAdd.add( ev.storage ); - } - } - } - else if( ev.type == PowerEventType.REQUEST_POWER ) - { - if( ev.storage.getPowerFlow() != AccessRestriction.READ ) - { - if( !ongoingInjectOperation ) - { - addRequester( ev.storage ); - } - else - { - this.requesterToAdd.add( ev.storage ); - } - } - } - } - else - { - ( new RuntimeException( "Attempt to ask the IEnergyGrid to charge a non public energy store." ) ).printStackTrace(); - } - } - - @Override - public void onUpdateTick() - { - if( !this.interests.isEmpty() ) - { - final double oldPower = this.lastStoredPower; - this.lastStoredPower = this.getStoredPower(); - - final EnergyThreshold low = new EnergyThreshold( Math.min( oldPower, this.lastStoredPower ), Integer.MIN_VALUE ); - final EnergyThreshold high = new EnergyThreshold( Math.max( oldPower, this.lastStoredPower ), Integer.MAX_VALUE ); - - for( final EnergyThreshold th : this.interests.subSet( low, true, high, true ) ) - { - ( (EnergyWatcher) th.getEnergyWatcher() ).post( this ); - } - } - - this.avgDrainPerTick *= ( this.averageLength - 1 ) / this.averageLength; - this.avgInjectionPerTick *= ( this.averageLength - 1 ) / this.averageLength; - - this.avgDrainPerTick += this.tickDrainPerTick / this.averageLength; - this.avgInjectionPerTick += this.tickInjectionPerTick / this.averageLength; - - this.tickDrainPerTick = 0; - this.tickInjectionPerTick = 0; - - // power information. - boolean currentlyHasPower = false; - - if( this.drainPerTick > 0.0001 ) - { - final double drained = this.extractAEPower( this.getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG ); - currentlyHasPower = drained >= this.drainPerTick - 0.001; - } - else - { - currentlyHasPower = this.extractAEPower( 0.1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0; - } - - // ticks since change.. - if( currentlyHasPower == this.hasPower ) - { - this.ticksSinceHasPowerChange++; - } - else - { - this.ticksSinceHasPowerChange = 0; - } - - // update status.. - this.hasPower = currentlyHasPower; - - // update public status, this buffers power ups for 30 ticks. - if( this.hasPower && this.ticksSinceHasPowerChange > 30 ) - { - this.publicPowerState( true, this.myGrid ); - } - else if( !this.hasPower ) - { - this.publicPowerState( false, this.myGrid ); - } - - this.availableTicksSinceUpdate++; - } - - @Override - public double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier pm ) - { - final double toExtract = pm.multiply( amt ); - final Queue toVisit = new PriorityQueue<>( COMPARATOR_HIGHEST_AMOUNT_STORED_FIRST ); - final Set visited = new HashSet<>(); - - double extracted = 0; - toVisit.add( this ); - - while( !toVisit.isEmpty() && extracted < toExtract ) - { - final IEnergyGridProvider next = toVisit.poll(); - visited.add( next ); - - extracted += next.extractProviderPower( toExtract - extracted, mode ); - - for( IEnergyGridProvider iEnergyGridProvider : next.providers() ) - { - if( !visited.contains( iEnergyGridProvider ) ) - { - toVisit.add( iEnergyGridProvider ); - } - } - } - - return pm.divide( extracted ); - } - - @Override - public double getIdlePowerUsage() - { - return this.drainPerTick + this.pgc.getChannelPowerUsage(); - } - - private void publicPowerState( final boolean newState, final IGrid grid ) - { - if( this.publicHasPower == newState ) - { - return; - } - - this.publicHasPower = newState; - ( (Grid) this.myGrid ).setImportantFlag( 0, this.publicHasPower ); - grid.postEvent( new MENetworkPowerStatusChange() ); - } - - /** - * refresh current stored power. - */ - private void refreshPower() - { - this.availableTicksSinceUpdate = 0; - this.globalAvailablePower = 0; - for( final IAEPowerStorage p : this.providers ) - { - this.globalAvailablePower += p.getAECurrentPower(); - } - } - - @Override - public Collection providers() - { - return this.energyGridProviders; - } - - @Override - public double extractProviderPower( final double amt, final Actionable mode ) - { - double extractedPower = 0; - - this.providers.addAll( providersToAdd ); - providersToAdd.clear(); - providers.removeIf( providerToRemove::contains ); - this.providerToRemove.clear(); - - final Iterator it = this.providers.iterator(); - - ongoingExtractOperation = true; - boolean ls = false; - try - { - while ( extractedPower < amt && it.hasNext() ) - { - final IAEPowerStorage node = it.next(); - if( node != null ) - { - if( node == localStorage && mode == Actionable.MODULATE ) - { - ls = true; - continue; - } - - final double req = amt - extractedPower; - final double newPower = node.extractAEPower( req, mode, PowerMultiplier.ONE ); - extractedPower += newPower; - - if( newPower < req && mode == Actionable.MODULATE ) - { - it.remove(); - } - } - else - { - it.remove(); - } - } - } finally - { - ongoingExtractOperation = false; - if( ls && extractedPower < amt ) - { - final double req = amt - extractedPower; - final double newPower = localStorage.extractAEPower( req, mode, PowerMultiplier.ONE ); - - extractedPower += newPower; - - if( newPower < req ) - { - providers.remove( localStorage ); - } - } - } - - final double result = Math.min( extractedPower, amt ); - - if( mode == Actionable.MODULATE ) - { - if( extractedPower > amt ) - { - this.localStorage.addCurrentAEPower( extractedPower - amt ); - } - - this.globalAvailablePower -= result; - this.tickDrainPerTick += result; - } - - return result; - } - - @Override - public double injectProviderPower( double amt, final Actionable mode ) - { - final double originalAmount = amt; - - this.requesters.addAll( requesterToAdd ); - requesterToAdd.clear(); - requesters.removeIf( requesterToRemove::contains ); - this.requesterToRemove.clear(); - - final Iterator it = this.requesters.iterator(); - - ongoingInjectOperation = true; - try - { - while ( amt > 0 && it.hasNext() ) - { - final IAEPowerStorage node = it.next(); - - if( node != null ) - { - amt = node.injectAEPower( amt, mode ); - - if( amt > 0 && mode == Actionable.MODULATE ) - { - it.remove(); - } - } - else - { - it.remove(); - } - } - } finally - { - ongoingInjectOperation = false; - } - - final double overflow = Math.max( 0.0, amt ); - - if( mode == Actionable.MODULATE ) - { - this.tickInjectionPerTick += originalAmount - overflow; - } - - return overflow; - } - - @Override - public double getProviderEnergyDemand( final double maxRequired ) - { - double required = 0; - - final Iterator it = this.requesters.iterator(); - while ( required < maxRequired && it.hasNext() ) - { - final IAEPowerStorage node = it.next(); - if( node.getPowerFlow() != AccessRestriction.READ ) - { - required += Math.max( 0.0, node.getAEMaxPower() - node.getAECurrentPower() ); - } - } - - return required; - } - - @Override - public double getAvgPowerUsage() - { - return this.avgDrainPerTick; - } - - @Override - public double getAvgPowerInjection() - { - return this.avgInjectionPerTick; - } - - @Override - public boolean isNetworkPowered() - { - return this.publicHasPower; - } - - @Override - public double injectPower( final double amt, final Actionable mode ) - { - final Queue toVisit = new PriorityQueue<>( COMPARATOR_LOWEST_PERCENTAGE_FIRST ); - final Set visited = new HashSet<>(); - toVisit.add( this ); - - double leftover = amt; - - while( !toVisit.isEmpty() && leftover > 0 ) - { - final IEnergyGridProvider next = toVisit.poll(); - visited.add( next ); - - leftover = next.injectProviderPower( leftover, mode ); - - for( IEnergyGridProvider iEnergyGridProvider : next.providers() ) - { - if( !visited.contains( iEnergyGridProvider ) ) - { - toVisit.add( iEnergyGridProvider ); - } - } - } - - return leftover; - } - - @Override - public double getStoredPower() - { - this.refreshPower(); - return Math.max( 0.0, this.globalAvailablePower ); - } - - @Override - public double getMaxStoredPower() - { - return this.globalMaxPower; - } - - @Override - public double getEnergyDemand( final double maxRequired ) - { - final Queue toVisit = new PriorityQueue<>( COMPARATOR_LOWEST_PERCENTAGE_FIRST ); - final Set visited = new HashSet<>(); - toVisit.add( this ); - - double required = 0; - - while( !toVisit.isEmpty() && required < maxRequired ) - { - final IEnergyGridProvider next = toVisit.poll(); - visited.add( next ); - - required += next.getProviderEnergyDemand( maxRequired - required ); - - for( IEnergyGridProvider iEnergyGridProvider : next.providers() ) - { - if( !visited.contains( iEnergyGridProvider ) ) - { - toVisit.add( iEnergyGridProvider ); - } - } - } - - return required; - } - - @Override - public double getProviderStoredEnergy() - { - return this.getStoredPower(); - } - - @Override - public double getProviderMaxEnergy() - { - return this.getMaxStoredPower(); - } - - @Override - public void removeNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof IEnergyGridProvider ) - { - this.energyGridProviders.remove( machine ); - } - - // idle draw. - final GridNode gridNode = (GridNode) node; - this.drainPerTick -= gridNode.getPreviousDraw(); - - // power storage. - if( machine instanceof IAEPowerStorage ) - { - final IAEPowerStorage ps = (IAEPowerStorage) machine; - if( ps.isAEPublicPowerStorage() ) - { - if( ps.getPowerFlow() != AccessRestriction.WRITE ) - { - this.globalMaxPower -= ps.getAEMaxPower(); - this.globalAvailablePower -= ps.getAECurrentPower(); - } - if( !ongoingExtractOperation ) - { - removeProvider( ps ); - } - else - { - this.providerToRemove.add( ps ); - } - if( !ongoingInjectOperation ) - { - removeRequester( ps ); - } - else - { - this.requesterToRemove.add( ps ); - } - } - } - - if( machine instanceof IEnergyWatcherHost ) - { - final IEnergyWatcher watcher = this.watchers.get( node ); - - if( watcher != null ) - { - watcher.reset(); - this.watchers.remove( node ); - } - } - } - - private void addRequester( IAEPowerStorage requester ) - { - Preconditions.checkState( !ongoingInjectOperation, "Cannot modify energy requesters while energy is being injected." ); - this.requesters.add( requester ); - } - - private void removeRequester( IAEPowerStorage requester ) - { - Preconditions.checkState( !ongoingInjectOperation, "Cannot modify energy requesters while energy is being injected." ); - this.requesters.remove( requester ); - } - - private void addProvider( IAEPowerStorage provider ) - { - Preconditions.checkState( !ongoingExtractOperation, "Cannot modify energy providers while energy is being extracted." ); - this.providers.add( provider ); - } - - private void removeProvider( IAEPowerStorage provider ) - { - Preconditions.checkState( !ongoingExtractOperation, "Cannot modify energy providers while energy is being extracted." ); - this.providers.remove( provider ); - } - - - @Override - public void addNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof IEnergyGridProvider ) - { - this.energyGridProviders.add( (IEnergyGridProvider) machine ); - } - - // idle draw... - final GridNode gridNode = (GridNode) node; - final IGridBlock gb = gridNode.getGridBlock(); - gridNode.setPreviousDraw( gb.getIdlePowerUsage() ); - this.drainPerTick += gridNode.getPreviousDraw(); - - // power storage - if( machine instanceof IAEPowerStorage ) - { - final IAEPowerStorage ps = (IAEPowerStorage) machine; - if( ps.isAEPublicPowerStorage() ) - { - final double max = ps.getAEMaxPower(); - final double current = ps.getAECurrentPower(); - - if( ps.getPowerFlow() != AccessRestriction.WRITE ) - { - this.globalMaxPower += ps.getAEMaxPower(); - } - - if( current > 0 && ps.getPowerFlow() != AccessRestriction.WRITE ) - { - this.globalAvailablePower += current; - if( !ongoingExtractOperation ) - { - addProvider( ps ); - } - else - { - this.providersToAdd.add( ps ); - } - } - - if( current < max && ps.getPowerFlow() != AccessRestriction.READ ) - { - if( !ongoingInjectOperation ) - { - addRequester( ps ); - } - else - { - this.requesterToAdd.add( ps ); - } - } - } - } - - if( machine instanceof IEnergyWatcherHost ) - { - final IEnergyWatcherHost swh = (IEnergyWatcherHost) machine; - final EnergyWatcher iw = new EnergyWatcher( this, swh ); - - this.watchers.put( node, iw ); - swh.updateWatcher( iw ); - } - - this.myGrid.postEventTo( node, new MENetworkPowerStatusChange() ); - } - - @Override - public void onSplit( final IGridStorage storageB ) - { - final double newBuffer = this.localStorage.getAECurrentPower() / 2; - this.localStorage.removeCurrentAEPower( newBuffer ); - storageB.dataObject().setDouble( "buffer", newBuffer ); - } - - @Override - public void onJoin( final IGridStorage storageB ) - { - this.localStorage.addCurrentAEPower( storageB.dataObject().getDouble( "buffer" ) ); - } - - @Override - public void populateGridStorage( final IGridStorage storage ) - { - storage.dataObject().setDouble( "buffer", this.localStorage.getAECurrentPower() ); - } - - public boolean registerEnergyInterest( final EnergyThreshold threshold ) - { - return this.interests.add( threshold ); - } - - public boolean unregisterEnergyInterest( final EnergyThreshold threshold ) - { - return this.interests.remove( threshold ); - } - - private class GridPowerStorage implements IAEPowerStorage - { - private double stored = 0; - - @Override - public double extractAEPower( double amt, Actionable mode, PowerMultiplier usePowerMultiplier ) - { - double extracted = Math.min( amt, this.stored ); - - if( mode == Actionable.MODULATE ) - { - this.removeCurrentAEPower( extracted ); - } - - return extracted; - } - - @Override - public boolean isAEPublicPowerStorage() - { - return true; - } - - @Override - public double injectAEPower( double amt, Actionable mode ) - { - double toStore = Math.min( amt, MAX_BUFFER_STORAGE - this.stored ); - - if( mode == Actionable.MODULATE ) - { - this.addCurrentAEPower( toStore ); - } - - return amt - toStore; - } - - @Override - public AccessRestriction getPowerFlow() - { - return AccessRestriction.READ_WRITE; - } - - @Override - public double getAEMaxPower() - { - return MAX_BUFFER_STORAGE; - } - - @Override - public double getAECurrentPower() - { - return this.stored; - } - - private void addCurrentAEPower( double amount ) - { - this.stored += amount; - - if( this.stored > 0.01 ) - { - EnergyGridCache.this.myGrid.postEvent( new MENetworkPowerStorage( this, PowerEventType.PROVIDE_POWER ) ); - } - } - - private void removeCurrentAEPower( double amount ) - { - this.stored -= amount; - - if( this.stored < MAX_BUFFER_STORAGE - 0.001 ) - { - EnergyGridCache.this.myGrid.postEvent( new MENetworkPowerStorage( this, PowerEventType.REQUEST_POWER ) ); - } - - if( this.stored < 0.01 ) - { - EnergyGridCache.this.ticksSinceHasPowerChange = 0; - EnergyGridCache.this.publicPowerState( false, EnergyGridCache.this.myGrid ); - } - } - } +import com.google.common.base.Preconditions; +import com.google.common.collect.HashMultiset; +import com.google.common.collect.Multiset; +import com.google.common.collect.Sets; + +import java.util.*; + + +public class EnergyGridCache implements IEnergyGrid { + + private static final double MAX_BUFFER_STORAGE = 800; + private static final Comparator COMPARATOR_HIGHEST_AMOUNT_STORED_FIRST = (o1, o2) -> Double.compare(o2.getProviderStoredEnergy(), o1.getProviderStoredEnergy()); + + private static final Comparator COMPARATOR_LOWEST_PERCENTAGE_FIRST = (o1, o2) -> { + final double percent1 = (o1.getProviderStoredEnergy() + 1) / (o1.getProviderMaxEnergy() + 1); + final double percent2 = (o2.getProviderStoredEnergy() + 1) / (o2.getProviderMaxEnergy() + 1); + + return Double.compare(percent1, percent2); + }; + + private final NavigableSet interests = Sets.newTreeSet(); + + // Should only be modified from the add/remove methods below to guard against + // concurrent modifications + private final double averageLength = 40.0; + private final Set providers = new LinkedHashSet<>(); + // Used to track whether an extraction is currently in progress, to fail fast + // when something externally + // modifies the energy grid. + private boolean ongoingExtractOperation = false; + + // Should only be modified from the add/remove methods below to guard against + // concurrent modifications + private final Set requesters = new LinkedHashSet<>(); + // Used to track whether an injection is currently in progress, to fail fast + // when something externally + // modifies the energy grid. + private boolean ongoingInjectOperation = false; + + private final Multiset energyGridProviders = HashMultiset.create(); + private final IGrid myGrid; + private final HashMap watchers = new HashMap<>(); + + /** + * estimated power available. + */ + private int availableTicksSinceUpdate = 0; + private double globalAvailablePower = 0; + private double globalMaxPower = MAX_BUFFER_STORAGE; + + /** + * idle draw. + */ + private double drainPerTick = 0; + private double avgDrainPerTick = 0; + private double avgInjectionPerTick = 0; + private double tickDrainPerTick = 0; + private double tickInjectionPerTick = 0; + + /** + * power status + */ + private boolean publicHasPower = false; + private boolean hasPower = true; + private long ticksSinceHasPowerChange = 900; + + private PathGridCache pgc; + private double lastStoredPower = -1; + + private final GridPowerStorage localStorage = new GridPowerStorage(); + private final Set providerToRemove = new HashSet<>(); + private final Set requesterToRemove = new HashSet<>(); + private final Set providersToAdd = new HashSet<>(); + private final Set requesterToAdd = new HashSet<>(); + + public EnergyGridCache(final IGrid g) { + this.myGrid = g; + this.requesters.add(this.localStorage); + this.providers.add(this.localStorage); + } + + @MENetworkEventSubscribe + public void postInit(final MENetworkPostCacheConstruction pcc) { + this.pgc = this.myGrid.getCache(IPathingGrid.class); + } + + @MENetworkEventSubscribe + public void nodeIdlePowerChangeHandler(final MENetworkPowerIdleChange ev) { + // update power usage based on event. + final GridNode node = (GridNode) ev.node; + final IGridBlock gb = node.getGridBlock(); + + final double newDraw = gb.getIdlePowerUsage(); + final double diffDraw = newDraw - node.getPreviousDraw(); + node.setPreviousDraw(newDraw); + + this.drainPerTick += diffDraw; + } + + @MENetworkEventSubscribe + public void storagePowerChangeHandler(final MENetworkPowerStorage ev) { + if (ev.storage.isAEPublicPowerStorage()) { + if (ev.type == PowerEventType.PROVIDE_POWER) { + if (ev.storage.getPowerFlow() != AccessRestriction.WRITE) { + if (!ongoingExtractOperation) { + addProvider(ev.storage); + } else { + this.providersToAdd.add(ev.storage); + } + } + } else if (ev.type == PowerEventType.REQUEST_POWER) { + if (ev.storage.getPowerFlow() != AccessRestriction.READ) { + if (!ongoingInjectOperation) { + addRequester(ev.storage); + } else { + this.requesterToAdd.add(ev.storage); + } + } + } + } else { + (new RuntimeException("Attempt to ask the IEnergyGrid to charge a non public energy store.")).printStackTrace(); + } + } + + @Override + public void onUpdateTick() { + if (!this.interests.isEmpty()) { + final double oldPower = this.lastStoredPower; + this.lastStoredPower = this.getStoredPower(); + + final EnergyThreshold low = new EnergyThreshold(Math.min(oldPower, this.lastStoredPower), Integer.MIN_VALUE); + final EnergyThreshold high = new EnergyThreshold(Math.max(oldPower, this.lastStoredPower), Integer.MAX_VALUE); + + for (final EnergyThreshold th : this.interests.subSet(low, true, high, true)) { + ((EnergyWatcher) th.getEnergyWatcher()).post(this); + } + } + + this.avgDrainPerTick *= (this.averageLength - 1) / this.averageLength; + this.avgInjectionPerTick *= (this.averageLength - 1) / this.averageLength; + + this.avgDrainPerTick += this.tickDrainPerTick / this.averageLength; + this.avgInjectionPerTick += this.tickInjectionPerTick / this.averageLength; + + this.tickDrainPerTick = 0; + this.tickInjectionPerTick = 0; + + // power information. + boolean currentlyHasPower = false; + + if (this.drainPerTick > 0.0001) { + final double drained = this.extractAEPower(this.getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG); + currentlyHasPower = drained >= this.drainPerTick - 0.001; + } else { + currentlyHasPower = this.extractAEPower(0.1, Actionable.SIMULATE, PowerMultiplier.CONFIG) > 0; + } + + // ticks since change.. + if (currentlyHasPower == this.hasPower) { + this.ticksSinceHasPowerChange++; + } else { + this.ticksSinceHasPowerChange = 0; + } + + // update status.. + this.hasPower = currentlyHasPower; + + // update public status, this buffers power ups for 30 ticks. + if (this.hasPower && this.ticksSinceHasPowerChange > 30) { + this.publicPowerState(true, this.myGrid); + } else if (!this.hasPower) { + this.publicPowerState(false, this.myGrid); + } + + this.availableTicksSinceUpdate++; + } + + @Override + public double extractAEPower(final double amt, final Actionable mode, final PowerMultiplier pm) { + final double toExtract = pm.multiply(amt); + final Queue toVisit = new PriorityQueue<>(COMPARATOR_HIGHEST_AMOUNT_STORED_FIRST); + final Set visited = new HashSet<>(); + + double extracted = 0; + toVisit.add(this); + + while (!toVisit.isEmpty() && extracted < toExtract) { + final IEnergyGridProvider next = toVisit.poll(); + visited.add(next); + + extracted += next.extractProviderPower(toExtract - extracted, mode); + + for (IEnergyGridProvider iEnergyGridProvider : next.providers()) { + if (!visited.contains(iEnergyGridProvider)) { + toVisit.add(iEnergyGridProvider); + } + } + } + + return pm.divide(extracted); + } + + @Override + public double getIdlePowerUsage() { + return this.drainPerTick + this.pgc.getChannelPowerUsage(); + } + + private void publicPowerState(final boolean newState, final IGrid grid) { + if (this.publicHasPower == newState) { + return; + } + + this.publicHasPower = newState; + ((Grid) this.myGrid).setImportantFlag(0, this.publicHasPower); + grid.postEvent(new MENetworkPowerStatusChange()); + } + + /** + * refresh current stored power. + */ + private void refreshPower() { + this.availableTicksSinceUpdate = 0; + this.globalAvailablePower = 0; + for (final IAEPowerStorage p : this.providers) { + this.globalAvailablePower += p.getAECurrentPower(); + } + } + + @Override + public Collection providers() { + return this.energyGridProviders; + } + + @Override + public double extractProviderPower(final double amt, final Actionable mode) { + double extractedPower = 0; + + this.providers.addAll(providersToAdd); + providersToAdd.clear(); + providers.removeIf(providerToRemove::contains); + this.providerToRemove.clear(); + + final Iterator it = this.providers.iterator(); + + ongoingExtractOperation = true; + boolean ls = false; + try { + while (extractedPower < amt && it.hasNext()) { + final IAEPowerStorage node = it.next(); + if (node != null) { + if (node == localStorage && mode == Actionable.MODULATE) { + ls = true; + continue; + } + + final double req = amt - extractedPower; + final double newPower = node.extractAEPower(req, mode, PowerMultiplier.ONE); + extractedPower += newPower; + + if (newPower < req && mode == Actionable.MODULATE) { + it.remove(); + } + } else { + it.remove(); + } + } + } finally { + ongoingExtractOperation = false; + if (ls && extractedPower < amt) { + final double req = amt - extractedPower; + final double newPower = localStorage.extractAEPower(req, mode, PowerMultiplier.ONE); + + extractedPower += newPower; + + if (newPower < req) { + providers.remove(localStorage); + } + } + } + + final double result = Math.min(extractedPower, amt); + + if (mode == Actionable.MODULATE) { + if (extractedPower > amt) { + this.localStorage.addCurrentAEPower(extractedPower - amt); + } + + this.globalAvailablePower -= result; + this.tickDrainPerTick += result; + } + + return result; + } + + @Override + public double injectProviderPower(double amt, final Actionable mode) { + final double originalAmount = amt; + + this.requesters.addAll(requesterToAdd); + requesterToAdd.clear(); + requesters.removeIf(requesterToRemove::contains); + this.requesterToRemove.clear(); + + final Iterator it = this.requesters.iterator(); + + ongoingInjectOperation = true; + try { + while (amt > 0 && it.hasNext()) { + final IAEPowerStorage node = it.next(); + + if (node != null) { + amt = node.injectAEPower(amt, mode); + + if (amt > 0 && mode == Actionable.MODULATE) { + it.remove(); + } + } else { + it.remove(); + } + } + } finally { + ongoingInjectOperation = false; + } + + final double overflow = Math.max(0.0, amt); + + if (mode == Actionable.MODULATE) { + this.tickInjectionPerTick += originalAmount - overflow; + } + + return overflow; + } + + @Override + public double getProviderEnergyDemand(final double maxRequired) { + double required = 0; + + final Iterator it = this.requesters.iterator(); + while (required < maxRequired && it.hasNext()) { + final IAEPowerStorage node = it.next(); + if (node.getPowerFlow() != AccessRestriction.READ) { + required += Math.max(0.0, node.getAEMaxPower() - node.getAECurrentPower()); + } + } + + return required; + } + + @Override + public double getAvgPowerUsage() { + return this.avgDrainPerTick; + } + + @Override + public double getAvgPowerInjection() { + return this.avgInjectionPerTick; + } + + @Override + public boolean isNetworkPowered() { + return this.publicHasPower; + } + + @Override + public double injectPower(final double amt, final Actionable mode) { + final Queue toVisit = new PriorityQueue<>(COMPARATOR_LOWEST_PERCENTAGE_FIRST); + final Set visited = new HashSet<>(); + toVisit.add(this); + + double leftover = amt; + + while (!toVisit.isEmpty() && leftover > 0) { + final IEnergyGridProvider next = toVisit.poll(); + visited.add(next); + + leftover = next.injectProviderPower(leftover, mode); + + for (IEnergyGridProvider iEnergyGridProvider : next.providers()) { + if (!visited.contains(iEnergyGridProvider)) { + toVisit.add(iEnergyGridProvider); + } + } + } + + return leftover; + } + + @Override + public double getStoredPower() { + this.refreshPower(); + return Math.max(0.0, this.globalAvailablePower); + } + + @Override + public double getMaxStoredPower() { + return this.globalMaxPower; + } + + @Override + public double getEnergyDemand(final double maxRequired) { + final Queue toVisit = new PriorityQueue<>(COMPARATOR_LOWEST_PERCENTAGE_FIRST); + final Set visited = new HashSet<>(); + toVisit.add(this); + + double required = 0; + + while (!toVisit.isEmpty() && required < maxRequired) { + final IEnergyGridProvider next = toVisit.poll(); + visited.add(next); + + required += next.getProviderEnergyDemand(maxRequired - required); + + for (IEnergyGridProvider iEnergyGridProvider : next.providers()) { + if (!visited.contains(iEnergyGridProvider)) { + toVisit.add(iEnergyGridProvider); + } + } + } + + return required; + } + + @Override + public double getProviderStoredEnergy() { + return this.getStoredPower(); + } + + @Override + public double getProviderMaxEnergy() { + return this.getMaxStoredPower(); + } + + @Override + public void removeNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof IEnergyGridProvider) { + this.energyGridProviders.remove(machine); + } + + // idle draw. + final GridNode gridNode = (GridNode) node; + this.drainPerTick -= gridNode.getPreviousDraw(); + + // power storage. + if (machine instanceof IAEPowerStorage) { + final IAEPowerStorage ps = (IAEPowerStorage) machine; + if (ps.isAEPublicPowerStorage()) { + if (ps.getPowerFlow() != AccessRestriction.WRITE) { + this.globalMaxPower -= ps.getAEMaxPower(); + this.globalAvailablePower -= ps.getAECurrentPower(); + } + if (!ongoingExtractOperation) { + removeProvider(ps); + } else { + this.providerToRemove.add(ps); + } + if (!ongoingInjectOperation) { + removeRequester(ps); + } else { + this.requesterToRemove.add(ps); + } + } + } + + if (machine instanceof IEnergyWatcherHost) { + final IEnergyWatcher watcher = this.watchers.get(node); + + if (watcher != null) { + watcher.reset(); + this.watchers.remove(node); + } + } + } + + private void addRequester(IAEPowerStorage requester) { + Preconditions.checkState(!ongoingInjectOperation, "Cannot modify energy requesters while energy is being injected."); + this.requesters.add(requester); + } + + private void removeRequester(IAEPowerStorage requester) { + Preconditions.checkState(!ongoingInjectOperation, "Cannot modify energy requesters while energy is being injected."); + this.requesters.remove(requester); + } + + private void addProvider(IAEPowerStorage provider) { + Preconditions.checkState(!ongoingExtractOperation, "Cannot modify energy providers while energy is being extracted."); + this.providers.add(provider); + } + + private void removeProvider(IAEPowerStorage provider) { + Preconditions.checkState(!ongoingExtractOperation, "Cannot modify energy providers while energy is being extracted."); + this.providers.remove(provider); + } + + + @Override + public void addNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof IEnergyGridProvider) { + this.energyGridProviders.add((IEnergyGridProvider) machine); + } + + // idle draw... + final GridNode gridNode = (GridNode) node; + final IGridBlock gb = gridNode.getGridBlock(); + gridNode.setPreviousDraw(gb.getIdlePowerUsage()); + this.drainPerTick += gridNode.getPreviousDraw(); + + // power storage + if (machine instanceof IAEPowerStorage) { + final IAEPowerStorage ps = (IAEPowerStorage) machine; + if (ps.isAEPublicPowerStorage()) { + final double max = ps.getAEMaxPower(); + final double current = ps.getAECurrentPower(); + + if (ps.getPowerFlow() != AccessRestriction.WRITE) { + this.globalMaxPower += ps.getAEMaxPower(); + } + + if (current > 0 && ps.getPowerFlow() != AccessRestriction.WRITE) { + this.globalAvailablePower += current; + if (!ongoingExtractOperation) { + addProvider(ps); + } else { + this.providersToAdd.add(ps); + } + } + + if (current < max && ps.getPowerFlow() != AccessRestriction.READ) { + if (!ongoingInjectOperation) { + addRequester(ps); + } else { + this.requesterToAdd.add(ps); + } + } + } + } + + if (machine instanceof IEnergyWatcherHost) { + final IEnergyWatcherHost swh = (IEnergyWatcherHost) machine; + final EnergyWatcher iw = new EnergyWatcher(this, swh); + + this.watchers.put(node, iw); + swh.updateWatcher(iw); + } + + this.myGrid.postEventTo(node, new MENetworkPowerStatusChange()); + } + + @Override + public void onSplit(final IGridStorage storageB) { + final double newBuffer = this.localStorage.getAECurrentPower() / 2; + this.localStorage.removeCurrentAEPower(newBuffer); + storageB.dataObject().setDouble("buffer", newBuffer); + } + + @Override + public void onJoin(final IGridStorage storageB) { + this.localStorage.addCurrentAEPower(storageB.dataObject().getDouble("buffer")); + } + + @Override + public void populateGridStorage(final IGridStorage storage) { + storage.dataObject().setDouble("buffer", this.localStorage.getAECurrentPower()); + } + + public boolean registerEnergyInterest(final EnergyThreshold threshold) { + return this.interests.add(threshold); + } + + public boolean unregisterEnergyInterest(final EnergyThreshold threshold) { + return this.interests.remove(threshold); + } + + private class GridPowerStorage implements IAEPowerStorage { + private double stored = 0; + + @Override + public double extractAEPower(double amt, Actionable mode, PowerMultiplier usePowerMultiplier) { + double extracted = Math.min(amt, this.stored); + + if (mode == Actionable.MODULATE) { + this.removeCurrentAEPower(extracted); + } + + return extracted; + } + + @Override + public boolean isAEPublicPowerStorage() { + return true; + } + + @Override + public double injectAEPower(double amt, Actionable mode) { + double toStore = Math.min(amt, MAX_BUFFER_STORAGE - this.stored); + + if (mode == Actionable.MODULATE) { + this.addCurrentAEPower(toStore); + } + + return amt - toStore; + } + + @Override + public AccessRestriction getPowerFlow() { + return AccessRestriction.READ_WRITE; + } + + @Override + public double getAEMaxPower() { + return MAX_BUFFER_STORAGE; + } + + @Override + public double getAECurrentPower() { + return this.stored; + } + + private void addCurrentAEPower(double amount) { + this.stored += amount; + + if (this.stored > 0.01) { + EnergyGridCache.this.myGrid.postEvent(new MENetworkPowerStorage(this, PowerEventType.PROVIDE_POWER)); + } + } + + private void removeCurrentAEPower(double amount) { + this.stored -= amount; + + if (this.stored < MAX_BUFFER_STORAGE - 0.001) { + EnergyGridCache.this.myGrid.postEvent(new MENetworkPowerStorage(this, PowerEventType.REQUEST_POWER)); + } + + if (this.stored < 0.01) { + EnergyGridCache.this.ticksSinceHasPowerChange = 0; + EnergyGridCache.this.publicPowerState(false, EnergyGridCache.this.myGrid); + } + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/me/cache/GridStorageCache.java b/src/main/java/appeng/me/cache/GridStorageCache.java index 60b3548fc..d6331e97d 100644 --- a/src/main/java/appeng/me/cache/GridStorageCache.java +++ b/src/main/java/appeng/me/cache/GridStorageCache.java @@ -19,15 +19,6 @@ package appeng.me.cache; -import java.util.*; - -import appeng.api.storage.channels.IItemStorageChannel; -import appeng.crafting.MECraftingInventory; -import appeng.helpers.IInterfaceHost; -import appeng.helpers.IPriorityHost; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.SetMultimap; - import appeng.api.AEApi; import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; @@ -41,11 +32,7 @@ import appeng.api.networking.security.ISecurityGrid; import appeng.api.networking.storage.IStackWatcher; import appeng.api.networking.storage.IStackWatcherHost; import appeng.api.networking.storage.IStorageGrid; -import appeng.api.storage.ICellContainer; -import appeng.api.storage.ICellProvider; -import appeng.api.storage.IMEInventoryHandler; -import appeng.api.storage.IMEMonitor; -import appeng.api.storage.IStorageChannel; +import appeng.api.storage.*; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; @@ -54,311 +41,259 @@ import appeng.me.helpers.GenericInterestManager; import appeng.me.helpers.MachineSource; import appeng.me.storage.ItemWatcher; import appeng.me.storage.NetworkInventoryHandler; -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import com.google.common.collect.HashMultimap; +import com.google.common.collect.SetMultimap; + +import java.util.*; -public class GridStorageCache implements IStorageGrid -{ +public class GridStorageCache implements IStorageGrid { - private final IGrid myGrid; - private final HashSet activeCellProviders = new HashSet<>(); - private final HashSet inactiveCellProviders = new HashSet<>(); - private final SetMultimap interests = HashMultimap.create(); - private final GenericInterestManager interestManager = new GenericInterestManager<>( this.interests ); - private final HashMap watchers = new HashMap<>(); - private final Map, NetworkInventoryHandler> storageNetworks; - private final Map, NetworkMonitor> storageMonitors; - private int localDepth; + private final IGrid myGrid; + private final HashSet activeCellProviders = new HashSet<>(); + private final HashSet inactiveCellProviders = new HashSet<>(); + private final SetMultimap interests = HashMultimap.create(); + private final GenericInterestManager interestManager = new GenericInterestManager<>(this.interests); + private final HashMap watchers = new HashMap<>(); + private final Map, NetworkInventoryHandler> storageNetworks; + private final Map, NetworkMonitor> storageMonitors; + private int localDepth; - public GridStorageCache( final IGrid g ) - { - this.myGrid = g; - this.storageNetworks = new IdentityHashMap<>(); - this.storageMonitors = new IdentityHashMap<>(); + public GridStorageCache(final IGrid g) { + this.myGrid = g; + this.storageNetworks = new IdentityHashMap<>(); + this.storageMonitors = new IdentityHashMap<>(); - AEApi.instance().storage().storageChannels().forEach( channel -> this.storageMonitors.put( channel, new NetworkMonitor<>( this, channel ) ) ); - } + AEApi.instance().storage().storageChannels().forEach(channel -> this.storageMonitors.put(channel, new NetworkMonitor<>(this, channel))); + } - @Override - public void onUpdateTick() - { - this.storageMonitors.forEach( ( channel, monitor ) -> monitor.onTick() ); - } + @Override + public void onUpdateTick() { + this.storageMonitors.forEach((channel, monitor) -> monitor.onTick()); + } - @Override - public void removeNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof ICellContainer ) - { - final ICellContainer cc = (ICellContainer) machine; - final CellChangeTracker tracker = new CellChangeTracker(); + @Override + public void removeNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof ICellContainer) { + final ICellContainer cc = (ICellContainer) machine; + final CellChangeTracker tracker = new CellChangeTracker(); - this.removeCellProvider( cc, tracker ); - this.inactiveCellProviders.remove( cc ); - cellUpdate( null ); + this.removeCellProvider(cc, tracker); + this.inactiveCellProviders.remove(cc); + cellUpdate(null); - tracker.applyChanges(); - } + tracker.applyChanges(); + } - if( machine instanceof IStackWatcherHost ) - { - final IStackWatcher myWatcher = this.watchers.get( node ); + if (machine instanceof IStackWatcherHost) { + final IStackWatcher myWatcher = this.watchers.get(node); - if( myWatcher != null ) - { - myWatcher.reset(); - this.watchers.remove( node ); - } - } - } + if (myWatcher != null) { + myWatcher.reset(); + this.watchers.remove(node); + } + } + } - @Override - public void addNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof ICellContainer ) - { - final ICellContainer cc = (ICellContainer) machine; - this.inactiveCellProviders.add( cc ); + @Override + public void addNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof ICellContainer) { + final ICellContainer cc = (ICellContainer) machine; + this.inactiveCellProviders.add(cc); - cellUpdate( null ); + cellUpdate(null); - if( node.isActive() ) - { - final CellChangeTracker tracker = new CellChangeTracker(); + if (node.isActive()) { + final CellChangeTracker tracker = new CellChangeTracker(); - this.addCellProvider( cc, tracker ); - tracker.applyChanges(); - } - } + this.addCellProvider(cc, tracker); + tracker.applyChanges(); + } + } - if( machine instanceof IStackWatcherHost ) - { - final IStackWatcherHost swh = (IStackWatcherHost) machine; - final ItemWatcher iw = new ItemWatcher( this, swh ); - this.watchers.put( node, iw ); - swh.updateWatcher( iw ); - } - } + if (machine instanceof IStackWatcherHost) { + final IStackWatcherHost swh = (IStackWatcherHost) machine; + final ItemWatcher iw = new ItemWatcher(this, swh); + this.watchers.put(node, iw); + swh.updateWatcher(iw); + } + } - @Override - public void onSplit( final IGridStorage storageB ) - { + @Override + public void onSplit(final IGridStorage storageB) { - } + } - @Override - public void onJoin( final IGridStorage storageB ) - { + @Override + public void onJoin(final IGridStorage storageB) { - } + } - @Override - public void populateGridStorage( final IGridStorage storage ) - { + @Override + public void populateGridStorage(final IGridStorage storage) { - } + } - public > IMEInventoryHandler getInventoryHandler( IStorageChannel channel ) - { - return (IMEInventoryHandler) this.storageNetworks.computeIfAbsent( channel, this::buildNetworkStorage ); - } + public > IMEInventoryHandler getInventoryHandler(IStorageChannel channel) { + return (IMEInventoryHandler) this.storageNetworks.computeIfAbsent(channel, this::buildNetworkStorage); + } - @Override - public > IMEMonitor getInventory( IStorageChannel channel ) - { - return (IMEMonitor) this.storageMonitors.get( channel ); - } + @Override + public > IMEMonitor getInventory(IStorageChannel channel) { + return (IMEMonitor) this.storageMonitors.get(channel); + } - private CellChangeTracker addCellProvider( final ICellProvider cc, final CellChangeTracker tracker ) - { - if( this.inactiveCellProviders.contains( cc ) ) - { - this.inactiveCellProviders.remove( cc ); - this.activeCellProviders.add( cc ); + private CellChangeTracker addCellProvider(final ICellProvider cc, final CellChangeTracker tracker) { + if (this.inactiveCellProviders.contains(cc)) { + this.inactiveCellProviders.remove(cc); + this.activeCellProviders.add(cc); - final IActionSource actionSrc = cc instanceof IActionHost ? new MachineSource( (IActionHost) cc ) : new BaseActionSource(); + final IActionSource actionSrc = cc instanceof IActionHost ? new MachineSource((IActionHost) cc) : new BaseActionSource(); - this.storageMonitors.forEach( ( channel, monitor ) -> - { - for( final IMEInventoryHandler h : cc.getCellArray( channel ) ) - { - tracker.postChanges( channel, 1, h, actionSrc ); - } - } ); - } + this.storageMonitors.forEach((channel, monitor) -> + { + for (final IMEInventoryHandler h : cc.getCellArray(channel)) { + tracker.postChanges(channel, 1, h, actionSrc); + } + }); + } - return tracker; - } + return tracker; + } - private CellChangeTracker removeCellProvider( final ICellProvider cc, final CellChangeTracker tracker ) - { - if( this.activeCellProviders.contains( cc ) ) - { - this.activeCellProviders.remove( cc ); - this.inactiveCellProviders.add( cc ); + private CellChangeTracker removeCellProvider(final ICellProvider cc, final CellChangeTracker tracker) { + if (this.activeCellProviders.contains(cc)) { + this.activeCellProviders.remove(cc); + this.inactiveCellProviders.add(cc); - final IActionSource actionSrc = cc instanceof IActionHost ? new MachineSource( (IActionHost) cc ) : new BaseActionSource(); + final IActionSource actionSrc = cc instanceof IActionHost ? new MachineSource((IActionHost) cc) : new BaseActionSource(); - this.storageMonitors.forEach( ( channel, monitor ) -> - { - for( final IMEInventoryHandler h : cc.getCellArray( channel ) ) - { - tracker.postChanges( channel, -1, h, actionSrc ); - } - } ); - } + this.storageMonitors.forEach((channel, monitor) -> + { + for (final IMEInventoryHandler h : cc.getCellArray(channel)) { + tracker.postChanges(channel, -1, h, actionSrc); + } + }); + } - return tracker; - } + return tracker; + } - @MENetworkEventSubscribe - public void cellUpdate( final MENetworkCellArrayUpdate ev ) - { - if( localDepth > 0 ) - { - return; - } - localDepth++; - this.storageNetworks.clear(); + @MENetworkEventSubscribe + public void cellUpdate(final MENetworkCellArrayUpdate ev) { + if (localDepth > 0) { + return; + } + localDepth++; + this.storageNetworks.clear(); - final List ll = new ArrayList(); - ll.addAll( this.inactiveCellProviders ); - ll.addAll( this.activeCellProviders ); + final List ll = new ArrayList(); + ll.addAll(this.inactiveCellProviders); + ll.addAll(this.activeCellProviders); - final CellChangeTracker tracker = new CellChangeTracker(); + final CellChangeTracker tracker = new CellChangeTracker(); - for( final ICellProvider cc : ll ) - { - boolean active = true; + for (final ICellProvider cc : ll) { + boolean active = true; - if( cc instanceof IActionHost ) - { - final IGridNode node = ( (IActionHost) cc ).getActionableNode(); - if( node != null && node.isActive() ) - { - active = true; - } - else - { - active = false; - } - } + if (cc instanceof IActionHost) { + final IGridNode node = ((IActionHost) cc).getActionableNode(); + active = node != null && node.isActive(); + } - if( active ) - { - this.addCellProvider( cc, tracker ); - } - else - { - this.removeCellProvider( cc, tracker ); - } - } - tracker.applyChanges(); - localDepth--; - this.storageMonitors.forEach( ( channel, monitor ) -> monitor.setForceUpdate( true ) ); - } + if (active) { + this.addCellProvider(cc, tracker); + } else { + this.removeCellProvider(cc, tracker); + } + } + tracker.applyChanges(); + localDepth--; + this.storageMonitors.forEach((channel, monitor) -> monitor.setForceUpdate(true)); + } - private , C extends IStorageChannel> void postChangesToNetwork( final C chan, final int upOrDown, final IItemList availableItems, final IActionSource src ) - { - this.storageMonitors.get( chan ).postChange( upOrDown > 0, (Iterable) availableItems, src ); - } + private , C extends IStorageChannel> void postChangesToNetwork(final C chan, final int upOrDown, final IItemList availableItems, final IActionSource src) { + this.storageMonitors.get(chan).postChange(upOrDown > 0, (Iterable) availableItems, src); + } - private , C extends IStorageChannel> NetworkInventoryHandler buildNetworkStorage( final C chan ) - { - final SecurityCache security = this.getGrid().getCache( ISecurityGrid.class ); + private , C extends IStorageChannel> NetworkInventoryHandler buildNetworkStorage(final C chan) { + final SecurityCache security = this.getGrid().getCache(ISecurityGrid.class); - final NetworkInventoryHandler storageNetwork = new NetworkInventoryHandler<>( chan, security ); + final NetworkInventoryHandler storageNetwork = new NetworkInventoryHandler<>(chan, security); - for( final ICellProvider cc : this.activeCellProviders ) - { - for( final IMEInventoryHandler h : cc.getCellArray( chan ) ) - { - storageNetwork.addNewStorage( h ); - } - } + for (final ICellProvider cc : this.activeCellProviders) { + for (final IMEInventoryHandler h : cc.getCellArray(chan)) { + storageNetwork.addNewStorage(h); + } + } - return storageNetwork; - } + return storageNetwork; + } - @Override - public void postAlterationOfStoredItems( final IStorageChannel chan, final Iterable> input, final IActionSource src ) - { - this.storageMonitors.get( chan ).postChange( true, (Iterable) input, src ); - } + @Override + public void postAlterationOfStoredItems(final IStorageChannel chan, final Iterable> input, final IActionSource src) { + this.storageMonitors.get(chan).postChange(true, (Iterable) input, src); + } - @Override - public void postCraftablesChanges( IStorageChannel chan, Iterable> input, IActionSource src ) - { - this.storageMonitors.get( chan ).updateCraftables( (Iterable) input, src ); - } + @Override + public void postCraftablesChanges(IStorageChannel chan, Iterable> input, IActionSource src) { + this.storageMonitors.get(chan).updateCraftables((Iterable) input, src); + } - @Override - public void registerCellProvider( final ICellProvider provider ) - { - this.inactiveCellProviders.add( provider ); - this.addCellProvider( provider, new CellChangeTracker() ).applyChanges(); - } + @Override + public void registerCellProvider(final ICellProvider provider) { + this.inactiveCellProviders.add(provider); + this.addCellProvider(provider, new CellChangeTracker()).applyChanges(); + } - @Override - public void unregisterCellProvider( final ICellProvider provider ) - { - this.removeCellProvider( provider, new CellChangeTracker() ).applyChanges(); - this.inactiveCellProviders.remove( provider ); - } + @Override + public void unregisterCellProvider(final ICellProvider provider) { + this.removeCellProvider(provider, new CellChangeTracker()).applyChanges(); + this.inactiveCellProviders.remove(provider); + } - public GenericInterestManager getInterestManager() - { - return this.interestManager; - } + public GenericInterestManager getInterestManager() { + return this.interestManager; + } - IGrid getGrid() - { - return this.myGrid; - } + IGrid getGrid() { + return this.myGrid; + } - private class CellChangeTrackerRecord> - { + private class CellChangeTrackerRecord> { - final IStorageChannel channel; - final int up_or_down; - final IItemList list; - final IActionSource src; + final IStorageChannel channel; + final int up_or_down; + final IItemList list; + final IActionSource src; - public CellChangeTrackerRecord( final IStorageChannel channel, final int i, final IMEInventoryHandler h, final IActionSource actionSrc ) - { - this.channel = channel; - this.up_or_down = i; - this.src = actionSrc; + public CellChangeTrackerRecord(final IStorageChannel channel, final int i, final IMEInventoryHandler h, final IActionSource actionSrc) { + this.channel = channel; + this.up_or_down = i; + this.src = actionSrc; - this.list = h.getAvailableItems( channel.createList() ); - } + this.list = h.getAvailableItems(channel.createList()); + } - public void applyChanges() - { - if( !this.list.isEmpty() ) - { - GridStorageCache.this.postChangesToNetwork( this.channel, this.up_or_down, this.list, this.src ); - } - } - } + public void applyChanges() { + if (!this.list.isEmpty()) { + GridStorageCache.this.postChangesToNetwork(this.channel, this.up_or_down, this.list, this.src); + } + } + } - private class CellChangeTracker> - { + private class CellChangeTracker> { - final List> data = new ArrayList<>(); + final List> data = new ArrayList<>(); - public void postChanges( final IStorageChannel channel, final int i, final IMEInventoryHandler h, final IActionSource actionSrc ) - { - this.data.add( new CellChangeTrackerRecord( channel, i, h, actionSrc ) ); - } + public void postChanges(final IStorageChannel channel, final int i, final IMEInventoryHandler h, final IActionSource actionSrc) { + this.data.add(new CellChangeTrackerRecord(channel, i, h, actionSrc)); + } - public void applyChanges() - { - for( final CellChangeTrackerRecord rec : this.data ) - { - rec.applyChanges(); - } - } - } + public void applyChanges() { + for (final CellChangeTrackerRecord rec : this.data) { + rec.applyChanges(); + } + } + } } diff --git a/src/main/java/appeng/me/cache/NetworkMonitor.java b/src/main/java/appeng/me/cache/NetworkMonitor.java index 0b2ef7bbe..50338d94a 100644 --- a/src/main/java/appeng/me/cache/NetworkMonitor.java +++ b/src/main/java/appeng/me/cache/NetworkMonitor.java @@ -19,8 +19,6 @@ package appeng.me.cache; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -38,339 +36,280 @@ import appeng.me.storage.ItemWatcher; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.*; import java.util.Map.Entry; -public class NetworkMonitor> implements IMEMonitor -{ - @Nonnull - private static final HashMap>> src2MonitorsMap = new HashMap<>(); - private static final Set nestingSources = new HashSet<>(); +public class NetworkMonitor> implements IMEMonitor { + @Nonnull + private static final HashMap>> src2MonitorsMap = new HashMap<>(); + private static final Set nestingSources = new HashSet<>(); - protected boolean wasNested = false; - protected boolean isNested = false; + protected boolean wasNested = false; + protected boolean isNested = false; - @Nonnull - private final GridStorageCache myGridCache; - @Nonnull - private final IStorageChannel myChannel; - @Nonnull - private final IItemList cachedList; - @Nonnull - private final Object2ObjectMap, Object> listeners; + @Nonnull + private final GridStorageCache myGridCache; + @Nonnull + private final IStorageChannel myChannel; + @Nonnull + private final IItemList cachedList; + @Nonnull + private final Object2ObjectMap, Object> listeners; - private boolean sendEvent = false; - private long gridItemCount; - private long gridFluidCount; - public boolean forceUpdate; + private boolean sendEvent = false; + private long gridItemCount; + private long gridFluidCount; + public boolean forceUpdate; - public NetworkMonitor( final GridStorageCache cache, final IStorageChannel chan ) - { - this.myGridCache = cache; - this.myChannel = chan; - this.cachedList = chan.createList(); - this.listeners = new Object2ObjectOpenHashMap<>(); - } + public NetworkMonitor(final GridStorageCache cache, final IStorageChannel chan) { + this.myGridCache = cache; + this.myChannel = chan; + this.cachedList = chan.createList(); + this.listeners = new Object2ObjectOpenHashMap<>(); + } - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } - @Override - public boolean canAccept( final T input ) - { - return this.getHandler().canAccept( input ); - } + @Override + public boolean canAccept(final T input) { + return this.getHandler().canAccept(input); + } - @Override - public T extractItems( final T request, final Actionable mode, final IActionSource src ) - { - return this.getHandler().extractItems( request, mode, src ); - } + @Override + public T extractItems(final T request, final Actionable mode, final IActionSource src) { + return this.getHandler().extractItems(request, mode, src); + } - @Override - public AccessRestriction getAccess() - { - return this.getHandler().getAccess(); - } + @Override + public AccessRestriction getAccess() { + return this.getHandler().getAccess(); + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return this.getHandler().getAvailableItems( out ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return this.getHandler().getAvailableItems(out); + } - @Override - public IStorageChannel getChannel() - { - return this.getHandler().getChannel(); - } + @Override + public IStorageChannel getChannel() { + return this.getHandler().getChannel(); + } - @Override - public int getPriority() - { - return this.getHandler().getPriority(); - } + @Override + public int getPriority() { + return this.getHandler().getPriority(); + } - @Override - public int getSlot() - { - return this.getHandler().getSlot(); - } + @Override + public int getSlot() { + return this.getHandler().getSlot(); + } - public long getGridCurrentCount() - { - if( myChannel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - return gridItemCount; - } - else if( myChannel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) - { - return gridFluidCount; - } - return 0; - } + public long getGridCurrentCount() { + if (myChannel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + return gridItemCount; + } else if (myChannel == AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)) { + return gridFluidCount; + } + return 0; + } - public void incGridCurrentCount( long count ) - { - if( myChannel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - gridItemCount += count; - } - else if( myChannel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) - { - gridFluidCount += count; - } - } + public void incGridCurrentCount(long count) { + if (myChannel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + gridItemCount += count; + } else if (myChannel == AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)) { + gridFluidCount += count; + } + } - @Nonnull - @Override - public IItemList getStorageList() - { - return this.cachedList; - } + @Nonnull + @Override + public IItemList getStorageList() { + return this.cachedList; + } - @Override - public T injectItems( final T input, final Actionable mode, final IActionSource src ) - { - return this.getHandler().injectItems( input, mode, src ); - } + @Override + public T injectItems(final T input, final Actionable mode, final IActionSource src) { + return this.getHandler().injectItems(input, mode, src); + } - @Override - public boolean isPrioritized( final T input ) - { - return this.getHandler().isPrioritized( input ); - } + @Override + public boolean isPrioritized(final T input) { + return this.getHandler().isPrioritized(input); + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } - @Override - public boolean validForPass( final int i ) - { - return this.getHandler().validForPass( i ); - } + @Override + public boolean validForPass(final int i) { + return this.getHandler().validForPass(i); + } - @Nullable - private IMEInventoryHandler getHandler() - { - return this.myGridCache.getInventoryHandler( this.myChannel ); - } + @Nullable + private IMEInventoryHandler getHandler() { + return this.myGridCache.getInventoryHandler(this.myChannel); + } - private Iterator, Object>> getListeners() - { - return this.listeners.entrySet().iterator(); - } + private Iterator, Object>> getListeners() { + return this.listeners.entrySet().iterator(); + } - private void notifyListenersOfChange( final Iterable diff, final IActionSource src ) - { - final Iterator, Object>> i = this.getListeners(); + private void notifyListenersOfChange(final Iterable diff, final IActionSource src) { + final Iterator, Object>> i = this.getListeners(); - while( i.hasNext() ) - { - final Entry, Object> o = i.next(); - final IMEMonitorHandlerReceiver receiver = o.getKey(); + while (i.hasNext()) { + final Entry, Object> o = i.next(); + final IMEMonitorHandlerReceiver receiver = o.getKey(); - if( receiver.isValid( o.getValue() ) ) - { - receiver.postChange( this, diff, src ); - } - else - { - i.remove(); - } - } - } + if (receiver.isValid(o.getValue())) { + receiver.postChange(this, diff, src); + } else { + i.remove(); + } + } + } - protected void updateCraftables( Iterable input, IActionSource src ) - { - for( final T changedItem : input ) - { - if (changedItem.isCraftable()) { - this.cachedList.add( changedItem ); - } - else - { - T i = this.cachedList.findPrecise( changedItem ); - if (i != null) - i.setCraftable( false ); - } - } - } + protected void updateCraftables(Iterable input, IActionSource src) { + for (final T changedItem : input) { + if (changedItem.isCraftable()) { + this.cachedList.add(changedItem); + } else { + T i = this.cachedList.findPrecise(changedItem); + if (i != null) + i.setCraftable(false); + } + } + } - protected void postChange( final boolean add, final Iterable changes, final IActionSource src ) - { - src2MonitorsMap.putIfAbsent( src, new LinkedList<>() ); - if( src2MonitorsMap.get( src ).contains( this ) ) - { - nestingSources.add( src ); - return; - } - src2MonitorsMap.get( src ).add( this ); + protected void postChange(final boolean add, final Iterable changes, final IActionSource src) { + src2MonitorsMap.putIfAbsent(src, new LinkedList<>()); + if (src2MonitorsMap.get(src).contains(this)) { + nestingSources.add(src); + return; + } + src2MonitorsMap.get(src).add(this); - this.sendEvent = true; + this.sendEvent = true; - for( final T change : changes ) - { - //T change = changed; - if( !add && change != null ) - { - //change = changed.copy(); - change.setStackSize( -change.getStackSize() ); - } + for (final T change : changes) { + //T change = changed; + if (!add && change != null) { + //change = changed.copy(); + change.setStackSize(-change.getStackSize()); + } - incGridCurrentCount( change.getStackSize() ); - this.cachedList.addStorage( change ); + incGridCurrentCount(change.getStackSize()); + this.cachedList.addStorage(change); - if( this.myGridCache.getInterestManager().containsKey( change ) ) - { - final Collection list = this.myGridCache.getInterestManager().get( change ); + if (this.myGridCache.getInterestManager().containsKey(change)) { + final Collection list = this.myGridCache.getInterestManager().get(change); - if( !list.isEmpty() ) - { - IAEStack fullStack = this.getStorageList().findPrecise( change ); + if (!list.isEmpty()) { + IAEStack fullStack = this.getStorageList().findPrecise(change); - if( fullStack == null ) - { - fullStack = change.copy(); - fullStack.setStackSize( 0 ); - } + if (fullStack == null) { + fullStack = change.copy(); + fullStack.setStackSize(0); + } - this.myGridCache.getInterestManager().enableTransactions(); + this.myGridCache.getInterestManager().enableTransactions(); - for( final ItemWatcher iw : list ) - { - iw.getHost().onStackChange( this.getStorageList(), fullStack, change, src, this.getChannel() ); - } + for (final ItemWatcher iw : list) { + iw.getHost().onStackChange(this.getStorageList(), fullStack, change, src, this.getChannel()); + } - this.myGridCache.getInterestManager().disableTransactions(); - } - } - } + this.myGridCache.getInterestManager().disableTransactions(); + } + } + } - this.notifyListenersOfChange( changes, src ); + this.notifyListenersOfChange(changes, src); - if( src2MonitorsMap.get( src ).getFirst() == this ) - { - boolean nested = nestingSources.contains( src ); - src2MonitorsMap.get( src ).forEach( networkMonitor -> networkMonitor.isNested = nested ); + if (src2MonitorsMap.get(src).getFirst() == this) { + boolean nested = nestingSources.contains(src); + src2MonitorsMap.get(src).forEach(networkMonitor -> networkMonitor.isNested = nested); - src2MonitorsMap.get( src ).forEach( networkMonitor -> { - if( networkMonitor.isNested != networkMonitor.wasNested ) - { - networkMonitor.wasNested = networkMonitor.isNested; - networkMonitor.setForceUpdate( true ); - } - } ); - src2MonitorsMap.remove( src ); - nestingSources.remove( src ); - } - } + src2MonitorsMap.get(src).forEach(networkMonitor -> { + if (networkMonitor.isNested != networkMonitor.wasNested) { + networkMonitor.wasNested = networkMonitor.isNested; + networkMonitor.setForceUpdate(true); + } + }); + src2MonitorsMap.remove(src); + nestingSources.remove(src); + } + } - public void setForceUpdate( boolean forceUpdate ) - { - this.forceUpdate = forceUpdate; - } + public void setForceUpdate(boolean forceUpdate) { + this.forceUpdate = forceUpdate; + } - void forceUpdate() - { - forceUpdate = false; - this.cachedList.resetStatus(); - this.getAvailableItems( this.cachedList ); + void forceUpdate() { + forceUpdate = false; + this.cachedList.resetStatus(); + this.getAvailableItems(this.cachedList); - long count = 0; - for( T stack : this.cachedList ) - { - count += stack.getStackSize(); + long count = 0; + for (T stack : this.cachedList) { + count += stack.getStackSize(); - if( this.myGridCache.getInterestManager().containsKey( stack ) ) - { - final Collection list = this.myGridCache.getInterestManager().get( stack ); + if (this.myGridCache.getInterestManager().containsKey(stack)) { + final Collection list = this.myGridCache.getInterestManager().get(stack); - if( !list.isEmpty() ) - { - IAEStack fullStack = this.getStorageList().findPrecise( stack ); + if (!list.isEmpty()) { + IAEStack fullStack = this.getStorageList().findPrecise(stack); - if( fullStack == null ) - { - fullStack = stack.copy(); - fullStack.setStackSize( 0 ); - } + if (fullStack == null) { + fullStack = stack.copy(); + fullStack.setStackSize(0); + } - this.myGridCache.getInterestManager().enableTransactions(); + this.myGridCache.getInterestManager().enableTransactions(); - for ( final ItemWatcher iw : list ) - { - iw.getHost().onStackChange( this.getStorageList(), fullStack, stack, null, this.getChannel() ); - } + for (final ItemWatcher iw : list) { + iw.getHost().onStackChange(this.getStorageList(), fullStack, stack, null, this.getChannel()); + } - this.myGridCache.getInterestManager().disableTransactions(); - } - } - } + this.myGridCache.getInterestManager().disableTransactions(); + } + } + } - if( myChannel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - gridItemCount = count; - } - else if( myChannel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) - { - gridFluidCount = count; - } + if (myChannel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + gridItemCount = count; + } else if (myChannel == AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)) { + gridFluidCount = count; + } - final Iterator, Object>> i = this.getListeners(); - while ( i.hasNext() ) - { - final Entry, Object> o = i.next(); - final IMEMonitorHandlerReceiver receiver = o.getKey(); + final Iterator, Object>> i = this.getListeners(); + while (i.hasNext()) { + final Entry, Object> o = i.next(); + final IMEMonitorHandlerReceiver receiver = o.getKey(); - if( receiver.isValid( o.getValue() ) ) - { - receiver.onListUpdate(); - } - else - { - i.remove(); - } - } - } + if (receiver.isValid(o.getValue())) { + receiver.onListUpdate(); + } else { + i.remove(); + } + } + } - void onTick() - { - if( forceUpdate ) - { - forceUpdate(); - } - if( this.sendEvent ) - { - this.sendEvent = false; - this.myGridCache.getGrid().postEvent( new MENetworkStorageEvent( this, this.myChannel ) ); - } - } + void onTick() { + if (forceUpdate) { + forceUpdate(); + } + if (this.sendEvent) { + this.sendEvent = false; + this.myGridCache.getGrid().postEvent(new MENetworkStorageEvent(this, this.myChannel)); + } + } } diff --git a/src/main/java/appeng/me/cache/P2PCache.java b/src/main/java/appeng/me/cache/P2PCache.java index 21b450d2a..39cfd1408 100644 --- a/src/main/java/appeng/me/cache/P2PCache.java +++ b/src/main/java/appeng/me/cache/P2PCache.java @@ -19,18 +19,7 @@ package appeng.me.cache; -import java.util.Collection; -import java.util.Random; - -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.Multimap; - -import appeng.api.networking.GridFlags; -import appeng.api.networking.IGrid; -import appeng.api.networking.IGridCache; -import appeng.api.networking.IGridHost; -import appeng.api.networking.IGridNode; -import appeng.api.networking.IGridStorage; +import appeng.api.networking.*; import appeng.api.networking.events.MENetworkBootingStatusChange; import appeng.api.networking.events.MENetworkEventSubscribe; import appeng.api.networking.events.MENetworkPowerStatusChange; @@ -39,261 +28,213 @@ import appeng.core.AELog; import appeng.me.cache.helpers.TunnelCollection; import appeng.parts.p2p.PartP2PTunnel; import appeng.parts.p2p.PartP2PTunnelME; +import com.google.common.collect.LinkedHashMultimap; +import com.google.common.collect.Multimap; + +import java.util.Collection; +import java.util.Random; -public class P2PCache implements IGridCache -{ - private static final TunnelCollection NULL_COLLECTION = new TunnelCollection( null, null ); +public class P2PCache implements IGridCache { + private static final TunnelCollection NULL_COLLECTION = new TunnelCollection(null, null); - private final IGrid myGrid; - private final Multimap inputs = LinkedHashMultimap.create(); - private final Multimap outputs = LinkedHashMultimap.create(); - private final Random frequencyGenerator; + private final IGrid myGrid; + private final Multimap inputs = LinkedHashMultimap.create(); + private final Multimap outputs = LinkedHashMultimap.create(); + private final Random frequencyGenerator; - public P2PCache( final IGrid g ) - { - this.myGrid = g; - this.frequencyGenerator = new Random( g.hashCode() ); - } + public P2PCache(final IGrid g) { + this.myGrid = g; + this.frequencyGenerator = new Random(g.hashCode()); + } - @MENetworkEventSubscribe - public void bootComplete( final MENetworkBootingStatusChange bootStatus ) - { - final ITickManager tm = this.myGrid.getCache( ITickManager.class ); - for( final PartP2PTunnel me : this.inputs.values() ) - { - if( me instanceof PartP2PTunnelME ) - { - tm.wakeDevice( me.getGridNode() ); - } - } - } + @MENetworkEventSubscribe + public void bootComplete(final MENetworkBootingStatusChange bootStatus) { + final ITickManager tm = this.myGrid.getCache(ITickManager.class); + for (final PartP2PTunnel me : this.inputs.values()) { + if (me instanceof PartP2PTunnelME) { + tm.wakeDevice(me.getGridNode()); + } + } + } - @MENetworkEventSubscribe - public void bootComplete( final MENetworkPowerStatusChange power ) - { - final ITickManager tm = this.myGrid.getCache( ITickManager.class ); - for( final PartP2PTunnel me : this.inputs.values() ) - { - if( me instanceof PartP2PTunnelME ) - { - tm.wakeDevice( me.getGridNode() ); - } - } - } + @MENetworkEventSubscribe + public void bootComplete(final MENetworkPowerStatusChange power) { + final ITickManager tm = this.myGrid.getCache(ITickManager.class); + for (final PartP2PTunnel me : this.inputs.values()) { + if (me instanceof PartP2PTunnelME) { + tm.wakeDevice(me.getGridNode()); + } + } + } - @Override - public void onUpdateTick() - { + @Override + public void onUpdateTick() { - } + } - @Override - public void removeNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof PartP2PTunnel ) - { - if( machine instanceof PartP2PTunnelME ) - { - if( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) ) - { - return; - } - } + @Override + public void removeNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof PartP2PTunnel) { + if (machine instanceof PartP2PTunnelME) { + if (!node.hasFlag(GridFlags.REQUIRE_CHANNEL)) { + return; + } + } - final PartP2PTunnel t = (PartP2PTunnel) machine; - // AELog.info( "rmv-" + (t.output ? "output: " : "input: ") + t.freq ); + final PartP2PTunnel t = (PartP2PTunnel) machine; + // AELog.info( "rmv-" + (t.output ? "output: " : "input: ") + t.freq ); - if( t.isOutput() ) - { - this.outputs.remove( t.getFrequency(), t ); - } - else - { - this.inputs.remove( t.getFrequency(), t ); - } + if (t.isOutput()) { + this.outputs.remove(t.getFrequency(), t); + } else { + this.inputs.remove(t.getFrequency(), t); + } - if( this.inputs.get( t.getFrequency() ).isEmpty() ) - { - this.inputs.removeAll( t.getFrequency() ); - } - if( this.outputs.get( t.getFrequency() ).isEmpty() ) - { - this.outputs.removeAll( t.getFrequency() ); - } + if (this.inputs.get(t.getFrequency()).isEmpty()) { + this.inputs.removeAll(t.getFrequency()); + } + if (this.outputs.get(t.getFrequency()).isEmpty()) { + this.outputs.removeAll(t.getFrequency()); + } - this.updateTunnel( t.getFrequency(), t.isOutput(), false ); - } - } + this.updateTunnel(t.getFrequency(), t.isOutput(), false); + } + } - @Override - public void addNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof PartP2PTunnel ) - { - if( machine instanceof PartP2PTunnelME ) - { - if( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) ) - { - return; - } - } + @Override + public void addNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof PartP2PTunnel) { + if (machine instanceof PartP2PTunnelME) { + if (!node.hasFlag(GridFlags.REQUIRE_CHANNEL)) { + return; + } + } - final PartP2PTunnel t = (PartP2PTunnel) machine; - // AELog.info( "add-" + (t.output ? "output: " : "input: ") + t.freq ); + final PartP2PTunnel t = (PartP2PTunnel) machine; + // AELog.info( "add-" + (t.output ? "output: " : "input: ") + t.freq ); - if( t.isOutput() ) - { - this.outputs.put( t.getFrequency(), t ); - } - else - { - this.inputs.put( t.getFrequency(), t ); - } + if (t.isOutput()) { + this.outputs.put(t.getFrequency(), t); + } else { + this.inputs.put(t.getFrequency(), t); + } - this.updateTunnel( t.getFrequency(), t.isOutput(), false ); - } - } + this.updateTunnel(t.getFrequency(), t.isOutput(), false); + } + } - @Override - public void onSplit( final IGridStorage storageB ) - { + @Override + public void onSplit(final IGridStorage storageB) { - } + } - @Override - public void onJoin( final IGridStorage storageB ) - { + @Override + public void onJoin(final IGridStorage storageB) { - } + } - @Override - public void populateGridStorage( final IGridStorage storage ) - { + @Override + public void populateGridStorage(final IGridStorage storage) { - } + } - public void removeTunnel( final PartP2PTunnel t, short freq ) - { - this.outputs.remove( freq, t ); - this.inputs.remove( freq, t ); - if( this.inputs.get( t.getFrequency() ).isEmpty() ) - { - this.inputs.removeAll( t.getFrequency() ); - } - if( this.outputs.get( t.getFrequency() ).isEmpty() ) - { - this.outputs.removeAll( t.getFrequency() ); - } - } + public void removeTunnel(final PartP2PTunnel t, short freq) { + this.outputs.remove(freq, t); + this.inputs.remove(freq, t); + if (this.inputs.get(t.getFrequency()).isEmpty()) { + this.inputs.removeAll(t.getFrequency()); + } + if (this.outputs.get(t.getFrequency()).isEmpty()) { + this.outputs.removeAll(t.getFrequency()); + } + } - private void updateTunnel( final short freq, final boolean updateOutputs, final boolean configChange ) - { - for( final PartP2PTunnel p : this.outputs.get( freq ) ) - { - if( configChange ) - { - p.onTunnelConfigChange(); - } - p.onTunnelNetworkChange(); - } + private void updateTunnel(final short freq, final boolean updateOutputs, final boolean configChange) { + for (final PartP2PTunnel p : this.outputs.get(freq)) { + if (configChange) { + p.onTunnelConfigChange(); + } + p.onTunnelNetworkChange(); + } - for( final PartP2PTunnel in : this.inputs.get( freq ) ) - { - if( configChange ) - { - in.onTunnelConfigChange(); - } - in.onTunnelNetworkChange(); - } - } + for (final PartP2PTunnel in : this.inputs.get(freq)) { + if (configChange) { + in.onTunnelConfigChange(); + } + in.onTunnelNetworkChange(); + } + } - public void updateFreq( final PartP2PTunnel t, final short newFrequency ) - { - if( this.outputs.containsValue( t ) ) - { - this.outputs.remove( t.getFrequency(), t ); - } + public void updateFreq(final PartP2PTunnel t, final short newFrequency) { + if (this.outputs.containsValue(t)) { + this.outputs.remove(t.getFrequency(), t); + } - if( this.inputs.containsValue( t ) ) - { - this.inputs.remove( t.getFrequency(), t ); - } + if (this.inputs.containsValue(t)) { + this.inputs.remove(t.getFrequency(), t); + } - t.setFrequency( newFrequency ); + t.setFrequency(newFrequency); - if( t.isOutput() ) - { - this.outputs.put( t.getFrequency(), t ); - } - else - { - this.inputs.put( t.getFrequency(), t ); - } + if (t.isOutput()) { + this.outputs.put(t.getFrequency(), t); + } else { + this.inputs.put(t.getFrequency(), t); + } - // AELog.info( "update-" + (t.output ? "output: " : "input: ") + t.freq ); - this.updateTunnel( t.getFrequency(), t.isOutput(), true ); - } + // AELog.info( "update-" + (t.output ? "output: " : "input: ") + t.freq ); + this.updateTunnel(t.getFrequency(), t.isOutput(), true); + } - public short newFrequency() - { - short newFrequency; - int cycles = 0; + public short newFrequency() { + short newFrequency; + int cycles = 0; - do - { - newFrequency = (short) this.frequencyGenerator.nextInt( 1 << 16 ); - cycles++; - } - while( newFrequency == 0 || this.inputs.containsKey( newFrequency ) ); + do { + newFrequency = (short) this.frequencyGenerator.nextInt(1 << 16); + cycles++; + } + while (newFrequency == 0 || this.inputs.containsKey(newFrequency)); - if( cycles > 25 ) - { - AELog.debug( "Generating a new P2P frequency '%1$d' took %2$d cycles", newFrequency, cycles ); - } + if (cycles > 25) { + AELog.debug("Generating a new P2P frequency '%1$d' took %2$d cycles", newFrequency, cycles); + } - return newFrequency; - } + return newFrequency; + } - public TunnelCollection getOutputs( final short freq, final Class c ) - { - Collection in = this.inputs.get( freq ); + public TunnelCollection getOutputs(final short freq, final Class c) { + Collection in = this.inputs.get(freq); - if( in == null ) - { - return NULL_COLLECTION; - } + if (in == null) { + return NULL_COLLECTION; + } - TunnelCollection out; - for( PartP2PTunnel part : this.inputs.get( freq ) ) - { - out = part.getCollection( this.outputs.get( freq ), c ); - if( out != null ) - { - return out; - } - } - return NULL_COLLECTION; - } + TunnelCollection out; + for (PartP2PTunnel part : this.inputs.get(freq)) { + out = part.getCollection(this.outputs.get(freq), c); + if (out != null) { + return out; + } + } + return NULL_COLLECTION; + } - public TunnelCollection getInputs( final short freq, final Class c ) - { - Collection out = this.outputs.get( freq ); + public TunnelCollection getInputs(final short freq, final Class c) { + Collection out = this.outputs.get(freq); - if( out == null ) - { - return NULL_COLLECTION; - } + if (out == null) { + return NULL_COLLECTION; + } - TunnelCollection in; - for( PartP2PTunnel part : this.outputs.get( freq ) ) - { - in = part.getCollection( this.inputs.get( freq ), c ); - if( in != null ) - { - return in; - } - } - return NULL_COLLECTION; - } + TunnelCollection in; + for (PartP2PTunnel part : this.outputs.get(freq)) { + in = part.getCollection(this.inputs.get(freq), c); + if (in != null) { + return in; + } + } + return NULL_COLLECTION; + } } diff --git a/src/main/java/appeng/me/cache/PathGridCache.java b/src/main/java/appeng/me/cache/PathGridCache.java index b874d4cd2..8ab6bc960 100644 --- a/src/main/java/appeng/me/cache/PathGridCache.java +++ b/src/main/java/appeng/me/cache/PathGridCache.java @@ -19,25 +19,8 @@ package appeng.me.cache; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; - import appeng.api.AEApi; -import appeng.api.networking.GridFlags; -import appeng.api.networking.IGrid; -import appeng.api.networking.IGridBlock; -import appeng.api.networking.IGridConnection; -import appeng.api.networking.IGridHost; -import appeng.api.networking.IGridMultiblock; -import appeng.api.networking.IGridNode; -import appeng.api.networking.IGridStorage; +import appeng.api.networking.*; import appeng.api.networking.events.MENetworkBootingStatusChange; import appeng.api.networking.events.MENetworkChannelChanged; import appeng.api.networking.events.MENetworkControllerChange; @@ -52,391 +35,322 @@ import appeng.core.features.AEFeature; import appeng.core.stats.IAdvancementTrigger; import appeng.me.GridConnection; import appeng.me.GridNode; -import appeng.me.pathfinding.AdHocChannelUpdater; -import appeng.me.pathfinding.ControllerChannelUpdater; -import appeng.me.pathfinding.ControllerValidator; -import appeng.me.pathfinding.IPathItem; -import appeng.me.pathfinding.PathSegment; +import appeng.me.pathfinding.*; import appeng.tile.networking.TileController; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; + +import java.util.*; -public class PathGridCache implements IPathingGrid -{ +public class PathGridCache implements IPathingGrid { - private final List active = new ArrayList<>(); - private final Set controllers = new HashSet<>(); - private final Set requireChannels = new HashSet<>(); - private final Set blockDense = new HashSet<>(); - private final IGrid myGrid; - private int channelsInUse = 0; - private int channelsByBlocks = 0; - private double channelPowerUsage = 0.0; - private boolean recalculateControllerNextTick = true; - private boolean updateNetwork = true; - private boolean booting = false; - private ControllerState controllerState = ControllerState.NO_CONTROLLER; - private int ticksUntilReady = 20; - private int lastChannels = 0; - private HashSet semiOpen = new HashSet<>(); + private final List active = new ArrayList<>(); + private final Set controllers = new HashSet<>(); + private final Set requireChannels = new HashSet<>(); + private final Set blockDense = new HashSet<>(); + private final IGrid myGrid; + private int channelsInUse = 0; + private int channelsByBlocks = 0; + private double channelPowerUsage = 0.0; + private boolean recalculateControllerNextTick = true; + private boolean updateNetwork = true; + private boolean booting = false; + private ControllerState controllerState = ControllerState.NO_CONTROLLER; + private int ticksUntilReady = 20; + private int lastChannels = 0; + private HashSet semiOpen = new HashSet<>(); - public PathGridCache( final IGrid g ) - { - this.myGrid = g; - } + public PathGridCache(final IGrid g) { + this.myGrid = g; + } - @Override - public void onUpdateTick() - { - if( this.recalculateControllerNextTick ) - { - this.recalcController(); - } + @Override + public void onUpdateTick() { + if (this.recalculateControllerNextTick) { + this.recalcController(); + } - if( this.updateNetwork ) - { - if( !this.booting ) - { - this.myGrid.postEvent( new MENetworkBootingStatusChange() ); - } + if (this.updateNetwork) { + if (!this.booting) { + this.myGrid.postEvent(new MENetworkBootingStatusChange()); + } - this.booting = true; - this.updateNetwork = false; - this.setChannelsInUse( 0 ); + this.booting = true; + this.updateNetwork = false; + this.setChannelsInUse(0); - if( this.controllerState == ControllerState.NO_CONTROLLER ) - { - final int requiredChannels = this.calculateRequiredChannels(); - int used = requiredChannels; - if( AEConfig.instance().isFeatureEnabled( AEFeature.CHANNELS ) && requiredChannels > 8 ) - { - used = 0; - } + if (this.controllerState == ControllerState.NO_CONTROLLER) { + final int requiredChannels = this.calculateRequiredChannels(); + int used = requiredChannels; + if (AEConfig.instance().isFeatureEnabled(AEFeature.CHANNELS) && requiredChannels > 8) { + used = 0; + } - final int nodes = this.myGrid.getNodes().size(); - this.setChannelsInUse( used ); + final int nodes = this.myGrid.getNodes().size(); + this.setChannelsInUse(used); - this.ticksUntilReady = 20 + Math.max( 0, nodes / 100 - 20 ); - this.setChannelsByBlocks( nodes * used ); - this.setChannelPowerUsage( this.getChannelsByBlocks() / 128.0 ); + this.ticksUntilReady = 20 + Math.max(0, nodes / 100 - 20); + this.setChannelsByBlocks(nodes * used); + this.setChannelPowerUsage(this.getChannelsByBlocks() / 128.0); - this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( used ) ); - } - else if( this.controllerState == ControllerState.CONTROLLER_CONFLICT ) - { - this.ticksUntilReady = 20; - this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 ) ); - } - else - { - final int nodes = this.myGrid.getNodes().size(); - this.ticksUntilReady = 20 + Math.max( 0, nodes / 100 - 20 ); - final HashSet closedList = new HashSet<>(); - this.semiOpen = new HashSet<>(); + this.myGrid.getPivot().beginVisit(new AdHocChannelUpdater(used)); + } else if (this.controllerState == ControllerState.CONTROLLER_CONFLICT) { + this.ticksUntilReady = 20; + this.myGrid.getPivot().beginVisit(new AdHocChannelUpdater(0)); + } else { + final int nodes = this.myGrid.getNodes().size(); + this.ticksUntilReady = 20 + Math.max(0, nodes / 100 - 20); + final HashSet closedList = new HashSet<>(); + this.semiOpen = new HashSet<>(); - // myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 ) - // ); - for( final IGridNode node : this.myGrid.getMachines( TileController.class ) ) - { - closedList.add( (IPathItem) node ); - for( final IGridConnection gcc : node.getConnections() ) - { - final GridConnection gc = (GridConnection) gcc; - if( !( gc.getOtherSide( node ).getMachine() instanceof TileController ) ) - { - final List open = new ArrayList<>(); - closedList.add( gc ); - open.add( gc ); - gc.setControllerRoute( (GridNode) node, true ); - this.active.add( new PathSegment( this, open, this.semiOpen, closedList ) ); - } - } - } - } - } + // myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 ) + // ); + for (final IGridNode node : this.myGrid.getMachines(TileController.class)) { + closedList.add((IPathItem) node); + for (final IGridConnection gcc : node.getConnections()) { + final GridConnection gc = (GridConnection) gcc; + if (!(gc.getOtherSide(node).getMachine() instanceof TileController)) { + final List open = new ArrayList<>(); + closedList.add(gc); + open.add(gc); + gc.setControllerRoute((GridNode) node, true); + this.active.add(new PathSegment(this, open, this.semiOpen, closedList)); + } + } + } + } + } - if( !this.active.isEmpty() || this.ticksUntilReady > 0 ) - { - final Iterator i = this.active.iterator(); - while ( i.hasNext() ) - { - final PathSegment pat = i.next(); - if( pat.step() ) - { - pat.setDead( true ); - i.remove(); - } - } + if (!this.active.isEmpty() || this.ticksUntilReady > 0) { + final Iterator i = this.active.iterator(); + while (i.hasNext()) { + final PathSegment pat = i.next(); + if (pat.step()) { + pat.setDead(true); + i.remove(); + } + } - this.ticksUntilReady--; + this.ticksUntilReady--; - if( this.active.isEmpty() && this.ticksUntilReady <= 0 ) - { - if( this.controllerState == ControllerState.CONTROLLER_ONLINE ) - { - final Iterator controllerIterator = this.controllers.iterator(); - if( controllerIterator.hasNext() ) - { - final TileController controller = controllerIterator.next(); - controller.getGridNode( AEPartLocation.INTERNAL ).beginVisit( new ControllerChannelUpdater() ); - } - } + if (this.active.isEmpty() && this.ticksUntilReady <= 0) { + if (this.controllerState == ControllerState.CONTROLLER_ONLINE) { + final Iterator controllerIterator = this.controllers.iterator(); + if (controllerIterator.hasNext()) { + final TileController controller = controllerIterator.next(); + controller.getGridNode(AEPartLocation.INTERNAL).beginVisit(new ControllerChannelUpdater()); + } + } - // check for achievements - this.achievementPost(); + // check for achievements + this.achievementPost(); - this.booting = false; - this.setChannelPowerUsage( this.getChannelsByBlocks() / 128.0 ); - this.myGrid.postEvent( new MENetworkBootingStatusChange() ); - } - } - } + this.booting = false; + this.setChannelPowerUsage(this.getChannelsByBlocks() / 128.0); + this.myGrid.postEvent(new MENetworkBootingStatusChange()); + } + } + } - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof TileController ) - { - this.controllers.remove( machine ); - this.recalculateControllerNextTick = true; - } + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof TileController) { + this.controllers.remove(machine); + this.recalculateControllerNextTick = true; + } - final EnumSet flags = gridNode.getGridBlock().getFlags(); + final EnumSet flags = gridNode.getGridBlock().getFlags(); - if( flags.contains( GridFlags.REQUIRE_CHANNEL ) ) - { - this.requireChannels.remove( gridNode ); - } + if (flags.contains(GridFlags.REQUIRE_CHANNEL)) { + this.requireChannels.remove(gridNode); + } - if( flags.contains( GridFlags.CANNOT_CARRY_COMPRESSED ) ) - { - this.blockDense.remove( gridNode ); - } + if (flags.contains(GridFlags.CANNOT_CARRY_COMPRESSED)) { + this.blockDense.remove(gridNode); + } - this.repath(); - } + this.repath(); + } - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof TileController ) - { - this.controllers.add( (TileController) machine ); - this.recalculateControllerNextTick = true; - } + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof TileController) { + this.controllers.add((TileController) machine); + this.recalculateControllerNextTick = true; + } - final EnumSet flags = gridNode.getGridBlock().getFlags(); + final EnumSet flags = gridNode.getGridBlock().getFlags(); - if( flags.contains( GridFlags.REQUIRE_CHANNEL ) ) - { - this.requireChannels.add( gridNode ); - } + if (flags.contains(GridFlags.REQUIRE_CHANNEL)) { + this.requireChannels.add(gridNode); + } - if( flags.contains( GridFlags.CANNOT_CARRY_COMPRESSED ) ) - { - this.blockDense.add( gridNode ); - } + if (flags.contains(GridFlags.CANNOT_CARRY_COMPRESSED)) { + this.blockDense.add(gridNode); + } - this.repath(); - } + this.repath(); + } - @Override - public void onSplit( final IGridStorage storageB ) - { + @Override + public void onSplit(final IGridStorage storageB) { - } + } - @Override - public void onJoin( final IGridStorage storageB ) - { + @Override + public void onJoin(final IGridStorage storageB) { - } + } - @Override - public void populateGridStorage( final IGridStorage storage ) - { + @Override + public void populateGridStorage(final IGridStorage storage) { - } + } - private void recalcController() - { - this.recalculateControllerNextTick = false; - final ControllerState old = this.controllerState; + private void recalcController() { + this.recalculateControllerNextTick = false; + final ControllerState old = this.controllerState; - if( this.controllers.isEmpty() ) - { - this.controllerState = ControllerState.NO_CONTROLLER; - } - else - { - final IGridNode startingNode = this.controllers.iterator().next().getGridNode( AEPartLocation.INTERNAL ); - if( startingNode == null ) - { - this.controllerState = ControllerState.CONTROLLER_CONFLICT; - return; - } + if (this.controllers.isEmpty()) { + this.controllerState = ControllerState.NO_CONTROLLER; + } else { + final IGridNode startingNode = this.controllers.iterator().next().getGridNode(AEPartLocation.INTERNAL); + if (startingNode == null) { + this.controllerState = ControllerState.CONTROLLER_CONFLICT; + return; + } - final DimensionalCoord dc = startingNode.getGridBlock().getLocation(); - final ControllerValidator cv = new ControllerValidator( dc.x, dc.y, dc.z ); + final DimensionalCoord dc = startingNode.getGridBlock().getLocation(); + final ControllerValidator cv = new ControllerValidator(dc.x, dc.y, dc.z); - startingNode.beginVisit( cv ); + startingNode.beginVisit(cv); - if( cv.isValid() && cv.getFound() == this.controllers.size() ) - { - this.controllerState = ControllerState.CONTROLLER_ONLINE; - } - else - { - this.controllerState = ControllerState.CONTROLLER_CONFLICT; - } - } + if (cv.isValid() && cv.getFound() == this.controllers.size()) { + this.controllerState = ControllerState.CONTROLLER_ONLINE; + } else { + this.controllerState = ControllerState.CONTROLLER_CONFLICT; + } + } - if( old != this.controllerState ) - { - this.myGrid.postEvent( new MENetworkControllerChange() ); - } - } + if (old != this.controllerState) { + this.myGrid.postEvent(new MENetworkControllerChange()); + } + } - private int calculateRequiredChannels() - { - this.semiOpen.clear(); + private int calculateRequiredChannels() { + this.semiOpen.clear(); - int depth = 0; - for( final IGridNode nodes : this.requireChannels ) - { - if( !this.semiOpen.contains( (IPathItem) nodes ) ) - { - final IGridBlock gb = nodes.getGridBlock(); - final EnumSet flags = gb.getFlags(); + int depth = 0; + for (final IGridNode nodes : this.requireChannels) { + if (!this.semiOpen.contains((IPathItem) nodes)) { + final IGridBlock gb = nodes.getGridBlock(); + final EnumSet flags = gb.getFlags(); - if( flags.contains( GridFlags.COMPRESSED_CHANNEL ) && !this.blockDense.isEmpty() ) - { - return 9; - } + if (flags.contains(GridFlags.COMPRESSED_CHANNEL) && !this.blockDense.isEmpty()) { + return 9; + } - depth++; + depth++; - if( flags.contains( GridFlags.MULTIBLOCK ) ) - { - final IGridMultiblock gmb = (IGridMultiblock) gb; - final Iterator i = gmb.getMultiblockNodes(); - while ( i.hasNext() ) - { - this.semiOpen.add( (IPathItem) i.next() ); - } - } - } - } + if (flags.contains(GridFlags.MULTIBLOCK)) { + final IGridMultiblock gmb = (IGridMultiblock) gb; + final Iterator i = gmb.getMultiblockNodes(); + while (i.hasNext()) { + this.semiOpen.add((IPathItem) i.next()); + } + } + } + } - return depth; - } + return depth; + } - private void achievementPost() - { - if( this.lastChannels != this.getChannelsInUse() && AEConfig.instance().isFeatureEnabled( AEFeature.CHANNELS ) ) - { - final IAdvancementTrigger currentBracket = this.getAchievementBracket( this.getChannelsInUse() ); - final IAdvancementTrigger lastBracket = this.getAchievementBracket( this.lastChannels ); - if( currentBracket != lastBracket && currentBracket != null ) - { - for( final IGridNode n : this.requireChannels ) - { - EntityPlayer player = AEApi.instance().registries().players().findPlayer( n.getPlayerID() ); - if( player instanceof EntityPlayerMP ) - { - currentBracket.trigger( (EntityPlayerMP) player ); - } - } - } - } - this.lastChannels = this.getChannelsInUse(); - } + private void achievementPost() { + if (this.lastChannels != this.getChannelsInUse() && AEConfig.instance().isFeatureEnabled(AEFeature.CHANNELS)) { + final IAdvancementTrigger currentBracket = this.getAchievementBracket(this.getChannelsInUse()); + final IAdvancementTrigger lastBracket = this.getAchievementBracket(this.lastChannels); + if (currentBracket != lastBracket && currentBracket != null) { + for (final IGridNode n : this.requireChannels) { + EntityPlayer player = AEApi.instance().registries().players().findPlayer(n.getPlayerID()); + if (player instanceof EntityPlayerMP) { + currentBracket.trigger((EntityPlayerMP) player); + } + } + } + } + this.lastChannels = this.getChannelsInUse(); + } - private IAdvancementTrigger getAchievementBracket( final int ch ) - { - if( ch < 8 ) - { - return null; - } + private IAdvancementTrigger getAchievementBracket(final int ch) { + if (ch < 8) { + return null; + } - if( ch < 128 ) - { - return AppEng.instance().getAdvancementTriggers().getNetworkApprentice(); - } + if (ch < 128) { + return AppEng.instance().getAdvancementTriggers().getNetworkApprentice(); + } - if( ch < 2048 ) - { - return AppEng.instance().getAdvancementTriggers().getNetworkEngineer(); - } + if (ch < 2048) { + return AppEng.instance().getAdvancementTriggers().getNetworkEngineer(); + } - return AppEng.instance().getAdvancementTriggers().getNetworkAdmin(); - } + return AppEng.instance().getAdvancementTriggers().getNetworkAdmin(); + } - @MENetworkEventSubscribe - void updateNodReq( final MENetworkChannelChanged ev ) - { - final IGridNode gridNode = ev.node; + @MENetworkEventSubscribe + void updateNodReq(final MENetworkChannelChanged ev) { + final IGridNode gridNode = ev.node; - if( gridNode.getGridBlock().getFlags().contains( GridFlags.REQUIRE_CHANNEL ) ) - { - this.requireChannels.add( gridNode ); - } - else - { - this.requireChannels.remove( gridNode ); - } + if (gridNode.getGridBlock().getFlags().contains(GridFlags.REQUIRE_CHANNEL)) { + this.requireChannels.add(gridNode); + } else { + this.requireChannels.remove(gridNode); + } - this.repath(); - } + this.repath(); + } - @Override - public boolean isNetworkBooting() - { - return !this.booting && !this.active.isEmpty(); - } + @Override + public boolean isNetworkBooting() { + return !this.booting && !this.active.isEmpty(); + } - @Override - public ControllerState getControllerState() - { - return this.controllerState; - } + @Override + public ControllerState getControllerState() { + return this.controllerState; + } - @Override - public void repath() - { - // clean up... - this.active.clear(); + @Override + public void repath() { + // clean up... + this.active.clear(); - this.setChannelsByBlocks( 0 ); - this.updateNetwork = true; - } + this.setChannelsByBlocks(0); + this.updateNetwork = true; + } - double getChannelPowerUsage() - { - return this.channelPowerUsage; - } + double getChannelPowerUsage() { + return this.channelPowerUsage; + } - private void setChannelPowerUsage( final double channelPowerUsage ) - { - this.channelPowerUsage = channelPowerUsage; - } + private void setChannelPowerUsage(final double channelPowerUsage) { + this.channelPowerUsage = channelPowerUsage; + } - public int getChannelsByBlocks() - { - return this.channelsByBlocks; - } + public int getChannelsByBlocks() { + return this.channelsByBlocks; + } - public void setChannelsByBlocks( final int channelsByBlocks ) - { - this.channelsByBlocks = channelsByBlocks; - } + public void setChannelsByBlocks(final int channelsByBlocks) { + this.channelsByBlocks = channelsByBlocks; + } - public int getChannelsInUse() - { - return this.channelsInUse; - } + public int getChannelsInUse() { + return this.channelsInUse; + } - public void setChannelsInUse( final int channelsInUse ) - { - this.channelsInUse = channelsInUse; - } + public void setChannelsInUse(final int channelsInUse) { + this.channelsInUse = channelsInUse; + } } diff --git a/src/main/java/appeng/me/cache/SecurityCache.java b/src/main/java/appeng/me/cache/SecurityCache.java index 529f90528..8b74d0453 100644 --- a/src/main/java/appeng/me/cache/SecurityCache.java +++ b/src/main/java/appeng/me/cache/SecurityCache.java @@ -19,16 +19,6 @@ package appeng.me.cache; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.List; - -import com.google.common.base.Preconditions; -import com.mojang.authlib.GameProfile; - -import net.minecraft.entity.player.EntityPlayer; - import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; @@ -40,163 +30,140 @@ import appeng.api.networking.security.ISecurityGrid; import appeng.api.networking.security.ISecurityProvider; import appeng.core.worlddata.WorldData; import appeng.me.GridNode; +import com.google.common.base.Preconditions; +import com.mojang.authlib.GameProfile; +import net.minecraft.entity.player.EntityPlayer; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; -public class SecurityCache implements ISecurityGrid -{ +public class SecurityCache implements ISecurityGrid { - private final IGrid myGrid; - private final List securityProvider = new ArrayList<>(); - private final HashMap> playerPerms = new HashMap<>(); - private long securityKey = -1; + private final IGrid myGrid; + private final List securityProvider = new ArrayList<>(); + private final HashMap> playerPerms = new HashMap<>(); + private long securityKey = -1; - public SecurityCache( final IGrid g ) - { - this.myGrid = g; - } + public SecurityCache(final IGrid g) { + this.myGrid = g; + } - @MENetworkEventSubscribe - public void updatePermissions( final MENetworkSecurityChange ev ) - { - this.playerPerms.clear(); - if( this.securityProvider.isEmpty() ) - { - return; - } + @MENetworkEventSubscribe + public void updatePermissions(final MENetworkSecurityChange ev) { + this.playerPerms.clear(); + if (this.securityProvider.isEmpty()) { + return; + } - this.securityProvider.get( 0 ).readPermissions( this.playerPerms ); - } + this.securityProvider.get(0).readPermissions(this.playerPerms); + } - public long getSecurityKey() - { - return this.securityKey; - } + public long getSecurityKey() { + return this.securityKey; + } - @Override - public void onUpdateTick() - { + @Override + public void onUpdateTick() { - } + } - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof ISecurityProvider ) - { - this.securityProvider.remove( machine ); - this.updateSecurityKey(); - } - } + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof ISecurityProvider) { + this.securityProvider.remove(machine); + this.updateSecurityKey(); + } + } - private void updateSecurityKey() - { - final long lastCode = this.securityKey; + private void updateSecurityKey() { + final long lastCode = this.securityKey; - if( this.securityProvider.size() == 1 ) - { - this.securityKey = this.securityProvider.get( 0 ).getSecurityKey(); - } - else - { - this.securityKey = -1; - } + if (this.securityProvider.size() == 1) { + this.securityKey = this.securityProvider.get(0).getSecurityKey(); + } else { + this.securityKey = -1; + } - if( lastCode != this.securityKey ) - { - this.getGrid().postEvent( new MENetworkSecurityChange() ); - for( final IGridNode n : this.getGrid().getNodes() ) - { - ( (GridNode) n ).setLastSecurityKey( this.securityKey ); - } - } - } + if (lastCode != this.securityKey) { + this.getGrid().postEvent(new MENetworkSecurityChange()); + for (final IGridNode n : this.getGrid().getNodes()) { + ((GridNode) n).setLastSecurityKey(this.securityKey); + } + } + } - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof ISecurityProvider ) - { - this.securityProvider.add( (ISecurityProvider) machine ); - this.updateSecurityKey(); - } - else - { - ( (GridNode) gridNode ).setLastSecurityKey( this.securityKey ); - } - } + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof ISecurityProvider) { + this.securityProvider.add((ISecurityProvider) machine); + this.updateSecurityKey(); + } else { + ((GridNode) gridNode).setLastSecurityKey(this.securityKey); + } + } - @Override - public void onSplit( final IGridStorage destinationStorage ) - { + @Override + public void onSplit(final IGridStorage destinationStorage) { - } + } - @Override - public void onJoin( final IGridStorage sourceStorage ) - { + @Override + public void onJoin(final IGridStorage sourceStorage) { - } + } - @Override - public void populateGridStorage( final IGridStorage destinationStorage ) - { + @Override + public void populateGridStorage(final IGridStorage destinationStorage) { - } + } - @Override - public boolean isAvailable() - { - return this.securityProvider.size() == 1 && this.securityProvider.get( 0 ).isSecurityEnabled(); - } + @Override + public boolean isAvailable() { + return this.securityProvider.size() == 1 && this.securityProvider.get(0).isSecurityEnabled(); + } - @Override - public boolean hasPermission( final EntityPlayer player, final SecurityPermissions perm ) - { - Preconditions.checkNotNull( player ); - Preconditions.checkNotNull( perm ); + @Override + public boolean hasPermission(final EntityPlayer player, final SecurityPermissions perm) { + Preconditions.checkNotNull(player); + Preconditions.checkNotNull(perm); - final GameProfile profile = player.getGameProfile(); - final int playerID = WorldData.instance().playerData().getPlayerID( profile ); + final GameProfile profile = player.getGameProfile(); + final int playerID = WorldData.instance().playerData().getPlayerID(profile); - return this.hasPermission( playerID, perm ); - } + return this.hasPermission(playerID, perm); + } - @Override - public boolean hasPermission( final int playerID, final SecurityPermissions perm ) - { - if( this.isAvailable() ) - { - final EnumSet perms = this.playerPerms.get( playerID ); + @Override + public boolean hasPermission(final int playerID, final SecurityPermissions perm) { + if (this.isAvailable()) { + final EnumSet perms = this.playerPerms.get(playerID); - if( perms == null ) - { - if( playerID == -1 ) // no default? - { - return false; - } - else - { - return this.hasPermission( -1, perm ); - } - } + if (perms == null) { + if (playerID == -1) // no default? + { + return false; + } else { + return this.hasPermission(-1, perm); + } + } - return perms.contains( perm ); - } - return true; - } + return perms.contains(perm); + } + return true; + } - @Override - public int getOwner() - { - if( this.isAvailable() ) - { - return this.securityProvider.get( 0 ).getOwner(); - } - return -1; - } + @Override + public int getOwner() { + if (this.isAvailable()) { + return this.securityProvider.get(0).getOwner(); + } + return -1; + } - public IGrid getGrid() - { - return this.myGrid; - } + public IGrid getGrid() { + return this.myGrid; + } } diff --git a/src/main/java/appeng/me/cache/SpatialPylonCache.java b/src/main/java/appeng/me/cache/SpatialPylonCache.java index 7bc2f9d29..4c6f1e33c 100644 --- a/src/main/java/appeng/me/cache/SpatialPylonCache.java +++ b/src/main/java/appeng/me/cache/SpatialPylonCache.java @@ -19,10 +19,6 @@ package appeng.me.cache; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -37,223 +33,197 @@ import appeng.me.cluster.implementations.SpatialPylonCluster; import appeng.tile.spatial.TileSpatialIOPort; import appeng.tile.spatial.TileSpatialPylon; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; -public class SpatialPylonCache implements ISpatialCache -{ - private final IGrid myGrid; - private long powerRequired = 0; - private double efficiency = 0.0; - private DimensionalCoord captureMin; - private DimensionalCoord captureMax; - private boolean isValid = false; - private List ioPorts = new ArrayList<>(); - private HashMap clusters = new HashMap<>(); +public class SpatialPylonCache implements ISpatialCache { - public SpatialPylonCache( final IGrid g ) - { - this.myGrid = g; - } + private final IGrid myGrid; + private long powerRequired = 0; + private double efficiency = 0.0; + private DimensionalCoord captureMin; + private DimensionalCoord captureMax; + private boolean isValid = false; + private List ioPorts = new ArrayList<>(); + private HashMap clusters = new HashMap<>(); - @MENetworkEventSubscribe - public void bootingRender( final MENetworkBootingStatusChange c ) - { - this.reset( this.myGrid ); - } + public SpatialPylonCache(final IGrid g) { + this.myGrid = g; + } - private void reset( final IGrid grid ) - { + @MENetworkEventSubscribe + public void bootingRender(final MENetworkBootingStatusChange c) { + this.reset(this.myGrid); + } - this.clusters = new HashMap<>(); - this.ioPorts = new ArrayList<>(); + private void reset(final IGrid grid) { - for( final IGridNode gm : grid.getMachines( TileSpatialIOPort.class ) ) - { - this.ioPorts.add( (TileSpatialIOPort) gm.getMachine() ); - } + this.clusters = new HashMap<>(); + this.ioPorts = new ArrayList<>(); - final IReadOnlyCollection set = grid.getMachines( TileSpatialPylon.class ); - for( final IGridNode gm : set ) - { - if( gm.meetsChannelRequirements() ) - { - final SpatialPylonCluster c = ( (TileSpatialPylon) gm.getMachine() ).getCluster(); - if( c != null ) - { - this.clusters.put( c, c ); - } - } - } + for (final IGridNode gm : grid.getMachines(TileSpatialIOPort.class)) { + this.ioPorts.add((TileSpatialIOPort) gm.getMachine()); + } - this.captureMax = null; - this.captureMin = null; - this.isValid = true; + final IReadOnlyCollection set = grid.getMachines(TileSpatialPylon.class); + for (final IGridNode gm : set) { + if (gm.meetsChannelRequirements()) { + final SpatialPylonCluster c = ((TileSpatialPylon) gm.getMachine()).getCluster(); + if (c != null) { + this.clusters.put(c, c); + } + } + } - int pylonBlocks = 0; - for( final SpatialPylonCluster cl : this.clusters.values() ) - { - if( this.captureMax == null ) - { - this.captureMax = cl.getMax().copy(); - } - if( this.captureMin == null ) - { - this.captureMin = cl.getMin().copy(); - } + this.captureMax = null; + this.captureMin = null; + this.isValid = true; - pylonBlocks += cl.tileCount(); + int pylonBlocks = 0; + for (final SpatialPylonCluster cl : this.clusters.values()) { + if (this.captureMax == null) { + this.captureMax = cl.getMax().copy(); + } + if (this.captureMin == null) { + this.captureMin = cl.getMin().copy(); + } - this.captureMin.x = Math.min( this.captureMin.x, cl.getMin().x ); - this.captureMin.y = Math.min( this.captureMin.y, cl.getMin().y ); - this.captureMin.z = Math.min( this.captureMin.z, cl.getMin().z ); + pylonBlocks += cl.tileCount(); - this.captureMax.x = Math.max( this.captureMax.x, cl.getMax().x ); - this.captureMax.y = Math.max( this.captureMax.y, cl.getMax().y ); - this.captureMax.z = Math.max( this.captureMax.z, cl.getMax().z ); - } + this.captureMin.x = Math.min(this.captureMin.x, cl.getMin().x); + this.captureMin.y = Math.min(this.captureMin.y, cl.getMin().y); + this.captureMin.z = Math.min(this.captureMin.z, cl.getMin().z); - double maxPower = 0; - double minPower = 0; - if( this.hasRegion() ) - { - this.isValid = this.captureMax.x - this.captureMin.x > 1 && this.captureMax.y - this.captureMin.y > 1 && this.captureMax.z - this.captureMin.z > 1; + this.captureMax.x = Math.max(this.captureMax.x, cl.getMax().x); + this.captureMax.y = Math.max(this.captureMax.y, cl.getMax().y); + this.captureMax.z = Math.max(this.captureMax.z, cl.getMax().z); + } - for( final SpatialPylonCluster cl : this.clusters.values() ) - { - switch( cl.getCurrentAxis() ) - { - case X: + double maxPower = 0; + double minPower = 0; + if (this.hasRegion()) { + this.isValid = this.captureMax.x - this.captureMin.x > 1 && this.captureMax.y - this.captureMin.y > 1 && this.captureMax.z - this.captureMin.z > 1; - this.isValid = this.isValid && ( ( this.captureMax.y == cl.getMin().y || this.captureMin.y == cl - .getMax().y ) || ( this.captureMax.z == cl.getMin().z || this.captureMin.z == cl.getMax().z ) ) && ( ( this.captureMax.y == cl - .getMax().y || this.captureMin.y == cl - .getMin().y ) || ( this.captureMax.z == cl.getMax().z || this.captureMin.z == cl.getMin().z ) ); + for (final SpatialPylonCluster cl : this.clusters.values()) { + switch (cl.getCurrentAxis()) { + case X: - break; - case Y: + this.isValid = this.isValid && ((this.captureMax.y == cl.getMin().y || this.captureMin.y == cl + .getMax().y) || (this.captureMax.z == cl.getMin().z || this.captureMin.z == cl.getMax().z)) && ((this.captureMax.y == cl + .getMax().y || this.captureMin.y == cl + .getMin().y) || (this.captureMax.z == cl.getMax().z || this.captureMin.z == cl.getMin().z)); - this.isValid = this.isValid && ( ( this.captureMax.x == cl.getMin().x || this.captureMin.x == cl - .getMax().x ) || ( this.captureMax.z == cl.getMin().z || this.captureMin.z == cl.getMax().z ) ) && ( ( this.captureMax.x == cl - .getMax().x || this.captureMin.x == cl - .getMin().x ) || ( this.captureMax.z == cl.getMax().z || this.captureMin.z == cl.getMin().z ) ); + break; + case Y: - break; - case Z: + this.isValid = this.isValid && ((this.captureMax.x == cl.getMin().x || this.captureMin.x == cl + .getMax().x) || (this.captureMax.z == cl.getMin().z || this.captureMin.z == cl.getMax().z)) && ((this.captureMax.x == cl + .getMax().x || this.captureMin.x == cl + .getMin().x) || (this.captureMax.z == cl.getMax().z || this.captureMin.z == cl.getMin().z)); - this.isValid = this.isValid && ( ( this.captureMax.y == cl.getMin().y || this.captureMin.y == cl - .getMax().y ) || ( this.captureMax.x == cl.getMin().x || this.captureMin.x == cl.getMax().x ) ) && ( ( this.captureMax.y == cl - .getMax().y || this.captureMin.y == cl - .getMin().y ) || ( this.captureMax.x == cl.getMax().x || this.captureMin.x == cl.getMin().x ) ); + break; + case Z: - break; - case UNFORMED: - this.isValid = false; - break; - } - } + this.isValid = this.isValid && ((this.captureMax.y == cl.getMin().y || this.captureMin.y == cl + .getMax().y) || (this.captureMax.x == cl.getMin().x || this.captureMin.x == cl.getMax().x)) && ((this.captureMax.y == cl + .getMax().y || this.captureMin.y == cl + .getMin().y) || (this.captureMax.x == cl.getMax().x || this.captureMin.x == cl.getMin().x)); - final int reqX = this.captureMax.x - this.captureMin.x; - final int reqY = this.captureMax.y - this.captureMin.y; - final int reqZ = this.captureMax.z - this.captureMin.z; - final int requirePylonBlocks = Math.max( 6, ( ( reqX * reqZ + reqX * reqY + reqY * reqZ ) * 3 ) / 8 ); + break; + case UNFORMED: + this.isValid = false; + break; + } + } - this.efficiency = (double) pylonBlocks / (double) requirePylonBlocks; + final int reqX = this.captureMax.x - this.captureMin.x; + final int reqY = this.captureMax.y - this.captureMin.y; + final int reqZ = this.captureMax.z - this.captureMin.z; + final int requirePylonBlocks = Math.max(6, ((reqX * reqZ + reqX * reqY + reqY * reqZ) * 3) / 8); - if( this.efficiency > 1.0 ) - { - this.efficiency = 1.0; - } - if( this.efficiency < 0.0 ) - { - this.efficiency = 0.0; - } + this.efficiency = (double) pylonBlocks / (double) requirePylonBlocks; - minPower = (double) reqX * (double) reqY * reqZ * AEConfig.instance().getSpatialPowerMultiplier(); - maxPower = Math.pow( minPower, AEConfig.instance().getSpatialPowerExponent() ); - } + if (this.efficiency > 1.0) { + this.efficiency = 1.0; + } + if (this.efficiency < 0.0) { + this.efficiency = 0.0; + } - final double affective_efficiency = Math.pow( this.efficiency, 0.25 ); - this.powerRequired = (long) ( affective_efficiency * minPower + ( 1.0 - affective_efficiency ) * maxPower ); + minPower = (double) reqX * (double) reqY * reqZ * AEConfig.instance().getSpatialPowerMultiplier(); + maxPower = Math.pow(minPower, AEConfig.instance().getSpatialPowerExponent()); + } - for( final SpatialPylonCluster cl : this.clusters.values() ) - { - final boolean myWasValid = cl.isValid(); - cl.setValid( this.isValid ); - if( myWasValid != this.isValid ) - { - cl.updateStatus( false ); - } - } - } + final double affective_efficiency = Math.pow(this.efficiency, 0.25); + this.powerRequired = (long) (affective_efficiency * minPower + (1.0 - affective_efficiency) * maxPower); - @Override - public boolean hasRegion() - { - return this.captureMin != null; - } + for (final SpatialPylonCluster cl : this.clusters.values()) { + final boolean myWasValid = cl.isValid(); + cl.setValid(this.isValid); + if (myWasValid != this.isValid) { + cl.updateStatus(false); + } + } + } - @Override - public boolean isValidRegion() - { - return this.hasRegion() && this.isValid; - } + @Override + public boolean hasRegion() { + return this.captureMin != null; + } - @Override - public DimensionalCoord getMin() - { - return this.captureMin; - } + @Override + public boolean isValidRegion() { + return this.hasRegion() && this.isValid; + } - @Override - public DimensionalCoord getMax() - { - return this.captureMax; - } + @Override + public DimensionalCoord getMin() { + return this.captureMin; + } - @Override - public long requiredPower() - { - return this.powerRequired; - } + @Override + public DimensionalCoord getMax() { + return this.captureMax; + } - @Override - public float currentEfficiency() - { - return (float) this.efficiency * 100; - } + @Override + public long requiredPower() { + return this.powerRequired; + } - @Override - public void onUpdateTick() - { - } + @Override + public float currentEfficiency() { + return (float) this.efficiency * 100; + } - @Override - public void removeNode( final IGridNode node, final IGridHost machine ) - { + @Override + public void onUpdateTick() { + } - } + @Override + public void removeNode(final IGridNode node, final IGridHost machine) { - @Override - public void addNode( final IGridNode node, final IGridHost machine ) - { + } - } + @Override + public void addNode(final IGridNode node, final IGridHost machine) { - @Override - public void onSplit( final IGridStorage storageB ) - { + } - } + @Override + public void onSplit(final IGridStorage storageB) { - @Override - public void onJoin( final IGridStorage storageB ) - { + } - } + @Override + public void onJoin(final IGridStorage storageB) { - @Override - public void populateGridStorage( final IGridStorage storage ) - { + } - } + @Override + public void populateGridStorage(final IGridStorage storage) { + + } } diff --git a/src/main/java/appeng/me/cache/TickManagerCache.java b/src/main/java/appeng/me/cache/TickManagerCache.java index bf258125c..6820a8234 100644 --- a/src/main/java/appeng/me/cache/TickManagerCache.java +++ b/src/main/java/appeng/me/cache/TickManagerCache.java @@ -19,15 +19,6 @@ package appeng.me.cache; -import java.util.*; - -import appeng.parts.automation.PartLevelEmitter; -import com.google.common.base.Preconditions; - -import net.minecraft.crash.CrashReport; -import net.minecraft.crash.CrashReportCategory; -import net.minecraft.util.ReportedException; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -37,234 +28,209 @@ import appeng.api.networking.ticking.ITickManager; import appeng.api.networking.ticking.TickRateModulation; import appeng.api.networking.ticking.TickingRequest; import appeng.me.cache.helpers.TickTracker; +import com.google.common.base.Preconditions; +import net.minecraft.crash.CrashReport; +import net.minecraft.crash.CrashReportCategory; +import net.minecraft.util.ReportedException; + +import java.util.HashMap; +import java.util.PriorityQueue; -public class TickManagerCache implements ITickManager -{ +public class TickManagerCache implements ITickManager { - private final IGrid myGrid; - private final HashMap alertable = new HashMap<>(); - private final HashMap sleeping = new HashMap<>(); - private final HashMap awake = new HashMap<>(); - private final HashMap laterTicker = new HashMap<>(); - private final PriorityQueue upcomingTicks = new PriorityQueue<>(); + private final IGrid myGrid; + private final HashMap alertable = new HashMap<>(); + private final HashMap sleeping = new HashMap<>(); + private final HashMap awake = new HashMap<>(); + private final HashMap laterTicker = new HashMap<>(); + private final PriorityQueue upcomingTicks = new PriorityQueue<>(); - private long currentTick = 0; + private long currentTick = 0; - public TickManagerCache( final IGrid g ) - { - this.myGrid = g; - } + public TickManagerCache(final IGrid g) { + this.myGrid = g; + } - public long getCurrentTick() - { - return this.currentTick; - } + public long getCurrentTick() { + return this.currentTick; + } - public long getAvgNanoTime( final IGridNode node ) - { - TickTracker tt = this.awake.get( node ); + public long getAvgNanoTime(final IGridNode node) { + TickTracker tt = this.awake.get(node); - if( tt == null ) - { - tt = this.sleeping.get( node ); - } + if (tt == null) { + tt = this.sleeping.get(node); + } - if( tt == null ) - { - return -1; - } + if (tt == null) { + return -1; + } - return tt.getAvgNanos(); - } + return tt.getAvgNanos(); + } - @Override - public void onUpdateTick() - { - TickTracker tt = null; + @Override + public void onUpdateTick() { + TickTracker tt = null; - try - { - this.currentTick++; + try { + this.currentTick++; - while ( !this.upcomingTicks.isEmpty() ) - { - tt = this.upcomingTicks.peek(); + while (!this.upcomingTicks.isEmpty()) { + tt = this.upcomingTicks.peek(); - // Stop once it reaches a TickTracker running at a later tick - if( tt.getNextTick() > this.currentTick ) - { - break; - } + // Stop once it reaches a TickTracker running at a later tick + if (tt.getNextTick() > this.currentTick) { + break; + } - this.upcomingTicks.poll(); + this.upcomingTicks.poll(); - final int diff = (int) ( this.currentTick - tt.getLastTick() ); - final TickRateModulation mod = tt.getGridTickable().tickingRequest( tt.getNode(), diff ); + final int diff = (int) (this.currentTick - tt.getLastTick()); + final TickRateModulation mod = tt.getGridTickable().tickingRequest(tt.getNode(), diff); - switch ( mod ) - { - case FASTER: - tt.setCurrentRate( tt.getCurrentRate() - 2 ); - break; - case IDLE: - tt.setCurrentRate( tt.getRequest().maxTickRate ); - break; - case SAME: - break; - case SLEEP: - this.sleepDevice( tt.getNode() ); - break; - case SLOWER: - tt.setCurrentRate( tt.getCurrentRate() + 1 ); - break; - case URGENT: - tt.setCurrentRate( 0 ); - break; - default: - break; - } + switch (mod) { + case FASTER: + tt.setCurrentRate(tt.getCurrentRate() - 2); + break; + case IDLE: + tt.setCurrentRate(tt.getRequest().maxTickRate); + break; + case SAME: + break; + case SLEEP: + this.sleepDevice(tt.getNode()); + break; + case SLOWER: + tt.setCurrentRate(tt.getCurrentRate() + 1); + break; + case URGENT: + tt.setCurrentRate(0); + break; + default: + break; + } - if( this.awake.containsKey( tt.getNode() ) ) - { - this.addToQueue( tt ); - } - } - } - catch( final Throwable t ) - { - final CrashReport crashreport = CrashReport.makeCrashReport( t, "Ticking GridNode" ); - final CrashReportCategory crashreportcategory = crashreport.makeCategory( tt.getGridTickable().getClass().getSimpleName() + " being ticked." ); - tt.addEntityCrashInfo( crashreportcategory ); - throw new ReportedException( crashreport ); - } - } + if (this.awake.containsKey(tt.getNode())) { + this.addToQueue(tt); + } + } + } catch (final Throwable t) { + final CrashReport crashreport = CrashReport.makeCrashReport(t, "Ticking GridNode"); + final CrashReportCategory crashreportcategory = crashreport.makeCategory(tt.getGridTickable().getClass().getSimpleName() + " being ticked."); + tt.addEntityCrashInfo(crashreportcategory); + throw new ReportedException(crashreport); + } + } - private void addToQueue( final TickTracker tt ) - { - tt.setLastTick( this.currentTick ); - this.upcomingTicks.add( tt ); - } + private void addToQueue(final TickTracker tt) { + tt.setLastTick(this.currentTick); + this.upcomingTicks.add(tt); + } - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof IGridTickable ) - { - this.alertable.remove( gridNode ); - this.sleeping.remove( gridNode ); - this.awake.remove( gridNode ); - } - } + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof IGridTickable) { + this.alertable.remove(gridNode); + this.sleeping.remove(gridNode); + this.awake.remove(gridNode); + } + } - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof IGridTickable ) - { - final IGridTickable tickable = ( (IGridTickable) machine ); - final TickingRequest tr = tickable.getTickingRequest( gridNode ); + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof IGridTickable) { + final IGridTickable tickable = ((IGridTickable) machine); + final TickingRequest tr = tickable.getTickingRequest(gridNode); - Preconditions.checkNotNull( tr ); + Preconditions.checkNotNull(tr); - final TickTracker tt = new TickTracker( tr, gridNode, (IGridTickable) machine, this.currentTick, this ); + final TickTracker tt = new TickTracker(tr, gridNode, (IGridTickable) machine, this.currentTick, this); - if( tr.canBeAlerted ) - { - this.alertable.put( gridNode, tt ); - } + if (tr.canBeAlerted) { + this.alertable.put(gridNode, tt); + } - if( tr.isSleeping ) - { - this.sleeping.put( gridNode, tt ); - } - else - { - this.awake.put( gridNode, tt ); - this.addToQueue( tt ); - } - } - } + if (tr.isSleeping) { + this.sleeping.put(gridNode, tt); + } else { + this.awake.put(gridNode, tt); + this.addToQueue(tt); + } + } + } - @Override - public void onSplit( final IGridStorage storageB ) - { + @Override + public void onSplit(final IGridStorage storageB) { - } + } - @Override - public void onJoin( final IGridStorage storageB ) - { + @Override + public void onJoin(final IGridStorage storageB) { - } + } - @Override - public void populateGridStorage( final IGridStorage storage ) - { + @Override + public void populateGridStorage(final IGridStorage storage) { - } + } - @Override - public boolean alertDevice( final IGridNode node ) - { - Preconditions.checkNotNull( node ); + @Override + public boolean alertDevice(final IGridNode node) { + Preconditions.checkNotNull(node); - final TickTracker tt = this.alertable.get( node ); - if( tt == null ) - { - return false; - } - // throw new RuntimeException( - // "Invalid alerted device, this node is not marked as alertable, or part of this grid." ); + final TickTracker tt = this.alertable.get(node); + if (tt == null) { + return false; + } + // throw new RuntimeException( + // "Invalid alerted device, this node is not marked as alertable, or part of this grid." ); - // set to awake, this is for sanity. - this.sleeping.remove( node ); - this.awake.put( node, tt ); + // set to awake, this is for sanity. + this.sleeping.remove(node); + this.awake.put(node, tt); - // configure sort. - tt.setLastTick( tt.getLastTick() - tt.getRequest().maxTickRate ); - tt.setCurrentRate( tt.getRequest().minTickRate ); + // configure sort. + tt.setLastTick(tt.getLastTick() - tt.getRequest().maxTickRate); + tt.setCurrentRate(tt.getRequest().minTickRate); - // prevent dupes and tick build up. - this.upcomingTicks.remove( tt ); - this.upcomingTicks.add( tt ); + // prevent dupes and tick build up. + this.upcomingTicks.remove(tt); + this.upcomingTicks.add(tt); - return true; - } + return true; + } - @Override - public boolean sleepDevice( final IGridNode node ) - { - Preconditions.checkNotNull( node ); + @Override + public boolean sleepDevice(final IGridNode node) { + Preconditions.checkNotNull(node); - if( this.awake.containsKey( node ) ) - { - final TickTracker gt = this.awake.get( node ); - this.awake.remove( node ); - this.sleeping.put( node, gt ); + if (this.awake.containsKey(node)) { + final TickTracker gt = this.awake.get(node); + this.awake.remove(node); + this.sleeping.put(node, gt); - return true; - } + return true; + } - return false; - } + return false; + } - @Override - public boolean wakeDevice( final IGridNode node ) - { - Preconditions.checkNotNull( node ); + @Override + public boolean wakeDevice(final IGridNode node) { + Preconditions.checkNotNull(node); - if( this.sleeping.containsKey( node ) ) - { - final TickTracker gt = this.sleeping.get( node ); - this.sleeping.remove( node ); - this.awake.put( node, gt ); - this.upcomingTicks.remove( gt ); - this.addToQueue( gt ); + if (this.sleeping.containsKey(node)) { + final TickTracker gt = this.sleeping.get(node); + this.sleeping.remove(node); + this.awake.put(node, gt); + this.upcomingTicks.remove(gt); + this.addToQueue(gt); - return true; - } + return true; + } - return false; - } + return false; + } } diff --git a/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java b/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java index 759a94080..31baf72f7 100644 --- a/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java +++ b/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java @@ -22,23 +22,19 @@ package appeng.me.cache.helpers; import appeng.api.networking.IGridConnection; -public class ConnectionWrapper -{ +public class ConnectionWrapper { - private IGridConnection connection; + private IGridConnection connection; - public ConnectionWrapper( final IGridConnection gc ) - { - this.setConnection( gc ); - } + public ConnectionWrapper(final IGridConnection gc) { + this.setConnection(gc); + } - public IGridConnection getConnection() - { - return this.connection; - } + public IGridConnection getConnection() { + return this.connection; + } - public void setConnection( final IGridConnection connection ) - { - this.connection = connection; - } + public void setConnection(final IGridConnection connection) { + this.connection = connection; + } } \ No newline at end of file diff --git a/src/main/java/appeng/me/cache/helpers/Connections.java b/src/main/java/appeng/me/cache/helpers/Connections.java index 295cb7ae5..5c9801753 100644 --- a/src/main/java/appeng/me/cache/helpers/Connections.java +++ b/src/main/java/appeng/me/cache/helpers/Connections.java @@ -19,70 +19,59 @@ package appeng.me.cache.helpers; -import java.util.HashMap; - -import net.minecraft.world.World; - import appeng.api.networking.IGridNode; import appeng.parts.p2p.PartP2PTunnelME; import appeng.util.IWorldCallable; +import net.minecraft.world.World; + +import java.util.HashMap; -public class Connections implements IWorldCallable -{ +public class Connections implements IWorldCallable { - private final HashMap connections = new HashMap<>(); - private final PartP2PTunnelME me; - private boolean create = false; - private boolean destroy = false; + private final HashMap connections = new HashMap<>(); + private final PartP2PTunnelME me; + private boolean create = false; + private boolean destroy = false; - public Connections( final PartP2PTunnelME o ) - { - this.me = o; - } + public Connections(final PartP2PTunnelME o) { + this.me = o; + } - @Override - public Void call( final World world ) throws Exception - { - this.me.updateConnections( this ); + @Override + public Void call(final World world) throws Exception { + this.me.updateConnections(this); - return null; - } + return null; + } - public void markDestroy() - { - this.setCreate( false ); - this.setDestroy( true ); - } + public void markDestroy() { + this.setCreate(false); + this.setDestroy(true); + } - public void markCreate() - { - this.setCreate( true ); - this.setDestroy( false ); - } + public void markCreate() { + this.setCreate(true); + this.setDestroy(false); + } - public HashMap getConnections() - { - return this.connections; - } + public HashMap getConnections() { + return this.connections; + } - public boolean isCreate() - { - return this.create; - } + public boolean isCreate() { + return this.create; + } - private void setCreate( final boolean create ) - { - this.create = create; - } + private void setCreate(final boolean create) { + this.create = create; + } - public boolean isDestroy() - { - return this.destroy; - } + public boolean isDestroy() { + return this.destroy; + } - private void setDestroy( final boolean destroy ) - { - this.destroy = destroy; - } + private void setDestroy(final boolean destroy) { + this.destroy = destroy; + } } diff --git a/src/main/java/appeng/me/cache/helpers/TickTracker.java b/src/main/java/appeng/me/cache/helpers/TickTracker.java index 730b48209..976b06ea8 100644 --- a/src/main/java/appeng/me/cache/helpers/TickTracker.java +++ b/src/main/java/appeng/me/cache/helpers/TickTracker.java @@ -19,124 +19,106 @@ package appeng.me.cache.helpers; -import javax.annotation.Nonnull; - -import net.minecraft.crash.CrashReportCategory; - import appeng.api.networking.IGridNode; import appeng.api.networking.ticking.IGridTickable; import appeng.api.networking.ticking.TickingRequest; import appeng.api.util.DimensionalCoord; import appeng.me.cache.TickManagerCache; import appeng.parts.AEBasePart; +import net.minecraft.crash.CrashReportCategory; + +import javax.annotation.Nonnull; -public class TickTracker implements Comparable -{ +public class TickTracker implements Comparable { - private final TickingRequest request; - private final IGridTickable gt; - private final IGridNode node; + private final TickingRequest request; + private final IGridTickable gt; + private final IGridNode node; - private final long LastFiveTicksTime = 0; + private final long LastFiveTicksTime = 0; - private long lastTick; - private int currentRate; + private long lastTick; + private int currentRate; - public TickTracker( final TickingRequest req, final IGridNode node, final IGridTickable gt, final long currentTick, final TickManagerCache tickManagerCache ) - { - this.request = req; - this.gt = gt; - this.node = node; - this.setCurrentRate( ( req.minTickRate + req.maxTickRate ) / 2 ); - this.setLastTick( currentTick ); - } + public TickTracker(final TickingRequest req, final IGridNode node, final IGridTickable gt, final long currentTick, final TickManagerCache tickManagerCache) { + this.request = req; + this.gt = gt; + this.node = node; + this.setCurrentRate((req.minTickRate + req.maxTickRate) / 2); + this.setLastTick(currentTick); + } - public long getAvgNanos() - { - return( this.LastFiveTicksTime / 5 ); - } + public long getAvgNanos() { + return (this.LastFiveTicksTime / 5); + } - @Override - public int compareTo( @Nonnull final TickTracker t ) - { - int next = Long.compare( this.getNextTick(), t.getNextTick() ); + @Override + public int compareTo(@Nonnull final TickTracker t) { + int next = Long.compare(this.getNextTick(), t.getNextTick()); - if( next != 0 ) - { - return next; - } + if (next != 0) { + return next; + } - int last = Long.compare( this.getLastTick(), t.getLastTick() ); + int last = Long.compare(this.getLastTick(), t.getLastTick()); - if( last != 0 ) - { - return last; - } + if (last != 0) { + return last; + } - return Integer.compare( this.getCurrentRate(), t.getCurrentRate() ); + return Integer.compare(this.getCurrentRate(), t.getCurrentRate()); - } + } - public void addEntityCrashInfo( final CrashReportCategory crashreportcategory ) - { - if( this.getGridTickable() instanceof AEBasePart ) - { - final AEBasePart part = (AEBasePart) this.getGridTickable(); - part.addEntityCrashInfo( crashreportcategory ); - } + public void addEntityCrashInfo(final CrashReportCategory crashreportcategory) { + if (this.getGridTickable() instanceof AEBasePart) { + final AEBasePart part = (AEBasePart) this.getGridTickable(); + part.addEntityCrashInfo(crashreportcategory); + } - crashreportcategory.addCrashSection( "CurrentTickRate", this.getCurrentRate() ); - crashreportcategory.addCrashSection( "MinTickRate", this.getRequest().minTickRate ); - crashreportcategory.addCrashSection( "MaxTickRate", this.getRequest().maxTickRate ); - crashreportcategory.addCrashSection( "MachineType", this.getGridTickable().getClass().getName() ); - crashreportcategory.addCrashSection( "GridBlockType", this.getNode().getGridBlock().getClass().getName() ); - crashreportcategory.addCrashSection( "ConnectedSides", this.getNode().getConnectedSides() ); + crashreportcategory.addCrashSection("CurrentTickRate", this.getCurrentRate()); + crashreportcategory.addCrashSection("MinTickRate", this.getRequest().minTickRate); + crashreportcategory.addCrashSection("MaxTickRate", this.getRequest().maxTickRate); + crashreportcategory.addCrashSection("MachineType", this.getGridTickable().getClass().getName()); + crashreportcategory.addCrashSection("GridBlockType", this.getNode().getGridBlock().getClass().getName()); + crashreportcategory.addCrashSection("ConnectedSides", this.getNode().getConnectedSides()); - final DimensionalCoord dc = this.getNode().getGridBlock().getLocation(); - if( dc != null ) - { - crashreportcategory.addCrashSection( "Location", dc ); - } - } + final DimensionalCoord dc = this.getNode().getGridBlock().getLocation(); + if (dc != null) { + crashreportcategory.addCrashSection("Location", dc); + } + } - public int getCurrentRate() - { - return this.currentRate; - } + public int getCurrentRate() { + return this.currentRate; + } - public void setCurrentRate( final int currentRate ) - { - this.currentRate = Math.min( this.getRequest().maxTickRate, Math.max( this.getRequest().minTickRate, currentRate ) ); - } + public void setCurrentRate(final int currentRate) { + this.currentRate = Math.min(this.getRequest().maxTickRate, Math.max(this.getRequest().minTickRate, currentRate)); + } - public long getNextTick() - { - return this.lastTick + this.currentRate; - } + public long getNextTick() { + return this.lastTick + this.currentRate; + } - public long getLastTick() - { - return this.lastTick; - } + public long getLastTick() { + return this.lastTick; + } - public void setLastTick( final long lastTick ) - { - this.lastTick = lastTick; - } + public void setLastTick(final long lastTick) { + this.lastTick = lastTick; + } - public IGridNode getNode() - { - return this.node; - } + public IGridNode getNode() { + return this.node; + } - public IGridTickable getGridTickable() - { - return this.gt; - } + public IGridTickable getGridTickable() { + return this.gt; + } - public TickingRequest getRequest() - { - return this.request; - } + public TickingRequest getRequest() { + return this.request; + } } diff --git a/src/main/java/appeng/me/cache/helpers/TunnelCollection.java b/src/main/java/appeng/me/cache/helpers/TunnelCollection.java index 9d6220ca4..a03bf6234 100644 --- a/src/main/java/appeng/me/cache/helpers/TunnelCollection.java +++ b/src/main/java/appeng/me/cache/helpers/TunnelCollection.java @@ -19,58 +19,49 @@ package appeng.me.cache.helpers; -import java.util.Collection; -import java.util.Iterator; - import appeng.parts.p2p.PartP2PTunnel; import appeng.util.iterators.NullIterator; +import java.util.Collection; +import java.util.Iterator; -public class TunnelCollection implements Iterable -{ - private final Class clz; - private Collection tunnelSources; +public class TunnelCollection implements Iterable { - public TunnelCollection( final Collection src, final Class c ) - { - this.tunnelSources = src; - this.clz = c; - } + private final Class clz; + private Collection tunnelSources; - public void setSource( final Collection c ) - { - this.tunnelSources = c; - } + public TunnelCollection(final Collection src, final Class c) { + this.tunnelSources = src; + this.clz = c; + } - public boolean isEmpty() - { - return !this.iterator().hasNext(); - } + public void setSource(final Collection c) { + this.tunnelSources = c; + } - @Override - public Iterator iterator() - { - if( this.tunnelSources == null ) - { - return new NullIterator<>(); - } - return new TunnelIterator<>( this.tunnelSources, this.clz ); - } + public boolean isEmpty() { + return !this.iterator().hasNext(); + } - public boolean matches( final Class c ) - { - return this.clz == c; - } + @Override + public Iterator iterator() { + if (this.tunnelSources == null) { + return new NullIterator<>(); + } + return new TunnelIterator<>(this.tunnelSources, this.clz); + } - public Class getClz() - { - return this.clz; - } + public boolean matches(final Class c) { + return this.clz == c; + } - public int size() - { - return this.tunnelSources == null ? 0 : this.tunnelSources.size(); - } + public Class getClz() { + return this.clz; + } + + public int size() { + return this.tunnelSources == null ? 0 : this.tunnelSources.size(); + } } diff --git a/src/main/java/appeng/me/cache/helpers/TunnelConnection.java b/src/main/java/appeng/me/cache/helpers/TunnelConnection.java index b4abb1b34..a92f9c772 100644 --- a/src/main/java/appeng/me/cache/helpers/TunnelConnection.java +++ b/src/main/java/appeng/me/cache/helpers/TunnelConnection.java @@ -23,25 +23,21 @@ import appeng.api.networking.IGridConnection; import appeng.parts.p2p.PartP2PTunnelME; -public class TunnelConnection -{ +public class TunnelConnection { - private final PartP2PTunnelME tunnel; - private final IGridConnection c; + private final PartP2PTunnelME tunnel; + private final IGridConnection c; - public TunnelConnection( final PartP2PTunnelME t, final IGridConnection con ) - { - this.tunnel = t; - this.c = con; - } + public TunnelConnection(final PartP2PTunnelME t, final IGridConnection con) { + this.tunnel = t; + this.c = con; + } - public IGridConnection getConnection() - { - return this.c; - } + public IGridConnection getConnection() { + return this.c; + } - public PartP2PTunnelME getTunnel() - { - return this.tunnel; - } + public PartP2PTunnelME getTunnel() { + return this.tunnel; + } } \ No newline at end of file diff --git a/src/main/java/appeng/me/cache/helpers/TunnelIterator.java b/src/main/java/appeng/me/cache/helpers/TunnelIterator.java index 3e86f1207..c3c03c1e4 100644 --- a/src/main/java/appeng/me/cache/helpers/TunnelIterator.java +++ b/src/main/java/appeng/me/cache/helpers/TunnelIterator.java @@ -19,56 +19,48 @@ package appeng.me.cache.helpers; +import appeng.parts.p2p.PartP2PTunnel; + import java.util.Collection; import java.util.Iterator; -import appeng.parts.p2p.PartP2PTunnel; +public class TunnelIterator implements Iterator { -public class TunnelIterator implements Iterator -{ + private final Iterator wrapped; + private final Class targetType; + private T Next; - private final Iterator wrapped; - private final Class targetType; - private T Next; + public TunnelIterator(final Collection tunnelSources, final Class clz) { + this.wrapped = tunnelSources.iterator(); + this.targetType = clz; + this.findNext(); + } - public TunnelIterator( final Collection tunnelSources, final Class clz ) - { - this.wrapped = tunnelSources.iterator(); - this.targetType = clz; - this.findNext(); - } + private void findNext() { + while (this.Next == null && this.wrapped.hasNext()) { + this.Next = this.wrapped.next(); + if (!this.targetType.isInstance(this.Next)) { + this.Next = null; + } + } + } - private void findNext() - { - while( this.Next == null && this.wrapped.hasNext() ) - { - this.Next = this.wrapped.next(); - if( !this.targetType.isInstance( this.Next ) ) - { - this.Next = null; - } - } - } + @Override + public boolean hasNext() { + this.findNext(); + return this.Next != null; + } - @Override - public boolean hasNext() - { - this.findNext(); - return this.Next != null; - } + @Override + public T next() { + final T tmp = this.Next; + this.Next = null; + return tmp; + } - @Override - public T next() - { - final T tmp = this.Next; - this.Next = null; - return tmp; - } - - @Override - public void remove() - { - // no. - } + @Override + public void remove() { + // no. + } } diff --git a/src/main/java/appeng/me/cluster/IAECluster.java b/src/main/java/appeng/me/cluster/IAECluster.java index 23944f755..8a148f305 100644 --- a/src/main/java/appeng/me/cluster/IAECluster.java +++ b/src/main/java/appeng/me/cluster/IAECluster.java @@ -19,17 +19,16 @@ package appeng.me.cluster; -import java.util.Iterator; - import appeng.api.networking.IGridHost; +import java.util.Iterator; -public interface IAECluster -{ - void updateStatus( boolean updateGrid ); +public interface IAECluster { - void destroy(); + void updateStatus(boolean updateGrid); - Iterator getTiles(); + void destroy(); + + Iterator getTiles(); } diff --git a/src/main/java/appeng/me/cluster/IAEMultiBlock.java b/src/main/java/appeng/me/cluster/IAEMultiBlock.java index 8dc36f998..0e7016c56 100644 --- a/src/main/java/appeng/me/cluster/IAEMultiBlock.java +++ b/src/main/java/appeng/me/cluster/IAEMultiBlock.java @@ -19,12 +19,11 @@ package appeng.me.cluster; -public interface IAEMultiBlock -{ +public interface IAEMultiBlock { - void disconnect( boolean b ); + void disconnect(boolean b); - IAECluster getCluster(); + IAECluster getCluster(); - boolean isValid(); + boolean isValid(); } diff --git a/src/main/java/appeng/me/cluster/MBCalculator.java b/src/main/java/appeng/me/cluster/MBCalculator.java index 2a352b72d..a09b139e6 100644 --- a/src/main/java/appeng/me/cluster/MBCalculator.java +++ b/src/main/java/appeng/me/cluster/MBCalculator.java @@ -19,222 +19,186 @@ package appeng.me.cluster; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import appeng.api.util.AEPartLocation; import appeng.api.util.WorldCoord; import appeng.core.AELog; import appeng.util.Platform; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; -public abstract class MBCalculator -{ +public abstract class MBCalculator { - private final IAEMultiBlock target; + private final IAEMultiBlock target; - public MBCalculator( final IAEMultiBlock t ) - { - this.target = t; - } + public MBCalculator(final IAEMultiBlock t) { + this.target = t; + } - public void calculateMultiblock( final World world, final WorldCoord loc ) - { - if( Platform.isClient() ) - { - return; - } + public void calculateMultiblock(final World world, final WorldCoord loc) { + if (Platform.isClient()) { + return; + } - try - { - final WorldCoord min = loc.copy(); - final WorldCoord max = loc.copy(); + try { + final WorldCoord min = loc.copy(); + final WorldCoord max = loc.copy(); - // find size of MB structure... - while( this.isValidTileAt( world, min.x - 1, min.y, min.z ) ) - { - min.x--; - } - while( this.isValidTileAt( world, min.x, min.y - 1, min.z ) ) - { - min.y--; - } - while( this.isValidTileAt( world, min.x, min.y, min.z - 1 ) ) - { - min.z--; - } - while( this.isValidTileAt( world, max.x + 1, max.y, max.z ) ) - { - max.x++; - } - while( this.isValidTileAt( world, max.x, max.y + 1, max.z ) ) - { - max.y++; - } - while( this.isValidTileAt( world, max.x, max.y, max.z + 1 ) ) - { - max.z++; - } + // find size of MB structure... + while (this.isValidTileAt(world, min.x - 1, min.y, min.z)) { + min.x--; + } + while (this.isValidTileAt(world, min.x, min.y - 1, min.z)) { + min.y--; + } + while (this.isValidTileAt(world, min.x, min.y, min.z - 1)) { + min.z--; + } + while (this.isValidTileAt(world, max.x + 1, max.y, max.z)) { + max.x++; + } + while (this.isValidTileAt(world, max.x, max.y + 1, max.z)) { + max.y++; + } + while (this.isValidTileAt(world, max.x, max.y, max.z + 1)) { + max.z++; + } - if( this.checkMultiblockScale( min, max ) ) - { - if( this.verifyUnownedRegion( world, min, max ) ) - { - IAECluster c = this.createCluster( world, min, max ); + if (this.checkMultiblockScale(min, max)) { + if (this.verifyUnownedRegion(world, min, max)) { + IAECluster c = this.createCluster(world, min, max); - try - { - if( !this.verifyInternalStructure( world, min, max ) ) - { - this.disconnect(); - return; - } - } - catch( final Exception err ) - { - this.disconnect(); - return; - } + try { + if (!this.verifyInternalStructure(world, min, max)) { + this.disconnect(); + return; + } + } catch (final Exception err) { + this.disconnect(); + return; + } - boolean updateGrid = false; - final IAECluster cluster = this.target.getCluster(); - if( cluster == null ) - { - this.updateTiles( c, world, min, max ); + boolean updateGrid = false; + final IAECluster cluster = this.target.getCluster(); + if (cluster == null) { + this.updateTiles(c, world, min, max); - updateGrid = true; - } - else - { - c = cluster; - } + updateGrid = true; + } else { + c = cluster; + } - c.updateStatus( updateGrid ); - return; - } - } - } - catch( final Throwable err ) - { - AELog.debug( err ); - } + c.updateStatus(updateGrid); + return; + } + } + } catch (final Throwable err) { + AELog.debug(err); + } - this.disconnect(); - } + this.disconnect(); + } - private boolean isValidTileAt( final World w, final int x, final int y, final int z ) - { - return this.isValidTile( w.getTileEntity( new BlockPos( x, y, z ) ) ); - } + private boolean isValidTileAt(final World w, final int x, final int y, final int z) { + return this.isValidTile(w.getTileEntity(new BlockPos(x, y, z))); + } - /** - * verify if the structure is the correct dimensions, or size - * - * @param min min world coord - * @param max max world coord - * - * @return true if structure has correct dimensions or size - */ - public abstract boolean checkMultiblockScale( WorldCoord min, WorldCoord max ); + /** + * verify if the structure is the correct dimensions, or size + * + * @param min min world coord + * @param max max world coord + * @return true if structure has correct dimensions or size + */ + public abstract boolean checkMultiblockScale(WorldCoord min, WorldCoord max); - private boolean verifyUnownedRegion( final World w, final WorldCoord min, final WorldCoord max ) - { - for( final AEPartLocation side : AEPartLocation.SIDE_LOCATIONS ) - { - if( this.verifyUnownedRegionInner( w, min.x, min.y, min.z, max.x, max.y, max.z, side ) ) - { - return false; - } - } + private boolean verifyUnownedRegion(final World w, final WorldCoord min, final WorldCoord max) { + for (final AEPartLocation side : AEPartLocation.SIDE_LOCATIONS) { + if (this.verifyUnownedRegionInner(w, min.x, min.y, min.z, max.x, max.y, max.z, side)) { + return false; + } + } - return true; - } + return true; + } - /** - * construct the correct cluster, usually very simple. - * - * @param w world - * @param min min world coord - * @param max max world coord - * - * @return created cluster - */ - public abstract IAECluster createCluster( World w, WorldCoord min, WorldCoord max ); + /** + * construct the correct cluster, usually very simple. + * + * @param w world + * @param min min world coord + * @param max max world coord + * @return created cluster + */ + public abstract IAECluster createCluster(World w, WorldCoord min, WorldCoord max); - public abstract boolean verifyInternalStructure( World world, WorldCoord min, WorldCoord max ); + public abstract boolean verifyInternalStructure(World world, WorldCoord min, WorldCoord max); - /** - * disassembles the multi-block. - */ - public abstract void disconnect(); + /** + * disassembles the multi-block. + */ + public abstract void disconnect(); - /** - * configure the multi-block tiles, most of the important stuff is in here. - * - * @param c updated cluster - * @param w in world - * @param min min world coord - * @param max max world coord - */ - public abstract void updateTiles( IAECluster c, World w, WorldCoord min, WorldCoord max ); + /** + * configure the multi-block tiles, most of the important stuff is in here. + * + * @param c updated cluster + * @param w in world + * @param min min world coord + * @param max max world coord + */ + public abstract void updateTiles(IAECluster c, World w, WorldCoord min, WorldCoord max); - /** - * check if the tile entities are correct for the structure. - * - * @param te to be checked tile entity - * - * @return true if tile entity is valid for structure - */ - public abstract boolean isValidTile( TileEntity te ); + /** + * check if the tile entities are correct for the structure. + * + * @param te to be checked tile entity + * @return true if tile entity is valid for structure + */ + public abstract boolean isValidTile(TileEntity te); - private boolean verifyUnownedRegionInner( final World w, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, final AEPartLocation side ) - { - switch( side ) - { - case WEST: - minX -= 1; - maxX = minX; - break; - case EAST: - maxX += 1; - minX = maxX; - break; - case DOWN: - minY -= 1; - maxY = minY; - break; - case NORTH: - maxZ += 1; - minZ = maxZ; - break; - case SOUTH: - minZ -= 1; - maxZ = minZ; - break; - case UP: - maxY += 1; - minY = maxY; - break; - case INTERNAL: - return false; - } + private boolean verifyUnownedRegionInner(final World w, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, final AEPartLocation side) { + switch (side) { + case WEST: + minX -= 1; + maxX = minX; + break; + case EAST: + maxX += 1; + minX = maxX; + break; + case DOWN: + minY -= 1; + maxY = minY; + break; + case NORTH: + maxZ += 1; + minZ = maxZ; + break; + case SOUTH: + minZ -= 1; + maxZ = minZ; + break; + case UP: + maxY += 1; + minY = maxY; + break; + case INTERNAL: + return false; + } - for( int x = minX; x <= maxX; x++ ) - { - for( int y = minY; y <= maxY; y++ ) - { - for( int z = minZ; z <= maxZ; z++ ) - { - final TileEntity te = w.getTileEntity( new BlockPos( x, y, z ) ); - if( this.isValidTile( te ) ) - { - return true; - } - } - } - } + for (int x = minX; x <= maxX; x++) { + for (int y = minY; y <= maxY; y++) { + for (int z = minZ; z <= maxZ; z++) { + final TileEntity te = w.getTileEntity(new BlockPos(x, y, z)); + if (this.isValidTile(te)) { + return true; + } + } + } + } - return false; - } + return false; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java index a95aa7c5d..beed83000 100644 --- a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java +++ b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java @@ -19,12 +19,6 @@ package appeng.me.cluster.implementations; -import java.util.Iterator; - -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -35,121 +29,100 @@ import appeng.me.cluster.IAECluster; import appeng.me.cluster.IAEMultiBlock; import appeng.me.cluster.MBCalculator; import appeng.tile.crafting.TileCraftingTile; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +import java.util.Iterator; -public class CraftingCPUCalculator extends MBCalculator -{ +public class CraftingCPUCalculator extends MBCalculator { - private final TileCraftingTile tqb; + private final TileCraftingTile tqb; - public CraftingCPUCalculator( final IAEMultiBlock t ) - { - super( t ); - this.tqb = (TileCraftingTile) t; - } + public CraftingCPUCalculator(final IAEMultiBlock t) { + super(t); + this.tqb = (TileCraftingTile) t; + } - @Override - public boolean checkMultiblockScale( final WorldCoord min, final WorldCoord max ) - { - if( max.x - min.x > 16 ) - { - return false; - } + @Override + public boolean checkMultiblockScale(final WorldCoord min, final WorldCoord max) { + if (max.x - min.x > 16) { + return false; + } - if( max.y - min.y > 16 ) - { - return false; - } + if (max.y - min.y > 16) { + return false; + } - if( max.z - min.z > 16 ) - { - return false; - } + return max.z - min.z <= 16; + } - return true; - } + @Override + public IAECluster createCluster(final World w, final WorldCoord min, final WorldCoord max) { + return new CraftingCPUCluster(min, max); + } - @Override - public IAECluster createCluster( final World w, final WorldCoord min, final WorldCoord max ) - { - return new CraftingCPUCluster( min, max ); - } + @Override + public boolean verifyInternalStructure(final World w, final WorldCoord min, final WorldCoord max) { + boolean storage = false; - @Override - public boolean verifyInternalStructure( final World w, final WorldCoord min, final WorldCoord max ) - { - boolean storage = false; + for (int x = min.x; x <= max.x; x++) { + for (int y = min.y; y <= max.y; y++) { + for (int z = min.z; z <= max.z; z++) { + final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity(new BlockPos(x, y, z)); - for( int x = min.x; x <= max.x; x++ ) - { - for( int y = min.y; y <= max.y; y++ ) - { - for( int z = min.z; z <= max.z; z++ ) - { - final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity( new BlockPos( x, y, z ) ); + if (!te.isValid()) { + return false; + } - if( !te.isValid() ) - { - return false; - } + if (!storage && te instanceof TileCraftingTile) { + storage = ((TileCraftingTile) te).getStorageBytes() > 0; + } + } + } + } - if( !storage && te instanceof TileCraftingTile ) - { - storage = ( (TileCraftingTile) te ).getStorageBytes() > 0; - } - } - } - } + return storage; + } - return storage; - } + @Override + public void disconnect() { + this.tqb.disconnect(true); + } - @Override - public void disconnect() - { - this.tqb.disconnect( true ); - } + @Override + public void updateTiles(final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max) { + final CraftingCPUCluster c = (CraftingCPUCluster) cl; - @Override - public void updateTiles( final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max ) - { - final CraftingCPUCluster c = (CraftingCPUCluster) cl; + for (int x = min.x; x <= max.x; x++) { + for (int y = min.y; y <= max.y; y++) { + for (int z = min.z; z <= max.z; z++) { + final TileCraftingTile te = (TileCraftingTile) w.getTileEntity(new BlockPos(x, y, z)); + te.updateStatus(c); + c.addTile(te); + } + } + } - for( int x = min.x; x <= max.x; x++ ) - { - for( int y = min.y; y <= max.y; y++ ) - { - for( int z = min.z; z <= max.z; z++ ) - { - final TileCraftingTile te = (TileCraftingTile) w.getTileEntity( new BlockPos( x, y, z ) ); - te.updateStatus( c ); - c.addTile( te ); - } - } - } + c.done(); - c.done(); + final Iterator i = c.getTiles(); + while (i.hasNext()) { + final IGridHost gh = i.next(); + final IGridNode n = gh.getGridNode(AEPartLocation.INTERNAL); + if (n != null) { + final IGrid g = n.getGrid(); + if (g != null) { + g.postEvent(new MENetworkCraftingCpuChange(n)); + return; + } + } + } + } - final Iterator i = c.getTiles(); - while( i.hasNext() ) - { - final IGridHost gh = i.next(); - final IGridNode n = gh.getGridNode( AEPartLocation.INTERNAL ); - if( n != null ) - { - final IGrid g = n.getGrid(); - if( g != null ) - { - g.postEvent( new MENetworkCraftingCpuChange( n ) ); - return; - } - } - } - } - - @Override - public boolean isValidTile( final TileEntity te ) - { - return te instanceof TileCraftingTile; - } + @Override + public boolean isValidTile(final TileEntity te) { + return te instanceof TileCraftingTile; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java index 2bbf85fa1..7b248d663 100644 --- a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java +++ b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java @@ -19,22 +19,6 @@ package appeng.me.cluster.implementations; -import java.util.*; -import java.util.Map.Entry; -import java.util.stream.Collectors; - -import appeng.api.config.Upgrades; -import appeng.helpers.DualityInterface; -import appeng.helpers.PatternHelper; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; - -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.world.World; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.FuzzyMode; @@ -43,14 +27,7 @@ import appeng.api.implementations.ICraftingPatternItem; import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; -import appeng.api.networking.crafting.CraftingItemList; -import appeng.api.networking.crafting.ICraftingCPU; -import appeng.api.networking.crafting.ICraftingGrid; -import appeng.api.networking.crafting.ICraftingJob; -import appeng.api.networking.crafting.ICraftingLink; -import appeng.api.networking.crafting.ICraftingMedium; -import appeng.api.networking.crafting.ICraftingPatternDetails; -import appeng.api.networking.crafting.ICraftingRequester; +import appeng.api.networking.crafting.*; import appeng.api.networking.energy.IEnergyGrid; import appeng.api.networking.events.MENetworkCraftingCpuChange; import appeng.api.networking.security.IActionSource; @@ -63,11 +40,8 @@ import appeng.api.storage.data.IItemList; import appeng.api.util.WorldCoord; import appeng.container.ContainerNull; import appeng.core.AELog; -import appeng.crafting.CraftBranchFailure; -import appeng.crafting.CraftingJob; -import appeng.crafting.CraftingLink; -import appeng.crafting.CraftingWatcher; -import appeng.crafting.MECraftingInventory; +import appeng.crafting.*; +import appeng.helpers.PatternHelper; import appeng.me.cache.CraftingGridCache; import appeng.me.cluster.IAECluster; import appeng.me.helpers.MachineSource; @@ -75,1383 +49,1155 @@ import appeng.tile.crafting.TileCraftingMonitorTile; import appeng.tile.crafting.TileCraftingTile; import appeng.util.Platform; import appeng.util.item.AEItemStack; - - -public final class CraftingCPUCluster implements IAECluster, ICraftingCPU -{ - - private static final String LOG_MARK_AS_COMPLETE = "Completed job for %s."; - - private final WorldCoord min; - private final WorldCoord max; - private final int[] usedOps = new int[3]; - private final Map tasks = new HashMap<>(); - // INSTANCE sate - private final List tiles = new ArrayList<>(); - private final List storage = new ArrayList<>(); - private final List status = new ArrayList<>(); - private final HashMap, Object> listeners = new HashMap<>(); - private final Map> visitedMediums = new HashMap<>(); - private ICraftingLink myLastLink; - private String myName = ""; - private boolean isDestroyed = false; - /** - * crafting job info - */ - private MECraftingInventory inventory = new MECraftingInventory(); - private IAEItemStack finalOutput; - private boolean waiting = false; - private IItemList waitingFor = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - private long availableStorage = 0; - private MachineSource machineSrc = null; - private int accelerator = 0; - private boolean isComplete = true; - private int remainingOperations; - private boolean somethingChanged; - - private long lastTime; - private long elapsedTime; - private long startItemCount; - private long remainingItemCount; - - public CraftingCPUCluster( final WorldCoord min, final WorldCoord max ) - { - this.min = min; - this.max = max; - } - - @Override - public IAEItemStack getFinalOutput() - { - return finalOutput; - } - - public boolean isDestroyed() - { - return this.isDestroyed; - } - - public ICraftingLink getLastCraftingLink() - { - return this.myLastLink; - } - - /** - * add a new Listener to the monitor, be sure to properly remove yourself when your done. - */ - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } - - /** - * remove a Listener to the monitor. - */ - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } - - public IMEInventory getInventory() - { - return this.inventory; - } - - @Override - public void updateStatus( final boolean updateGrid ) - { - for( final TileCraftingTile r : this.tiles ) - { - r.updateMeta( true ); - } - } - - @Override - public void destroy() - { - if( this.isDestroyed ) - { - return; - } - this.isDestroyed = true; - - boolean posted = false; - - for( final TileCraftingTile r : this.tiles ) - { - final IGridNode n = r.getActionableNode(); - if( n != null && !posted ) - { - final IGrid g = n.getGrid(); - if( g != null ) - { - g.postEvent( new MENetworkCraftingCpuChange( n ) ); - posted = true; - } - } - - r.updateStatus( null ); - } - } - - @Override - public Iterator getTiles() - { - return (Iterator) this.tiles.iterator(); - } - - void addTile( final TileCraftingTile te ) - { - if( this.machineSrc == null || te.isCoreBlock() ) - { - this.machineSrc = new MachineSource( te ); - } - - te.setCoreBlock( false ); - te.saveChanges(); - this.tiles.add( 0, te ); - - if( te.isStorage() ) - { - this.availableStorage += te.getStorageBytes(); - this.storage.add( te ); - } - else if( te.isStatus() ) - { - this.status.add( (TileCraftingMonitorTile) te ); - } - else if( te.isAccelerator() ) - { - this.accelerator++; - } - } - - public boolean canAccept( final IAEItemStack input ) - { - if( input instanceof IAEItemStack ) - { - final IAEItemStack is = this.waitingFor.findPrecise( input ); - if( is != null && is.getStackSize() > 0 ) - { - return true; - } - } - return false; - } - - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final IActionSource src ) - { - // also stop accepting items when the job is complete, i.e. to prevent re-insertion when pushing out - // items during storeItems - if( input == null || isComplete ) - { - return input; - } - - final IAEItemStack what = input.copy(); - final IAEItemStack is = this.waitingFor.findPrecise( what ); - - if( type == Actionable.SIMULATE )// causes crafting to lock up? - { - if( is != null && is.getStackSize() > 0 ) - { - if( is.getStackSize() >= what.getStackSize() ) - { - if( this.finalOutput.equals( what ) ) - { - if( this.myLastLink != null ) - { - return ( (CraftingLink) this.myLastLink ).injectItems( what.copy(), type ); - } - - return what; // ignore it. - } - - return null; - } - - final IAEItemStack leftOver = what.copy(); - leftOver.decStackSize( is.getStackSize() ); - - final IAEItemStack used = what.copy(); - used.setStackSize( is.getStackSize() ); - - if( this.finalOutput.equals( what ) ) - { - if( this.myLastLink != null ) - { - leftOver.add( ( (CraftingLink) this.myLastLink ).injectItems( used.copy(), type ) ); - return leftOver; - } - - return what; // ignore it. - } - - return leftOver; - } - } - else if( type == Actionable.MODULATE ) - { - if( is != null && is.getStackSize() > 0 ) - { - this.waiting = false; - - this.postChange( what, src ); - - if( is.getStackSize() >= what.getStackSize() ) - { - is.decStackSize( what.getStackSize() ); - - this.updateRemainingItemCount( what ); - this.markDirty(); - this.postCraftingStatusChange( what.copy().setStackSize( -what.getStackSize() ) ); - - if( this.finalOutput.equals( what ) ) - { - IAEItemStack leftover = what; - - this.finalOutput.decStackSize( what.getStackSize() ); - - if( this.myLastLink != null ) - { - leftover = ( (CraftingLink) this.myLastLink ).injectItems( what, type ); - } - - if( this.finalOutput.getStackSize() <= 0 ) - { - this.completeJob(); - } - - this.updateCPU(); - - return leftover; // ignore it. - } - - // 2000 - return this.inventory.injectItems( what, type, src ); - } - - final IAEItemStack insert = what.copy(); - insert.setStackSize( is.getStackSize() ); - what.decStackSize( is.getStackSize() ); - - is.setStackSize( 0 ); - this.postCraftingStatusChange( insert.copy().setStackSize( -insert.getStackSize() ) ); - - if( this.finalOutput.equals( insert ) ) - { - IAEItemStack leftover = input; - - this.finalOutput.decStackSize( insert.getStackSize() ); - - if( this.myLastLink != null ) - { - what.add( ( (CraftingLink) this.myLastLink ).injectItems( insert.copy(), type ) ); - leftover = what; - } - - if( this.finalOutput.getStackSize() <= 0 ) - { - this.completeJob(); - } - - this.updateCPU(); - this.markDirty(); - - return leftover; // ignore it. - } - - this.inventory.injectItems( insert, type, src ); - this.markDirty(); - - return what; - } - } - - return input; - } - - private void postChange( final IAEItemStack diff, final IActionSource src ) - { - final Iterator, Object>> i = this.getListeners(); - - // protect integrity - if( i.hasNext() ) - { - final ImmutableList single = ImmutableList.of( diff.copy() ); - - while ( i.hasNext() ) - { - final Entry, Object> o = i.next(); - final IMEMonitorHandlerReceiver receiver = o.getKey(); - - if( receiver.isValid( o.getValue() ) ) - { - receiver.postChange( null, single, src ); - } - else - { - i.remove(); - } - } - } - - } - - private void markDirty() - { - this.getCore().saveChanges(); - } - - private void postCraftingStatusChange( final IAEItemStack diff ) - { - if( this.getGrid() == null ) - { - return; - } - - final CraftingGridCache sg = this.getGrid().getCache( ICraftingGrid.class ); - - if( sg.getInterestManager().containsKey( diff ) ) - { - final Collection list = sg.getInterestManager().get( diff ); - - if( !list.isEmpty() ) - { - for( final CraftingWatcher iw : list ) - - { - iw.getHost().onRequestChange( sg, diff ); - } - } - } - } - - private void completeJob() - { - if( this.myLastLink != null ) - { - ( (CraftingLink) this.myLastLink ).markDone(); - } - - if( AELog.isCraftingLogEnabled() ) - { - final IAEItemStack logStack = this.finalOutput.copy(); - logStack.setStackSize( this.startItemCount ); - AELog.crafting( LOG_MARK_AS_COMPLETE, logStack ); - } - - // Waiting for can potentially contain items at this point, if the user has a 64xplank->64xbutton processing - // recipe for example, but only requested 1xbutton. We just ignore the rest since it will be dumped - // back into the network inventory regardless. For this to work it's important that injectItems in this CPU - // does not accept any further items if isComplete is true. - this.waitingFor.resetStatus(); - this.remainingItemCount = 0; - this.startItemCount = 0; - this.lastTime = 0; - this.elapsedTime = 0; - this.isComplete = true; - } - - private void updateCPU() - { - IAEItemStack send = this.finalOutput; - - if( this.finalOutput != null && this.finalOutput.getStackSize() <= 0 ) - { - send = null; - } - - for( final TileCraftingMonitorTile t : this.status ) - { - t.setJob( send ); - } - } - - private Iterator, Object>> getListeners() - { - return this.listeners.entrySet().iterator(); - } - - private TileCraftingTile getCore() - { - if( this.machineSrc == null ) - { - return null; - } - return (TileCraftingTile) this.machineSrc.machine().get(); - } - - private IGrid getGrid() - { - for( final TileCraftingTile r : this.tiles ) - { - final IGridNode gn = r.getActionableNode(); - if( gn != null ) - { - final IGrid g = gn.getGrid(); - if( g != null ) - { - return r.getActionableNode().getGrid(); - } - } - } - - return null; - } - - private boolean canCraft( final ICraftingPatternDetails details, final IAEItemStack[] condensedInputs ) - { - if( !details.isCraftable() ) - { - // Processing patterns are relatively easy - for( IAEItemStack input : condensedInputs ) - { - final IAEItemStack ais = this.inventory.extractItems( input.copy(), Actionable.SIMULATE, this.machineSrc ); - - if( ais == null || ais.getStackSize() < input.getStackSize() ) - { - return false; - } - } - } - else if( details.canSubstitute() ) - { - // When substitutions are allowed, we have to keep track of which items we've reserved - IAEItemStack[] inputs = details.getInputs(); - Map consumedCount = new HashMap<>(); - for( int i = 0; i < inputs.length; i++ ) - { - List substitutes = details.getSubstituteInputs( i ); - if( substitutes.isEmpty() ) - { - continue; - } - - boolean found = false; - for( IAEItemStack substitute : substitutes ) - { - for( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( substitute, FuzzyMode.IGNORE_ALL ) ) - { - int alreadyConsumed = consumedCount.getOrDefault( fuzz, 0 ); - if( fuzz.getStackSize() - alreadyConsumed <= 0 ) - { - continue; // Already fully consumed by a previous slot of this recipe - } - - fuzz = fuzz.copy(); - fuzz.setStackSize( 1 ); // We're iterating over non condensed inputs which means there's 1 of each needed - final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.SIMULATE, this.machineSrc ); - - if( ais != null && ais.getStackSize() > 0 ) - { - // Mark 1 of the stack as consumed - consumedCount.merge( fuzz, 1, Integer::sum ); - found = true; - break; - } - } - if( found ) - { - break; - } - } - - if( !found ) - { - return false; - } - } - - } - else - { - // When no substitutions can occur, we can simply check that all items are accounted since - // each type of item should only occur once - for( IAEItemStack g : condensedInputs ) - { - boolean found = false; - - for( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( g, FuzzyMode.IGNORE_ALL ) ) - { - fuzz = fuzz.copy(); - fuzz.setStackSize( g.getStackSize() ); - final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.SIMULATE, this.machineSrc ); - - if( ais != null && ais.getStackSize() >= g.getStackSize() ) - { - found = true; - break; - } - else if( ais != null ) - { - g = g.copy(); - g.decStackSize( ais.getStackSize() ); - } - } - - if( !found ) - { - return false; - } - } - - } - - return true; - } - - public void cancel() - { - if( this.myLastLink != null ) - { - this.myLastLink.cancel(); - } - - final IItemList list; - this.getListOfItem( list = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(), CraftingItemList.ALL ); - for( final IAEItemStack is : list ) - { - this.postChange( is, this.machineSrc ); - } - - this.isComplete = true; - this.myLastLink = null; - this.tasks.clear(); - - // final ImmutableSet items = ImmutableSet.copyOf( this.waitingFor ); - final List items = new ArrayList<>( this.waitingFor.size() ); - this.waitingFor.forEach( stack -> items.add( stack.copy().setStackSize( -stack.getStackSize() ) ) ); - - this.waitingFor.resetStatus(); - - for( final IAEItemStack is : items ) - { - this.postCraftingStatusChange( is ); - } - - this.finalOutput = null; - this.updateCPU(); - - this.storeItems(); // marks dirty - } - - public void updateCraftingLogic( final IGrid grid, final IEnergyGrid eg, final CraftingGridCache cc ) - { - if( !this.getCore().isActive() ) - { - return; - } - - if( this.myLastLink != null ) - { - if( this.myLastLink.isCanceled() ) - { - this.myLastLink = null; - this.cancel(); - } - } - - if( this.isComplete ) - { - if( this.inventory.getItemList().isEmpty() ) - { - return; - } - - this.storeItems(); - return; - } - - this.waiting = false; - if( this.waiting || this.tasks.isEmpty() ) // nothing to do here... - { - return; - } - - this.remainingOperations = this.accelerator + 1 - ( this.usedOps[0] + this.usedOps[1] + this.usedOps[2] ); - final int started = this.remainingOperations; - - if( this.remainingOperations > 0 ) - { - do - { - this.somethingChanged = false; - this.executeCrafting( eg, cc ); - } while ( this.somethingChanged && this.remainingOperations > 0 ); - } - this.usedOps[2] = this.usedOps[1]; - this.usedOps[1] = this.usedOps[0]; - this.usedOps[0] = started - this.remainingOperations; - - if( this.remainingOperations > 0 && !this.somethingChanged ) - { - this.waiting = true; - } - } - - private void executeCrafting( final IEnergyGrid eg, final CraftingGridCache cc ) - { - final Iterator> i = this.tasks.entrySet().iterator(); - - while ( i.hasNext() ) - { - final Entry e = i.next(); - - if( e.getValue().value <= 0 ) - { - i.remove(); - continue; - } - - final ICraftingPatternDetails details = e.getKey(); - - if( this.canCraft( details, details.getCondensedInputs() ) ) - { - InventoryCrafting ic = null; - - if( !visitedMediums.containsKey( details ) || visitedMediums.get( details ).isEmpty() ) - { - visitedMediums.put( details, new ArrayDeque<>( cc.getMediums( details ).stream().filter( Objects::nonNull ).collect( Collectors.toList() ) ) ); - } - - while ( !visitedMediums.get( details ).isEmpty() ) - { - - ICraftingMedium m = visitedMediums.get( details ).poll(); - - if( e.getValue().value <= 0 ) - { - continue; - } - - if( m != null && !m.isBusy() ) - { - if( ic == null ) - { - final IAEItemStack[] input = details.getInputs(); - double sum = 0; - - for( final IAEItemStack anInput : input ) - { - if( anInput != null ) - { - sum += anInput.getStackSize(); - } - } - - // power... - if( eg.extractAEPower( sum, Actionable.MODULATE, PowerMultiplier.CONFIG ) < sum - 0.01 ) - { - continue; - } - if( details.isCraftable() ) - { - ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); - } - else - { - ic = new InventoryCrafting( new ContainerNull(), PatternHelper.PROCESSING_INPUT_WIDTH, PatternHelper.PROCESSING_INPUT_HEIGHT ); - } - - boolean found = false; - - for( int x = 0; x < input.length; x++ ) - { - if( input[x] != null ) - { - found = false; - - if( details.isCraftable() ) - { - final Collection itemList; - - if( details.canSubstitute() ) - { - final List substitutes = details.getSubstituteInputs( x ); - itemList = new ArrayList<>( substitutes.size() ); - - for( IAEItemStack stack : substitutes ) - { - itemList.addAll( this.inventory.getItemList().findFuzzy( stack, FuzzyMode.IGNORE_ALL ) ); - } - } - else - { - itemList = new ArrayList<>( 1 ); - - final IAEItemStack item = this.inventory.getItemList().findPrecise( input[x] ); - - if( item != null ) - { - itemList.add( item ); - } - } - - for( IAEItemStack fuzz : itemList ) - { - fuzz = fuzz.copy(); - fuzz.setStackSize( input[x].getStackSize() ); - - if( details.isValidItemForSlot( x, fuzz.createItemStack(), this.getWorld() ) ) - { - final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.MODULATE, this.machineSrc ); - final ItemStack is = ais == null ? ItemStack.EMPTY : ais.createItemStack(); - - if( !is.isEmpty() ) - { - this.postChange( AEItemStack.fromItemStack( is ), this.machineSrc ); - ic.setInventorySlotContents( x, is ); - found = true; - break; - } - } - } - } - else - { - final IAEItemStack ais = this.inventory.extractItems( input[x].copy(), Actionable.MODULATE, this.machineSrc ); - final ItemStack is = ais == null ? ItemStack.EMPTY : ais.createItemStack(); - - if( !is.isEmpty() ) - { - this.postChange( input[x], this.machineSrc ); - ic.setInventorySlotContents( x, is ); - if( is.getCount() == input[x].getStackSize() ) - { - found = true; - continue; - } - } - } - - if( !found ) - { - break; - } - } - } - - if( !found ) - { - // put stuff back.. - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack is = ic.getStackInSlot( x ); - if( !is.isEmpty() ) - { - this.inventory.injectItems( AEItemStack.fromItemStack( is ), Actionable.MODULATE, this.machineSrc ); - } - } - ic = null; - break; - } - } - - if( m.pushPattern( details, ic ) ) - { - this.somethingChanged = true; - this.remainingOperations--; - - for( final IAEItemStack out : details.getCondensedOutputs() ) - { - this.postChange( out, this.machineSrc ); - this.waitingFor.add( out.copy() ); - this.postCraftingStatusChange( out.copy() ); - } - - if( details.isCraftable() ) - { - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack output = Platform.getContainerItem( ic.getStackInSlot( x ) ); - if( !output.isEmpty() ) - { - final IAEItemStack cItem = AEItemStack.fromItemStack( output ); - this.postChange( cItem, this.machineSrc ); - this.waitingFor.add( cItem ); - this.postCraftingStatusChange( cItem ); - } - } - } - - ic = null; // hand off complete! - this.markDirty(); - - e.getValue().value--; - if( e.getValue().value <= 0 ) - { - continue; - } - - if( this.remainingOperations == 0 ) - { - return; - } - } - } - } - - if( ic != null ) - { - // put stuff back.. - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack is = ic.getStackInSlot( x ); - if( !is.isEmpty() ) - { - this.inventory.injectItems( AEItemStack.fromItemStack( is ), Actionable.MODULATE, this.machineSrc ); - } - } - } - } - } - } - - private void storeItems() - { - Preconditions.checkState( isComplete, "CPU should be complete to prevent re-insertion when dumping items" ); - final IGrid g = this.getGrid(); - - if( g == null ) - { - return; - } - - final IStorageGrid sg = g.getCache( IStorageGrid.class ); - final IMEInventory ii = sg.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - - IItemList itemList = this.inventory.getItemList(); - for( IAEItemStack is : itemList ) - { - this.postChange( is, this.machineSrc ); - IAEItemStack remainder = ii.injectItems( is.copy(), Actionable.MODULATE, this.machineSrc ); - - // The network was unable to receive all of the items, i.e. no or not enough storage space left - if( remainder != null ) - { - is.setStackSize( remainder.getStackSize() ); - } - else - { - is.reset(); - } - } - - if( itemList.isEmpty() ) - { - this.inventory = new MECraftingInventory(); - } - - this.markDirty(); - } - - public ICraftingLink submitJob( final IGrid g, final ICraftingJob job, final IActionSource src, final ICraftingRequester requestingMachine ) - { - if( !this.tasks.isEmpty() || !this.waitingFor.isEmpty() ) - { - return null; - } - - if( !( job instanceof CraftingJob ) ) - { - return null; - } - - if( this.isBusy() || !this.isActive() || this.availableStorage < job.getByteTotal() ) - { - return null; - } - - final IStorageGrid sg = g.getCache( IStorageGrid.class ); - final IMEInventory storage = sg.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - final MECraftingInventory ci = new MECraftingInventory( storage, true, false, false ); - - try - { - this.waitingFor.resetStatus(); - ( (CraftingJob) job ).getTree().setJob( ci, this, src ); - if( ci.commit( src ) ) - { - this.finalOutput = job.getOutput(); - this.waiting = false; - this.isComplete = false; - this.markDirty(); - - this.updateCPU(); - final String craftID = this.generateCraftingID(); - - this.myLastLink = new CraftingLink( this.generateLinkData( craftID, requestingMachine == null, false ), this ); - - this.prepareElapsedTime(); - - if( requestingMachine == null ) - { - return this.myLastLink; - } - - final ICraftingLink whatLink = new CraftingLink( this.generateLinkData( craftID, false, true ), requestingMachine ); - - this.submitLink( this.myLastLink ); - this.submitLink( whatLink ); - - final IItemList list = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - this.getListOfItem( list, CraftingItemList.ALL ); - for( final IAEItemStack ge : list ) - { - this.postChange( ge, this.machineSrc ); - } - - return whatLink; - } - else - { - this.tasks.clear(); - this.inventory.getItemList().resetStatus(); - } - } - catch( final CraftBranchFailure e ) - { - this.tasks.clear(); - this.inventory.getItemList().resetStatus(); - // AELog.error( e ); - } - - return null; - } - - @Override - public boolean isBusy() - { - - this.tasks.entrySet().removeIf( taskProgressEntry -> taskProgressEntry.getValue().value <= 0 ); - - if( !this.waitingFor.isEmpty() || !this.tasks.isEmpty() ) - { - this.updateElapsedTime(); - } - - return !this.tasks.isEmpty() || !this.waitingFor.isEmpty(); - } - - @Override - public IActionSource getActionSource() - { - return this.machineSrc; - } - - @Override - public long getAvailableStorage() - { - return this.availableStorage; - } - - @Override - public int getCoProcessors() - { - return this.accelerator; - } - - @Override - public String getName() - { - return this.myName; - } - - public boolean isActive() - { - final TileCraftingTile core = this.getCore(); - - if( core == null ) - { - return false; - } - - final IGridNode node = core.getActionableNode(); - if( node == null ) - { - return false; - } - - return node.isActive(); - } - - private String generateCraftingID() - { - final long now = System.currentTimeMillis(); - final int hash = System.identityHashCode( this ); - final int hmm = this.finalOutput == null ? 0 : this.finalOutput.hashCode(); - - return Long.toString( now, Character.MAX_RADIX ) + '-' + Integer.toString( hash, Character.MAX_RADIX ) + '-' + Integer.toString( hmm, Character.MAX_RADIX ); - } - - private NBTTagCompound generateLinkData( final String craftingID, final boolean standalone, final boolean req ) - { - final NBTTagCompound tag = new NBTTagCompound(); - - tag.setString( "CraftID", craftingID ); - tag.setBoolean( "canceled", false ); - tag.setBoolean( "done", false ); - tag.setBoolean( "standalone", standalone ); - tag.setBoolean( "req", req ); - - return tag; - } - - private void submitLink( final ICraftingLink myLastLink2 ) - { - if( this.getGrid() != null ) - { - final CraftingGridCache cc = this.getGrid().getCache( ICraftingGrid.class ); - cc.addLink( (CraftingLink) myLastLink2 ); - } - } - - public void getListOfItem( final IItemList list, final CraftingItemList whichList ) - { - switch ( whichList ) - { - case ACTIVE: - for( final IAEItemStack ais : this.waitingFor ) - { - list.add( ais ); - } - break; - case PENDING: - for( final Entry t : this.tasks.entrySet() ) - { - for( IAEItemStack ais : t.getKey().getCondensedOutputs() ) - { - ais = ais.copy(); - ais.setStackSize( ais.getStackSize() * t.getValue().value ); - list.add( ais ); - } - } - break; - case STORAGE: - this.inventory.getAvailableItems( list ); - break; - default: - case ALL: - this.inventory.getAvailableItems( list ); - - for( final IAEItemStack ais : this.waitingFor ) - { - list.add( ais ); - } - - for( final Entry t : this.tasks.entrySet() ) - { - for( IAEItemStack ais : t.getKey().getCondensedOutputs() ) - { - ais = ais.copy(); - ais.setStackSize( ais.getStackSize() * t.getValue().value ); - list.add( ais ); - } - } - break; - } - } - - public void addStorage( final IAEItemStack extractItems ) - { - this.inventory.injectItems( extractItems, Actionable.MODULATE, null ); - } - - public void addEmitable( final IAEItemStack i ) - { - this.waitingFor.add( i ); - this.postCraftingStatusChange( i ); - } - - public void addCrafting( final ICraftingPatternDetails details, final long crafts ) - { - TaskProgress i = this.tasks.get( details ); - - if( i == null ) - { - this.tasks.put( details, i = new TaskProgress() ); - } - - i.value += crafts; - } - - public IAEItemStack getItemStack( final IAEItemStack what, final CraftingItemList storage2 ) - { - IAEItemStack is; - - switch ( storage2 ) - { - case STORAGE: - is = this.inventory.getItemList().findPrecise( what ); - break; - case ACTIVE: - is = this.waitingFor.findPrecise( what ); - break; - case PENDING: - - is = what.copy(); - is.setStackSize( 0 ); - - for( final Entry t : this.tasks.entrySet() ) - { - for( final IAEItemStack ais : t.getKey().getCondensedOutputs() ) - { - if( ais.isSameType( is ) ) - { - is.setStackSize( is.getStackSize() + ais.getStackSize() * t.getValue().value ); - } - } - } - - break; - default: - case ALL: - throw new IllegalStateException( "Invalid Operation" ); - } - - if( is != null ) - { - return is.copy(); - } - - is = what.copy(); - is.setStackSize( 0 ); - return is; - } - - public void writeToNBT( final NBTTagCompound data ) - { - data.setTag( "finalOutput", this.writeItem( this.finalOutput ) ); - data.setTag( "inventory", this.writeList( this.inventory.getItemList() ) ); - data.setBoolean( "waiting", this.waiting ); - data.setBoolean( "isComplete", this.isComplete ); - - if( this.myLastLink != null ) - { - final NBTTagCompound link = new NBTTagCompound(); - this.myLastLink.writeToNBT( link ); - data.setTag( "link", link ); - } - - final NBTTagList list = new NBTTagList(); - for( final Entry e : this.tasks.entrySet() ) - { - final NBTTagCompound item = this.writeItem( AEItemStack.fromItemStack( e.getKey().getPattern() ) ); - item.setLong( "craftingProgress", e.getValue().value ); - list.appendTag( item ); - } - data.setTag( "tasks", list ); - - data.setTag( "waitingFor", this.writeList( this.waitingFor ) ); - - data.setLong( "elapsedTime", this.getElapsedTime() ); - data.setLong( "startItemCount", this.getStartItemCount() ); - data.setLong( "remainingItemCount", this.getRemainingItemCount() ); - } - - private NBTTagCompound writeItem( final IAEItemStack finalOutput2 ) - { - final NBTTagCompound out = new NBTTagCompound(); - - if( finalOutput2 != null ) - { - finalOutput2.writeToNBT( out ); - } - - return out; - } - - private NBTTagList writeList( final IItemList myList ) - { - final NBTTagList out = new NBTTagList(); - - for( final IAEItemStack ais : myList ) - { - out.appendTag( this.writeItem( ais ) ); - } - - return out; - } - - void done() - { - final TileCraftingTile core = this.getCore(); - - core.setCoreBlock( true ); - - if( core.getPreviousState() != null ) - { - this.readFromNBT( core.getPreviousState() ); - core.setPreviousState( null ); - } - - this.updateCPU(); - this.updateName(); - } - - public void readFromNBT( final NBTTagCompound data ) - { - this.finalOutput = AEItemStack.fromNBT( (NBTTagCompound) data.getTag( "finalOutput" ) ); - for( final IAEItemStack ais : this.readList( (NBTTagList) data.getTag( "inventory" ) ) ) - { - this.inventory.injectItems( ais, Actionable.MODULATE, this.machineSrc ); - } - - this.waiting = data.getBoolean( "waiting" ); - this.isComplete = data.getBoolean( "isComplete" ); - - if( data.hasKey( "link" ) ) - { - final NBTTagCompound link = data.getCompoundTag( "link" ); - this.myLastLink = new CraftingLink( link, this ); - this.submitLink( this.myLastLink ); - } - - final NBTTagList list = data.getTagList( "tasks", 10 ); - for( int x = 0; x < list.tagCount(); x++ ) - { - final NBTTagCompound item = list.getCompoundTagAt( x ); - final IAEItemStack pattern = AEItemStack.fromNBT( item ); - if( pattern != null && pattern.getItem() instanceof ICraftingPatternItem ) - { - final ICraftingPatternItem cpi = (ICraftingPatternItem) pattern.getItem(); - final ICraftingPatternDetails details = cpi.getPatternForItem( pattern.createItemStack(), this.getWorld() ); - if( details != null ) - { - final TaskProgress tp = new TaskProgress(); - tp.value = item.getLong( "craftingProgress" ); - this.tasks.put( details, tp ); - } - } - } - - this.waitingFor = this.readList( (NBTTagList) data.getTag( "waitingFor" ) ); - for( final IAEItemStack is : this.waitingFor ) - { - this.postCraftingStatusChange( is.copy() ); - } - - this.lastTime = System.nanoTime(); - this.elapsedTime = data.getLong( "elapsedTime" ); - this.startItemCount = data.getLong( "startItemCount" ); - this.remainingItemCount = data.getLong( "remainingItemCount" ); - } - - public void updateName() - { - this.myName = ""; - for( final TileCraftingTile te : this.tiles ) - { - - if( te.hasCustomInventoryName() ) - { - if( this.myName.length() > 0 ) - { - this.myName += ' ' + te.getCustomInventoryName(); - } - else - { - this.myName = te.getCustomInventoryName(); - } - } - } - } - - private IItemList readList( final NBTTagList tag ) - { - final IItemList out = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - - if( tag == null ) - { - return out; - } - - for( int x = 0; x < tag.tagCount(); x++ ) - { - final IAEItemStack ais = AEItemStack.fromNBT( tag.getCompoundTagAt( x ) ); - if( ais != null ) - { - out.add( ais ); - } - } - - return out; - } - - private World getWorld() - { - return this.getCore().getWorld(); - } - - public IAEItemStack making( final IAEItemStack what ) - { - return this.waitingFor.findPrecise( what ); - } - - public void breakCluster() - { - final TileCraftingTile t = this.getCore(); - - if( t != null ) - { - t.breakCluster(); - } - } - - private void prepareElapsedTime() - { - this.lastTime = System.nanoTime(); - this.elapsedTime = 0; - - final IItemList list = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - - this.getListOfItem( list, CraftingItemList.ACTIVE ); - this.getListOfItem( list, CraftingItemList.PENDING ); - - int itemCount = 0; - for( final IAEItemStack ge : list ) - { - itemCount += ge.getStackSize(); - } - - this.startItemCount = itemCount; - this.remainingItemCount = itemCount; - } - - private void updateRemainingItemCount( final IAEItemStack is ) - { - this.remainingItemCount = this.getRemainingItemCount() - is.getStackSize(); - } - - private void updateElapsedTime() - { - final long nextStartTime = System.nanoTime(); - this.elapsedTime = this.getElapsedTime() + nextStartTime - this.lastTime; - this.lastTime = nextStartTime; - } - - public long getElapsedTime() - { - return this.elapsedTime; - } - - @Override - public long getRemainingItemCount() - { - return this.remainingItemCount; - } - - @Override - public long getStartItemCount() - { - return this.startItemCount; - } - - private static class TaskProgress - { - private long value; - } +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.world.World; + +import java.util.*; +import java.util.Map.Entry; +import java.util.stream.Collectors; + + +public final class CraftingCPUCluster implements IAECluster, ICraftingCPU { + + private static final String LOG_MARK_AS_COMPLETE = "Completed job for %s."; + + private final WorldCoord min; + private final WorldCoord max; + private final int[] usedOps = new int[3]; + private final Map tasks = new HashMap<>(); + // INSTANCE sate + private final List tiles = new ArrayList<>(); + private final List storage = new ArrayList<>(); + private final List status = new ArrayList<>(); + private final HashMap, Object> listeners = new HashMap<>(); + private final Map> visitedMediums = new HashMap<>(); + private ICraftingLink myLastLink; + private String myName = ""; + private boolean isDestroyed = false; + /** + * crafting job info + */ + private MECraftingInventory inventory = new MECraftingInventory(); + private IAEItemStack finalOutput; + private boolean waiting = false; + private IItemList waitingFor = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + private long availableStorage = 0; + private MachineSource machineSrc = null; + private int accelerator = 0; + private boolean isComplete = true; + private int remainingOperations; + private boolean somethingChanged; + + private long lastTime; + private long elapsedTime; + private long startItemCount; + private long remainingItemCount; + + public CraftingCPUCluster(final WorldCoord min, final WorldCoord max) { + this.min = min; + this.max = max; + } + + @Override + public IAEItemStack getFinalOutput() { + return finalOutput; + } + + public boolean isDestroyed() { + return this.isDestroyed; + } + + public ICraftingLink getLastCraftingLink() { + return this.myLastLink; + } + + /** + * add a new Listener to the monitor, be sure to properly remove yourself when your done. + */ + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } + + /** + * remove a Listener to the monitor. + */ + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } + + public IMEInventory getInventory() { + return this.inventory; + } + + @Override + public void updateStatus(final boolean updateGrid) { + for (final TileCraftingTile r : this.tiles) { + r.updateMeta(true); + } + } + + @Override + public void destroy() { + if (this.isDestroyed) { + return; + } + this.isDestroyed = true; + + boolean posted = false; + + for (final TileCraftingTile r : this.tiles) { + final IGridNode n = r.getActionableNode(); + if (n != null && !posted) { + final IGrid g = n.getGrid(); + if (g != null) { + g.postEvent(new MENetworkCraftingCpuChange(n)); + posted = true; + } + } + + r.updateStatus(null); + } + } + + @Override + public Iterator getTiles() { + return (Iterator) this.tiles.iterator(); + } + + void addTile(final TileCraftingTile te) { + if (this.machineSrc == null || te.isCoreBlock()) { + this.machineSrc = new MachineSource(te); + } + + te.setCoreBlock(false); + te.saveChanges(); + this.tiles.add(0, te); + + if (te.isStorage()) { + this.availableStorage += te.getStorageBytes(); + this.storage.add(te); + } else if (te.isStatus()) { + this.status.add((TileCraftingMonitorTile) te); + } else if (te.isAccelerator()) { + this.accelerator++; + } + } + + public boolean canAccept(final IAEItemStack input) { + if (input instanceof IAEItemStack) { + final IAEItemStack is = this.waitingFor.findPrecise(input); + return is != null && is.getStackSize() > 0; + } + return false; + } + + public IAEItemStack injectItems(final IAEItemStack input, final Actionable type, final IActionSource src) { + // also stop accepting items when the job is complete, i.e. to prevent re-insertion when pushing out + // items during storeItems + if (input == null || isComplete) { + return input; + } + + final IAEItemStack what = input.copy(); + final IAEItemStack is = this.waitingFor.findPrecise(what); + + if (type == Actionable.SIMULATE)// causes crafting to lock up? + { + if (is != null && is.getStackSize() > 0) { + if (is.getStackSize() >= what.getStackSize()) { + if (this.finalOutput.equals(what)) { + if (this.myLastLink != null) { + return ((CraftingLink) this.myLastLink).injectItems(what.copy(), type); + } + + return what; // ignore it. + } + + return null; + } + + final IAEItemStack leftOver = what.copy(); + leftOver.decStackSize(is.getStackSize()); + + final IAEItemStack used = what.copy(); + used.setStackSize(is.getStackSize()); + + if (this.finalOutput.equals(what)) { + if (this.myLastLink != null) { + leftOver.add(((CraftingLink) this.myLastLink).injectItems(used.copy(), type)); + return leftOver; + } + + return what; // ignore it. + } + + return leftOver; + } + } else if (type == Actionable.MODULATE) { + if (is != null && is.getStackSize() > 0) { + this.waiting = false; + + this.postChange(what, src); + + if (is.getStackSize() >= what.getStackSize()) { + is.decStackSize(what.getStackSize()); + + this.updateRemainingItemCount(what); + this.markDirty(); + this.postCraftingStatusChange(what.copy().setStackSize(-what.getStackSize())); + + if (this.finalOutput.equals(what)) { + IAEItemStack leftover = what; + + this.finalOutput.decStackSize(what.getStackSize()); + + if (this.myLastLink != null) { + leftover = ((CraftingLink) this.myLastLink).injectItems(what, type); + } + + if (this.finalOutput.getStackSize() <= 0) { + this.completeJob(); + } + + this.updateCPU(); + + return leftover; // ignore it. + } + + // 2000 + return this.inventory.injectItems(what, type, src); + } + + final IAEItemStack insert = what.copy(); + insert.setStackSize(is.getStackSize()); + what.decStackSize(is.getStackSize()); + + is.setStackSize(0); + this.postCraftingStatusChange(insert.copy().setStackSize(-insert.getStackSize())); + + if (this.finalOutput.equals(insert)) { + IAEItemStack leftover = input; + + this.finalOutput.decStackSize(insert.getStackSize()); + + if (this.myLastLink != null) { + what.add(((CraftingLink) this.myLastLink).injectItems(insert.copy(), type)); + leftover = what; + } + + if (this.finalOutput.getStackSize() <= 0) { + this.completeJob(); + } + + this.updateCPU(); + this.markDirty(); + + return leftover; // ignore it. + } + + this.inventory.injectItems(insert, type, src); + this.markDirty(); + + return what; + } + } + + return input; + } + + private void postChange(final IAEItemStack diff, final IActionSource src) { + final Iterator, Object>> i = this.getListeners(); + + // protect integrity + if (i.hasNext()) { + final ImmutableList single = ImmutableList.of(diff.copy()); + + while (i.hasNext()) { + final Entry, Object> o = i.next(); + final IMEMonitorHandlerReceiver receiver = o.getKey(); + + if (receiver.isValid(o.getValue())) { + receiver.postChange(null, single, src); + } else { + i.remove(); + } + } + } + + } + + private void markDirty() { + this.getCore().saveChanges(); + } + + private void postCraftingStatusChange(final IAEItemStack diff) { + if (this.getGrid() == null) { + return; + } + + final CraftingGridCache sg = this.getGrid().getCache(ICraftingGrid.class); + + if (sg.getInterestManager().containsKey(diff)) { + final Collection list = sg.getInterestManager().get(diff); + + if (!list.isEmpty()) { + for (final CraftingWatcher iw : list) { + iw.getHost().onRequestChange(sg, diff); + } + } + } + } + + private void completeJob() { + if (this.myLastLink != null) { + ((CraftingLink) this.myLastLink).markDone(); + } + + if (AELog.isCraftingLogEnabled()) { + final IAEItemStack logStack = this.finalOutput.copy(); + logStack.setStackSize(this.startItemCount); + AELog.crafting(LOG_MARK_AS_COMPLETE, logStack); + } + + // Waiting for can potentially contain items at this point, if the user has a 64xplank->64xbutton processing + // recipe for example, but only requested 1xbutton. We just ignore the rest since it will be dumped + // back into the network inventory regardless. For this to work it's important that injectItems in this CPU + // does not accept any further items if isComplete is true. + this.waitingFor.resetStatus(); + this.remainingItemCount = 0; + this.startItemCount = 0; + this.lastTime = 0; + this.elapsedTime = 0; + this.isComplete = true; + } + + private void updateCPU() { + IAEItemStack send = this.finalOutput; + + if (this.finalOutput != null && this.finalOutput.getStackSize() <= 0) { + send = null; + } + + for (final TileCraftingMonitorTile t : this.status) { + t.setJob(send); + } + } + + private Iterator, Object>> getListeners() { + return this.listeners.entrySet().iterator(); + } + + private TileCraftingTile getCore() { + if (this.machineSrc == null) { + return null; + } + return (TileCraftingTile) this.machineSrc.machine().get(); + } + + private IGrid getGrid() { + for (final TileCraftingTile r : this.tiles) { + final IGridNode gn = r.getActionableNode(); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + return r.getActionableNode().getGrid(); + } + } + } + + return null; + } + + private boolean canCraft(final ICraftingPatternDetails details, final IAEItemStack[] condensedInputs) { + if (!details.isCraftable()) { + // Processing patterns are relatively easy + for (IAEItemStack input : condensedInputs) { + final IAEItemStack ais = this.inventory.extractItems(input.copy(), Actionable.SIMULATE, this.machineSrc); + + if (ais == null || ais.getStackSize() < input.getStackSize()) { + return false; + } + } + } else if (details.canSubstitute()) { + // When substitutions are allowed, we have to keep track of which items we've reserved + IAEItemStack[] inputs = details.getInputs(); + Map consumedCount = new HashMap<>(); + for (int i = 0; i < inputs.length; i++) { + List substitutes = details.getSubstituteInputs(i); + if (substitutes.isEmpty()) { + continue; + } + + boolean found = false; + for (IAEItemStack substitute : substitutes) { + for (IAEItemStack fuzz : this.inventory.getItemList().findFuzzy(substitute, FuzzyMode.IGNORE_ALL)) { + int alreadyConsumed = consumedCount.getOrDefault(fuzz, 0); + if (fuzz.getStackSize() - alreadyConsumed <= 0) { + continue; // Already fully consumed by a previous slot of this recipe + } + + fuzz = fuzz.copy(); + fuzz.setStackSize(1); // We're iterating over non condensed inputs which means there's 1 of each needed + final IAEItemStack ais = this.inventory.extractItems(fuzz, Actionable.SIMULATE, this.machineSrc); + + if (ais != null && ais.getStackSize() > 0) { + // Mark 1 of the stack as consumed + consumedCount.merge(fuzz, 1, Integer::sum); + found = true; + break; + } + } + if (found) { + break; + } + } + + if (!found) { + return false; + } + } + + } else { + // When no substitutions can occur, we can simply check that all items are accounted since + // each type of item should only occur once + for (IAEItemStack g : condensedInputs) { + boolean found = false; + + for (IAEItemStack fuzz : this.inventory.getItemList().findFuzzy(g, FuzzyMode.IGNORE_ALL)) { + fuzz = fuzz.copy(); + fuzz.setStackSize(g.getStackSize()); + final IAEItemStack ais = this.inventory.extractItems(fuzz, Actionable.SIMULATE, this.machineSrc); + + if (ais != null && ais.getStackSize() >= g.getStackSize()) { + found = true; + break; + } else if (ais != null) { + g = g.copy(); + g.decStackSize(ais.getStackSize()); + } + } + + if (!found) { + return false; + } + } + + } + + return true; + } + + public void cancel() { + if (this.myLastLink != null) { + this.myLastLink.cancel(); + } + + final IItemList list; + this.getListOfItem(list = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(), CraftingItemList.ALL); + for (final IAEItemStack is : list) { + this.postChange(is, this.machineSrc); + } + + this.isComplete = true; + this.myLastLink = null; + this.tasks.clear(); + + // final ImmutableSet items = ImmutableSet.copyOf( this.waitingFor ); + final List items = new ArrayList<>(this.waitingFor.size()); + this.waitingFor.forEach(stack -> items.add(stack.copy().setStackSize(-stack.getStackSize()))); + + this.waitingFor.resetStatus(); + + for (final IAEItemStack is : items) { + this.postCraftingStatusChange(is); + } + + this.finalOutput = null; + this.updateCPU(); + + this.storeItems(); // marks dirty + } + + public void updateCraftingLogic(final IGrid grid, final IEnergyGrid eg, final CraftingGridCache cc) { + if (!this.getCore().isActive()) { + return; + } + + if (this.myLastLink != null) { + if (this.myLastLink.isCanceled()) { + this.myLastLink = null; + this.cancel(); + } + } + + if (this.isComplete) { + if (this.inventory.getItemList().isEmpty()) { + return; + } + + this.storeItems(); + return; + } + + this.waiting = false; + if (this.waiting || this.tasks.isEmpty()) // nothing to do here... + { + return; + } + + this.remainingOperations = this.accelerator + 1 - (this.usedOps[0] + this.usedOps[1] + this.usedOps[2]); + final int started = this.remainingOperations; + + if (this.remainingOperations > 0) { + do { + this.somethingChanged = false; + this.executeCrafting(eg, cc); + } while (this.somethingChanged && this.remainingOperations > 0); + } + this.usedOps[2] = this.usedOps[1]; + this.usedOps[1] = this.usedOps[0]; + this.usedOps[0] = started - this.remainingOperations; + + if (this.remainingOperations > 0 && !this.somethingChanged) { + this.waiting = true; + } + } + + private void executeCrafting(final IEnergyGrid eg, final CraftingGridCache cc) { + final Iterator> i = this.tasks.entrySet().iterator(); + + while (i.hasNext()) { + final Entry e = i.next(); + + if (e.getValue().value <= 0) { + i.remove(); + continue; + } + + final ICraftingPatternDetails details = e.getKey(); + + if (this.canCraft(details, details.getCondensedInputs())) { + InventoryCrafting ic = null; + + if (!visitedMediums.containsKey(details) || visitedMediums.get(details).isEmpty()) { + visitedMediums.put(details, new ArrayDeque<>(cc.getMediums(details).stream().filter(Objects::nonNull).collect(Collectors.toList()))); + } + + while (!visitedMediums.get(details).isEmpty()) { + + ICraftingMedium m = visitedMediums.get(details).poll(); + + if (e.getValue().value <= 0) { + continue; + } + + if (m != null && !m.isBusy()) { + if (ic == null) { + final IAEItemStack[] input = details.getInputs(); + double sum = 0; + + for (final IAEItemStack anInput : input) { + if (anInput != null) { + sum += anInput.getStackSize(); + } + } + + // power... + if (eg.extractAEPower(sum, Actionable.MODULATE, PowerMultiplier.CONFIG) < sum - 0.01) { + continue; + } + if (details.isCraftable()) { + ic = new InventoryCrafting(new ContainerNull(), 3, 3); + } else { + ic = new InventoryCrafting(new ContainerNull(), PatternHelper.PROCESSING_INPUT_WIDTH, PatternHelper.PROCESSING_INPUT_HEIGHT); + } + + boolean found = false; + + for (int x = 0; x < input.length; x++) { + if (input[x] != null) { + found = false; + + if (details.isCraftable()) { + final Collection itemList; + + if (details.canSubstitute()) { + final List substitutes = details.getSubstituteInputs(x); + itemList = new ArrayList<>(substitutes.size()); + + for (IAEItemStack stack : substitutes) { + itemList.addAll(this.inventory.getItemList().findFuzzy(stack, FuzzyMode.IGNORE_ALL)); + } + } else { + itemList = new ArrayList<>(1); + + final IAEItemStack item = this.inventory.getItemList().findPrecise(input[x]); + + if (item != null) { + itemList.add(item); + } + } + + for (IAEItemStack fuzz : itemList) { + fuzz = fuzz.copy(); + fuzz.setStackSize(input[x].getStackSize()); + + if (details.isValidItemForSlot(x, fuzz.createItemStack(), this.getWorld())) { + final IAEItemStack ais = this.inventory.extractItems(fuzz, Actionable.MODULATE, this.machineSrc); + final ItemStack is = ais == null ? ItemStack.EMPTY : ais.createItemStack(); + + if (!is.isEmpty()) { + this.postChange(AEItemStack.fromItemStack(is), this.machineSrc); + ic.setInventorySlotContents(x, is); + found = true; + break; + } + } + } + } else { + final IAEItemStack ais = this.inventory.extractItems(input[x].copy(), Actionable.MODULATE, this.machineSrc); + final ItemStack is = ais == null ? ItemStack.EMPTY : ais.createItemStack(); + + if (!is.isEmpty()) { + this.postChange(input[x], this.machineSrc); + ic.setInventorySlotContents(x, is); + if (is.getCount() == input[x].getStackSize()) { + found = true; + continue; + } + } + } + + if (!found) { + break; + } + } + } + + if (!found) { + // put stuff back.. + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack is = ic.getStackInSlot(x); + if (!is.isEmpty()) { + this.inventory.injectItems(AEItemStack.fromItemStack(is), Actionable.MODULATE, this.machineSrc); + } + } + ic = null; + break; + } + } + + if (m.pushPattern(details, ic)) { + this.somethingChanged = true; + this.remainingOperations--; + + for (final IAEItemStack out : details.getCondensedOutputs()) { + this.postChange(out, this.machineSrc); + this.waitingFor.add(out.copy()); + this.postCraftingStatusChange(out.copy()); + } + + if (details.isCraftable()) { + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack output = Platform.getContainerItem(ic.getStackInSlot(x)); + if (!output.isEmpty()) { + final IAEItemStack cItem = AEItemStack.fromItemStack(output); + this.postChange(cItem, this.machineSrc); + this.waitingFor.add(cItem); + this.postCraftingStatusChange(cItem); + } + } + } + + ic = null; // hand off complete! + this.markDirty(); + + e.getValue().value--; + if (e.getValue().value <= 0) { + continue; + } + + if (this.remainingOperations == 0) { + return; + } + } + } + } + + if (ic != null) { + // put stuff back.. + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack is = ic.getStackInSlot(x); + if (!is.isEmpty()) { + this.inventory.injectItems(AEItemStack.fromItemStack(is), Actionable.MODULATE, this.machineSrc); + } + } + } + } + } + } + + private void storeItems() { + Preconditions.checkState(isComplete, "CPU should be complete to prevent re-insertion when dumping items"); + final IGrid g = this.getGrid(); + + if (g == null) { + return; + } + + final IStorageGrid sg = g.getCache(IStorageGrid.class); + final IMEInventory ii = sg.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + + IItemList itemList = this.inventory.getItemList(); + for (IAEItemStack is : itemList) { + this.postChange(is, this.machineSrc); + IAEItemStack remainder = ii.injectItems(is.copy(), Actionable.MODULATE, this.machineSrc); + + // The network was unable to receive all of the items, i.e. no or not enough storage space left + if (remainder != null) { + is.setStackSize(remainder.getStackSize()); + } else { + is.reset(); + } + } + + if (itemList.isEmpty()) { + this.inventory = new MECraftingInventory(); + } + + this.markDirty(); + } + + public ICraftingLink submitJob(final IGrid g, final ICraftingJob job, final IActionSource src, final ICraftingRequester requestingMachine) { + if (!this.tasks.isEmpty() || !this.waitingFor.isEmpty()) { + return null; + } + + if (!(job instanceof CraftingJob)) { + return null; + } + + if (this.isBusy() || !this.isActive() || this.availableStorage < job.getByteTotal()) { + return null; + } + + final IStorageGrid sg = g.getCache(IStorageGrid.class); + final IMEInventory storage = sg.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + final MECraftingInventory ci = new MECraftingInventory(storage, true, false, false); + + try { + this.waitingFor.resetStatus(); + ((CraftingJob) job).getTree().setJob(ci, this, src); + if (ci.commit(src)) { + this.finalOutput = job.getOutput(); + this.waiting = false; + this.isComplete = false; + this.markDirty(); + + this.updateCPU(); + final String craftID = this.generateCraftingID(); + + this.myLastLink = new CraftingLink(this.generateLinkData(craftID, requestingMachine == null, false), this); + + this.prepareElapsedTime(); + + if (requestingMachine == null) { + return this.myLastLink; + } + + final ICraftingLink whatLink = new CraftingLink(this.generateLinkData(craftID, false, true), requestingMachine); + + this.submitLink(this.myLastLink); + this.submitLink(whatLink); + + final IItemList list = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + this.getListOfItem(list, CraftingItemList.ALL); + for (final IAEItemStack ge : list) { + this.postChange(ge, this.machineSrc); + } + + return whatLink; + } else { + this.tasks.clear(); + this.inventory.getItemList().resetStatus(); + } + } catch (final CraftBranchFailure e) { + this.tasks.clear(); + this.inventory.getItemList().resetStatus(); + // AELog.error( e ); + } + + return null; + } + + @Override + public boolean isBusy() { + + this.tasks.entrySet().removeIf(taskProgressEntry -> taskProgressEntry.getValue().value <= 0); + + if (!this.waitingFor.isEmpty() || !this.tasks.isEmpty()) { + this.updateElapsedTime(); + } + + return !this.tasks.isEmpty() || !this.waitingFor.isEmpty(); + } + + @Override + public IActionSource getActionSource() { + return this.machineSrc; + } + + @Override + public long getAvailableStorage() { + return this.availableStorage; + } + + @Override + public int getCoProcessors() { + return this.accelerator; + } + + @Override + public String getName() { + return this.myName; + } + + public boolean isActive() { + final TileCraftingTile core = this.getCore(); + + if (core == null) { + return false; + } + + final IGridNode node = core.getActionableNode(); + if (node == null) { + return false; + } + + return node.isActive(); + } + + private String generateCraftingID() { + final long now = System.currentTimeMillis(); + final int hash = System.identityHashCode(this); + final int hmm = this.finalOutput == null ? 0 : this.finalOutput.hashCode(); + + return Long.toString(now, Character.MAX_RADIX) + '-' + Integer.toString(hash, Character.MAX_RADIX) + '-' + Integer.toString(hmm, Character.MAX_RADIX); + } + + private NBTTagCompound generateLinkData(final String craftingID, final boolean standalone, final boolean req) { + final NBTTagCompound tag = new NBTTagCompound(); + + tag.setString("CraftID", craftingID); + tag.setBoolean("canceled", false); + tag.setBoolean("done", false); + tag.setBoolean("standalone", standalone); + tag.setBoolean("req", req); + + return tag; + } + + private void submitLink(final ICraftingLink myLastLink2) { + if (this.getGrid() != null) { + final CraftingGridCache cc = this.getGrid().getCache(ICraftingGrid.class); + cc.addLink((CraftingLink) myLastLink2); + } + } + + public void getListOfItem(final IItemList list, final CraftingItemList whichList) { + switch (whichList) { + case ACTIVE: + for (final IAEItemStack ais : this.waitingFor) { + list.add(ais); + } + break; + case PENDING: + for (final Entry t : this.tasks.entrySet()) { + for (IAEItemStack ais : t.getKey().getCondensedOutputs()) { + ais = ais.copy(); + ais.setStackSize(ais.getStackSize() * t.getValue().value); + list.add(ais); + } + } + break; + case STORAGE: + this.inventory.getAvailableItems(list); + break; + default: + case ALL: + this.inventory.getAvailableItems(list); + + for (final IAEItemStack ais : this.waitingFor) { + list.add(ais); + } + + for (final Entry t : this.tasks.entrySet()) { + for (IAEItemStack ais : t.getKey().getCondensedOutputs()) { + ais = ais.copy(); + ais.setStackSize(ais.getStackSize() * t.getValue().value); + list.add(ais); + } + } + break; + } + } + + public void addStorage(final IAEItemStack extractItems) { + this.inventory.injectItems(extractItems, Actionable.MODULATE, null); + } + + public void addEmitable(final IAEItemStack i) { + this.waitingFor.add(i); + this.postCraftingStatusChange(i); + } + + public void addCrafting(final ICraftingPatternDetails details, final long crafts) { + TaskProgress i = this.tasks.get(details); + + if (i == null) { + this.tasks.put(details, i = new TaskProgress()); + } + + i.value += crafts; + } + + public IAEItemStack getItemStack(final IAEItemStack what, final CraftingItemList storage2) { + IAEItemStack is; + + switch (storage2) { + case STORAGE: + is = this.inventory.getItemList().findPrecise(what); + break; + case ACTIVE: + is = this.waitingFor.findPrecise(what); + break; + case PENDING: + + is = what.copy(); + is.setStackSize(0); + + for (final Entry t : this.tasks.entrySet()) { + for (final IAEItemStack ais : t.getKey().getCondensedOutputs()) { + if (ais.isSameType(is)) { + is.setStackSize(is.getStackSize() + ais.getStackSize() * t.getValue().value); + } + } + } + + break; + default: + case ALL: + throw new IllegalStateException("Invalid Operation"); + } + + if (is != null) { + return is.copy(); + } + + is = what.copy(); + is.setStackSize(0); + return is; + } + + public void writeToNBT(final NBTTagCompound data) { + data.setTag("finalOutput", this.writeItem(this.finalOutput)); + data.setTag("inventory", this.writeList(this.inventory.getItemList())); + data.setBoolean("waiting", this.waiting); + data.setBoolean("isComplete", this.isComplete); + + if (this.myLastLink != null) { + final NBTTagCompound link = new NBTTagCompound(); + this.myLastLink.writeToNBT(link); + data.setTag("link", link); + } + + final NBTTagList list = new NBTTagList(); + for (final Entry e : this.tasks.entrySet()) { + final NBTTagCompound item = this.writeItem(AEItemStack.fromItemStack(e.getKey().getPattern())); + item.setLong("craftingProgress", e.getValue().value); + list.appendTag(item); + } + data.setTag("tasks", list); + + data.setTag("waitingFor", this.writeList(this.waitingFor)); + + data.setLong("elapsedTime", this.getElapsedTime()); + data.setLong("startItemCount", this.getStartItemCount()); + data.setLong("remainingItemCount", this.getRemainingItemCount()); + } + + private NBTTagCompound writeItem(final IAEItemStack finalOutput2) { + final NBTTagCompound out = new NBTTagCompound(); + + if (finalOutput2 != null) { + finalOutput2.writeToNBT(out); + } + + return out; + } + + private NBTTagList writeList(final IItemList myList) { + final NBTTagList out = new NBTTagList(); + + for (final IAEItemStack ais : myList) { + out.appendTag(this.writeItem(ais)); + } + + return out; + } + + void done() { + final TileCraftingTile core = this.getCore(); + + core.setCoreBlock(true); + + if (core.getPreviousState() != null) { + this.readFromNBT(core.getPreviousState()); + core.setPreviousState(null); + } + + this.updateCPU(); + this.updateName(); + } + + public void readFromNBT(final NBTTagCompound data) { + this.finalOutput = AEItemStack.fromNBT((NBTTagCompound) data.getTag("finalOutput")); + for (final IAEItemStack ais : this.readList((NBTTagList) data.getTag("inventory"))) { + this.inventory.injectItems(ais, Actionable.MODULATE, this.machineSrc); + } + + this.waiting = data.getBoolean("waiting"); + this.isComplete = data.getBoolean("isComplete"); + + if (data.hasKey("link")) { + final NBTTagCompound link = data.getCompoundTag("link"); + this.myLastLink = new CraftingLink(link, this); + this.submitLink(this.myLastLink); + } + + final NBTTagList list = data.getTagList("tasks", 10); + for (int x = 0; x < list.tagCount(); x++) { + final NBTTagCompound item = list.getCompoundTagAt(x); + final IAEItemStack pattern = AEItemStack.fromNBT(item); + if (pattern != null && pattern.getItem() instanceof ICraftingPatternItem) { + final ICraftingPatternItem cpi = (ICraftingPatternItem) pattern.getItem(); + final ICraftingPatternDetails details = cpi.getPatternForItem(pattern.createItemStack(), this.getWorld()); + if (details != null) { + final TaskProgress tp = new TaskProgress(); + tp.value = item.getLong("craftingProgress"); + this.tasks.put(details, tp); + } + } + } + + this.waitingFor = this.readList((NBTTagList) data.getTag("waitingFor")); + for (final IAEItemStack is : this.waitingFor) { + this.postCraftingStatusChange(is.copy()); + } + + this.lastTime = System.nanoTime(); + this.elapsedTime = data.getLong("elapsedTime"); + this.startItemCount = data.getLong("startItemCount"); + this.remainingItemCount = data.getLong("remainingItemCount"); + } + + public void updateName() { + this.myName = ""; + for (final TileCraftingTile te : this.tiles) { + + if (te.hasCustomInventoryName()) { + if (this.myName.length() > 0) { + this.myName += ' ' + te.getCustomInventoryName(); + } else { + this.myName = te.getCustomInventoryName(); + } + } + } + } + + private IItemList readList(final NBTTagList tag) { + final IItemList out = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + + if (tag == null) { + return out; + } + + for (int x = 0; x < tag.tagCount(); x++) { + final IAEItemStack ais = AEItemStack.fromNBT(tag.getCompoundTagAt(x)); + if (ais != null) { + out.add(ais); + } + } + + return out; + } + + private World getWorld() { + return this.getCore().getWorld(); + } + + public IAEItemStack making(final IAEItemStack what) { + return this.waitingFor.findPrecise(what); + } + + public void breakCluster() { + final TileCraftingTile t = this.getCore(); + + if (t != null) { + t.breakCluster(); + } + } + + private void prepareElapsedTime() { + this.lastTime = System.nanoTime(); + this.elapsedTime = 0; + + final IItemList list = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + + this.getListOfItem(list, CraftingItemList.ACTIVE); + this.getListOfItem(list, CraftingItemList.PENDING); + + int itemCount = 0; + for (final IAEItemStack ge : list) { + itemCount += ge.getStackSize(); + } + + this.startItemCount = itemCount; + this.remainingItemCount = itemCount; + } + + private void updateRemainingItemCount(final IAEItemStack is) { + this.remainingItemCount = this.getRemainingItemCount() - is.getStackSize(); + } + + private void updateElapsedTime() { + final long nextStartTime = System.nanoTime(); + this.elapsedTime = this.getElapsedTime() + nextStartTime - this.lastTime; + this.lastTime = nextStartTime; + } + + public long getElapsedTime() { + return this.elapsedTime; + } + + @Override + public long getRemainingItemCount() { + return this.remainingItemCount; + } + + @Override + public long getStartItemCount() { + return this.startItemCount; + } + + private static class TaskProgress { + private long value; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java b/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java index c8f28ce09..0a1b82748 100644 --- a/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java +++ b/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java @@ -19,11 +19,6 @@ package appeng.me.cluster.implementations; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IBlocks; @@ -32,138 +27,114 @@ import appeng.me.cluster.IAECluster; import appeng.me.cluster.IAEMultiBlock; import appeng.me.cluster.MBCalculator; import appeng.tile.qnb.TileQuantumBridge; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; -public class QuantumCalculator extends MBCalculator -{ +public class QuantumCalculator extends MBCalculator { - private final TileQuantumBridge tqb; + private final TileQuantumBridge tqb; - public QuantumCalculator( final IAEMultiBlock t ) - { - super( t ); - this.tqb = (TileQuantumBridge) t; - } + public QuantumCalculator(final IAEMultiBlock t) { + super(t); + this.tqb = (TileQuantumBridge) t; + } - @Override - public boolean checkMultiblockScale( final WorldCoord min, final WorldCoord max ) - { + @Override + public boolean checkMultiblockScale(final WorldCoord min, final WorldCoord max) { - if( ( max.x - min.x + 1 ) * ( max.y - min.y + 1 ) * ( max.z - min.z + 1 ) == 9 ) - { - final int ones = ( ( max.x - min.x ) == 0 ? 1 : 0 ) + ( ( max.y - min.y ) == 0 ? 1 : 0 ) + ( ( max.z - min.z ) == 0 ? 1 : 0 ); + if ((max.x - min.x + 1) * (max.y - min.y + 1) * (max.z - min.z + 1) == 9) { + final int ones = ((max.x - min.x) == 0 ? 1 : 0) + ((max.y - min.y) == 0 ? 1 : 0) + ((max.z - min.z) == 0 ? 1 : 0); - final int threes = ( ( max.x - min.x ) == 2 ? 1 : 0 ) + ( ( max.y - min.y ) == 2 ? 1 : 0 ) + ( ( max.z - min.z ) == 2 ? 1 : 0 ); + final int threes = ((max.x - min.x) == 2 ? 1 : 0) + ((max.y - min.y) == 2 ? 1 : 0) + ((max.z - min.z) == 2 ? 1 : 0); - return ones == 1 && threes == 2; - } - return false; - } + return ones == 1 && threes == 2; + } + return false; + } - @Override - public IAECluster createCluster( final World w, final WorldCoord min, final WorldCoord max ) - { - return new QuantumCluster( min, max ); - } + @Override + public IAECluster createCluster(final World w, final WorldCoord min, final WorldCoord max) { + return new QuantumCluster(min, max); + } - @Override - public boolean verifyInternalStructure( final World w, final WorldCoord min, final WorldCoord max ) - { + @Override + public boolean verifyInternalStructure(final World w, final WorldCoord min, final WorldCoord max) { - byte num = 0; + byte num = 0; - for( int x = min.x; x <= max.x; x++ ) - { - for( int y = min.y; y <= max.y; y++ ) - { - for( int z = min.z; z <= max.z; z++ ) - { - final BlockPos p = new BlockPos( x, y, z ); - final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity( p ); + for (int x = min.x; x <= max.x; x++) { + for (int y = min.y; y <= max.y; y++) { + for (int z = min.z; z <= max.z; z++) { + final BlockPos p = new BlockPos(x, y, z); + final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity(p); - if( !te.isValid() ) - { - return false; - } + if (!te.isValid()) { + return false; + } - num++; - final IBlocks blocks = AEApi.instance().definitions().blocks(); - if( num == 5 ) - { - if( !this.isBlockAtLocation( w, p, blocks.quantumLink() ) ) - { - return false; - } - } - else - { - if( !this.isBlockAtLocation( w, p, blocks.quantumRing() ) ) - { - return false; - } - } - } - } - } - return true; - } + num++; + final IBlocks blocks = AEApi.instance().definitions().blocks(); + if (num == 5) { + if (!this.isBlockAtLocation(w, p, blocks.quantumLink())) { + return false; + } + } else { + if (!this.isBlockAtLocation(w, p, blocks.quantumRing())) { + return false; + } + } + } + } + } + return true; + } - @Override - public void disconnect() - { - this.tqb.disconnect( true ); - } + @Override + public void disconnect() { + this.tqb.disconnect(true); + } - @Override - public void updateTiles( final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max ) - { - byte num = 0; - byte ringNum = 0; - final QuantumCluster c = (QuantumCluster) cl; + @Override + public void updateTiles(final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max) { + byte num = 0; + byte ringNum = 0; + final QuantumCluster c = (QuantumCluster) cl; - for( int x = min.x; x <= max.x; x++ ) - { - for( int y = min.y; y <= max.y; y++ ) - { - for( int z = min.z; z <= max.z; z++ ) - { - final TileQuantumBridge te = (TileQuantumBridge) w.getTileEntity( new BlockPos( x, y, z ) ); + for (int x = min.x; x <= max.x; x++) { + for (int y = min.y; y <= max.y; y++) { + for (int z = min.z; z <= max.z; z++) { + final TileQuantumBridge te = (TileQuantumBridge) w.getTileEntity(new BlockPos(x, y, z)); - num++; - final byte flags; - if( num == 5 ) - { - flags = num; - c.setCenter( te ); - } - else - { - if( num == 1 || num == 3 || num == 7 || num == 9 ) - { - flags = (byte) ( this.tqb.getCorner() | num ); - } - else - { - flags = num; - } - c.getRing()[ringNum] = te; - ringNum++; - } + num++; + final byte flags; + if (num == 5) { + flags = num; + c.setCenter(te); + } else { + if (num == 1 || num == 3 || num == 7 || num == 9) { + flags = (byte) (this.tqb.getCorner() | num); + } else { + flags = num; + } + c.getRing()[ringNum] = te; + ringNum++; + } - te.updateStatus( c, flags, true ); - } - } - } - } + te.updateStatus(c, flags, true); + } + } + } + } - @Override - public boolean isValidTile( final TileEntity te ) - { - return te instanceof TileQuantumBridge; - } + @Override + public boolean isValidTile(final TileEntity te) { + return te instanceof TileQuantumBridge; + } - private boolean isBlockAtLocation( final IBlockAccess w, final BlockPos pos, final IBlockDefinition def ) - { - return def.maybeBlock().map( block -> block == w.getBlockState( pos ).getBlock() ).orElse( false ); - } + private boolean isBlockAtLocation(final IBlockAccess w, final BlockPos pos, final IBlockDefinition def) { + return def.maybeBlock().map(block -> block == w.getBlockState(pos).getBlock()).orElse(false); + } } diff --git a/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java b/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java index b9fa26a74..40a9b3283 100644 --- a/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java +++ b/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java @@ -19,16 +19,6 @@ package appeng.me.cluster.implementations; -import java.util.Iterator; - -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraft.world.chunk.Chunk; -import net.minecraftforge.common.DimensionManager; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.world.WorldEvent; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; - import appeng.api.AEApi; import appeng.api.events.LocatableEventAnnounce; import appeng.api.events.LocatableEventAnnounce.LocatableEvent; @@ -43,273 +33,230 @@ import appeng.me.cache.helpers.ConnectionWrapper; import appeng.me.cluster.IAECluster; import appeng.tile.qnb.TileQuantumBridge; import appeng.util.iterators.ChainedIterator; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.common.DimensionManager; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.world.WorldEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; + +import java.util.Iterator; -public class QuantumCluster implements ILocatable, IAECluster -{ +public class QuantumCluster implements ILocatable, IAECluster { - private final WorldCoord min; - private final WorldCoord max; - private boolean isDestroyed = false; - private boolean updateStatus = true; - private TileQuantumBridge[] Ring; - private boolean registered = false; - private ConnectionWrapper connection; - private long thisSide; - private long otherSide; - private TileQuantumBridge center; + private final WorldCoord min; + private final WorldCoord max; + private boolean isDestroyed = false; + private boolean updateStatus = true; + private TileQuantumBridge[] Ring; + private boolean registered = false; + private ConnectionWrapper connection; + private long thisSide; + private long otherSide; + private TileQuantumBridge center; - public QuantumCluster( final WorldCoord min, final WorldCoord max ) - { - this.min = min; - this.max = max; - this.setRing( new TileQuantumBridge[8] ); - } + public QuantumCluster(final WorldCoord min, final WorldCoord max) { + this.min = min; + this.max = max; + this.setRing(new TileQuantumBridge[8]); + } - @SubscribeEvent - public void onUnload( final WorldEvent.Unload e ) - { - if( this.center.getWorld() == e.getWorld() ) - { - this.setUpdateStatus( false ); - this.destroy(); - } - } + @SubscribeEvent + public void onUnload(final WorldEvent.Unload e) { + if (this.center.getWorld() == e.getWorld()) { + this.setUpdateStatus(false); + this.destroy(); + } + } - @Override - public void updateStatus( final boolean updateGrid ) - { + @Override + public void updateStatus(final boolean updateGrid) { - final long qe = this.center.getQEFrequency(); + final long qe = this.center.getQEFrequency(); - if( this.thisSide != qe && this.thisSide != -qe ) - { - if( qe != 0 ) - { - if( this.thisSide != 0 ) - { - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.UNREGISTER ) ); - } + if (this.thisSide != qe && this.thisSide != -qe) { + if (qe != 0) { + if (this.thisSide != 0) { + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.UNREGISTER)); + } - if( this.canUseNode( -qe ) ) - { - this.otherSide = qe; - this.thisSide = -qe; - } - else if( this.canUseNode( qe ) ) - { - this.thisSide = qe; - this.otherSide = -qe; - } + if (this.canUseNode(-qe)) { + this.otherSide = qe; + this.thisSide = -qe; + } else if (this.canUseNode(qe)) { + this.thisSide = qe; + this.otherSide = -qe; + } - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.REGISTER ) ); - } - else - { - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.UNREGISTER ) ); + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.REGISTER)); + } else { + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.UNREGISTER)); - this.otherSide = 0; - this.thisSide = 0; - } - } + this.otherSide = 0; + this.thisSide = 0; + } + } - final ILocatable myOtherSide = this.otherSide == 0 ? null : AEApi.instance().registries().locatable().getLocatableBy( this.otherSide ); + final ILocatable myOtherSide = this.otherSide == 0 ? null : AEApi.instance().registries().locatable().getLocatableBy(this.otherSide); - boolean shutdown = false; + boolean shutdown = false; - if( myOtherSide instanceof QuantumCluster ) - { - final QuantumCluster sideA = this; - final QuantumCluster sideB = (QuantumCluster) myOtherSide; + if (myOtherSide instanceof QuantumCluster) { + final QuantumCluster sideA = this; + final QuantumCluster sideB = (QuantumCluster) myOtherSide; - if( sideA.isActive() && sideB.isActive() ) - { - if( this.connection != null && this.connection.getConnection() != null ) - { - final IGridNode a = this.connection.getConnection().a(); - final IGridNode b = this.connection.getConnection().b(); - final IGridNode sa = sideA.getNode(); - final IGridNode sb = sideB.getNode(); - if( ( a == sa || b == sa ) && ( a == sb || b == sb ) ) - { - return; - } - } + if (sideA.isActive() && sideB.isActive()) { + if (this.connection != null && this.connection.getConnection() != null) { + final IGridNode a = this.connection.getConnection().a(); + final IGridNode b = this.connection.getConnection().b(); + final IGridNode sa = sideA.getNode(); + final IGridNode sb = sideB.getNode(); + if ((a == sa || b == sa) && (a == sb || b == sb)) { + return; + } + } - try - { - if( sideA.connection != null ) - { - if( sideA.connection.getConnection() != null ) - { - sideA.connection.getConnection().destroy(); - sideA.connection = new ConnectionWrapper( null ); - } - } + try { + if (sideA.connection != null) { + if (sideA.connection.getConnection() != null) { + sideA.connection.getConnection().destroy(); + sideA.connection = new ConnectionWrapper(null); + } + } - if( sideB.connection != null ) - { - if( sideB.connection.getConnection() != null ) - { - sideB.connection.getConnection().destroy(); - sideB.connection = new ConnectionWrapper( null ); - } - } + if (sideB.connection != null) { + if (sideB.connection.getConnection() != null) { + sideB.connection.getConnection().destroy(); + sideB.connection = new ConnectionWrapper(null); + } + } - sideA.connection = sideB.connection = new ConnectionWrapper( AEApi.instance() - .grid() - .createGridConnection( sideA.getNode(), - sideB.getNode() ) ); - } - catch( final FailedConnectionException e ) - { - // :( - AELog.debug( e ); - } - } - else - { - shutdown = true; - } - } - else - { - shutdown = true; - } + sideA.connection = sideB.connection = new ConnectionWrapper(AEApi.instance() + .grid() + .createGridConnection(sideA.getNode(), + sideB.getNode())); + } catch (final FailedConnectionException e) { + // :( + AELog.debug(e); + } + } else { + shutdown = true; + } + } else { + shutdown = true; + } - if( shutdown && this.connection != null ) - { - if( this.connection.getConnection() != null ) - { - this.connection.getConnection().destroy(); - this.connection.setConnection( null ); - this.connection = new ConnectionWrapper( null ); - } - } - } + if (shutdown && this.connection != null) { + if (this.connection.getConnection() != null) { + this.connection.getConnection().destroy(); + this.connection.setConnection(null); + this.connection = new ConnectionWrapper(null); + } + } + } - private boolean canUseNode( final long qe ) - { - final QuantumCluster qc = (QuantumCluster) AEApi.instance().registries().locatable().getLocatableBy( qe ); - if( qc != null ) - { - final World theWorld = qc.center.getWorld(); - if( !qc.isDestroyed ) - { - final Chunk c = theWorld.getChunkFromBlockCoords( qc.center.getPos() ); - if( c.isLoaded() ) - { - final int id = theWorld.provider.getDimension(); - final World cur = DimensionManager.getWorld( id ); + private boolean canUseNode(final long qe) { + final QuantumCluster qc = (QuantumCluster) AEApi.instance().registries().locatable().getLocatableBy(qe); + if (qc != null) { + final World theWorld = qc.center.getWorld(); + if (!qc.isDestroyed) { + final Chunk c = theWorld.getChunkFromBlockCoords(qc.center.getPos()); + if (c.isLoaded()) { + final int id = theWorld.provider.getDimension(); + final World cur = DimensionManager.getWorld(id); - final TileEntity te = theWorld.getTileEntity( qc.center.getPos() ); - return te != qc.center || theWorld != cur; - } - } - } - return true; - } + final TileEntity te = theWorld.getTileEntity(qc.center.getPos()); + return te != qc.center || theWorld != cur; + } + } + } + return true; + } - private boolean isActive() - { - if( this.isDestroyed || !this.registered ) - { - return false; - } + private boolean isActive() { + if (this.isDestroyed || !this.registered) { + return false; + } - return this.center.isPowered() && this.hasQES(); - } + return this.center.isPowered() && this.hasQES(); + } - private IGridNode getNode() - { - return this.center.getGridNode( AEPartLocation.INTERNAL ); - } + private IGridNode getNode() { + return this.center.getGridNode(AEPartLocation.INTERNAL); + } - private boolean hasQES() - { - return this.thisSide != 0; - } + private boolean hasQES() { + return this.thisSide != 0; + } - @Override - public void destroy() - { - if( this.isDestroyed ) - { - return; - } - this.isDestroyed = true; + @Override + public void destroy() { + if (this.isDestroyed) { + return; + } + this.isDestroyed = true; - if( this.registered ) - { - MinecraftForge.EVENT_BUS.unregister( this ); - this.registered = false; - } + if (this.registered) { + MinecraftForge.EVENT_BUS.unregister(this); + this.registered = false; + } - if( this.thisSide != 0 ) - { - this.updateStatus( true ); - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.UNREGISTER ) ); - } + if (this.thisSide != 0) { + this.updateStatus(true); + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.UNREGISTER)); + } - this.center.updateStatus( null, (byte) -1, this.isUpdateStatus() ); + this.center.updateStatus(null, (byte) -1, this.isUpdateStatus()); - for( final TileQuantumBridge r : this.getRing() ) - { - r.updateStatus( null, (byte) -1, this.isUpdateStatus() ); - } + for (final TileQuantumBridge r : this.getRing()) { + r.updateStatus(null, (byte) -1, this.isUpdateStatus()); + } - this.center = null; - this.setRing( new TileQuantumBridge[8] ); - } + this.center = null; + this.setRing(new TileQuantumBridge[8]); + } - @Override - public Iterator getTiles() - { - return new ChainedIterator<>( this.getRing()[0], this.getRing()[1], this.getRing()[2], this.getRing()[3], this.getRing()[4], this - .getRing()[5], this.getRing()[6], this.getRing()[7], this.center ); - } + @Override + public Iterator getTiles() { + return new ChainedIterator<>(this.getRing()[0], this.getRing()[1], this.getRing()[2], this.getRing()[3], this.getRing()[4], this + .getRing()[5], this.getRing()[6], this.getRing()[7], this.center); + } - public boolean isCorner( final TileQuantumBridge tileQuantumBridge ) - { - return this.getRing()[0] == tileQuantumBridge || this.getRing()[2] == tileQuantumBridge || this.getRing()[4] == tileQuantumBridge || this - .getRing()[6] == tileQuantumBridge; - } + public boolean isCorner(final TileQuantumBridge tileQuantumBridge) { + return this.getRing()[0] == tileQuantumBridge || this.getRing()[2] == tileQuantumBridge || this.getRing()[4] == tileQuantumBridge || this + .getRing()[6] == tileQuantumBridge; + } - @Override - public long getLocatableSerial() - { - return this.thisSide; - } + @Override + public long getLocatableSerial() { + return this.thisSide; + } - public TileQuantumBridge getCenter() - { - return this.center; - } + public TileQuantumBridge getCenter() { + return this.center; + } - void setCenter( final TileQuantumBridge c ) - { - this.registered = true; - MinecraftForge.EVENT_BUS.register( this ); - this.center = c; - } + void setCenter(final TileQuantumBridge c) { + this.registered = true; + MinecraftForge.EVENT_BUS.register(this); + this.center = c; + } - private boolean isUpdateStatus() - { - return this.updateStatus; - } + private boolean isUpdateStatus() { + return this.updateStatus; + } - public void setUpdateStatus( final boolean updateStatus ) - { - this.updateStatus = updateStatus; - } + public void setUpdateStatus(final boolean updateStatus) { + this.updateStatus = updateStatus; + } - TileQuantumBridge[] getRing() - { - return this.Ring; - } + TileQuantumBridge[] getRing() { + return this.Ring; + } - private void setRing( final TileQuantumBridge[] ring ) - { - this.Ring = ring; - } + private void setRing(final TileQuantumBridge[] ring) { + this.Ring = ring; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java index 57960c28e..3c840a2ba 100644 --- a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java +++ b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java @@ -19,92 +19,76 @@ package appeng.me.cluster.implementations; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import appeng.api.util.DimensionalCoord; import appeng.api.util.WorldCoord; import appeng.me.cluster.IAECluster; import appeng.me.cluster.IAEMultiBlock; import appeng.me.cluster.MBCalculator; import appeng.tile.spatial.TileSpatialPylon; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; -public class SpatialPylonCalculator extends MBCalculator -{ +public class SpatialPylonCalculator extends MBCalculator { - private final TileSpatialPylon tqb; + private final TileSpatialPylon tqb; - public SpatialPylonCalculator( final IAEMultiBlock t ) - { - super( t ); - this.tqb = (TileSpatialPylon) t; - } + public SpatialPylonCalculator(final IAEMultiBlock t) { + super(t); + this.tqb = (TileSpatialPylon) t; + } - @Override - public boolean checkMultiblockScale( final WorldCoord min, final WorldCoord max ) - { - return ( min.x == max.x && min.y == max.y && min.z != max.z ) || ( min.x == max.x && min.y != max.y && min.z == max.z ) || ( min.x != max.x && min.y == max.y && min.z == max.z ); - } + @Override + public boolean checkMultiblockScale(final WorldCoord min, final WorldCoord max) { + return (min.x == max.x && min.y == max.y && min.z != max.z) || (min.x == max.x && min.y != max.y && min.z == max.z) || (min.x != max.x && min.y == max.y && min.z == max.z); + } - @Override - public IAECluster createCluster( final World w, final WorldCoord min, final WorldCoord max ) - { - return new SpatialPylonCluster( new DimensionalCoord( w, min.x, min.y, min.z ), new DimensionalCoord( w, max.x, max.y, max.z ) ); - } + @Override + public IAECluster createCluster(final World w, final WorldCoord min, final WorldCoord max) { + return new SpatialPylonCluster(new DimensionalCoord(w, min.x, min.y, min.z), new DimensionalCoord(w, max.x, max.y, max.z)); + } - @Override - public boolean verifyInternalStructure( final World w, final WorldCoord min, final WorldCoord max ) - { + @Override + public boolean verifyInternalStructure(final World w, final WorldCoord min, final WorldCoord max) { - for( int x = min.x; x <= max.x; x++ ) - { - for( int y = min.y; y <= max.y; y++ ) - { - for( int z = min.z; z <= max.z; z++ ) - { - final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity( new BlockPos( x, y, z ) ); + for (int x = min.x; x <= max.x; x++) { + for (int y = min.y; y <= max.y; y++) { + for (int z = min.z; z <= max.z; z++) { + final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity(new BlockPos(x, y, z)); - if( !te.isValid() ) - { - return false; - } - } - } - } + if (!te.isValid()) { + return false; + } + } + } + } - return true; - } + return true; + } - @Override - public void disconnect() - { - this.tqb.disconnect( true ); - } + @Override + public void disconnect() { + this.tqb.disconnect(true); + } - @Override - public void updateTiles( final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max ) - { - final SpatialPylonCluster c = (SpatialPylonCluster) cl; + @Override + public void updateTiles(final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max) { + final SpatialPylonCluster c = (SpatialPylonCluster) cl; - for( int x = min.x; x <= max.x; x++ ) - { - for( int y = min.y; y <= max.y; y++ ) - { - for( int z = min.z; z <= max.z; z++ ) - { - final TileSpatialPylon te = (TileSpatialPylon) w.getTileEntity( new BlockPos( x, y, z ) ); - te.updateStatus( c ); - c.getLine().add( ( te ) ); - } - } - } - } + for (int x = min.x; x <= max.x; x++) { + for (int y = min.y; y <= max.y; y++) { + for (int z = min.z; z <= max.z; z++) { + final TileSpatialPylon te = (TileSpatialPylon) w.getTileEntity(new BlockPos(x, y, z)); + te.updateStatus(c); + c.getLine().add((te)); + } + } + } + } - @Override - public boolean isValidTile( final TileEntity te ) - { - return te instanceof TileSpatialPylon; - } + @Override + public boolean isValidTile(final TileEntity te) { + return te instanceof TileSpatialPylon; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java index c01ba90d3..009a6eaa0 100644 --- a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java +++ b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java @@ -19,123 +19,99 @@ package appeng.me.cluster.implementations; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - import appeng.api.networking.IGridHost; import appeng.api.util.DimensionalCoord; import appeng.me.cluster.IAECluster; import appeng.tile.spatial.TileSpatialPylon; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; -public class SpatialPylonCluster implements IAECluster -{ - private final DimensionalCoord min; - private final DimensionalCoord max; - private final List line = new ArrayList<>(); - private boolean isDestroyed = false; +public class SpatialPylonCluster implements IAECluster { - private Axis currentAxis = Axis.UNFORMED; - private boolean isValid; + private final DimensionalCoord min; + private final DimensionalCoord max; + private final List line = new ArrayList<>(); + private boolean isDestroyed = false; - public SpatialPylonCluster( final DimensionalCoord min, final DimensionalCoord max ) - { - this.min = min.copy(); - this.max = max.copy(); + private Axis currentAxis = Axis.UNFORMED; + private boolean isValid; - if( this.getMin().x != this.getMax().x ) - { - this.setCurrentAxis( Axis.X ); - } - else if( this.getMin().y != this.getMax().y ) - { - this.setCurrentAxis( Axis.Y ); - } - else if( this.getMin().z != this.getMax().z ) - { - this.setCurrentAxis( Axis.Z ); - } - else - { - this.setCurrentAxis( Axis.UNFORMED ); - } - } + public SpatialPylonCluster(final DimensionalCoord min, final DimensionalCoord max) { + this.min = min.copy(); + this.max = max.copy(); - @Override - public void updateStatus( final boolean updateGrid ) - { - for( final TileSpatialPylon r : this.getLine() ) - { - r.recalculateDisplay(); - } - } + if (this.getMin().x != this.getMax().x) { + this.setCurrentAxis(Axis.X); + } else if (this.getMin().y != this.getMax().y) { + this.setCurrentAxis(Axis.Y); + } else if (this.getMin().z != this.getMax().z) { + this.setCurrentAxis(Axis.Z); + } else { + this.setCurrentAxis(Axis.UNFORMED); + } + } - @Override - public void destroy() - { + @Override + public void updateStatus(final boolean updateGrid) { + for (final TileSpatialPylon r : this.getLine()) { + r.recalculateDisplay(); + } + } - if( this.isDestroyed ) - { - return; - } - this.isDestroyed = true; + @Override + public void destroy() { - for( final TileSpatialPylon r : this.getLine() ) - { - r.updateStatus( null ); - } - } + if (this.isDestroyed) { + return; + } + this.isDestroyed = true; - @Override - public Iterator getTiles() - { - return (Iterator) this.getLine().iterator(); - } + for (final TileSpatialPylon r : this.getLine()) { + r.updateStatus(null); + } + } - public int tileCount() - { - return this.getLine().size(); - } + @Override + public Iterator getTiles() { + return (Iterator) this.getLine().iterator(); + } - public Axis getCurrentAxis() - { - return this.currentAxis; - } + public int tileCount() { + return this.getLine().size(); + } - private void setCurrentAxis( final Axis currentAxis ) - { - this.currentAxis = currentAxis; - } + public Axis getCurrentAxis() { + return this.currentAxis; + } - public boolean isValid() - { - return this.isValid; - } + private void setCurrentAxis(final Axis currentAxis) { + this.currentAxis = currentAxis; + } - public void setValid( final boolean isValid ) - { - this.isValid = isValid; - } + public boolean isValid() { + return this.isValid; + } - public DimensionalCoord getMax() - { - return this.max; - } + public void setValid(final boolean isValid) { + this.isValid = isValid; + } - public DimensionalCoord getMin() - { - return this.min; - } + public DimensionalCoord getMax() { + return this.max; + } - List getLine() - { - return this.line; - } + public DimensionalCoord getMin() { + return this.min; + } - public enum Axis - { - X, Y, Z, UNFORMED - } + List getLine() { + return this.line; + } + + public enum Axis { + X, Y, Z, UNFORMED + } } diff --git a/src/main/java/appeng/me/energy/EnergyThreshold.java b/src/main/java/appeng/me/energy/EnergyThreshold.java index cc97bacb7..d2d557618 100644 --- a/src/main/java/appeng/me/energy/EnergyThreshold.java +++ b/src/main/java/appeng/me/energy/EnergyThreshold.java @@ -22,96 +22,75 @@ package appeng.me.energy; import appeng.api.networking.energy.IEnergyWatcher; -public class EnergyThreshold implements Comparable -{ +public class EnergyThreshold implements Comparable { - private final double threshold; - private final IEnergyWatcher watcher; - private final int watcherHash; + private final double threshold; + private final IEnergyWatcher watcher; + private final int watcherHash; - public EnergyThreshold( final double lim, final IEnergyWatcher watcher ) - { - this.threshold = lim; - this.watcher = watcher; - this.watcherHash = watcher.hashCode(); - } + public EnergyThreshold(final double lim, final IEnergyWatcher watcher) { + this.threshold = lim; + this.watcher = watcher; + this.watcherHash = watcher.hashCode(); + } - /** - * Special constructor to allow querying a for a subset of thresholds. - * - * @param lim - * @param bound - */ - public EnergyThreshold( final double lim, final int bound ) - { - this.threshold = lim; - this.watcher = null; - this.watcherHash = bound; - } + /** + * Special constructor to allow querying a for a subset of thresholds. + * + * @param lim + * @param bound + */ + public EnergyThreshold(final double lim, final int bound) { + this.threshold = lim; + this.watcher = null; + this.watcherHash = bound; + } - public IEnergyWatcher getEnergyWatcher() - { - return this.watcher; - } + public IEnergyWatcher getEnergyWatcher() { + return this.watcher; + } - @Override - public int compareTo( EnergyThreshold o ) - { - int a = Double.compare( this.threshold, o.threshold ); + @Override + public int compareTo(EnergyThreshold o) { + int a = Double.compare(this.threshold, o.threshold); - if( a == 0 ) - { - return Integer.compare( this.watcherHash, o.watcherHash ); - } + if (a == 0) { + return Integer.compare(this.watcherHash, o.watcherHash); + } - return a; - } + return a; + } - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - long temp; - temp = Double.doubleToLongBits( this.threshold ); - result = prime * result + (int) ( temp ^ ( temp >>> 32 ) ); - result = prime * result + ( ( this.watcher == null ) ? 0 : this.watcher.hashCode() ); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + long temp; + temp = Double.doubleToLongBits(this.threshold); + result = prime * result + (int) (temp ^ (temp >>> 32)); + result = prime * result + ((this.watcher == null) ? 0 : this.watcher.hashCode()); + return result; + } - @Override - public boolean equals( Object obj ) - { - if( this == obj ) - { - return true; - } - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } - EnergyThreshold other = (EnergyThreshold) obj; - if( Double.doubleToLongBits( this.threshold ) != Double.doubleToLongBits( other.threshold ) ) - { - return false; - } + EnergyThreshold other = (EnergyThreshold) obj; + if (Double.doubleToLongBits(this.threshold) != Double.doubleToLongBits(other.threshold)) { + return false; + } - if( this.watcher == null ) - { - if( other.watcher != null ) - { - return false; - } - } - else if( !this.watcher.equals( other.watcher ) ) - { - return false; - } - return true; - } + if (this.watcher == null) { + return other.watcher == null; + } else return this.watcher.equals(other.watcher); + } } diff --git a/src/main/java/appeng/me/energy/EnergyWatcher.java b/src/main/java/appeng/me/energy/EnergyWatcher.java index 45be0a95b..aac9f26fd 100644 --- a/src/main/java/appeng/me/energy/EnergyWatcher.java +++ b/src/main/java/appeng/me/energy/EnergyWatcher.java @@ -19,73 +19,63 @@ package appeng.me.energy; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - import appeng.api.networking.energy.IEnergyWatcher; import appeng.api.networking.energy.IEnergyWatcherHost; import appeng.me.cache.EnergyGridCache; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + /** * Maintain my interests, and a global watch list, they should always be fully synchronized. */ -public class EnergyWatcher implements IEnergyWatcher -{ +public class EnergyWatcher implements IEnergyWatcher { - private final EnergyGridCache gsc; - private final IEnergyWatcherHost watcherHost; - private final Set myInterests = new HashSet<>(); + private final EnergyGridCache gsc; + private final IEnergyWatcherHost watcherHost; + private final Set myInterests = new HashSet<>(); - public EnergyWatcher( final EnergyGridCache cache, final IEnergyWatcherHost host ) - { - this.gsc = cache; - this.watcherHost = host; - } + public EnergyWatcher(final EnergyGridCache cache, final IEnergyWatcherHost host) { + this.gsc = cache; + this.watcherHost = host; + } - public void post( final EnergyGridCache energyGridCache ) - { - this.watcherHost.onThresholdPass( energyGridCache ); - } + public void post(final EnergyGridCache energyGridCache) { + this.watcherHost.onThresholdPass(energyGridCache); + } - public IEnergyWatcherHost getHost() - { - return this.watcherHost; - } + public IEnergyWatcherHost getHost() { + return this.watcherHost; + } - @Override - public boolean add( final double amount ) - { - final EnergyThreshold eh = new EnergyThreshold( amount, this ); + @Override + public boolean add(final double amount) { + final EnergyThreshold eh = new EnergyThreshold(amount, this); - if( this.myInterests.contains( eh ) ) + if (this.myInterests.contains(eh)) { + return false; + } - { - return false; - } + return this.gsc.registerEnergyInterest(eh) && this.myInterests.add(eh); + } - return this.gsc.registerEnergyInterest( eh ) && this.myInterests.add( eh ); - } + @Override + public boolean remove(final double amount) { + final EnergyThreshold eh = new EnergyThreshold(amount, this); - @Override - public boolean remove( final double amount ) - { - final EnergyThreshold eh = new EnergyThreshold( amount, this ); + return this.myInterests.remove(eh) && this.gsc.unregisterEnergyInterest(eh); + } - return this.myInterests.remove( eh ) && this.gsc.unregisterEnergyInterest( eh ); - } + @Override + public void reset() { + for (Iterator iterator = this.myInterests.iterator(); iterator.hasNext(); ) { + final EnergyThreshold threshold = iterator.next(); - @Override - public void reset() - { - for( Iterator iterator = this.myInterests.iterator(); iterator.hasNext(); ) - { - final EnergyThreshold threshold = iterator.next(); - - this.gsc.unregisterEnergyInterest( threshold ); - iterator.remove(); - } - } + this.gsc.unregisterEnergyInterest(threshold); + iterator.remove(); + } + } } diff --git a/src/main/java/appeng/me/helpers/AENetworkProxy.java b/src/main/java/appeng/me/helpers/AENetworkProxy.java index f6f5215a1..7a8b4de62 100644 --- a/src/main/java/appeng/me/helpers/AENetworkProxy.java +++ b/src/main/java/appeng/me/helpers/AENetworkProxy.java @@ -19,23 +19,8 @@ package appeng.me.helpers; -import java.util.Collections; -import java.util.EnumSet; - -import com.mojang.authlib.GameProfile; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; - import appeng.api.AEApi; -import appeng.api.networking.GridFlags; -import appeng.api.networking.GridNotification; -import appeng.api.networking.IGrid; -import appeng.api.networking.IGridBlock; -import appeng.api.networking.IGridHost; -import appeng.api.networking.IGridNode; +import appeng.api.networking.*; import appeng.api.networking.crafting.ICraftingGrid; import appeng.api.networking.energy.IEnergyGrid; import appeng.api.networking.events.MENetworkPowerIdleChange; @@ -53,399 +38,333 @@ import appeng.me.cache.P2PCache; import appeng.parts.networking.PartCable; import appeng.tile.AEBaseTile; import appeng.util.Platform; +import com.mojang.authlib.GameProfile; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; + +import java.util.Collections; +import java.util.EnumSet; -public class AENetworkProxy implements IGridBlock -{ +public class AENetworkProxy implements IGridBlock { - private final IGridProxyable gp; - private final boolean worldNode; - private final String nbtName; // name - private AEColor myColor = AEColor.TRANSPARENT; - private NBTTagCompound data = null; // input - private ItemStack myRepInstance = ItemStack.EMPTY; - private boolean isReady = false; - private IGridNode node = null; - private EnumSet validSides; - private EnumSet flags = EnumSet.noneOf( GridFlags.class ); - private double idleDraw = 1.0; - private EntityPlayer owner; + private final IGridProxyable gp; + private final boolean worldNode; + private final String nbtName; // name + private AEColor myColor = AEColor.TRANSPARENT; + private NBTTagCompound data = null; // input + private ItemStack myRepInstance = ItemStack.EMPTY; + private boolean isReady = false; + private IGridNode node = null; + private EnumSet validSides; + private EnumSet flags = EnumSet.noneOf(GridFlags.class); + private double idleDraw = 1.0; + private EntityPlayer owner; - public AENetworkProxy( final IGridProxyable te, final String nbtName, final ItemStack visual, final boolean inWorld ) - { - this.gp = te; - this.nbtName = nbtName; - this.worldNode = inWorld; - this.myRepInstance = visual; - this.validSides = EnumSet.allOf( EnumFacing.class ); - } + public AENetworkProxy(final IGridProxyable te, final String nbtName, final ItemStack visual, final boolean inWorld) { + this.gp = te; + this.nbtName = nbtName; + this.worldNode = inWorld; + this.myRepInstance = visual; + this.validSides = EnumSet.allOf(EnumFacing.class); + } - public void setVisualRepresentation( final ItemStack is ) - { - this.myRepInstance = is; - } + public void setVisualRepresentation(final ItemStack is) { + this.myRepInstance = is; + } - public void writeToNBT( final NBTTagCompound tag ) - { - if( this.node != null ) - { - this.node.saveToNBT( this.nbtName, tag ); - } - } + public void writeToNBT(final NBTTagCompound tag) { + if (this.node != null) { + this.node.saveToNBT(this.nbtName, tag); + } + } - public void setValidSides( final EnumSet validSides ) - { - this.validSides = validSides; - if( this.node != null ) - { - this.node.updateState(); - } - } + public void setValidSides(final EnumSet validSides) { + this.validSides = validSides; + if (this.node != null) { + this.node.updateState(); + } + } - public void validate() - { - if( this.gp instanceof AEBaseTile ) - { - TickHandler.INSTANCE.addInit( (AEBaseTile) this.gp ); - } - } + public void validate() { + if (this.gp instanceof AEBaseTile) { + TickHandler.INSTANCE.addInit((AEBaseTile) this.gp); + } + } - public void onChunkUnload() - { - this.isReady = false; - this.invalidate(); - } + public void onChunkUnload() { + this.isReady = false; + this.invalidate(); + } - public void invalidate() - { - this.isReady = false; - if( this.node != null ) - { - this.node.destroy(); - this.node = null; - } - } + public void invalidate() { + this.isReady = false; + if (this.node != null) { + this.node.destroy(); + this.node = null; + } + } - public void onReady() - { - this.isReady = true; + public void onReady() { + this.isReady = true; - // send orientation based directionality to the node. - if( this.gp instanceof IOrientable ) - { - final IOrientable ori = (IOrientable) this.gp; - if( ori.canBeRotated() ) - { - ori.setOrientation( ori.getForward(), ori.getUp() ); - } - } + // send orientation based directionality to the node. + if (this.gp instanceof IOrientable) { + final IOrientable ori = (IOrientable) this.gp; + if (ori.canBeRotated()) { + ori.setOrientation(ori.getForward(), ori.getUp()); + } + } - this.getNode(); - } + this.getNode(); + } - public IGridNode getNode() - { - if( this.node == null && Platform.isServer() && this.isReady ) - { - this.node = AEApi.instance().grid().createGridNode( this ); - this.readFromNBT( this.data ); - this.node.updateState(); - } + public IGridNode getNode() { + if (this.node == null && Platform.isServer() && this.isReady) { + this.node = AEApi.instance().grid().createGridNode(this); + this.readFromNBT(this.data); + this.node.updateState(); + } - return this.node; - } + return this.node; + } - public void readFromNBT( final NBTTagCompound tag ) - { - this.data = tag; - if( this.node != null && this.data != null ) - { - this.node.loadFromNBT( this.nbtName, this.data ); - this.data = null; - } - else if( this.node != null && this.owner != null ) - { - final GameProfile profile = this.owner.getGameProfile(); - final int playerID = WorldData.instance().playerData().getPlayerID( profile ); + public void readFromNBT(final NBTTagCompound tag) { + this.data = tag; + if (this.node != null && this.data != null) { + this.node.loadFromNBT(this.nbtName, this.data); + this.data = null; + } else if (this.node != null && this.owner != null) { + final GameProfile profile = this.owner.getGameProfile(); + final int playerID = WorldData.instance().playerData().getPlayerID(profile); - this.node.setPlayerID( playerID ); - this.owner = null; - } - } + this.node.setPlayerID(playerID); + this.owner = null; + } + } - public IPathingGrid getPath() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - final IPathingGrid pg = grid.getCache( IPathingGrid.class ); - if( pg == null ) - { - throw new GridAccessException(); - } - return pg; - } + public IPathingGrid getPath() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + final IPathingGrid pg = grid.getCache(IPathingGrid.class); + if (pg == null) { + throw new GridAccessException(); + } + return pg; + } - /** - * short cut! - * - * @return grid of node - * - * @throws GridAccessException of node or grid is null - */ - public IGrid getGrid() throws GridAccessException - { - if( this.node == null ) - { - throw new GridAccessException(); - } - final IGrid grid = this.node.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - return grid; - } + /** + * short cut! + * + * @return grid of node + * @throws GridAccessException of node or grid is null + */ + public IGrid getGrid() throws GridAccessException { + if (this.node == null) { + throw new GridAccessException(); + } + final IGrid grid = this.node.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + return grid; + } - public ITickManager getTick() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - final ITickManager pg = grid.getCache( ITickManager.class ); - if( pg == null ) - { - throw new GridAccessException(); - } - return pg; - } + public ITickManager getTick() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + final ITickManager pg = grid.getCache(ITickManager.class); + if (pg == null) { + throw new GridAccessException(); + } + return pg; + } - public IStorageGrid getStorage() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } + public IStorageGrid getStorage() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } - final IStorageGrid pg = grid.getCache( IStorageGrid.class ); + final IStorageGrid pg = grid.getCache(IStorageGrid.class); - if( pg == null ) - { - throw new GridAccessException(); - } + if (pg == null) { + throw new GridAccessException(); + } - return pg; - } + return pg; + } - public P2PCache getP2P() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } + public P2PCache getP2P() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } - final P2PCache pg = grid.getCache( P2PCache.class ); + final P2PCache pg = grid.getCache(P2PCache.class); - if( pg == null ) - { - throw new GridAccessException(); - } + if (pg == null) { + throw new GridAccessException(); + } - return pg; - } + return pg; + } - public ISecurityGrid getSecurity() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } + public ISecurityGrid getSecurity() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } - final ISecurityGrid sg = grid.getCache( ISecurityGrid.class ); + final ISecurityGrid sg = grid.getCache(ISecurityGrid.class); - if( sg == null ) - { - throw new GridAccessException(); - } + if (sg == null) { + throw new GridAccessException(); + } - return sg; - } + return sg; + } - public ICraftingGrid getCrafting() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } + public ICraftingGrid getCrafting() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } - final ICraftingGrid sg = grid.getCache( ICraftingGrid.class ); + final ICraftingGrid sg = grid.getCache(ICraftingGrid.class); - if( sg == null ) - { - throw new GridAccessException(); - } + if (sg == null) { + throw new GridAccessException(); + } - return sg; - } + return sg; + } - @Override - public double getIdlePowerUsage() - { - return this.idleDraw; - } + @Override + public double getIdlePowerUsage() { + return this.idleDraw; + } - @Override - public EnumSet getFlags() - { - return this.flags; - } + @Override + public EnumSet getFlags() { + return this.flags; + } - @Override - public boolean isWorldAccessible() - { - return this.worldNode; - } + @Override + public boolean isWorldAccessible() { + return this.worldNode; + } - @Override - public DimensionalCoord getLocation() - { - return this.gp.getLocation(); - } + @Override + public DimensionalCoord getLocation() { + return this.gp.getLocation(); + } - @Override - public AEColor getGridColor() - { - return this.getColor(); - } + @Override + public AEColor getGridColor() { + return this.getColor(); + } - @Override - public void onGridNotification( final GridNotification notification ) - { - if( this.gp instanceof PartCable ) - { - ( (PartCable) this.gp ).markForUpdate(); - } - } + @Override + public void onGridNotification(final GridNotification notification) { + if (this.gp instanceof PartCable) { + ((PartCable) this.gp).markForUpdate(); + } + } - @Override - public void setNetworkStatus( final IGrid grid, final int channelsInUse ) - { + @Override + public void setNetworkStatus(final IGrid grid, final int channelsInUse) { - } + } - @Override - public EnumSet getConnectableSides() - { - return this.validSides; - } + @Override + public EnumSet getConnectableSides() { + return this.validSides; + } - @Override - public IGridHost getMachine() - { - return this.gp; - } + @Override + public IGridHost getMachine() { + return this.gp; + } - @Override - public void gridChanged() - { - this.gp.gridChanged(); - } + @Override + public void gridChanged() { + this.gp.gridChanged(); + } - @Override - public ItemStack getMachineRepresentation() - { - return this.myRepInstance; - } + @Override + public ItemStack getMachineRepresentation() { + return this.myRepInstance; + } - public void setFlags( final GridFlags... requireChannel ) - { - final EnumSet flags = EnumSet.noneOf( GridFlags.class ); + public void setFlags(final GridFlags... requireChannel) { + final EnumSet flags = EnumSet.noneOf(GridFlags.class); - Collections.addAll( flags, requireChannel ); + Collections.addAll(flags, requireChannel); - this.flags = flags; - } + this.flags = flags; + } - public void setIdlePowerUsage( final double idle ) - { - this.idleDraw = idle; + public void setIdlePowerUsage(final double idle) { + this.idleDraw = idle; - if( this.node != null ) - { - try - { - final IGrid g = this.getGrid(); - g.postEvent( new MENetworkPowerIdleChange( this.node ) ); - } - catch( final GridAccessException e ) - { - // not ready for this yet.. - } - } - } + if (this.node != null) { + try { + final IGrid g = this.getGrid(); + g.postEvent(new MENetworkPowerIdleChange(this.node)); + } catch (final GridAccessException e) { + // not ready for this yet.. + } + } + } - public boolean isReady() - { - return this.isReady; - } + public boolean isReady() { + return this.isReady; + } - public boolean isActive() - { - if( this.node == null ) - { - return false; - } + public boolean isActive() { + if (this.node == null) { + return false; + } - return this.node.isActive(); - } + return this.node.isActive(); + } - public boolean isPowered() - { - try - { - return this.getEnergy().isNetworkPowered(); - } - catch( final GridAccessException e ) - { - return false; - } - } + public boolean isPowered() { + try { + return this.getEnergy().isNetworkPowered(); + } catch (final GridAccessException e) { + return false; + } + } - public IEnergyGrid getEnergy() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - final IEnergyGrid eg = grid.getCache( IEnergyGrid.class ); - if( eg == null ) - { - throw new GridAccessException(); - } - return eg; - } + public IEnergyGrid getEnergy() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + final IEnergyGrid eg = grid.getCache(IEnergyGrid.class); + if (eg == null) { + throw new GridAccessException(); + } + return eg; + } - public void setOwner( final EntityPlayer player ) - { - this.owner = player; - } + public void setOwner(final EntityPlayer player) { + this.owner = player; + } - public AEColor getColor() - { - return this.myColor; - } + public AEColor getColor() { + return this.myColor; + } - public void setColor( final AEColor myColor ) - { - this.myColor = myColor; - } + public void setColor(final AEColor myColor) { + this.myColor = myColor; + } } diff --git a/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java b/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java index a0a14e77d..82317124e 100644 --- a/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java +++ b/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java @@ -19,39 +19,33 @@ package appeng.me.helpers; -import java.util.Iterator; - -import net.minecraft.item.ItemStack; - import appeng.api.networking.IGridMultiblock; import appeng.api.networking.IGridNode; import appeng.me.cluster.IAECluster; import appeng.me.cluster.IAEMultiBlock; import appeng.util.iterators.ChainedIterator; import appeng.util.iterators.ProxyNodeIterator; +import net.minecraft.item.ItemStack; + +import java.util.Iterator; -public class AENetworkProxyMultiblock extends AENetworkProxy implements IGridMultiblock -{ +public class AENetworkProxyMultiblock extends AENetworkProxy implements IGridMultiblock { - public AENetworkProxyMultiblock( final IGridProxyable te, final String nbtName, final ItemStack itemStack, final boolean inWorld ) - { - super( te, nbtName, itemStack, inWorld ); - } + public AENetworkProxyMultiblock(final IGridProxyable te, final String nbtName, final ItemStack itemStack, final boolean inWorld) { + super(te, nbtName, itemStack, inWorld); + } - @Override - public Iterator getMultiblockNodes() - { - if( this.getCluster() == null ) - { - return new ChainedIterator<>(); - } + @Override + public Iterator getMultiblockNodes() { + if (this.getCluster() == null) { + return new ChainedIterator<>(); + } - return new ProxyNodeIterator( this.getCluster().getTiles() ); - } + return new ProxyNodeIterator(this.getCluster().getTiles()); + } - private IAECluster getCluster() - { - return ( (IAEMultiBlock) this.getMachine() ).getCluster(); - } + private IAECluster getCluster() { + return ((IAEMultiBlock) this.getMachine()).getCluster(); + } } diff --git a/src/main/java/appeng/me/helpers/BaseActionSource.java b/src/main/java/appeng/me/helpers/BaseActionSource.java index 4c7ded5b2..e9887e5b9 100644 --- a/src/main/java/appeng/me/helpers/BaseActionSource.java +++ b/src/main/java/appeng/me/helpers/BaseActionSource.java @@ -19,32 +19,27 @@ package appeng.me.helpers; -import java.util.Optional; - -import net.minecraft.entity.player.EntityPlayer; - import appeng.api.networking.security.IActionHost; import appeng.api.networking.security.IActionSource; +import net.minecraft.entity.player.EntityPlayer; + +import java.util.Optional; -public class BaseActionSource implements IActionSource -{ +public class BaseActionSource implements IActionSource { - @Override - public Optional player() - { - return Optional.empty(); - } + @Override + public Optional player() { + return Optional.empty(); + } - @Override - public Optional machine() - { - return Optional.empty(); - } + @Override + public Optional machine() { + return Optional.empty(); + } - @Override - public Optional context( Class key ) - { - return Optional.empty(); - } + @Override + public Optional context(Class key) { + return Optional.empty(); + } } diff --git a/src/main/java/appeng/me/helpers/ChannelPowerSrc.java b/src/main/java/appeng/me/helpers/ChannelPowerSrc.java index 8ca76443c..ec55ab115 100644 --- a/src/main/java/appeng/me/helpers/ChannelPowerSrc.java +++ b/src/main/java/appeng/me/helpers/ChannelPowerSrc.java @@ -25,25 +25,21 @@ import appeng.api.networking.IGridNode; import appeng.api.networking.energy.IEnergySource; -public class ChannelPowerSrc implements IEnergySource -{ +public class ChannelPowerSrc implements IEnergySource { - private final IGridNode node; - private final IEnergySource realSrc; + private final IGridNode node; + private final IEnergySource realSrc; - public ChannelPowerSrc( final IGridNode networkNode, final IEnergySource src ) - { - this.node = networkNode; - this.realSrc = src; - } + public ChannelPowerSrc(final IGridNode networkNode, final IEnergySource src) { + this.node = networkNode; + this.realSrc = src; + } - @Override - public double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier ) - { - if( this.node.isActive() ) - { - return this.realSrc.extractAEPower( amt, mode, usePowerMultiplier ); - } - return 0.0; - } + @Override + public double extractAEPower(final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier) { + if (this.node.isActive()) { + return this.realSrc.extractAEPower(amt, mode, usePowerMultiplier); + } + return 0.0; + } } diff --git a/src/main/java/appeng/me/helpers/GenericInterestManager.java b/src/main/java/appeng/me/helpers/GenericInterestManager.java index 34997fb05..4324088a2 100644 --- a/src/main/java/appeng/me/helpers/GenericInterestManager.java +++ b/src/main/java/appeng/me/helpers/GenericInterestManager.java @@ -19,108 +19,85 @@ package appeng.me.helpers; +import appeng.api.storage.data.IAEStack; +import com.google.common.collect.Multimap; + import java.util.ArrayList; import java.util.Collection; import java.util.List; -import com.google.common.collect.Multimap; -import appeng.api.storage.data.IAEStack; +public class GenericInterestManager { + private final Multimap container; + private List transactions = null; + private int transDepth = 0; -public class GenericInterestManager -{ + public GenericInterestManager(final Multimap interests) { + this.container = interests; + } - private final Multimap container; - private List transactions = null; - private int transDepth = 0; + public void enableTransactions() { + if (this.transDepth == 0) { + this.transactions = new ArrayList<>(); + } - public GenericInterestManager( final Multimap interests ) - { - this.container = interests; - } + this.transDepth++; + } - public void enableTransactions() - { - if( this.transDepth == 0 ) - { - this.transactions = new ArrayList<>(); - } + public void disableTransactions() { + this.transDepth--; - this.transDepth++; - } + if (this.transDepth == 0) { + final List myActions = this.transactions; + this.transactions = null; - public void disableTransactions() - { - this.transDepth--; + for (final SavedTransactions t : myActions) { + if (t.put) { + this.put(t.stack, t.iw); + } else { + this.remove(t.stack, t.iw); + } + } + } + } - if( this.transDepth == 0 ) - { - final List myActions = this.transactions; - this.transactions = null; + public boolean put(final IAEStack stack, final T iw) { + if (this.transactions != null) { + this.transactions.add(new SavedTransactions(true, stack, iw)); + return true; + } else { + return this.container.put(stack, iw); + } + } - for( final SavedTransactions t : myActions ) - { - if( t.put ) - { - this.put( t.stack, t.iw ); - } - else - { - this.remove( t.stack, t.iw ); - } - } - } - } + public boolean remove(final IAEStack stack, final T iw) { + if (this.transactions != null) { + this.transactions.add(new SavedTransactions(false, stack, iw)); + return true; + } else { + return this.container.remove(stack, iw); + } + } - public boolean put( final IAEStack stack, final T iw ) - { - if( this.transactions != null ) - { - this.transactions.add( new SavedTransactions( true, stack, iw ) ); - return true; - } - else - { - return this.container.put( stack, iw ); - } - } + public boolean containsKey(final IAEStack stack) { + return this.container.containsKey(stack); + } - public boolean remove( final IAEStack stack, final T iw ) - { - if( this.transactions != null ) - { - this.transactions.add( new SavedTransactions( false, stack, iw ) ); - return true; - } - else - { - return this.container.remove( stack, iw ); - } - } + public Collection get(final IAEStack stack) { + return this.container.get(stack); + } - public boolean containsKey( final IAEStack stack ) - { - return this.container.containsKey( stack ); - } + private class SavedTransactions { - public Collection get( final IAEStack stack ) - { - return this.container.get( stack ); - } + private final boolean put; + private final IAEStack stack; + private final T iw; - private class SavedTransactions - { - - private final boolean put; - private final IAEStack stack; - private final T iw; - - public SavedTransactions( final boolean putOperation, final IAEStack myStack, final T watcher ) - { - this.put = putOperation; - this.stack = myStack; - this.iw = watcher; - } - } + public SavedTransactions(final boolean putOperation, final IAEStack myStack, final T watcher) { + this.put = putOperation; + this.stack = myStack; + this.iw = watcher; + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/me/helpers/IGridProxyable.java b/src/main/java/appeng/me/helpers/IGridProxyable.java index 916a5659a..3cb5c67f5 100644 --- a/src/main/java/appeng/me/helpers/IGridProxyable.java +++ b/src/main/java/appeng/me/helpers/IGridProxyable.java @@ -23,12 +23,11 @@ import appeng.api.networking.IGridHost; import appeng.api.util.DimensionalCoord; -public interface IGridProxyable extends IGridHost -{ +public interface IGridProxyable extends IGridHost { - AENetworkProxy getProxy(); + AENetworkProxy getProxy(); - DimensionalCoord getLocation(); + DimensionalCoord getLocation(); - void gridChanged(); + void gridChanged(); } diff --git a/src/main/java/appeng/me/helpers/MEMonitorHandler.java b/src/main/java/appeng/me/helpers/MEMonitorHandler.java index e9e013788..046d70b21 100644 --- a/src/main/java/appeng/me/helpers/MEMonitorHandler.java +++ b/src/main/java/appeng/me/helpers/MEMonitorHandler.java @@ -24,10 +24,6 @@ package appeng.me.helpers; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.security.IActionSource; @@ -38,153 +34,130 @@ import appeng.api.storage.IStorageChannel; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; + /** * Common implementation of a simple class that monitors injection/extraction of a inventory to send events to a list of * listeners. * - * @param - * - * TODO: Needs to be redesigned to solve performance issues. + * @param TODO: Needs to be redesigned to solve performance issues. */ -public class MEMonitorHandler> implements IMEMonitor -{ +public class MEMonitorHandler> implements IMEMonitor { - private final IMEInventoryHandler internalHandler; - private final IItemList cachedList; - private final HashMap, Object> listeners = new HashMap<>(); + private final IMEInventoryHandler internalHandler; + private final IItemList cachedList; + private final HashMap, Object> listeners = new HashMap<>(); - protected boolean hasChanged = true; + protected boolean hasChanged = true; - public MEMonitorHandler( final IMEInventoryHandler t ) - { - this.internalHandler = t; - this.cachedList = t.getChannel().createList(); - } + public MEMonitorHandler(final IMEInventoryHandler t) { + this.internalHandler = t; + this.cachedList = t.getChannel().createList(); + } - public MEMonitorHandler( final IMEInventoryHandler t, final IStorageChannel chan ) - { - this.internalHandler = t; - this.cachedList = chan.createList(); - } + public MEMonitorHandler(final IMEInventoryHandler t, final IStorageChannel chan) { + this.internalHandler = t; + this.cachedList = chan.createList(); + } - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } - @Override - public T injectItems( final T input, final Actionable mode, final IActionSource src ) - { - return this.getHandler().injectItems( input, mode, src ); - } + @Override + public T injectItems(final T input, final Actionable mode, final IActionSource src) { + return this.getHandler().injectItems(input, mode, src); + } - protected IMEInventoryHandler getHandler() - { - return this.internalHandler; - } + protected IMEInventoryHandler getHandler() { + return this.internalHandler; + } - public void postChangesToListeners( final Iterable changes, final IActionSource src ) - { - this.notifyListenersOfChange( changes, src ); - } + public void postChangesToListeners(final Iterable changes, final IActionSource src) { + this.notifyListenersOfChange(changes, src); + } - protected void notifyListenersOfChange( final Iterable diff, final IActionSource src ) - { - this.hasChanged = true;// need to update the cache. - final Iterator, Object>> i = this.getListeners(); - while( i.hasNext() ) - { - final Entry, Object> o = i.next(); - final IMEMonitorHandlerReceiver receiver = o.getKey(); - if( receiver.isValid( o.getValue() ) ) - { - receiver.postChange( this, diff, src ); - } - else - { - i.remove(); - } - } - } + protected void notifyListenersOfChange(final Iterable diff, final IActionSource src) { + this.hasChanged = true;// need to update the cache. + final Iterator, Object>> i = this.getListeners(); + while (i.hasNext()) { + final Entry, Object> o = i.next(); + final IMEMonitorHandlerReceiver receiver = o.getKey(); + if (receiver.isValid(o.getValue())) { + receiver.postChange(this, diff, src); + } else { + i.remove(); + } + } + } - protected Iterator, Object>> getListeners() - { - return this.listeners.entrySet().iterator(); - } + protected Iterator, Object>> getListeners() { + return this.listeners.entrySet().iterator(); + } - @Override - public T extractItems( final T request, final Actionable mode, final IActionSource src ) - { - return this.getHandler().extractItems( request, mode, src ); - } + @Override + public T extractItems(final T request, final Actionable mode, final IActionSource src) { + return this.getHandler().extractItems(request, mode, src); + } - @Override - public IStorageChannel getChannel() - { - return this.getHandler().getChannel(); - } + @Override + public IStorageChannel getChannel() { + return this.getHandler().getChannel(); + } - @Override - public AccessRestriction getAccess() - { - return this.getHandler().getAccess(); - } + @Override + public AccessRestriction getAccess() { + return this.getHandler().getAccess(); + } - @Override - public IItemList getStorageList() - { - if( this.hasChanged ) - { - this.hasChanged = false; - this.cachedList.resetStatus(); - return this.getAvailableItems( this.cachedList ); - } + @Override + public IItemList getStorageList() { + if (this.hasChanged) { + this.hasChanged = false; + this.cachedList.resetStatus(); + return this.getAvailableItems(this.cachedList); + } - return this.cachedList; - } + return this.cachedList; + } - @Override - public boolean isPrioritized( final T input ) - { - return this.getHandler().isPrioritized( input ); - } + @Override + public boolean isPrioritized(final T input) { + return this.getHandler().isPrioritized(input); + } - @Override - public boolean canAccept( final T input ) - { - return this.getHandler().canAccept( input ); - } + @Override + public boolean canAccept(final T input) { + return this.getHandler().canAccept(input); + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return this.getHandler().getAvailableItems( out ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return this.getHandler().getAvailableItems(out); + } - @Override - public int getPriority() - { - return this.getHandler().getPriority(); - } + @Override + public int getPriority() { + return this.getHandler().getPriority(); + } - @Override - public int getSlot() - { - return this.getHandler().getSlot(); - } + @Override + public int getSlot() { + return this.getHandler().getSlot(); + } - @Override - public boolean validForPass( final int i ) - { - return this.getHandler().validForPass( i ); - } + @Override + public boolean validForPass(final int i) { + return this.getHandler().validForPass(i); + } } diff --git a/src/main/java/appeng/me/helpers/MachineSource.java b/src/main/java/appeng/me/helpers/MachineSource.java index 9da25b5f3..c957ef2d3 100644 --- a/src/main/java/appeng/me/helpers/MachineSource.java +++ b/src/main/java/appeng/me/helpers/MachineSource.java @@ -19,61 +19,51 @@ package appeng.me.helpers; +import appeng.api.networking.security.IActionHost; +import appeng.api.networking.security.IActionSource; +import net.minecraft.entity.player.EntityPlayer; + import java.util.Objects; import java.util.Optional; -import net.minecraft.entity.player.EntityPlayer; -import appeng.api.networking.security.IActionHost; -import appeng.api.networking.security.IActionSource; +public class MachineSource implements IActionSource { + private final IActionHost via; -public class MachineSource implements IActionSource -{ + public MachineSource(final IActionHost v) { + this.via = v; + } - private final IActionHost via; + @Override + public Optional player() { + return Optional.empty(); + } - public MachineSource( final IActionHost v ) - { - this.via = v; - } + @Override + public Optional machine() { + return Optional.of(this.via); + } - @Override - public Optional player() - { - return Optional.empty(); - } + @Override + public Optional context(Class key) { + return Optional.empty(); + } - @Override - public Optional machine() - { - return Optional.of( this.via ); - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MachineSource that = (MachineSource) o; + return via.equals(that.via); + } - @Override - public Optional context( Class key ) - { - return Optional.empty(); - } - - @Override - public boolean equals( Object o ) - { - if( this == o ) - { - return true; - } - if( o == null || getClass() != o.getClass() ) - { - return false; - } - MachineSource that = (MachineSource) o; - return via.equals( that.via ); - } - - @Override - public int hashCode() - { - return Objects.hash( via ); - } + @Override + public int hashCode() { + return Objects.hash(via); + } } diff --git a/src/main/java/appeng/me/helpers/PlayerSource.java b/src/main/java/appeng/me/helpers/PlayerSource.java index 2024d56f7..c8632d396 100644 --- a/src/main/java/appeng/me/helpers/PlayerSource.java +++ b/src/main/java/appeng/me/helpers/PlayerSource.java @@ -19,44 +19,37 @@ package appeng.me.helpers; -import java.util.Optional; - -import com.google.common.base.Preconditions; - -import net.minecraft.entity.player.EntityPlayer; - import appeng.api.networking.security.IActionHost; import appeng.api.networking.security.IActionSource; +import com.google.common.base.Preconditions; +import net.minecraft.entity.player.EntityPlayer; + +import java.util.Optional; -public class PlayerSource implements IActionSource -{ +public class PlayerSource implements IActionSource { - private final EntityPlayer player; - private final IActionHost via; + private final EntityPlayer player; + private final IActionHost via; - public PlayerSource( final EntityPlayer p, final IActionHost v ) - { - Preconditions.checkNotNull( p ); - this.player = p; - this.via = v; - } + public PlayerSource(final EntityPlayer p, final IActionHost v) { + Preconditions.checkNotNull(p); + this.player = p; + this.via = v; + } - @Override - public Optional player() - { - return Optional.of( this.player ); - } + @Override + public Optional player() { + return Optional.of(this.player); + } - @Override - public Optional machine() - { - return Optional.ofNullable( this.via ); - } + @Override + public Optional machine() { + return Optional.ofNullable(this.via); + } - @Override - public Optional context( Class key ) - { - return Optional.empty(); - } + @Override + public Optional context(Class key) { + return Optional.empty(); + } } diff --git a/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java b/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java index 8a0afab1f..602db76cd 100644 --- a/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java +++ b/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java @@ -26,32 +26,28 @@ import appeng.me.GridConnection; import appeng.me.GridNode; -public class AdHocChannelUpdater implements IGridConnectionVisitor -{ +public class AdHocChannelUpdater implements IGridConnectionVisitor { - private final int usedChannels; + private final int usedChannels; - public AdHocChannelUpdater( final int used ) - { - this.usedChannels = used; - } + public AdHocChannelUpdater(final int used) { + this.usedChannels = used; + } - @Override - public boolean visitNode( final IGridNode n ) - { - final GridNode gn = (GridNode) n; - gn.setControllerRoute( null, true ); - gn.incrementChannelCount( this.usedChannels ); - gn.finalizeChannels(); - return true; - } + @Override + public boolean visitNode(final IGridNode n) { + final GridNode gn = (GridNode) n; + gn.setControllerRoute(null, true); + gn.incrementChannelCount(this.usedChannels); + gn.finalizeChannels(); + return true; + } - @Override - public void visitConnection( final IGridConnection gcc ) - { - final GridConnection gc = (GridConnection) gcc; - gc.setControllerRoute( null, true ); - gc.incrementChannelCount( this.usedChannels ); - gc.finalizeChannels(); - } + @Override + public void visitConnection(final IGridConnection gcc) { + final GridConnection gc = (GridConnection) gcc; + gc.setControllerRoute(null, true); + gc.incrementChannelCount(this.usedChannels); + gc.finalizeChannels(); + } } diff --git a/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java b/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java index f6bb4ff7c..8f40abccf 100644 --- a/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java +++ b/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java @@ -26,21 +26,18 @@ import appeng.me.GridConnection; import appeng.me.GridNode; -public class ControllerChannelUpdater implements IGridConnectionVisitor -{ +public class ControllerChannelUpdater implements IGridConnectionVisitor { - @Override - public boolean visitNode( final IGridNode n ) - { - final GridNode gn = (GridNode) n; - gn.finalizeChannels(); - return true; - } + @Override + public boolean visitNode(final IGridNode n) { + final GridNode gn = (GridNode) n; + gn.finalizeChannels(); + return true; + } - @Override - public void visitConnection( final IGridConnection gcc ) - { - final GridConnection gc = (GridConnection) gcc; - gc.finalizeChannels(); - } + @Override + public void visitConnection(final IGridConnection gcc) { + final GridConnection gc = (GridConnection) gcc; + gc.finalizeChannels(); + } } diff --git a/src/main/java/appeng/me/pathfinding/ControllerValidator.java b/src/main/java/appeng/me/pathfinding/ControllerValidator.java index 8b791ce2e..23548abcd 100644 --- a/src/main/java/appeng/me/pathfinding/ControllerValidator.java +++ b/src/main/java/appeng/me/pathfinding/ControllerValidator.java @@ -19,87 +19,75 @@ package appeng.me.pathfinding; -import appeng.core.AEConfig; -import net.minecraft.util.math.BlockPos; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.networking.IGridVisitor; +import appeng.core.AEConfig; import appeng.tile.networking.TileController; +import net.minecraft.util.math.BlockPos; -public class ControllerValidator implements IGridVisitor -{ +public class ControllerValidator implements IGridVisitor { - private boolean isValid = true; - private int found = 0; - private int minX; - private int minY; - private int minZ; - private int maxX; - private int maxY; - private int maxZ; + private boolean isValid = true; + private int found = 0; + private int minX; + private int minY; + private int minZ; + private int maxX; + private int maxY; + private int maxZ; - public ControllerValidator( final int x, final int y, final int z ) - { - this.minX = x; - this.maxX = x; - this.minY = y; - this.maxY = y; - this.minZ = z; - this.maxZ = z; - } + public ControllerValidator(final int x, final int y, final int z) { + this.minX = x; + this.maxX = x; + this.minY = y; + this.maxY = y; + this.minZ = z; + this.maxZ = z; + } - @Override - public boolean visitNode( final IGridNode n ) - { - final IGridHost host = n.getMachine(); - if( this.isValid() && host instanceof TileController ) - { - final TileController c = (TileController) host; + @Override + public boolean visitNode(final IGridNode n) { + final IGridHost host = n.getMachine(); + if (this.isValid() && host instanceof TileController) { + final TileController c = (TileController) host; - final BlockPos pos = c.getPos(); + final BlockPos pos = c.getPos(); - this.minX = Math.min( pos.getX(), this.minX ); - this.maxX = Math.max( pos.getX(), this.maxX ); - this.minY = Math.min( pos.getY(), this.minY ); - this.maxY = Math.max( pos.getY(), this.maxY ); - this.minZ = Math.min( pos.getZ(), this.minZ ); - this.maxZ = Math.max( pos.getZ(), this.maxZ ); + this.minX = Math.min(pos.getX(), this.minX); + this.maxX = Math.max(pos.getX(), this.maxX); + this.minY = Math.min(pos.getY(), this.minY); + this.maxY = Math.max(pos.getY(), this.maxY); + this.minZ = Math.min(pos.getZ(), this.minZ); + this.maxZ = Math.max(pos.getZ(), this.maxZ); - if( this.maxX - this.minX < AEConfig.instance().getMaxControllerSizeX() && this.maxY - this.minY < AEConfig.instance().getMaxControllerSizeY() && this.maxZ - this.minZ < AEConfig.instance().getMaxControllerSizeZ() ) - { - this.setFound( this.getFound() + 1 ); - return true; - } + if (this.maxX - this.minX < AEConfig.instance().getMaxControllerSizeX() && this.maxY - this.minY < AEConfig.instance().getMaxControllerSizeY() && this.maxZ - this.minZ < AEConfig.instance().getMaxControllerSizeZ()) { + this.setFound(this.getFound() + 1); + return true; + } - this.setValid( false ); - } - else - { - return false; - } + this.setValid(false); + } else { + return false; + } - return this.isValid(); - } + return this.isValid(); + } - public boolean isValid() - { - return this.isValid; - } + public boolean isValid() { + return this.isValid; + } - private void setValid( final boolean isValid ) - { - this.isValid = isValid; - } + private void setValid(final boolean isValid) { + this.isValid = isValid; + } - public int getFound() - { - return this.found; - } + public int getFound() { + return this.found; + } - private void setFound( final int found ) - { - this.found = found; - } + private void setFound(final int found) { + this.found = found; + } } diff --git a/src/main/java/appeng/me/pathfinding/IPathItem.java b/src/main/java/appeng/me/pathfinding/IPathItem.java index bc9835a2c..1a6d32337 100644 --- a/src/main/java/appeng/me/pathfinding/IPathItem.java +++ b/src/main/java/appeng/me/pathfinding/IPathItem.java @@ -19,43 +19,42 @@ package appeng.me.pathfinding; -import java.util.EnumSet; - import appeng.api.networking.GridFlags; import appeng.api.util.IReadOnlyCollection; +import java.util.EnumSet; -public interface IPathItem -{ - IPathItem getControllerRoute(); +public interface IPathItem { - void setControllerRoute( IPathItem fast, boolean zeroOut ); + IPathItem getControllerRoute(); - /** - * used to determine if the finder can continue. - */ - boolean canSupportMoreChannels(); + void setControllerRoute(IPathItem fast, boolean zeroOut); - /** - * find possible choices for other pathing. - */ - IReadOnlyCollection getPossibleOptions(); + /** + * used to determine if the finder can continue. + */ + boolean canSupportMoreChannels(); - /** - * add one to the channel count, this is mostly for cables. - */ - void incrementChannelCount( int usedChannels ); + /** + * find possible choices for other pathing. + */ + IReadOnlyCollection getPossibleOptions(); - /** - * get the grid flags for this IPathItem. - * - * @return the flag set. - */ - EnumSet getFlags(); + /** + * add one to the channel count, this is mostly for cables. + */ + void incrementChannelCount(int usedChannels); - /** - * channels are done, wrap it up. - */ - void finalizeChannels(); + /** + * get the grid flags for this IPathItem. + * + * @return the flag set. + */ + EnumSet getFlags(); + + /** + * channels are done, wrap it up. + */ + void finalizeChannels(); } diff --git a/src/main/java/appeng/me/pathfinding/PathSegment.java b/src/main/java/appeng/me/pathfinding/PathSegment.java index 6209fc60c..412cc1a67 100644 --- a/src/main/java/appeng/me/pathfinding/PathSegment.java +++ b/src/main/java/appeng/me/pathfinding/PathSegment.java @@ -19,153 +19,123 @@ package appeng.me.pathfinding; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - import appeng.api.networking.GridFlags; import appeng.api.networking.IGridMultiblock; import appeng.api.networking.IGridNode; import appeng.me.cache.PathGridCache; +import java.util.*; -public class PathSegment -{ - private final PathGridCache pgc; - private final Set semiOpen; - private final Set closed; - private boolean isDead; - private List open; +public class PathSegment { - public PathSegment( final PathGridCache myPGC, final List open, final Set semiOpen, final Set closed ) - { - this.open = open; - this.semiOpen = semiOpen; - this.closed = closed; - this.pgc = myPGC; - this.setDead( false ); - } + private final PathGridCache pgc; + private final Set semiOpen; + private final Set closed; + private boolean isDead; + private List open; - public boolean step() - { - final List oldOpen = this.open; - this.open = new ArrayList<>(); + public PathSegment(final PathGridCache myPGC, final List open, final Set semiOpen, final Set closed) { + this.open = open; + this.semiOpen = semiOpen; + this.closed = closed; + this.pgc = myPGC; + this.setDead(false); + } - for( final IPathItem i : oldOpen ) - { - for( final IPathItem pi : i.getPossibleOptions() ) - { - final EnumSet flags = pi.getFlags(); + public boolean step() { + final List oldOpen = this.open; + this.open = new ArrayList<>(); - if( !this.closed.contains( pi ) ) - { - pi.setControllerRoute( i, true ); + for (final IPathItem i : oldOpen) { + for (final IPathItem pi : i.getPossibleOptions()) { + final EnumSet flags = pi.getFlags(); - if( flags.contains( GridFlags.REQUIRE_CHANNEL ) ) - { - // close the semi open. - if( !this.semiOpen.contains( pi ) ) - { - final boolean worked; + if (!this.closed.contains(pi)) { + pi.setControllerRoute(i, true); - if( flags.contains( GridFlags.COMPRESSED_CHANNEL ) ) - { - worked = this.useDenseChannel( pi ); - } - else - { - worked = this.useChannel( pi ); - } + if (flags.contains(GridFlags.REQUIRE_CHANNEL)) { + // close the semi open. + if (!this.semiOpen.contains(pi)) { + final boolean worked; - if( worked && flags.contains( GridFlags.MULTIBLOCK ) ) - { - final Iterator oni = ( (IGridMultiblock) ( (IGridNode) pi ).getGridBlock() ).getMultiblockNodes(); - while( oni.hasNext() ) - { - final IGridNode otherNodes = oni.next(); - if( otherNodes != pi ) - { - this.semiOpen.add( (IPathItem) otherNodes ); - } - } - } - } - else - { - pi.incrementChannelCount( 1 ); // give a channel. - this.semiOpen.remove( pi ); - } - } + if (flags.contains(GridFlags.COMPRESSED_CHANNEL)) { + worked = this.useDenseChannel(pi); + } else { + worked = this.useChannel(pi); + } - this.closed.add( pi ); - this.open.add( pi ); - } - } - } + if (worked && flags.contains(GridFlags.MULTIBLOCK)) { + final Iterator oni = ((IGridMultiblock) ((IGridNode) pi).getGridBlock()).getMultiblockNodes(); + while (oni.hasNext()) { + final IGridNode otherNodes = oni.next(); + if (otherNodes != pi) { + this.semiOpen.add((IPathItem) otherNodes); + } + } + } + } else { + pi.incrementChannelCount(1); // give a channel. + this.semiOpen.remove(pi); + } + } - return this.open.isEmpty(); - } + this.closed.add(pi); + this.open.add(pi); + } + } + } - private boolean useDenseChannel( final IPathItem start ) - { - IPathItem pi = start; - while( pi != null ) - { - if( !pi.canSupportMoreChannels() || pi.getFlags().contains( GridFlags.CANNOT_CARRY_COMPRESSED ) ) - { - return false; - } + return this.open.isEmpty(); + } - pi = pi.getControllerRoute(); - } + private boolean useDenseChannel(final IPathItem start) { + IPathItem pi = start; + while (pi != null) { + if (!pi.canSupportMoreChannels() || pi.getFlags().contains(GridFlags.CANNOT_CARRY_COMPRESSED)) { + return false; + } - pi = start; - while( pi != null ) - { - this.pgc.setChannelsByBlocks( this.pgc.getChannelsByBlocks() + 1 ); - pi.incrementChannelCount( 1 ); - pi = pi.getControllerRoute(); - } + pi = pi.getControllerRoute(); + } - this.pgc.setChannelsInUse( this.pgc.getChannelsInUse() + 1 ); - return true; - } + pi = start; + while (pi != null) { + this.pgc.setChannelsByBlocks(this.pgc.getChannelsByBlocks() + 1); + pi.incrementChannelCount(1); + pi = pi.getControllerRoute(); + } - private boolean useChannel( final IPathItem start ) - { - IPathItem pi = start; - while( pi != null ) - { - if( !pi.canSupportMoreChannels() ) - { - return false; - } + this.pgc.setChannelsInUse(this.pgc.getChannelsInUse() + 1); + return true; + } - pi = pi.getControllerRoute(); - } + private boolean useChannel(final IPathItem start) { + IPathItem pi = start; + while (pi != null) { + if (!pi.canSupportMoreChannels()) { + return false; + } - pi = start; - while( pi != null ) - { - this.pgc.setChannelsByBlocks( this.pgc.getChannelsByBlocks() + 1 ); - pi.incrementChannelCount( 1 ); - pi = pi.getControllerRoute(); - } + pi = pi.getControllerRoute(); + } - this.pgc.setChannelsInUse( this.pgc.getChannelsInUse() + 1 ); - return true; - } + pi = start; + while (pi != null) { + this.pgc.setChannelsByBlocks(this.pgc.getChannelsByBlocks() + 1); + pi.incrementChannelCount(1); + pi = pi.getControllerRoute(); + } - public boolean isDead() - { - return this.isDead; - } + this.pgc.setChannelsInUse(this.pgc.getChannelsInUse() + 1); + return true; + } - public void setDead( final boolean isDead ) - { - this.isDead = isDead; - } + public boolean isDead() { + return this.isDead; + } + + public void setDead(final boolean isDead) { + this.isDead = isDead; + } } diff --git a/src/main/java/appeng/me/storage/AbstractCellInventory.java b/src/main/java/appeng/me/storage/AbstractCellInventory.java index e428e6493..6a218510f 100644 --- a/src/main/java/appeng/me/storage/AbstractCellInventory.java +++ b/src/main/java/appeng/me/storage/AbstractCellInventory.java @@ -19,10 +19,6 @@ package appeng.me.storage; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.FuzzyMode; import appeng.api.implementations.items.IStorageCell; import appeng.api.storage.ICellInventory; @@ -30,6 +26,9 @@ import appeng.api.storage.ISaveProvider; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; import appeng.util.Platform; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.items.IItemHandler; /** @@ -37,316 +36,267 @@ import appeng.util.Platform; * @version rv6 - 2018-01-17 * @since rv6 2018-01-17 */ -public abstract class AbstractCellInventory> implements ICellInventory -{ - private static final int MAX_ITEM_TYPES = 63; - private static final String ITEM_TYPE_TAG = "it"; - private static final String ITEM_COUNT_TAG = "ic"; - private static final String ITEM_SLOT = "#"; - private static final String ITEM_SLOT_COUNT = "@"; - protected static final String ITEM_PRE_FORMATTED_COUNT = "PF"; - protected static final String ITEM_PRE_FORMATTED_SLOT = "PF#"; - protected static final String ITEM_PRE_FORMATTED_NAME = "PN"; - protected static final String ITEM_PRE_FORMATTED_FUZZY = "FP"; - private static final String[] ITEM_SLOT_KEYS = new String[MAX_ITEM_TYPES]; - private static final String[] ITEM_SLOT_COUNT_KEYS = new String[MAX_ITEM_TYPES]; - private final NBTTagCompound tagCompound; - protected final ISaveProvider container; - private int maxItemTypes = MAX_ITEM_TYPES; - private short storedItems = 0; - private int storedItemCount = 0; - protected IItemList cellItems; - private final ItemStack i; - protected final IStorageCell cellType; - protected final int itemsPerByte; - private boolean isPersisted = true; +public abstract class AbstractCellInventory> implements ICellInventory { + private static final int MAX_ITEM_TYPES = 63; + private static final String ITEM_TYPE_TAG = "it"; + private static final String ITEM_COUNT_TAG = "ic"; + private static final String ITEM_SLOT = "#"; + private static final String ITEM_SLOT_COUNT = "@"; + protected static final String ITEM_PRE_FORMATTED_COUNT = "PF"; + protected static final String ITEM_PRE_FORMATTED_SLOT = "PF#"; + protected static final String ITEM_PRE_FORMATTED_NAME = "PN"; + protected static final String ITEM_PRE_FORMATTED_FUZZY = "FP"; + private static final String[] ITEM_SLOT_KEYS = new String[MAX_ITEM_TYPES]; + private static final String[] ITEM_SLOT_COUNT_KEYS = new String[MAX_ITEM_TYPES]; + private final NBTTagCompound tagCompound; + protected final ISaveProvider container; + private int maxItemTypes = MAX_ITEM_TYPES; + private short storedItems = 0; + private int storedItemCount = 0; + protected IItemList cellItems; + private final ItemStack i; + protected final IStorageCell cellType; + protected final int itemsPerByte; + private boolean isPersisted = true; - static - { - for( int x = 0; x < MAX_ITEM_TYPES; x++ ) - { - ITEM_SLOT_KEYS[x] = ITEM_SLOT + x; - ITEM_SLOT_COUNT_KEYS[x] = ITEM_SLOT_COUNT + x; - } - } + static { + for (int x = 0; x < MAX_ITEM_TYPES; x++) { + ITEM_SLOT_KEYS[x] = ITEM_SLOT + x; + ITEM_SLOT_COUNT_KEYS[x] = ITEM_SLOT_COUNT + x; + } + } - protected AbstractCellInventory( final IStorageCell cellType, final ItemStack o, final ISaveProvider container ) - { - this.i = o; - this.cellType = cellType; - this.itemsPerByte = this.cellType.getChannel().getUnitsPerByte(); - this.maxItemTypes = this.cellType.getTotalTypes( this.i ); + protected AbstractCellInventory(final IStorageCell cellType, final ItemStack o, final ISaveProvider container) { + this.i = o; + this.cellType = cellType; + this.itemsPerByte = this.cellType.getChannel().getUnitsPerByte(); + this.maxItemTypes = this.cellType.getTotalTypes(this.i); - if( this.maxItemTypes > MAX_ITEM_TYPES ) - { - this.maxItemTypes = MAX_ITEM_TYPES; - } - if( this.maxItemTypes < 1 ) - { - this.maxItemTypes = 1; - } + if (this.maxItemTypes > MAX_ITEM_TYPES) { + this.maxItemTypes = MAX_ITEM_TYPES; + } + if (this.maxItemTypes < 1) { + this.maxItemTypes = 1; + } - this.container = container; - this.tagCompound = Platform.openNbtData( o ); - this.storedItems = this.tagCompound.getShort( ITEM_TYPE_TAG ); - this.storedItemCount = this.tagCompound.getInteger( ITEM_COUNT_TAG ); - this.cellItems = null; - } + this.container = container; + this.tagCompound = Platform.openNbtData(o); + this.storedItems = this.tagCompound.getShort(ITEM_TYPE_TAG); + this.storedItemCount = this.tagCompound.getInteger(ITEM_COUNT_TAG); + this.cellItems = null; + } - protected IItemList getCellItems() - { - if( this.cellItems == null ) - { - this.cellItems = this.getChannel().createList(); - this.loadCellItems(); - } + protected IItemList getCellItems() { + if (this.cellItems == null) { + this.cellItems = this.getChannel().createList(); + this.loadCellItems(); + } - return this.cellItems; - } + return this.cellItems; + } - @Override - public void persist() - { - if( this.isPersisted ) - { - return; - } + @Override + public void persist() { + if (this.isPersisted) { + return; + } - int itemCount = 0; + int itemCount = 0; - // add new pretty stuff... - int x = 0; - for( final T v : this.cellItems ) - { - itemCount += v.getStackSize(); + // add new pretty stuff... + int x = 0; + for (final T v : this.cellItems) { + itemCount += v.getStackSize(); - final NBTTagCompound g = new NBTTagCompound(); - v.writeToNBT( g ); - this.tagCompound.setTag( ITEM_SLOT_KEYS[x], g ); - this.tagCompound.setInteger( ITEM_SLOT_COUNT_KEYS[x], (int) v.getStackSize() ); + final NBTTagCompound g = new NBTTagCompound(); + v.writeToNBT(g); + this.tagCompound.setTag(ITEM_SLOT_KEYS[x], g); + this.tagCompound.setInteger(ITEM_SLOT_COUNT_KEYS[x], (int) v.getStackSize()); - x++; - } + x++; + } - final short oldStoredItems = this.storedItems; + final short oldStoredItems = this.storedItems; - this.storedItems = (short) this.cellItems.size(); - if( this.cellItems.isEmpty() ) - { - this.tagCompound.removeTag( ITEM_TYPE_TAG ); - } - else - { - this.tagCompound.setShort( ITEM_TYPE_TAG, this.storedItems ); - } + this.storedItems = (short) this.cellItems.size(); + if (this.cellItems.isEmpty()) { + this.tagCompound.removeTag(ITEM_TYPE_TAG); + } else { + this.tagCompound.setShort(ITEM_TYPE_TAG, this.storedItems); + } - this.storedItemCount = itemCount; - if( itemCount == 0 ) - { - this.tagCompound.removeTag( ITEM_COUNT_TAG ); - } - else - { - this.tagCompound.setInteger( ITEM_COUNT_TAG, itemCount ); - } + this.storedItemCount = itemCount; + if (itemCount == 0) { + this.tagCompound.removeTag(ITEM_COUNT_TAG); + } else { + this.tagCompound.setInteger(ITEM_COUNT_TAG, itemCount); + } - // clean any old crusty stuff... - for( ; x >= oldStoredItems && x < this.maxItemTypes; x++ ) - { - this.tagCompound.removeTag( ITEM_SLOT_KEYS[x] ); - this.tagCompound.removeTag( ITEM_SLOT_COUNT_KEYS[x] ); - } + // clean any old crusty stuff... + for (; x >= oldStoredItems && x < this.maxItemTypes; x++) { + this.tagCompound.removeTag(ITEM_SLOT_KEYS[x]); + this.tagCompound.removeTag(ITEM_SLOT_COUNT_KEYS[x]); + } - this.isPersisted = true; - } + this.isPersisted = true; + } - protected void saveChanges() - { - // recalculate values - this.storedItems = (short) this.cellItems.size(); - this.storedItemCount = 0; - for( final T v : this.cellItems ) - { - this.storedItemCount += v.getStackSize(); - } + protected void saveChanges() { + // recalculate values + this.storedItems = (short) this.cellItems.size(); + this.storedItemCount = 0; + for (final T v : this.cellItems) { + this.storedItemCount += v.getStackSize(); + } - this.isPersisted = false; - if( this.container != null ) - { - this.container.saveChanges( this ); - } - else - { - // if there is no ISaveProvider, store to NBT immediately - this.persist(); - } - } + this.isPersisted = false; + if (this.container != null) { + this.container.saveChanges(this); + } else { + // if there is no ISaveProvider, store to NBT immediately + this.persist(); + } + } - private void loadCellItems() - { - if( this.cellItems == null ) - { - this.cellItems = this.getChannel().createList(); - } + private void loadCellItems() { + if (this.cellItems == null) { + this.cellItems = this.getChannel().createList(); + } - this.cellItems.resetStatus(); // clears totals and stuff. + this.cellItems.resetStatus(); // clears totals and stuff. - final int types = (int) this.getStoredItemTypes(); - boolean needsUpdate = false; + final int types = (int) this.getStoredItemTypes(); + boolean needsUpdate = false; - for( int slot = 0; slot < types; slot++ ) - { - NBTTagCompound compoundTag = this.tagCompound.getCompoundTag( ITEM_SLOT_KEYS[slot] ); - int stackSize = this.tagCompound.getInteger( ITEM_SLOT_COUNT_KEYS[slot] ); - needsUpdate |= !this.loadCellItem( compoundTag, stackSize ); - } + for (int slot = 0; slot < types; slot++) { + NBTTagCompound compoundTag = this.tagCompound.getCompoundTag(ITEM_SLOT_KEYS[slot]); + int stackSize = this.tagCompound.getInteger(ITEM_SLOT_COUNT_KEYS[slot]); + needsUpdate |= !this.loadCellItem(compoundTag, stackSize); + } - if( needsUpdate ) - { - this.saveChanges(); - } - } + if (needsUpdate) { + this.saveChanges(); + } + } - /** - * Load a single item. - * - * @param compoundTag - * @param stackSize - * @return true when successfully loaded - */ - protected abstract boolean loadCellItem( NBTTagCompound compoundTag, int stackSize ); + /** + * Load a single item. + * + * @param compoundTag + * @param stackSize + * @return true when successfully loaded + */ + protected abstract boolean loadCellItem(NBTTagCompound compoundTag, int stackSize); - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final T item : this.getCellItems() ) - { - out.add( item ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final T item : this.getCellItems()) { + out.add(item); + } - return out; - } + return out; + } - @Override - public ItemStack getItemStack() - { - return this.i; - } + @Override + public ItemStack getItemStack() { + return this.i; + } - @Override - public double getIdleDrain() - { - return this.cellType.getIdleDrain(); - } + @Override + public double getIdleDrain() { + return this.cellType.getIdleDrain(); + } - @Override - public FuzzyMode getFuzzyMode() - { - return this.cellType.getFuzzyMode( this.i ); - } + @Override + public FuzzyMode getFuzzyMode() { + return this.cellType.getFuzzyMode(this.i); + } - @Override - public IItemHandler getConfigInventory() - { - return this.cellType.getConfigInventory( this.i ); - } + @Override + public IItemHandler getConfigInventory() { + return this.cellType.getConfigInventory(this.i); + } - @Override - public IItemHandler getUpgradesInventory() - { - return this.cellType.getUpgradesInventory( this.i ); - } + @Override + public IItemHandler getUpgradesInventory() { + return this.cellType.getUpgradesInventory(this.i); + } - @Override - public int getBytesPerType() - { - return this.cellType.getBytesPerType( this.i ); - } + @Override + public int getBytesPerType() { + return this.cellType.getBytesPerType(this.i); + } - @Override - public boolean canHoldNewItem() - { - final long bytesFree = this.getFreeBytes(); - return ( bytesFree > this.getBytesPerType() || ( bytesFree == this.getBytesPerType() && this.getUnusedItemCount() > 0 ) ) && this - .getRemainingItemTypes() > 0; - } + @Override + public boolean canHoldNewItem() { + final long bytesFree = this.getFreeBytes(); + return (bytesFree > this.getBytesPerType() || (bytesFree == this.getBytesPerType() && this.getUnusedItemCount() > 0)) && this + .getRemainingItemTypes() > 0; + } - @Override - public long getTotalBytes() - { - return this.cellType.getBytes( this.i ); - } + @Override + public long getTotalBytes() { + return this.cellType.getBytes(this.i); + } - @Override - public long getFreeBytes() - { - return this.getTotalBytes() - this.getUsedBytes(); - } + @Override + public long getFreeBytes() { + return this.getTotalBytes() - this.getUsedBytes(); + } - @Override - public long getTotalItemTypes() - { - return this.maxItemTypes; - } + @Override + public long getTotalItemTypes() { + return this.maxItemTypes; + } - @Override - public long getStoredItemCount() - { - return this.storedItemCount; - } + @Override + public long getStoredItemCount() { + return this.storedItemCount; + } - @Override - public long getStoredItemTypes() - { - return this.storedItems; - } + @Override + public long getStoredItemTypes() { + return this.storedItems; + } - @Override - public long getRemainingItemTypes() - { - final long basedOnStorage = this.getFreeBytes() / this.getBytesPerType(); - final long baseOnTotal = this.getTotalItemTypes() - this.getStoredItemTypes(); - return basedOnStorage > baseOnTotal ? baseOnTotal : basedOnStorage; - } + @Override + public long getRemainingItemTypes() { + final long basedOnStorage = this.getFreeBytes() / this.getBytesPerType(); + final long baseOnTotal = this.getTotalItemTypes() - this.getStoredItemTypes(); + return basedOnStorage > baseOnTotal ? baseOnTotal : basedOnStorage; + } - @Override - public long getUsedBytes() - { - final long bytesForItemCount = ( this.getStoredItemCount() + this.getUnusedItemCount() ) / this.itemsPerByte; - return this.getStoredItemTypes() * this.getBytesPerType() + bytesForItemCount; - } + @Override + public long getUsedBytes() { + final long bytesForItemCount = (this.getStoredItemCount() + this.getUnusedItemCount()) / this.itemsPerByte; + return this.getStoredItemTypes() * this.getBytesPerType() + bytesForItemCount; + } - @Override - public long getRemainingItemCount() - { - final long remaining = this.getFreeBytes() * this.itemsPerByte + this.getUnusedItemCount(); - return remaining > 0 ? remaining : 0; - } + @Override + public long getRemainingItemCount() { + final long remaining = this.getFreeBytes() * this.itemsPerByte + this.getUnusedItemCount(); + return remaining > 0 ? remaining : 0; + } - @Override - public int getUnusedItemCount() - { - final int div = (int) ( this.getStoredItemCount() % 8 ); + @Override + public int getUnusedItemCount() { + final int div = (int) (this.getStoredItemCount() % 8); - if( div == 0 ) - { - return 0; - } + if (div == 0) { + return 0; + } - return this.itemsPerByte - div; - } + return this.itemsPerByte - div; + } - @Override - public int getStatusForCell() - { - if( this.canHoldNewItem() ) - { - return 1; - } - if( this.getRemainingItemCount() > 0 ) - { - return 2; - } - return 3; - } + @Override + public int getStatusForCell() { + if (this.canHoldNewItem()) { + return 1; + } + if (this.getRemainingItemCount() > 0) { + return 2; + } + return 3; + } } diff --git a/src/main/java/appeng/me/storage/BasicCellInventory.java b/src/main/java/appeng/me/storage/BasicCellInventory.java index f7ab99c85..ac8d8259b 100644 --- a/src/main/java/appeng/me/storage/BasicCellInventory.java +++ b/src/main/java/appeng/me/storage/BasicCellInventory.java @@ -1,11 +1,6 @@ - package appeng.me.storage; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import appeng.api.config.Actionable; import appeng.api.exceptions.AppEngException; import appeng.api.implementations.items.IStorageCell; @@ -18,272 +13,222 @@ import appeng.api.storage.data.IAEStack; import appeng.core.AEConfig; import appeng.core.AELog; import appeng.util.item.AEStack; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; -public class BasicCellInventory> extends AbstractCellInventory -{ - private final IStorageChannel channel; +public class BasicCellInventory> extends AbstractCellInventory { + private final IStorageChannel channel; - private BasicCellInventory( final IStorageCell cellType, final ItemStack o, final ISaveProvider container ) - { - super( cellType, o, container ); - this.channel = cellType.getChannel(); - } + private BasicCellInventory(final IStorageCell cellType, final ItemStack o, final ISaveProvider container) { + super(cellType, o, container); + this.channel = cellType.getChannel(); + } - public static > ICellInventory createInventory( final ItemStack o, final ISaveProvider container ) - { - try - { - if( o == null ) - { - throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); - } + public static > ICellInventory createInventory(final ItemStack o, final ISaveProvider container) { + try { + if (o == null) { + throw new AppEngException("ItemStack was used as a cell, but was not a cell!"); + } - final Item type = o.getItem(); - final IStorageCell cellType; - if( type instanceof IStorageCell ) - { - cellType = (IStorageCell) type; - } - else - { - throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); - } + final Item type = o.getItem(); + final IStorageCell cellType; + if (type instanceof IStorageCell) { + cellType = (IStorageCell) type; + } else { + throw new AppEngException("ItemStack was used as a cell, but was not a cell!"); + } - if( !cellType.isStorageCell( o ) ) - { - throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); - } + if (!cellType.isStorageCell(o)) { + throw new AppEngException("ItemStack was used as a cell, but was not a cell!"); + } - return new BasicCellInventory( cellType, o, container ); - } - catch( final AppEngException e ) - { - AELog.error( e ); - return null; - } - } + return new BasicCellInventory(cellType, o, container); + } catch (final AppEngException e) { + AELog.error(e); + return null; + } + } - public static > boolean isCellOfType( final ItemStack input, IStorageChannel channel ) - { - final IStorageCell type = getStorageCell( input ); + public static > boolean isCellOfType(final ItemStack input, IStorageChannel channel) { + final IStorageCell type = getStorageCell(input); - return type != null && type.getChannel() == channel; - } + return type != null && type.getChannel() == channel; + } - public static boolean isCell( final ItemStack input ) - { - return getStorageCell( input ) != null; - } + public static boolean isCell(final ItemStack input) { + return getStorageCell(input) != null; + } - private boolean isStorageCell( final T input ) - { - if( input instanceof IAEItemStack ) - { - final IAEItemStack stack = (IAEItemStack) input; - final IStorageCell type = getStorageCell( stack.getDefinition() ); + private boolean isStorageCell(final T input) { + if (input instanceof IAEItemStack) { + final IAEItemStack stack = (IAEItemStack) input; + final IStorageCell type = getStorageCell(stack.getDefinition()); - return type != null && !type.storableInStorageCell(); - } + return type != null && !type.storableInStorageCell(); + } - return false; - } + return false; + } - private static IStorageCell getStorageCell( final ItemStack input ) - { - if( input != null ) - { - final Item type = input.getItem(); + private static IStorageCell getStorageCell(final ItemStack input) { + if (input != null) { + final Item type = input.getItem(); - if( type instanceof IStorageCell ) - { - return (IStorageCell) type; - } - } + if (type instanceof IStorageCell) { + return (IStorageCell) type; + } + } - return null; - } + return null; + } - @SuppressWarnings( { "rawtypes", "unchecked" } ) - private static boolean isCellEmpty( ICellInventory inv ) - { - if( inv != null ) - { - return inv.getAvailableItems( inv.getChannel().createList() ).isEmpty(); - } - return true; - } + @SuppressWarnings({"rawtypes", "unchecked"}) + private static boolean isCellEmpty(ICellInventory inv) { + if (inv != null) { + return inv.getAvailableItems(inv.getChannel().createList()).isEmpty(); + } + return true; + } - @Override - public T injectItems( T input, Actionable mode, IActionSource src ) - { - if( input == null ) - { - return null; - } - if( input.getStackSize() == 0 ) - { - return null; - } + @Override + public T injectItems(T input, Actionable mode, IActionSource src) { + if (input == null) { + return null; + } + if (input.getStackSize() == 0) { + return null; + } - if( this.cellType.isBlackListed( this.getItemStack(), input ) ) - { - return input; - } - // This is slightly hacky as it expects a read-only access, but fine for now. - // TODO: Guarantee a read-only access. E.g. provide an isEmpty() method and ensure CellInventory does not write - // any NBT data for empty cells instead of relying on an empty IItemContainer - if( this.isStorageCell( input ) ) - { - final ICellInventory meInventory = createInventory( ( (IAEItemStack) input ).createItemStack(), null ); - if( !isCellEmpty( meInventory ) ) - { - return input; - } - } + if (this.cellType.isBlackListed(this.getItemStack(), input)) { + return input; + } + // This is slightly hacky as it expects a read-only access, but fine for now. + // TODO: Guarantee a read-only access. E.g. provide an isEmpty() method and ensure CellInventory does not write + // any NBT data for empty cells instead of relying on an empty IItemContainer + if (this.isStorageCell(input)) { + final ICellInventory meInventory = createInventory(((IAEItemStack) input).createItemStack(), null); + if (!isCellEmpty(meInventory)) { + return input; + } + } - final T l = this.getCellItems().findPrecise( input ); - if( l != null ) - { - final long remainingItemCount = this.getRemainingItemCount(); - if( remainingItemCount <= 0 ) - { - return input; - } + final T l = this.getCellItems().findPrecise(input); + if (l != null) { + final long remainingItemCount = this.getRemainingItemCount(); + if (remainingItemCount <= 0) { + return input; + } - if( input.getStackSize() > remainingItemCount ) - { - final T r = input.copy(); - r.setStackSize( r.getStackSize() - remainingItemCount ); - if( mode == Actionable.MODULATE ) - { - l.setStackSize( l.getStackSize() + remainingItemCount ); - this.saveChanges(); - } - return r; - } - else - { - if( mode == Actionable.MODULATE ) - { - l.setStackSize( l.getStackSize() + input.getStackSize() ); - this.saveChanges(); - } - return null; - } - } + if (input.getStackSize() > remainingItemCount) { + final T r = input.copy(); + r.setStackSize(r.getStackSize() - remainingItemCount); + if (mode == Actionable.MODULATE) { + l.setStackSize(l.getStackSize() + remainingItemCount); + this.saveChanges(); + } + return r; + } else { + if (mode == Actionable.MODULATE) { + l.setStackSize(l.getStackSize() + input.getStackSize()); + this.saveChanges(); + } + return null; + } + } - if( this.canHoldNewItem() ) // room for new type, and for at least one item! - { - final int remainingItemCount = (int) this.getRemainingItemCount() - this.getBytesPerType() * this.itemsPerByte; - if( remainingItemCount > 0 ) - { - if( input.getStackSize() > remainingItemCount ) - { - final T toReturn = input.copy(); - toReturn.setStackSize( input.getStackSize() - remainingItemCount ); - if( mode == Actionable.MODULATE ) - { - final T toWrite = input.copy(); - toWrite.setStackSize( remainingItemCount ); + if (this.canHoldNewItem()) // room for new type, and for at least one item! + { + final int remainingItemCount = (int) this.getRemainingItemCount() - this.getBytesPerType() * this.itemsPerByte; + if (remainingItemCount > 0) { + if (input.getStackSize() > remainingItemCount) { + final T toReturn = input.copy(); + toReturn.setStackSize(input.getStackSize() - remainingItemCount); + if (mode == Actionable.MODULATE) { + final T toWrite = input.copy(); + toWrite.setStackSize(remainingItemCount); - this.cellItems.add( toWrite ); - this.saveChanges(); - } - return toReturn; - } + this.cellItems.add(toWrite); + this.saveChanges(); + } + return toReturn; + } - if( mode == Actionable.MODULATE ) - { - this.cellItems.add( input ); - this.saveChanges(); - } + if (mode == Actionable.MODULATE) { + this.cellItems.add(input); + this.saveChanges(); + } - return null; - } - } + return null; + } + } - return input; - } + return input; + } - @Override - public T extractItems( T request, Actionable mode, IActionSource src ) - { - if( request == null ) - { - return null; - } + @Override + public T extractItems(T request, Actionable mode, IActionSource src) { + if (request == null) { + return null; + } - final long size = Math.min( Integer.MAX_VALUE, request.getStackSize() ); + final long size = Math.min(Integer.MAX_VALUE, request.getStackSize()); - T Results = null; + T Results = null; - final T l = this.getCellItems().findPrecise( request ); - if( l != null ) - { - Results = l.copy(); + final T l = this.getCellItems().findPrecise(request); + if (l != null) { + Results = l.copy(); - if( l.getStackSize() <= size ) - { - Results.setStackSize( l.getStackSize() ); - if( mode == Actionable.MODULATE ) - { - l.setStackSize( 0 ); - this.saveChanges(); - } - } - else - { - Results.setStackSize( size ); - if( mode == Actionable.MODULATE ) - { - l.setStackSize( l.getStackSize() - size ); - this.saveChanges(); - } - } - } + if (l.getStackSize() <= size) { + Results.setStackSize(l.getStackSize()); + if (mode == Actionable.MODULATE) { + l.setStackSize(0); + this.saveChanges(); + } + } else { + Results.setStackSize(size); + if (mode == Actionable.MODULATE) { + l.setStackSize(l.getStackSize() - size); + this.saveChanges(); + } + } + } - return Results; - } + return Results; + } - @Override - public IStorageChannel getChannel() - { - return this.channel; - } + @Override + public IStorageChannel getChannel() { + return this.channel; + } - @Override - protected boolean loadCellItem( NBTTagCompound compoundTag, int stackSize ) - { - // Now load the item stack - final T t; - try - { - t = this.getChannel().createFromNBT( compoundTag ); - if( t == null ) - { - AELog.warn( "Removing item " + compoundTag + " from storage cell because the associated item type couldn't be found." ); - return false; - } - } - catch( Throwable ex ) - { - if( AEConfig.instance().isRemoveCrashingItemsOnLoad() ) - { - AELog.warn( ex, "Removing item " + compoundTag + " from storage cell because loading the ItemStack crashed." ); - return false; - } - throw ex; - } + @Override + protected boolean loadCellItem(NBTTagCompound compoundTag, int stackSize) { + // Now load the item stack + final T t; + try { + t = this.getChannel().createFromNBT(compoundTag); + if (t == null) { + AELog.warn("Removing item " + compoundTag + " from storage cell because the associated item type couldn't be found."); + return false; + } + } catch (Throwable ex) { + if (AEConfig.instance().isRemoveCrashingItemsOnLoad()) { + AELog.warn(ex, "Removing item " + compoundTag + " from storage cell because loading the ItemStack crashed."); + return false; + } + throw ex; + } - t.setStackSize( stackSize ); - t.setCraftable( false ); + t.setStackSize(stackSize); + t.setCraftable(false); - if( stackSize > 0 ) - { - this.cellItems.add( t ); - } + if (stackSize > 0) { + this.cellItems.add(t); + } - return true; - } + return true; + } } diff --git a/src/main/java/appeng/me/storage/BasicCellInventoryHandler.java b/src/main/java/appeng/me/storage/BasicCellInventoryHandler.java index 5a0bce287..69850300e 100644 --- a/src/main/java/appeng/me/storage/BasicCellInventoryHandler.java +++ b/src/main/java/appeng/me/storage/BasicCellInventoryHandler.java @@ -19,10 +19,6 @@ package appeng.me.storage; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.FuzzyMode; import appeng.api.config.IncludeExclude; import appeng.api.config.Upgrades; @@ -36,6 +32,9 @@ import appeng.api.storage.data.IItemList; import appeng.util.Platform; import appeng.util.prioritylist.FuzzyPriorityList; import appeng.util.prioritylist.PrecisePriorityList; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.items.IItemHandler; /** @@ -43,108 +42,88 @@ import appeng.util.prioritylist.PrecisePriorityList; * @version rv6 - 2018-01-23 * @since rv6 2018-01-23 */ -public class BasicCellInventoryHandler> extends MEInventoryHandler implements ICellInventoryHandler -{ - public BasicCellInventoryHandler( final IMEInventory c, final IStorageChannel channel ) - { - super( c, channel ); +public class BasicCellInventoryHandler> extends MEInventoryHandler implements ICellInventoryHandler { + public BasicCellInventoryHandler(final IMEInventory c, final IStorageChannel channel) { + super(c, channel); - final ICellInventory ci = this.getCellInv(); - if( ci != null ) - { - final IItemList priorityList = channel.createList(); + final ICellInventory ci = this.getCellInv(); + if (ci != null) { + final IItemList priorityList = channel.createList(); - final IItemHandler upgrades = ci.getUpgradesInventory(); - final IItemHandler config = ci.getConfigInventory(); - final FuzzyMode fzMode = ci.getFuzzyMode(); + final IItemHandler upgrades = ci.getUpgradesInventory(); + final IItemHandler config = ci.getConfigInventory(); + final FuzzyMode fzMode = ci.getFuzzyMode(); - boolean hasInverter = false; - boolean hasFuzzy = false; + boolean hasInverter = false; + boolean hasFuzzy = false; - for( int x = 0; x < upgrades.getSlots(); x++ ) - { - final ItemStack is = upgrades.getStackInSlot( x ); - if( !is.isEmpty() && is.getItem() instanceof IUpgradeModule ) - { - final Upgrades u = ( (IUpgradeModule) is.getItem() ).getType( is ); - if( u != null ) - { - switch( u ) - { - case FUZZY: - hasFuzzy = true; - break; - case INVERTER: - hasInverter = true; - break; - default: - } - } - } - } + for (int x = 0; x < upgrades.getSlots(); x++) { + final ItemStack is = upgrades.getStackInSlot(x); + if (!is.isEmpty() && is.getItem() instanceof IUpgradeModule) { + final Upgrades u = ((IUpgradeModule) is.getItem()).getType(is); + if (u != null) { + switch (u) { + case FUZZY: + hasFuzzy = true; + break; + case INVERTER: + hasInverter = true; + break; + default: + } + } + } + } - for( int x = 0; x < config.getSlots(); x++ ) - { - final ItemStack is = config.getStackInSlot( x ); - if( !is.isEmpty() ) - { - final T configItem = channel.createStack( is ); - if( configItem != null ) - { - priorityList.add( configItem ); - } - } - } + for (int x = 0; x < config.getSlots(); x++) { + final ItemStack is = config.getStackInSlot(x); + if (!is.isEmpty()) { + final T configItem = channel.createStack(is); + if (configItem != null) { + priorityList.add(configItem); + } + } + } - this.setWhitelist( hasInverter ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST ); + this.setWhitelist(hasInverter ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST); - if( !priorityList.isEmpty() ) - { - if( hasFuzzy ) - { - this.setPartitionList( new FuzzyPriorityList<>( priorityList, fzMode ) ); - } - else - { - this.setPartitionList( new PrecisePriorityList<>( priorityList ) ); - } - } - } - } + if (!priorityList.isEmpty()) { + if (hasFuzzy) { + this.setPartitionList(new FuzzyPriorityList<>(priorityList, fzMode)); + } else { + this.setPartitionList(new PrecisePriorityList<>(priorityList)); + } + } + } + } - @Override - public ICellInventory getCellInv() - { - Object o = this.getInternal(); + @Override + public ICellInventory getCellInv() { + Object o = this.getInternal(); - if( o instanceof MEPassThrough ) - { - o = ( (MEPassThrough) o ).getInternal(); - } + if (o instanceof MEPassThrough) { + o = ((MEPassThrough) o).getInternal(); + } - return (ICellInventory) ( o instanceof ICellInventory ? o : null ); - } + return (ICellInventory) (o instanceof ICellInventory ? o : null); + } - @Override - public boolean isPreformatted() - { - return !this.getPartitionList().isEmpty(); - } + @Override + public boolean isPreformatted() { + return !this.getPartitionList().isEmpty(); + } - @Override - public boolean isFuzzy() - { - return this.getPartitionList() instanceof FuzzyPriorityList; - } + @Override + public boolean isFuzzy() { + return this.getPartitionList() instanceof FuzzyPriorityList; + } - @Override - public IncludeExclude getIncludeExcludeMode() - { - return this.getWhitelist(); - } + @Override + public IncludeExclude getIncludeExcludeMode() { + return this.getWhitelist(); + } - NBTTagCompound openNbtData() - { - return Platform.openNbtData( this.getCellInv().getItemStack() ); - } + NBTTagCompound openNbtData() { + return Platform.openNbtData(this.getCellInv().getItemStack()); + } } diff --git a/src/main/java/appeng/me/storage/CreativeCellInventory.java b/src/main/java/appeng/me/storage/CreativeCellInventory.java index 53031553c..1ac0feeae 100644 --- a/src/main/java/appeng/me/storage/CreativeCellInventory.java +++ b/src/main/java/appeng/me/storage/CreativeCellInventory.java @@ -19,8 +19,6 @@ package appeng.me.storage; -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -33,105 +31,88 @@ import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import appeng.items.contents.CellConfig; import appeng.util.item.AEItemStack; +import net.minecraft.item.ItemStack; -public class CreativeCellInventory implements IMEInventoryHandler -{ +public class CreativeCellInventory implements IMEInventoryHandler { - private final IItemList itemListCache = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); + private final IItemList itemListCache = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); - protected CreativeCellInventory( final ItemStack o ) - { - final CellConfig cc = new CellConfig( o ); - for( final ItemStack is : cc ) - { - if( !is.isEmpty() ) - { - final IAEItemStack i = AEItemStack.fromItemStack( is ); - i.setStackSize( Integer.MAX_VALUE ); - this.itemListCache.add( i ); - } - } - } + protected CreativeCellInventory(final ItemStack o) { + final CellConfig cc = new CellConfig(o); + for (final ItemStack is : cc) { + if (!is.isEmpty()) { + final IAEItemStack i = AEItemStack.fromItemStack(is); + i.setStackSize(Integer.MAX_VALUE); + this.itemListCache.add(i); + } + } + } - public static ICellInventoryHandler getCell( final ItemStack o ) - { - return new BasicCellInventoryHandler( new CreativeCellInventory( o ), AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - } + public static ICellInventoryHandler getCell(final ItemStack o) { + return new BasicCellInventoryHandler(new CreativeCellInventory(o), AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final IActionSource src ) - { - final IAEItemStack local = this.itemListCache.findPrecise( input ); - if( local == null ) - { - return input; - } + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, final IActionSource src) { + final IAEItemStack local = this.itemListCache.findPrecise(input); + if (local == null) { + return input; + } - return null; - } + return null; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final IActionSource src ) - { - final IAEItemStack local = this.itemListCache.findPrecise( request ); - if( local == null ) - { - return null; - } + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final IActionSource src) { + final IAEItemStack local = this.itemListCache.findPrecise(request); + if (local == null) { + return null; + } - return request.copy(); - } + return request.copy(); + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final IAEItemStack ais : this.itemListCache ) - { - out.add( ais ); - } - return out; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final IAEItemStack ais : this.itemListCache) { + out.add(ais); + } + return out; + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - return this.itemListCache.findPrecise( input ) != null; - } + @Override + public boolean isPrioritized(final IAEItemStack input) { + return this.itemListCache.findPrecise(input) != null; + } - @Override - public boolean canAccept( final IAEItemStack input ) - { - return this.itemListCache.findPrecise( input ) != null; - } + @Override + public boolean canAccept(final IAEItemStack input) { + return this.itemListCache.findPrecise(input) != null; + } - @Override - public int getPriority() - { - return 0; - } + @Override + public int getPriority() { + return 0; + } - @Override - public int getSlot() - { - return 0; - } + @Override + public int getSlot() { + return 0; + } - @Override - public boolean validForPass( final int i ) - { - return true; - } + @Override + public boolean validForPass(final int i) { + return true; + } } diff --git a/src/main/java/appeng/me/storage/DriveWatcher.java b/src/main/java/appeng/me/storage/DriveWatcher.java index 89d997897..3c2f20d22 100644 --- a/src/main/java/appeng/me/storage/DriveWatcher.java +++ b/src/main/java/appeng/me/storage/DriveWatcher.java @@ -19,101 +19,85 @@ package appeng.me.storage; +import appeng.api.config.Actionable; +import appeng.api.networking.security.IActionSource; +import appeng.api.storage.ICellHandler; +import appeng.api.storage.ICellInventoryHandler; +import appeng.api.storage.data.IAEStack; import appeng.core.features.registries.cell.CreativeCellHandler; import appeng.me.GridAccessException; import appeng.me.helpers.MachineSource; import appeng.tile.storage.TileDrive; import net.minecraft.item.ItemStack; -import appeng.api.config.Actionable; -import appeng.api.networking.security.IActionSource; -import appeng.api.storage.ICellHandler; -import appeng.api.storage.ICellInventoryHandler; -import appeng.api.storage.data.IAEStack; - import java.util.Collections; -public class DriveWatcher> extends MEInventoryHandler -{ +public class DriveWatcher> extends MEInventoryHandler { - private int oldStatus = 0; - private final ItemStack is; - private final ICellHandler handler; - private final TileDrive drive; - private IActionSource source; + private int oldStatus = 0; + private final ItemStack is; + private final ICellHandler handler; + private final TileDrive drive; + private final IActionSource source; - public DriveWatcher( final ICellInventoryHandler i, final ItemStack is, final ICellHandler han, final TileDrive drive ) - { - super( i, i.getChannel() ); - this.is = is; - this.handler = han; - this.drive = drive; - this.source = new MachineSource( drive ); - } + public DriveWatcher(final ICellInventoryHandler i, final ItemStack is, final ICellHandler han, final TileDrive drive) { + super(i, i.getChannel()); + this.is = is; + this.handler = han; + this.drive = drive; + this.source = new MachineSource(drive); + } - public int getStatus() - { - return this.handler.getStatusForCell( this.is, (ICellInventoryHandler) this.getInternal() ); - } + public int getStatus() { + return this.handler.getStatusForCell(this.is, (ICellInventoryHandler) this.getInternal()); + } - @Override - public T injectItems( final T input, final Actionable type, final IActionSource src ) - { - final long size = input.getStackSize(); + @Override + public T injectItems(final T input, final Actionable type, final IActionSource src) { + final long size = input.getStackSize(); - final T remainder = super.injectItems( input, type, src ); + final T remainder = super.injectItems(input, type, src); - if( type == Actionable.MODULATE && ( remainder == null || remainder.getStackSize() != size ) ) - { - final int newStatus = this.getStatus(); + if (type == Actionable.MODULATE && (remainder == null || remainder.getStackSize() != size)) { + final int newStatus = this.getStatus(); - if( newStatus != this.oldStatus ) - { - this.drive.blinkCell( this.getSlot() ); - this.oldStatus = newStatus; - } - if (this.drive.getProxy().isActive() && !(handler instanceof CreativeCellHandler)) - { - try - { - this.drive.getProxy().getStorage().postAlterationOfStoredItems( this.getChannel(), Collections.singletonList( input.copy().setStackSize( input.getStackSize() - ( remainder == null ? 0 : remainder.getStackSize() ) ) ), this.source ); - } catch ( GridAccessException e ) - { - e.printStackTrace(); - } - } - } + if (newStatus != this.oldStatus) { + this.drive.blinkCell(this.getSlot()); + this.oldStatus = newStatus; + } + if (this.drive.getProxy().isActive() && !(handler instanceof CreativeCellHandler)) { + try { + this.drive.getProxy().getStorage().postAlterationOfStoredItems(this.getChannel(), Collections.singletonList(input.copy().setStackSize(input.getStackSize() - (remainder == null ? 0 : remainder.getStackSize()))), this.source); + } catch (GridAccessException e) { + e.printStackTrace(); + } + } + } - return remainder; - } + return remainder; + } - @Override - public T extractItems( final T request, final Actionable type, final IActionSource src ) - { - final T extractable = super.extractItems( request, type, src ); + @Override + public T extractItems(final T request, final Actionable type, final IActionSource src) { + final T extractable = super.extractItems(request, type, src); - if( type == Actionable.MODULATE && extractable != null ) - { - final int newStatus = this.getStatus(); + if (type == Actionable.MODULATE && extractable != null) { + final int newStatus = this.getStatus(); - if( newStatus != this.oldStatus ) - { - this.drive.blinkCell( this.getSlot() ); - this.oldStatus = newStatus; - } - if (this.drive.getProxy().isActive() && !(handler instanceof CreativeCellHandler )) - { - try - { - this.drive.getProxy().getStorage().postAlterationOfStoredItems( this.getChannel(), Collections.singletonList( request.copy().setStackSize( -extractable.getStackSize() ) ), this.source ); - } catch ( GridAccessException e ) - { - e.printStackTrace(); - } - } - } + if (newStatus != this.oldStatus) { + this.drive.blinkCell(this.getSlot()); + this.oldStatus = newStatus; + } + if (this.drive.getProxy().isActive() && !(handler instanceof CreativeCellHandler)) { + try { + this.drive.getProxy().getStorage().postAlterationOfStoredItems(this.getChannel(), Collections.singletonList(request.copy().setStackSize(-extractable.getStackSize())), this.source); + } catch (GridAccessException e) { + e.printStackTrace(); + } + } + } - return extractable; - } + return extractable; + } } diff --git a/src/main/java/appeng/me/storage/ITickingMonitor.java b/src/main/java/appeng/me/storage/ITickingMonitor.java index fea99db80..7581a27b4 100644 --- a/src/main/java/appeng/me/storage/ITickingMonitor.java +++ b/src/main/java/appeng/me/storage/ITickingMonitor.java @@ -24,15 +24,13 @@ import appeng.api.networking.security.IActionSource; import appeng.api.networking.ticking.TickRateModulation; -public interface ITickingMonitor -{ +public interface ITickingMonitor { - TickRateModulation onTick(); + TickRateModulation onTick(); - void setActionSource( IActionSource actionSource ); + void setActionSource(IActionSource actionSource); - default void setMode( StorageFilter setting ) - { + default void setMode(StorageFilter setting) { - } + } } diff --git a/src/main/java/appeng/me/storage/ItemWatcher.java b/src/main/java/appeng/me/storage/ItemWatcher.java index 0732d7bc4..c135adc38 100644 --- a/src/main/java/appeng/me/storage/ItemWatcher.java +++ b/src/main/java/appeng/me/storage/ItemWatcher.java @@ -19,63 +19,55 @@ package appeng.me.storage; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - import appeng.api.networking.storage.IStackWatcher; import appeng.api.networking.storage.IStackWatcherHost; import appeng.api.storage.data.IAEStack; import appeng.me.cache.GridStorageCache; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + /** * Maintain my interests, and a global watch list, they should always be fully synchronized. */ -public class ItemWatcher implements IStackWatcher -{ +public class ItemWatcher implements IStackWatcher { - private final GridStorageCache gsc; - private final IStackWatcherHost myObject; - private final Set myInterests = new HashSet<>(); + private final GridStorageCache gsc; + private final IStackWatcherHost myObject; + private final Set myInterests = new HashSet<>(); - public ItemWatcher( final GridStorageCache cache, final IStackWatcherHost host ) - { - this.gsc = cache; - this.myObject = host; - } + public ItemWatcher(final GridStorageCache cache, final IStackWatcherHost host) { + this.gsc = cache; + this.myObject = host; + } - public IStackWatcherHost getHost() - { - return this.myObject; - } + public IStackWatcherHost getHost() { + return this.myObject; + } - @Override - public boolean add( final IAEStack e ) - { - if( this.myInterests.contains( e ) ) - { - return false; - } + @Override + public boolean add(final IAEStack e) { + if (this.myInterests.contains(e)) { + return false; + } - return this.myInterests.add( e.copy() ) && this.gsc.getInterestManager().put( e, this ); - } + return this.myInterests.add(e.copy()) && this.gsc.getInterestManager().put(e, this); + } - @Override - public boolean remove( final IAEStack o ) - { - return this.myInterests.remove( o ) && this.gsc.getInterestManager().remove( o, this ); - } + @Override + public boolean remove(final IAEStack o) { + return this.myInterests.remove(o) && this.gsc.getInterestManager().remove(o, this); + } - @Override - public void reset() - { - final Iterator i = this.myInterests.iterator(); + @Override + public void reset() { + final Iterator i = this.myInterests.iterator(); - while( i.hasNext() ) - { - this.gsc.getInterestManager().remove( i.next(), this ); - i.remove(); - } - } + while (i.hasNext()) { + this.gsc.getInterestManager().remove(i.next(), this); + i.remove(); + } + } } diff --git a/src/main/java/appeng/me/storage/MEInventoryHandler.java b/src/main/java/appeng/me/storage/MEInventoryHandler.java index 9f3a2c84b..16c853da9 100644 --- a/src/main/java/appeng/me/storage/MEInventoryHandler.java +++ b/src/main/java/appeng/me/storage/MEInventoryHandler.java @@ -32,168 +32,138 @@ import appeng.util.prioritylist.DefaultPriorityList; import appeng.util.prioritylist.IPartitionList; -public class MEInventoryHandler> implements IMEInventoryHandler -{ +public class MEInventoryHandler> implements IMEInventoryHandler { - private final IMEInventoryHandler internal; - private int myPriority; - private IncludeExclude myWhitelist; - private AccessRestriction myAccess; - private IPartitionList myPartitionList; + private final IMEInventoryHandler internal; + private int myPriority; + private IncludeExclude myWhitelist; + private AccessRestriction myAccess; + private IPartitionList myPartitionList; - private AccessRestriction cachedAccessRestriction; - private boolean hasReadAccess; - private boolean hasWriteAccess; + private AccessRestriction cachedAccessRestriction; + private boolean hasReadAccess; + private boolean hasWriteAccess; - public MEInventoryHandler( final IMEInventory i, final IStorageChannel channel ) - { - if( i instanceof IMEInventoryHandler ) - { - this.internal = (IMEInventoryHandler) i; - } - else - { - this.internal = new MEPassThrough<>( i, channel ); - } + public MEInventoryHandler(final IMEInventory i, final IStorageChannel channel) { + if (i instanceof IMEInventoryHandler) { + this.internal = (IMEInventoryHandler) i; + } else { + this.internal = new MEPassThrough<>(i, channel); + } - this.myPriority = 0; - this.myWhitelist = IncludeExclude.WHITELIST; - this.setBaseAccess( AccessRestriction.READ_WRITE ); - this.myPartitionList = new DefaultPriorityList<>(); - } + this.myPriority = 0; + this.myWhitelist = IncludeExclude.WHITELIST; + this.setBaseAccess(AccessRestriction.READ_WRITE); + this.myPartitionList = new DefaultPriorityList<>(); + } - IncludeExclude getWhitelist() - { - return this.myWhitelist; - } + IncludeExclude getWhitelist() { + return this.myWhitelist; + } - public void setWhitelist( final IncludeExclude myWhitelist ) - { - this.myWhitelist = myWhitelist; - } + public void setWhitelist(final IncludeExclude myWhitelist) { + this.myWhitelist = myWhitelist; + } - public AccessRestriction getBaseAccess() - { - return this.myAccess; - } + public AccessRestriction getBaseAccess() { + return this.myAccess; + } - public void setBaseAccess( final AccessRestriction myAccess ) - { - this.myAccess = myAccess; - this.cachedAccessRestriction = this.myAccess.restrictPermissions( this.internal.getAccess() ); - this.hasReadAccess = this.cachedAccessRestriction.hasPermission( AccessRestriction.READ ); - this.hasWriteAccess = this.cachedAccessRestriction.hasPermission( AccessRestriction.WRITE ); - } + public void setBaseAccess(final AccessRestriction myAccess) { + this.myAccess = myAccess; + this.cachedAccessRestriction = this.myAccess.restrictPermissions(this.internal.getAccess()); + this.hasReadAccess = this.cachedAccessRestriction.hasPermission(AccessRestriction.READ); + this.hasWriteAccess = this.cachedAccessRestriction.hasPermission(AccessRestriction.WRITE); + } - IPartitionList getPartitionList() - { - return this.myPartitionList; - } + IPartitionList getPartitionList() { + return this.myPartitionList; + } - public void setPartitionList( final IPartitionList myPartitionList ) - { - this.myPartitionList = myPartitionList; - } + public void setPartitionList(final IPartitionList myPartitionList) { + this.myPartitionList = myPartitionList; + } - @Override - public T injectItems( final T input, final Actionable type, final IActionSource src ) - { - if( !this.canAccept( input ) ) - { - return input; - } + @Override + public T injectItems(final T input, final Actionable type, final IActionSource src) { + if (!this.canAccept(input)) { + return input; + } - return this.internal.injectItems( input, type, src ); - } + return this.internal.injectItems(input, type, src); + } - @Override - public T extractItems( final T request, final Actionable type, final IActionSource src ) - { - if( !this.hasReadAccess ) - { - return null; - } + @Override + public T extractItems(final T request, final Actionable type, final IActionSource src) { + if (!this.hasReadAccess) { + return null; + } - return this.internal.extractItems( request, type, src ); - } + return this.internal.extractItems(request, type, src); + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - if( !this.hasReadAccess ) - { - return out; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + if (!this.hasReadAccess) { + return out; + } - return this.internal.getAvailableItems( out ); - } + return this.internal.getAvailableItems(out); + } - @Override - public IStorageChannel getChannel() - { - return this.internal.getChannel(); - } + @Override + public IStorageChannel getChannel() { + return this.internal.getChannel(); + } - @Override - public AccessRestriction getAccess() - { - return this.cachedAccessRestriction; - } + @Override + public AccessRestriction getAccess() { + return this.cachedAccessRestriction; + } - @Override - public boolean isPrioritized( final T input ) - { - if( this.myWhitelist == IncludeExclude.WHITELIST ) - { - return this.myPartitionList.isListed( input ) || this.internal.isPrioritized( input ); - } - return false; - } + @Override + public boolean isPrioritized(final T input) { + if (this.myWhitelist == IncludeExclude.WHITELIST) { + return this.myPartitionList.isListed(input) || this.internal.isPrioritized(input); + } + return false; + } - @Override - public boolean canAccept( final T input ) - { - if( !this.hasWriteAccess ) - { - return false; - } + @Override + public boolean canAccept(final T input) { + if (!this.hasWriteAccess) { + return false; + } - if( this.myWhitelist == IncludeExclude.BLACKLIST && this.myPartitionList.isListed( input ) ) - { - return false; - } - if( this.myPartitionList.isEmpty() || this.myWhitelist == IncludeExclude.BLACKLIST ) - { - return this.internal.canAccept( input ); - } - return this.myPartitionList.isListed( input ) && this.internal.canAccept( input ); - } + if (this.myWhitelist == IncludeExclude.BLACKLIST && this.myPartitionList.isListed(input)) { + return false; + } + if (this.myPartitionList.isEmpty() || this.myWhitelist == IncludeExclude.BLACKLIST) { + return this.internal.canAccept(input); + } + return this.myPartitionList.isListed(input) && this.internal.canAccept(input); + } - @Override - public int getPriority() - { - return this.myPriority; - } + @Override + public int getPriority() { + return this.myPriority; + } - public void setPriority( final int myPriority ) - { - this.myPriority = myPriority; - } + public void setPriority(final int myPriority) { + this.myPriority = myPriority; + } - @Override - public int getSlot() - { - return this.internal.getSlot(); - } + @Override + public int getSlot() { + return this.internal.getSlot(); + } - @Override - public boolean validForPass( final int i ) - { - return true; - } + @Override + public boolean validForPass(final int i) { + return true; + } - public IMEInventory getInternal() - { - return this.internal; - } + public IMEInventory getInternal() { + return this.internal; + } } diff --git a/src/main/java/appeng/me/storage/MEMonitorIFluidHandler.java b/src/main/java/appeng/me/storage/MEMonitorIFluidHandler.java index b28f28b8b..799abf199 100644 --- a/src/main/java/appeng/me/storage/MEMonitorIFluidHandler.java +++ b/src/main/java/appeng/me/storage/MEMonitorIFluidHandler.java @@ -19,15 +19,6 @@ package appeng.me.storage; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentSkipListMap; - -import appeng.fluids.util.AEFluidStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidTankProperties; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -40,234 +31,201 @@ import appeng.api.storage.IStorageChannel; import appeng.api.storage.channels.IFluidStorageChannel; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; +import appeng.fluids.util.AEFluidStack; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.capability.IFluidHandler; +import net.minecraftforge.fluids.capability.IFluidTankProperties; + +import java.util.*; +import java.util.Map.Entry; -public class MEMonitorIFluidHandler implements IMEMonitor, ITickingMonitor -{ - private final IFluidHandler handler; - private IItemList cache = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList(); - private final HashMap, Object> listeners = new HashMap<>(); - private IActionSource mySource; - private StorageFilter mode = StorageFilter.EXTRACTABLE_ONLY; +public class MEMonitorIFluidHandler implements IMEMonitor, ITickingMonitor { + private final IFluidHandler handler; + private IItemList cache = AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class).createList(); + private final HashMap, Object> listeners = new HashMap<>(); + private IActionSource mySource; + private StorageFilter mode = StorageFilter.EXTRACTABLE_ONLY; - public MEMonitorIFluidHandler( final IFluidHandler handler ) - { - this.handler = handler; - } + public MEMonitorIFluidHandler(final IFluidHandler handler) { + this.handler = handler; + } - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } - @Override - public IAEFluidStack injectItems( final IAEFluidStack input, final Actionable type, final IActionSource src ) - { - final int filled = this.handler.fill( input.getFluidStack(), type == Actionable.MODULATE ); + @Override + public IAEFluidStack injectItems(final IAEFluidStack input, final Actionable type, final IActionSource src) { + final int filled = this.handler.fill(input.getFluidStack(), type == Actionable.MODULATE); - if( filled == 0 ) - { - return input.copy(); - } + if (filled == 0) { + return input.copy(); + } - if( filled == input.getStackSize() ) - { - return null; - } + if (filled == input.getStackSize()) { + return null; + } - final IAEFluidStack o = input.copy(); - o.setStackSize( input.getStackSize() - filled ); + final IAEFluidStack o = input.copy(); + o.setStackSize(input.getStackSize() - filled); - if( type == Actionable.MODULATE ) - { - IAEFluidStack added = o.copy(); - this.cache.add( added ); - this.postDifference( Collections.singletonList( added ) ); - this.onTick(); - } + if (type == Actionable.MODULATE) { + IAEFluidStack added = o.copy(); + this.cache.add(added); + this.postDifference(Collections.singletonList(added)); + this.onTick(); + } - return o; - } + return o; + } - @Override - public IAEFluidStack extractItems( final IAEFluidStack request, final Actionable type, final IActionSource src ) - { - final FluidStack removed = this.handler.drain( request.getFluidStack(), type == Actionable.MODULATE ); + @Override + public IAEFluidStack extractItems(final IAEFluidStack request, final Actionable type, final IActionSource src) { + final FluidStack removed = this.handler.drain(request.getFluidStack(), type == Actionable.MODULATE); - if( removed == null || removed.amount == 0 ) - { - return null; - } + if (removed == null || removed.amount == 0) { + return null; + } - final IAEFluidStack o = request.copy(); - o.setStackSize( removed.amount ); + final IAEFluidStack o = request.copy(); + o.setStackSize(removed.amount); - if( type == Actionable.MODULATE ) - { - IAEFluidStack cachedStack = this.cache.findPrecise( request ); - if( cachedStack != null ) - { - cachedStack.decStackSize( o.getStackSize() ); - this.postDifference( Collections.singletonList( o.copy().setStackSize( -o.getStackSize() ) ) ); - } - } - return o; - } + if (type == Actionable.MODULATE) { + IAEFluidStack cachedStack = this.cache.findPrecise(request); + if (cachedStack != null) { + cachedStack.decStackSize(o.getStackSize()); + this.postDifference(Collections.singletonList(o.copy().setStackSize(-o.getStackSize()))); + } + } + return o; + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class); + } - @Override - public TickRateModulation onTick() - { - boolean changed = false; + @Override + public TickRateModulation onTick() { + boolean changed = false; - final List changes = new ArrayList<>(); - final IFluidTankProperties[] tankProperties = this.handler.getTankProperties(); + final List changes = new ArrayList<>(); + final IFluidTankProperties[] tankProperties = this.handler.getTankProperties(); - IItemList currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList(); + IItemList currentlyOnStorage = AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class).createList(); - for( IFluidTankProperties tankProperty : tankProperties ) - { - if( this.mode == StorageFilter.EXTRACTABLE_ONLY && this.handler.drain( 1, false ) == null ) - { - continue; - } - currentlyOnStorage.add( AEFluidStack.fromFluidStack( tankProperty.getContents() ) ); - } + for (IFluidTankProperties tankProperty : tankProperties) { + if (this.mode == StorageFilter.EXTRACTABLE_ONLY && this.handler.drain(1, false) == null) { + continue; + } + currentlyOnStorage.add(AEFluidStack.fromFluidStack(tankProperty.getContents())); + } - for( final IAEFluidStack is : cache ) - { - is.setStackSize( -is.getStackSize() ); - } + for (final IAEFluidStack is : cache) { + is.setStackSize(-is.getStackSize()); + } - for( final IAEFluidStack is : currentlyOnStorage ) - { - cache.add( is ); - } + for (final IAEFluidStack is : currentlyOnStorage) { + cache.add(is); + } - for( final IAEFluidStack is : cache ) - { - if( is.getStackSize() != 0 ) - { - changes.add( is ); - } - } + for (final IAEFluidStack is : cache) { + if (is.getStackSize() != 0) { + changes.add(is); + } + } - cache = currentlyOnStorage; + cache = currentlyOnStorage; - if( !changes.isEmpty() ) - { - this.postDifference( changes ); - changed = true; - } + if (!changes.isEmpty()) { + this.postDifference(changes); + changed = true; + } - return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER; - } + return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER; + } - private void postDifference( final Iterable a ) - { - if( a != null ) - { - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while( i.hasNext() ) - { - final Entry, Object> l = i.next(); - final IMEMonitorHandlerReceiver key = l.getKey(); - if( key.isValid( l.getValue() ) ) - { - key.postChange( this, a, this.getActionSource() ); - } - else - { - i.remove(); - } - } - } - } + private void postDifference(final Iterable a) { + if (a != null) { + final Iterator, Object>> i = this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Entry, Object> l = i.next(); + final IMEMonitorHandlerReceiver key = l.getKey(); + if (key.isValid(l.getValue())) { + key.postChange(this, a, this.getActionSource()); + } else { + i.remove(); + } + } + } + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } - @Override - public boolean isPrioritized( final IAEFluidStack input ) - { - return false; - } + @Override + public boolean isPrioritized(final IAEFluidStack input) { + return false; + } - @Override - public boolean canAccept( final IAEFluidStack input ) - { - return true; - } + @Override + public boolean canAccept(final IAEFluidStack input) { + return true; + } - @Override - public int getPriority() - { - return 0; - } + @Override + public int getPriority() { + return 0; + } - @Override - public int getSlot() - { - return 0; - } + @Override + public int getSlot() { + return 0; + } - @Override - public boolean validForPass( final int i ) - { - return true; - } + @Override + public boolean validForPass(final int i) { + return true; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final IAEFluidStack fs : cache ) - { - out.addStorage( fs ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final IAEFluidStack fs : cache) { + out.addStorage(fs); + } - return out; - } + return out; + } - @Override - public IItemList getStorageList() - { - return this.cache; - } + @Override + public IItemList getStorageList() { + return this.cache; + } - private StorageFilter getMode() - { - return this.mode; - } + private StorageFilter getMode() { + return this.mode; + } - public void setMode( final StorageFilter mode ) - { - this.mode = mode; - } + public void setMode(final StorageFilter mode) { + this.mode = mode; + } - private IActionSource getActionSource() - { - return this.mySource; - } + private IActionSource getActionSource() { + return this.mySource; + } - @Override - public void setActionSource( final IActionSource mySource ) - { - this.mySource = mySource; - } + @Override + public void setActionSource(final IActionSource mySource) { + this.mySource = mySource; + } } diff --git a/src/main/java/appeng/me/storage/MEMonitorIInventory.java b/src/main/java/appeng/me/storage/MEMonitorIInventory.java index 8e30dc90d..8384a074c 100644 --- a/src/main/java/appeng/me/storage/MEMonitorIInventory.java +++ b/src/main/java/appeng/me/storage/MEMonitorIInventory.java @@ -19,12 +19,6 @@ package appeng.me.storage; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentSkipListMap; - -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -38,254 +32,212 @@ import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import appeng.util.InventoryAdaptor; -import appeng.util.Platform; import appeng.util.inv.ItemSlot; +import net.minecraft.item.ItemStack; + +import java.util.*; +import java.util.Map.Entry; -public class MEMonitorIInventory implements IMEMonitor, ITickingMonitor -{ +public class MEMonitorIInventory implements IMEMonitor, ITickingMonitor { - private final InventoryAdaptor adaptor; - private IItemList cache = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); + private final InventoryAdaptor adaptor; + private IItemList cache = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); - private final HashMap, Object> listeners = new HashMap<>(); - private IActionSource mySource; - private StorageFilter mode = StorageFilter.EXTRACTABLE_ONLY; + private final HashMap, Object> listeners = new HashMap<>(); + private IActionSource mySource; + private StorageFilter mode = StorageFilter.EXTRACTABLE_ONLY; - public MEMonitorIInventory( final InventoryAdaptor adaptor ) - { - this.adaptor = adaptor; - } + public MEMonitorIInventory(final InventoryAdaptor adaptor) { + this.adaptor = adaptor; + } - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final IActionSource src ) - { - ItemStack out = ItemStack.EMPTY; + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable type, final IActionSource src) { + ItemStack out = ItemStack.EMPTY; - if( type == Actionable.SIMULATE ) - { - out = this.adaptor.simulateAdd( input.createItemStack() ); - } - else - { - out = this.adaptor.addItems( input.createItemStack() ); - } + if (type == Actionable.SIMULATE) { + out = this.adaptor.simulateAdd(input.createItemStack()); + } else { + out = this.adaptor.addItems(input.createItemStack()); + } - if( out.isEmpty() ) - { - return null; - } + if (out.isEmpty()) { + return null; + } - // better then doing construction from scratch :3 - final IAEItemStack o = input.copy(); - o.setStackSize( out.getCount() ); + // better then doing construction from scratch :3 + final IAEItemStack o = input.copy(); + o.setStackSize(out.getCount()); - if( type == Actionable.MODULATE ) - { - IAEItemStack added = o.copy(); - this.cache.add( added ); - this.postDifference( Collections.singletonList( added ) ); - this.onTick(); - } + if (type == Actionable.MODULATE) { + IAEItemStack added = o.copy(); + this.cache.add(added); + this.postDifference(Collections.singletonList(added)); + this.onTick(); + } - return o; - } + return o; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable type, final IActionSource src ) - { - ItemStack out = ItemStack.EMPTY; + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable type, final IActionSource src) { + ItemStack out = ItemStack.EMPTY; - if( type == Actionable.SIMULATE ) - { - out = this.adaptor.simulateRemove( (int) request.getStackSize(), request.getDefinition(), null ); - } - else - { - out = this.adaptor.removeItems( (int) request.getStackSize(), request.getDefinition(), null ); - } + if (type == Actionable.SIMULATE) { + out = this.adaptor.simulateRemove((int) request.getStackSize(), request.getDefinition(), null); + } else { + out = this.adaptor.removeItems((int) request.getStackSize(), request.getDefinition(), null); + } - if( out.isEmpty() ) - { - return null; - } + if (out.isEmpty()) { + return null; + } - // better then doing construction from scratch :3 - final IAEItemStack o = request.copy(); - o.setStackSize( out.getCount() ); + // better then doing construction from scratch :3 + final IAEItemStack o = request.copy(); + o.setStackSize(out.getCount()); - if( type == Actionable.MODULATE ) - { - IAEItemStack cachedStack = this.cache.findPrecise( request ); - if( cachedStack != null ) - { - cachedStack.decStackSize( o.getStackSize() ); - this.postDifference( Collections.singletonList( o.copy().setStackSize( -o.getStackSize() ) ) ); - } - this.onTick(); - } + if (type == Actionable.MODULATE) { + IAEItemStack cachedStack = this.cache.findPrecise(request); + if (cachedStack != null) { + cachedStack.decStackSize(o.getStackSize()); + this.postDifference(Collections.singletonList(o.copy().setStackSize(-o.getStackSize()))); + } + this.onTick(); + } - return o; - } + return o; + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } - @Override - public TickRateModulation onTick() - { - boolean changed = false; + @Override + public TickRateModulation onTick() { + boolean changed = false; - final List changes = new ArrayList<>(); + final List changes = new ArrayList<>(); - IItemList currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); + IItemList currentlyOnStorage = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); - for( final ItemSlot is : adaptor ) - { - if( this.mode == StorageFilter.EXTRACTABLE_ONLY && !is.isExtractable() ) - { - continue; - } - currentlyOnStorage.add( is.getAEItemStack() ); - } + for (final ItemSlot is : adaptor) { + if (this.mode == StorageFilter.EXTRACTABLE_ONLY && !is.isExtractable()) { + continue; + } + currentlyOnStorage.add(is.getAEItemStack()); + } - for( final IAEItemStack is : cache ) - { - is.setStackSize( -is.getStackSize() ); - } + for (final IAEItemStack is : cache) { + is.setStackSize(-is.getStackSize()); + } - for( final IAEItemStack is : currentlyOnStorage ) - { - cache.add( is ); - } + for (final IAEItemStack is : currentlyOnStorage) { + cache.add(is); + } - for( final IAEItemStack is : cache ) - { - if( is.getStackSize() != 0 ) - { - changes.add( is ); - } - } + for (final IAEItemStack is : cache) { + if (is.getStackSize() != 0) { + changes.add(is); + } + } - cache = currentlyOnStorage; + cache = currentlyOnStorage; - if( !changes.isEmpty() ) - { - this.postDifference( changes ); - changed = true; - } + if (!changes.isEmpty()) { + this.postDifference(changes); + changed = true; + } - return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER; - } + return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER; + } - private void postDifference( final Iterable a ) - { - if( a != null ) - { - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while( i.hasNext() ) - { - final Entry, Object> l = i.next(); - final IMEMonitorHandlerReceiver key = l.getKey(); - if( key.isValid( l.getValue() ) ) - { - key.postChange( this, a, this.getActionSource() ); - } - else - { - i.remove(); - } - } - } - } + private void postDifference(final Iterable a) { + if (a != null) { + final Iterator, Object>> i = this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Entry, Object> l = i.next(); + final IMEMonitorHandlerReceiver key = l.getKey(); + if (key.isValid(l.getValue())) { + key.postChange(this, a, this.getActionSource()); + } else { + i.remove(); + } + } + } + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - return false; - } + @Override + public boolean isPrioritized(final IAEItemStack input) { + return false; + } - @Override - public boolean canAccept( final IAEItemStack input ) - { - return true; - } + @Override + public boolean canAccept(final IAEItemStack input) { + return true; + } - @Override - public int getPriority() - { - return 0; - } + @Override + public int getPriority() { + return 0; + } - @Override - public int getSlot() - { - return 0; - } + @Override + public int getSlot() { + return 0; + } - @Override - public boolean validForPass( final int i ) - { - return true; - } + @Override + public boolean validForPass(final int i) { + return true; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( IAEItemStack is : cache ) - { - out.addStorage( is ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + for (IAEItemStack is : cache) { + out.addStorage(is); + } - return out; - } + return out; + } - @Override - public IItemList getStorageList() - { - return this.cache; - } + @Override + public IItemList getStorageList() { + return this.cache; + } - private StorageFilter getMode() - { - return this.mode; - } + private StorageFilter getMode() { + return this.mode; + } - public void setMode( final StorageFilter mode ) - { - this.mode = mode; - } + public void setMode(final StorageFilter mode) { + this.mode = mode; + } - private IActionSource getActionSource() - { - return this.mySource; - } + private IActionSource getActionSource() { + return this.mySource; + } - @Override - public void setActionSource( final IActionSource mySource ) - { - this.mySource = mySource; - } + @Override + public void setActionSource(final IActionSource mySource) { + this.mySource = mySource; + } } diff --git a/src/main/java/appeng/me/storage/MEMonitorPassThrough.java b/src/main/java/appeng/me/storage/MEMonitorPassThrough.java index 559b90649..fa5f0c505 100644 --- a/src/main/java/appeng/me/storage/MEMonitorPassThrough.java +++ b/src/main/java/appeng/me/storage/MEMonitorPassThrough.java @@ -19,10 +19,6 @@ package appeng.me.storage; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - import appeng.api.networking.security.IActionSource; import appeng.api.networking.storage.IBaseMonitor; import appeng.api.storage.IMEInventory; @@ -34,142 +30,119 @@ import appeng.api.storage.data.IItemList; import appeng.util.Platform; import appeng.util.inv.ItemListIgnoreCrafting; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; -public class MEMonitorPassThrough> extends MEPassThrough implements IMEMonitor, IMEMonitorHandlerReceiver -{ - private final HashMap, Object> listeners = new HashMap<>(); - private IActionSource changeSource; - private IMEMonitor monitor; +public class MEMonitorPassThrough> extends MEPassThrough implements IMEMonitor, IMEMonitorHandlerReceiver { - public MEMonitorPassThrough( final IMEInventory i, final IStorageChannel channel ) - { - super( i, channel ); - if( i instanceof IMEMonitor ) - { - this.monitor = (IMEMonitor) i; - } - } + private final HashMap, Object> listeners = new HashMap<>(); + private IActionSource changeSource; + private IMEMonitor monitor; - @Override - public void setInternal( final IMEInventory i ) - { - if( this.monitor != null ) - { - this.monitor.removeListener( this ); - } + public MEMonitorPassThrough(final IMEInventory i, final IStorageChannel channel) { + super(i, channel); + if (i instanceof IMEMonitor) { + this.monitor = (IMEMonitor) i; + } + } - this.monitor = null; - final IItemList before = this.getInternal() == null ? this.getWrappedChannel().createList() : this.getInternal() - .getAvailableItems( new ItemListIgnoreCrafting( this.getWrappedChannel().createList() ) ); + @Override + public void setInternal(final IMEInventory i) { + if (this.monitor != null) { + this.monitor.removeListener(this); + } - super.setInternal( i ); - if( i instanceof IMEMonitor ) - { - this.monitor = (IMEMonitor) i; - } + this.monitor = null; + final IItemList before = this.getInternal() == null ? this.getWrappedChannel().createList() : this.getInternal() + .getAvailableItems(new ItemListIgnoreCrafting(this.getWrappedChannel().createList())); - final IItemList after = this.getInternal() == null ? this.getWrappedChannel().createList() : this.getInternal() - .getAvailableItems( new ItemListIgnoreCrafting( this.getWrappedChannel().createList() ) ); + super.setInternal(i); + if (i instanceof IMEMonitor) { + this.monitor = (IMEMonitor) i; + } - if( this.monitor != null && this.listeners.size() > 0 ) - { - this.monitor.addListener( this, this.monitor ); - } + final IItemList after = this.getInternal() == null ? this.getWrappedChannel().createList() : this.getInternal() + .getAvailableItems(new ItemListIgnoreCrafting(this.getWrappedChannel().createList())); - Platform.postListChanges( before, after, this, this.getChangeSource() ); - } + if (this.monitor != null && this.listeners.size() > 0) { + this.monitor.addListener(this, this.monitor); + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - super.getAvailableItems( new ItemListIgnoreCrafting( out ) ); - return out; - } + Platform.postListChanges(before, after, this, this.getChangeSource()); + } - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - if( this.listeners.size() == 0 ) - { - if( this.monitor != null ) - { - this.monitor.addListener( this, this.monitor ); - } - } - this.listeners.put( l, verificationToken ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + super.getAvailableItems(new ItemListIgnoreCrafting(out)); + return out; + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + if (this.listeners.size() == 0) { + if (this.monitor != null) { + this.monitor.addListener(this, this.monitor); + } + } + this.listeners.put(l, verificationToken); + } - @Override - public IItemList getStorageList() - { - if( this.monitor == null ) - { - final IItemList out = this.getWrappedChannel().createList(); - this.getInternal().getAvailableItems( new ItemListIgnoreCrafting( out ) ); - return out; - } - return this.monitor.getStorageList(); - } + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } - @Override - public boolean isValid( final Object verificationToken ) - { - return verificationToken == this.monitor; - } + @Override + public IItemList getStorageList() { + if (this.monitor == null) { + final IItemList out = this.getWrappedChannel().createList(); + this.getInternal().getAvailableItems(new ItemListIgnoreCrafting(out)); + return out; + } + return this.monitor.getStorageList(); + } - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final IActionSource source ) - { - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while( i.hasNext() ) - { - final Entry, Object> e = i.next(); - final IMEMonitorHandlerReceiver receiver = e.getKey(); - if( receiver.isValid( e.getValue() ) ) - { - receiver.postChange( this, change, source ); - } - else - { - i.remove(); - } - } - } + @Override + public boolean isValid(final Object verificationToken) { + return verificationToken == this.monitor; + } - @Override - public void onListUpdate() - { - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while( i.hasNext() ) - { - final Entry, Object> e = i.next(); - final IMEMonitorHandlerReceiver receiver = e.getKey(); - if( receiver.isValid( e.getValue() ) ) - { - receiver.onListUpdate(); - } - else - { - i.remove(); - } - } - } + @Override + public void postChange(final IBaseMonitor monitor, final Iterable change, final IActionSource source) { + final Iterator, Object>> i = this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Entry, Object> e = i.next(); + final IMEMonitorHandlerReceiver receiver = e.getKey(); + if (receiver.isValid(e.getValue())) { + receiver.postChange(this, change, source); + } else { + i.remove(); + } + } + } - private IActionSource getChangeSource() - { - return this.changeSource; - } + @Override + public void onListUpdate() { + final Iterator, Object>> i = this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Entry, Object> e = i.next(); + final IMEMonitorHandlerReceiver receiver = e.getKey(); + if (receiver.isValid(e.getValue())) { + receiver.onListUpdate(); + } else { + i.remove(); + } + } + } - public void setChangeSource( final IActionSource changeSource ) - { - this.changeSource = changeSource; - } + private IActionSource getChangeSource() { + return this.changeSource; + } + + public void setChangeSource(final IActionSource changeSource) { + this.changeSource = changeSource; + } } diff --git a/src/main/java/appeng/me/storage/MEPassThrough.java b/src/main/java/appeng/me/storage/MEPassThrough.java index c2314f716..72d009d00 100644 --- a/src/main/java/appeng/me/storage/MEPassThrough.java +++ b/src/main/java/appeng/me/storage/MEPassThrough.java @@ -29,90 +29,75 @@ import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; -public class MEPassThrough> implements IMEInventoryHandler -{ +public class MEPassThrough> implements IMEInventoryHandler { - private final IStorageChannel wrappedChannel; - private IMEInventory internal; + private final IStorageChannel wrappedChannel; + private IMEInventory internal; - public MEPassThrough( final IMEInventory i, final IStorageChannel channel ) - { - this.wrappedChannel = channel; - this.setInternal( i ); - } + public MEPassThrough(final IMEInventory i, final IStorageChannel channel) { + this.wrappedChannel = channel; + this.setInternal(i); + } - public IMEInventory getInternal() - { - return this.internal; - } + public IMEInventory getInternal() { + return this.internal; + } - public void setInternal( final IMEInventory i ) - { - this.internal = i; - } + public void setInternal(final IMEInventory i) { + this.internal = i; + } - @Override - public T injectItems( final T input, final Actionable type, final IActionSource src ) - { - return this.internal.injectItems( input, type, src ); - } + @Override + public T injectItems(final T input, final Actionable type, final IActionSource src) { + return this.internal.injectItems(input, type, src); + } - @Override - public T extractItems( final T request, final Actionable type, final IActionSource src ) - { - return this.internal.extractItems( request, type, src ); - } + @Override + public T extractItems(final T request, final Actionable type, final IActionSource src) { + return this.internal.extractItems(request, type, src); + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return this.internal.getAvailableItems( out ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return this.internal.getAvailableItems(out); + } - @Override - public IStorageChannel getChannel() - { - return this.internal.getChannel(); - } + @Override + public IStorageChannel getChannel() { + return this.internal.getChannel(); + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } - @Override - public boolean isPrioritized( final T input ) - { - return false; - } + @Override + public boolean isPrioritized(final T input) { + return false; + } - @Override - public boolean canAccept( final T input ) - { - return true; - } + @Override + public boolean canAccept(final T input) { + return true; + } - @Override - public int getPriority() - { - return 0; - } + @Override + public int getPriority() { + return 0; + } - @Override - public int getSlot() - { - return 0; - } + @Override + public int getSlot() { + return 0; + } - @Override - public boolean validForPass( final int i ) - { - return true; - } + @Override + public boolean validForPass(final int i) { + return true; + } - IStorageChannel getWrappedChannel() - { - return this.wrappedChannel; - } + IStorageChannel getWrappedChannel() { + return this.wrappedChannel; + } } diff --git a/src/main/java/appeng/me/storage/NetworkInventoryHandler.java b/src/main/java/appeng/me/storage/NetworkInventoryHandler.java index 54ddd1047..c90f7a215 100644 --- a/src/main/java/appeng/me/storage/NetworkInventoryHandler.java +++ b/src/main/java/appeng/me/storage/NetworkInventoryHandler.java @@ -19,15 +19,6 @@ package appeng.me.storage; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Deque; -import java.util.Iterator; -import java.util.List; -import java.util.NavigableMap; -import java.util.TreeMap; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; @@ -41,289 +32,236 @@ import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; import appeng.me.cache.SecurityCache; +import java.util.*; -public class NetworkInventoryHandler> implements IMEInventoryHandler -{ - private static final ThreadLocal DEPTH_MOD = new ThreadLocal<>(); - private static final ThreadLocal DEPTH_SIM = new ThreadLocal<>(); - private static final Comparator PRIORITY_SORTER = ( o1, o2 ) -> Integer.compare( o2, o1 ); +public class NetworkInventoryHandler> implements IMEInventoryHandler { - private static int currentPass = 0; - private final IStorageChannel myChannel; - private final SecurityCache security; - private final NavigableMap>> priorityInventory; - private int myPass = 0; + private static final ThreadLocal DEPTH_MOD = new ThreadLocal<>(); + private static final ThreadLocal DEPTH_SIM = new ThreadLocal<>(); + private static final Comparator PRIORITY_SORTER = (o1, o2) -> Integer.compare(o2, o1); - public NetworkInventoryHandler( final IStorageChannel chan, final SecurityCache security ) - { - this.myChannel = chan; - this.security = security; - this.priorityInventory = new TreeMap<>( PRIORITY_SORTER ); - } + private static int currentPass = 0; + private final IStorageChannel myChannel; + private final SecurityCache security; + private final NavigableMap>> priorityInventory; + private int myPass = 0; - public void addNewStorage( final IMEInventoryHandler h ) - { - final int priority = h.getPriority(); - List> list = this.priorityInventory.get( priority ); - if( list == null ) - { - this.priorityInventory.put( priority, list = new ArrayList<>() ); - } + public NetworkInventoryHandler(final IStorageChannel chan, final SecurityCache security) { + this.myChannel = chan; + this.security = security; + this.priorityInventory = new TreeMap<>(PRIORITY_SORTER); + } - list.add( h ); - } + public void addNewStorage(final IMEInventoryHandler h) { + final int priority = h.getPriority(); + List> list = this.priorityInventory.get(priority); + if (list == null) { + this.priorityInventory.put(priority, list = new ArrayList<>()); + } - @Override - public T injectItems( T input, final Actionable type, final IActionSource src ) - { - if( this.diveList( this, type ) ) - { - return input; - } + list.add(h); + } - if( this.testPermission( src, SecurityPermissions.INJECT ) ) - { - this.surface( this, type ); - return input; - } + @Override + public T injectItems(T input, final Actionable type, final IActionSource src) { + if (this.diveList(this, type)) { + return input; + } - for( final List> invList : this.priorityInventory.values() ) - { - Iterator> ii = invList.iterator(); - while( ii.hasNext() && input != null ) - { - final IMEInventoryHandler inv = ii.next(); + if (this.testPermission(src, SecurityPermissions.INJECT)) { + this.surface(this, type); + return input; + } - if( inv.validForPass( 1 ) && inv - .canAccept( input ) && ( inv.isPrioritized( input ) || inv.extractItems( input, Actionable.SIMULATE, src ) != null ) ) - { - input = inv.injectItems( input, type, src ); - } - } + for (final List> invList : this.priorityInventory.values()) { + Iterator> ii = invList.iterator(); + while (ii.hasNext() && input != null) { + final IMEInventoryHandler inv = ii.next(); - // We need to ignore prioritized inventories in the second pass. If they were not able to store everything - // during the first pass, they will do so in the second, but as this is stateless we will just report twice - // the amount of storable items. - // ignores craftingcache on the second pass. - ii = invList.iterator(); - while( ii.hasNext() && input != null ) - { - final IMEInventoryHandler inv = ii.next(); + if (inv.validForPass(1) && inv + .canAccept(input) && (inv.isPrioritized(input) || inv.extractItems(input, Actionable.SIMULATE, src) != null)) { + input = inv.injectItems(input, type, src); + } + } - if( inv.validForPass( 2 ) && inv.canAccept( input ) && !inv.isPrioritized( input ) ) - { - input = inv.injectItems( input, type, src ); - } - } - } + // We need to ignore prioritized inventories in the second pass. If they were not able to store everything + // during the first pass, they will do so in the second, but as this is stateless we will just report twice + // the amount of storable items. + // ignores craftingcache on the second pass. + ii = invList.iterator(); + while (ii.hasNext() && input != null) { + final IMEInventoryHandler inv = ii.next(); - this.surface( this, type ); + if (inv.validForPass(2) && inv.canAccept(input) && !inv.isPrioritized(input)) { + input = inv.injectItems(input, type, src); + } + } + } - return input; - } + this.surface(this, type); - private boolean diveList( final NetworkInventoryHandler networkInventoryHandler, final Actionable type ) - { - final Deque cDepth = this.getDepth( type ); - if( cDepth.contains( networkInventoryHandler ) ) - { - return true; - } + return input; + } - cDepth.push( this ); - return false; - } + private boolean diveList(final NetworkInventoryHandler networkInventoryHandler, final Actionable type) { + final Deque cDepth = this.getDepth(type); + if (cDepth.contains(networkInventoryHandler)) { + return true; + } - private boolean testPermission( final IActionSource src, final SecurityPermissions permission ) - { - if( src.player().isPresent() ) - { - if( !this.security.hasPermission( src.player().get(), permission ) ) - { - return true; - } - } - else if( src.machine().isPresent() ) - { - if( this.security.isAvailable() ) - { - final IGridNode n = src.machine().get().getActionableNode(); - if( n == null ) - { - return true; - } + cDepth.push(this); + return false; + } - final IGrid gn = n.getGrid(); - if( gn != this.security.getGrid() ) - { + private boolean testPermission(final IActionSource src, final SecurityPermissions permission) { + if (src.player().isPresent()) { + return !this.security.hasPermission(src.player().get(), permission); + } else if (src.machine().isPresent()) { + if (this.security.isAvailable()) { + final IGridNode n = src.machine().get().getActionableNode(); + if (n == null) { + return true; + } - final ISecurityGrid sg = gn.getCache( ISecurityGrid.class ); - final int playerID = sg.getOwner(); + final IGrid gn = n.getGrid(); + if (gn != this.security.getGrid()) { - if( !this.security.hasPermission( playerID, permission ) ) - { - return true; - } - } - } - } + final ISecurityGrid sg = gn.getCache(ISecurityGrid.class); + final int playerID = sg.getOwner(); - return false; - } + return !this.security.hasPermission(playerID, permission); + } + } + } - private void surface( final NetworkInventoryHandler networkInventoryHandler, final Actionable type ) - { - if( this.getDepth( type ).pop() != this ) - { - throw new IllegalStateException( "Invalid Access to Networked Storage API detected." ); - } - } + return false; + } - private Deque getDepth( final Actionable type ) - { - final ThreadLocal depth = type == Actionable.MODULATE ? DEPTH_MOD : DEPTH_SIM; + private void surface(final NetworkInventoryHandler networkInventoryHandler, final Actionable type) { + if (this.getDepth(type).pop() != this) { + throw new IllegalStateException("Invalid Access to Networked Storage API detected."); + } + } - Deque s = depth.get(); + private Deque getDepth(final Actionable type) { + final ThreadLocal depth = type == Actionable.MODULATE ? DEPTH_MOD : DEPTH_SIM; - if( s == null ) - { - depth.set( s = new ArrayDeque<>() ); - } + Deque s = depth.get(); - return s; - } + if (s == null) { + depth.set(s = new ArrayDeque<>()); + } - @Override - public T extractItems( T request, final Actionable mode, final IActionSource src ) - { - if( this.diveList( this, mode ) ) - { - return null; - } + return s; + } - if( this.testPermission( src, SecurityPermissions.EXTRACT ) ) - { - this.surface( this, mode ); - return null; - } + @Override + public T extractItems(T request, final Actionable mode, final IActionSource src) { + if (this.diveList(this, mode)) { + return null; + } - final Iterator>> i = this.priorityInventory.descendingMap().values().iterator();// priorityInventory.asMap().descendingMap().entrySet().iterator(); + if (this.testPermission(src, SecurityPermissions.EXTRACT)) { + this.surface(this, mode); + return null; + } - final T output = request.copy(); - request = request.copy(); - output.setStackSize( 0 ); - final long req = request.getStackSize(); + final Iterator>> i = this.priorityInventory.descendingMap().values().iterator();// priorityInventory.asMap().descendingMap().entrySet().iterator(); - while( i.hasNext() ) - { - final List> invList = i.next(); + final T output = request.copy(); + request = request.copy(); + output.setStackSize(0); + final long req = request.getStackSize(); - final Iterator> ii = invList.iterator(); - while( ii.hasNext() && output.getStackSize() < req ) - { - final IMEInventoryHandler inv = ii.next(); + while (i.hasNext()) { + final List> invList = i.next(); - request.setStackSize( req - output.getStackSize() ); - output.add( inv.extractItems( request, mode, src ) ); - } - } + final Iterator> ii = invList.iterator(); + while (ii.hasNext() && output.getStackSize() < req) { + final IMEInventoryHandler inv = ii.next(); - this.surface( this, mode ); + request.setStackSize(req - output.getStackSize()); + output.add(inv.extractItems(request, mode, src)); + } + } - if( output.getStackSize() <= 0 ) - { - return null; - } + this.surface(this, mode); - return output; - } + if (output.getStackSize() <= 0) { + return null; + } - @Override - public IItemList getAvailableItems( IItemList out ) - { - if( this.diveIteration( this, Actionable.SIMULATE ) ) - { - return out; - } + return output; + } - // for (Entry> h : priorityInventory.entries()) - for( final List> i : this.priorityInventory.values() ) - { - for( final IMEInventoryHandler j : i ) - { - out = j.getAvailableItems( out ); - } - } + @Override + public IItemList getAvailableItems(IItemList out) { + if (this.diveIteration(this, Actionable.SIMULATE)) { + return out; + } - this.surface( this, Actionable.SIMULATE ); + // for (Entry> h : priorityInventory.entries()) + for (final List> i : this.priorityInventory.values()) { + for (final IMEInventoryHandler j : i) { + out = j.getAvailableItems(out); + } + } - return out; - } + this.surface(this, Actionable.SIMULATE); - private boolean diveIteration( final NetworkInventoryHandler networkInventoryHandler, final Actionable type ) - { - final Deque cDepth = this.getDepth( type ); - if( cDepth.isEmpty() ) - { - currentPass++; - this.myPass = currentPass; - } - else - { - if( currentPass == this.myPass ) - { - return true; - } - else - { - this.myPass = currentPass; - } - } + return out; + } - cDepth.push( this ); - return false; - } + private boolean diveIteration(final NetworkInventoryHandler networkInventoryHandler, final Actionable type) { + final Deque cDepth = this.getDepth(type); + if (cDepth.isEmpty()) { + currentPass++; + this.myPass = currentPass; + } else { + if (currentPass == this.myPass) { + return true; + } else { + this.myPass = currentPass; + } + } - @Override - public IStorageChannel getChannel() - { - return this.myChannel; - } + cDepth.push(this); + return false; + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } + @Override + public IStorageChannel getChannel() { + return this.myChannel; + } - @Override - public boolean isPrioritized( final T input ) - { - return false; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } - @Override - public boolean canAccept( final T input ) - { - return true; - } + @Override + public boolean isPrioritized(final T input) { + return false; + } - @Override - public int getPriority() - { - return 0; - } + @Override + public boolean canAccept(final T input) { + return true; + } - @Override - public int getSlot() - { - return 0; - } + @Override + public int getPriority() { + return 0; + } - @Override - public boolean validForPass( final int i ) - { - return true; - } + @Override + public int getSlot() { + return 0; + } + + @Override + public boolean validForPass(final int i) { + return true; + } } diff --git a/src/main/java/appeng/me/storage/NullInventory.java b/src/main/java/appeng/me/storage/NullInventory.java index 615a11f3f..da9297a8d 100644 --- a/src/main/java/appeng/me/storage/NullInventory.java +++ b/src/main/java/appeng/me/storage/NullInventory.java @@ -30,66 +30,55 @@ import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; -public class NullInventory> implements IMEInventoryHandler -{ +public class NullInventory> implements IMEInventoryHandler { - @Override - public T injectItems( final T input, final Actionable mode, final IActionSource src ) - { - return input; - } + @Override + public T injectItems(final T input, final Actionable mode, final IActionSource src) { + return input; + } - @Override - public T extractItems( final T request, final Actionable mode, final IActionSource src ) - { - return null; - } + @Override + public T extractItems(final T request, final Actionable mode, final IActionSource src) { + return null; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return out; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return out; + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ; + } - @Override - public boolean isPrioritized( final T input ) - { - return false; - } + @Override + public boolean isPrioritized(final T input) { + return false; + } - @Override - public boolean canAccept( final T input ) - { - return false; - } + @Override + public boolean canAccept(final T input) { + return false; + } - @Override - public int getPriority() - { - return 0; - } + @Override + public int getPriority() { + return 0; + } - @Override - public int getSlot() - { - return 0; - } + @Override + public int getSlot() { + return 0; + } - @Override - public boolean validForPass( final int i ) - { - return i == 2; - } + @Override + public boolean validForPass(final int i) { + return i == 2; + } } diff --git a/src/main/java/appeng/me/storage/SecurityStationInventory.java b/src/main/java/appeng/me/storage/SecurityStationInventory.java index d34ee0bd4..facaa75f2 100644 --- a/src/main/java/appeng/me/storage/SecurityStationInventory.java +++ b/src/main/java/appeng/me/storage/SecurityStationInventory.java @@ -19,10 +19,6 @@ package appeng.me.storage; -import appeng.me.helpers.MEMonitorHandler; -import appeng.me.helpers.MachineSource; -import com.mojang.authlib.GameProfile; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -35,181 +31,150 @@ import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import appeng.me.GridAccessException; +import appeng.me.helpers.MEMonitorHandler; +import appeng.me.helpers.MachineSource; import appeng.tile.misc.TileSecurityStation; +import com.mojang.authlib.GameProfile; import java.util.Collections; -public class SecurityStationInventory implements IMEInventoryHandler -{ +public class SecurityStationInventory implements IMEInventoryHandler { - private final IItemList storedItems = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - private final TileSecurityStation securityTile; - private final MachineSource src; + private final IItemList storedItems = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + private final TileSecurityStation securityTile; + private final MachineSource src; - public SecurityStationInventory( final TileSecurityStation ts ) - { - this.securityTile = ts; - this.src = new MachineSource( securityTile ); - } + public SecurityStationInventory(final TileSecurityStation ts) { + this.securityTile = ts; + this.src = new MachineSource(securityTile); + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final IActionSource src ) - { - if( this.hasPermission( src ) ) - { - if( AEApi.instance().definitions().items().biometricCard().isSameAs( input.createItemStack() ) ) - { - if( this.canAccept( input ) ) - { - if( type == Actionable.SIMULATE ) - { - return null; - } + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable type, final IActionSource src) { + if (this.hasPermission(src)) { + if (AEApi.instance().definitions().items().biometricCard().isSameAs(input.createItemStack())) { + if (this.canAccept(input)) { + if (type == Actionable.SIMULATE) { + return null; + } - if( securityTile.getProxy().isActive() ) - { - ( ( MEMonitorHandler ) securityTile.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) ).postChangesToListeners( Collections.singletonList( input.copy() ), this.src ); - } + if (securityTile.getProxy().isActive()) { + ((MEMonitorHandler) securityTile.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class))).postChangesToListeners(Collections.singletonList(input.copy()), this.src); + } - this.getStoredItems().add( input ); - this.securityTile.inventoryChanged(); - return null; - } - } - } - return input; - } + this.getStoredItems().add(input); + this.securityTile.inventoryChanged(); + return null; + } + } + } + return input; + } - private boolean hasPermission( final IActionSource src ) - { - if( src.player().isPresent() ) - { - try - { - return this.securityTile.getProxy().getSecurity().hasPermission( src.player().get(), SecurityPermissions.SECURITY ); - } - catch( final GridAccessException e ) - { - // :P - } - } - return false; - } + private boolean hasPermission(final IActionSource src) { + if (src.player().isPresent()) { + try { + return this.securityTile.getProxy().getSecurity().hasPermission(src.player().get(), SecurityPermissions.SECURITY); + } catch (final GridAccessException e) { + // :P + } + } + return false; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final IActionSource src ) - { - if( this.hasPermission( src ) ) - { - final IAEItemStack target = this.getStoredItems().findPrecise( request ); - if( target != null ) - { - final IAEItemStack output = target.copy(); + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final IActionSource src) { + if (this.hasPermission(src)) { + final IAEItemStack target = this.getStoredItems().findPrecise(request); + if (target != null) { + final IAEItemStack output = target.copy(); - if( mode == Actionable.SIMULATE ) - { - return output; - } + if (mode == Actionable.SIMULATE) { + return output; + } - if( securityTile.getProxy().isActive() ) - { - ( ( MEMonitorHandler ) securityTile.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) ).postChangesToListeners( Collections.singletonList( target.copy().setStackSize( -target.getStackSize() ) ), this.src ); - } + if (securityTile.getProxy().isActive()) { + ((MEMonitorHandler) securityTile.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class))).postChangesToListeners(Collections.singletonList(target.copy().setStackSize(-target.getStackSize())), this.src); + } - target.setStackSize( 0 ); - this.securityTile.inventoryChanged(); - return output; - } - } - return null; - } + target.setStackSize(0); + this.securityTile.inventoryChanged(); + return output; + } + } + return null; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final IAEItemStack ais : this.getStoredItems() ) - { - out.add( ais ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final IAEItemStack ais : this.getStoredItems()) { + out.add(ais); + } - return out; - } + return out; + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - return false; - } + @Override + public boolean isPrioritized(final IAEItemStack input) { + return false; + } - @Override - public boolean canAccept( final IAEItemStack input ) - { - if( input.getItem() instanceof IBiometricCard ) - { - final IBiometricCard tbc = (IBiometricCard) input.getItem(); - final GameProfile newUser = tbc.getProfile( input.createItemStack() ); + @Override + public boolean canAccept(final IAEItemStack input) { + if (input.getItem() instanceof IBiometricCard) { + final IBiometricCard tbc = (IBiometricCard) input.getItem(); + final GameProfile newUser = tbc.getProfile(input.createItemStack()); - final int PlayerID = AEApi.instance().registries().players().getID( newUser ); - if( this.securityTile.getOwner() == PlayerID ) - { - return false; - } + final int PlayerID = AEApi.instance().registries().players().getID(newUser); + if (this.securityTile.getOwner() == PlayerID) { + return false; + } - for( final IAEItemStack ais : this.getStoredItems() ) - { - if( ais.isMeaningful() ) - { - final GameProfile thisUser = tbc.getProfile( ais.createItemStack() ); - if( thisUser == newUser ) - { - return false; - } + for (final IAEItemStack ais : this.getStoredItems()) { + if (ais.isMeaningful()) { + final GameProfile thisUser = tbc.getProfile(ais.createItemStack()); + if (thisUser == newUser) { + return false; + } - if( thisUser != null && thisUser.equals( newUser ) ) - { - return false; - } - } - } + if (thisUser != null && thisUser.equals(newUser)) { + return false; + } + } + } - return true; - } - return false; - } + return true; + } + return false; + } - @Override - public int getPriority() - { - return 0; - } + @Override + public int getPriority() { + return 0; + } - @Override - public int getSlot() - { - return 0; - } + @Override + public int getSlot() { + return 0; + } - @Override - public boolean validForPass( final int i ) - { - return true; - } + @Override + public boolean validForPass(final int i) { + return true; + } - public IItemList getStoredItems() - { - return this.storedItems; - } + public IItemList getStoredItems() { + return this.storedItems; + } } diff --git a/src/main/java/appeng/parts/AEBasePart.java b/src/main/java/appeng/parts/AEBasePart.java index 0cce70131..b990f4cd5 100644 --- a/src/main/java/appeng/parts/AEBasePart.java +++ b/src/main/java/appeng/parts/AEBasePart.java @@ -19,23 +19,34 @@ package appeng.parts; -import java.io.IOException; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.Optional; -import java.util.Random; - +import appeng.api.AEApi; +import appeng.api.config.Upgrades; +import appeng.api.definitions.IDefinitions; +import appeng.api.implementations.IUpgradeableHost; +import appeng.api.implementations.items.IMemoryCard; +import appeng.api.implementations.items.MemoryCardMessages; +import appeng.api.networking.IGridNode; +import appeng.api.networking.security.IActionHost; +import appeng.api.parts.*; +import appeng.api.util.*; import appeng.core.sync.GuiBridge; import appeng.fluids.helper.IConfigurableFluidInventory; import appeng.fluids.parts.PartFluidLevelEmitter; import appeng.fluids.util.AEFluidInventory; +import appeng.helpers.ICustomNameObject; +import appeng.helpers.IPriorityHost; +import appeng.items.parts.ItemPart; +import appeng.items.parts.PartType; import appeng.items.tools.quartz.ToolQuartzCuttingKnife; +import appeng.me.helpers.AENetworkProxy; +import appeng.me.helpers.IGridProxyable; import appeng.parts.automation.PartLevelEmitter; +import appeng.parts.networking.PartCable; +import appeng.tile.inventory.AppEngInternalAEInventory; +import appeng.util.Platform; +import appeng.util.SettingsFrom; import com.google.common.base.Preconditions; - import io.netty.buffer.ByteBuf; - import net.minecraft.crash.CrashReportCategory; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -55,545 +66,439 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.IItemHandler; -import appeng.api.AEApi; -import appeng.api.config.Upgrades; -import appeng.api.definitions.IDefinitions; -import appeng.api.implementations.IUpgradeableHost; -import appeng.api.implementations.items.IMemoryCard; -import appeng.api.implementations.items.MemoryCardMessages; -import appeng.api.networking.IGridNode; -import appeng.api.networking.security.IActionHost; -import appeng.api.parts.BusSupport; -import appeng.api.parts.IPart; -import appeng.api.parts.IPartCollisionHelper; -import appeng.api.parts.IPartHost; -import appeng.api.parts.PartItemStack; -import appeng.api.util.AECableType; -import appeng.api.util.AEColor; -import appeng.api.util.AEPartLocation; -import appeng.api.util.DimensionalCoord; -import appeng.api.util.IConfigManager; -import appeng.helpers.ICustomNameObject; -import appeng.helpers.IPriorityHost; -import appeng.items.parts.ItemPart; -import appeng.items.parts.PartType; -import appeng.me.helpers.AENetworkProxy; -import appeng.me.helpers.IGridProxyable; -import appeng.parts.networking.PartCable; -import appeng.tile.inventory.AppEngInternalAEInventory; -import appeng.util.Platform; -import appeng.util.SettingsFrom; - - -public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, IUpgradeableHost, ICustomNameObject -{ - - private final AENetworkProxy proxy; - private final ItemStack is; - private TileEntity tile = null; - private IPartHost host = null; - private AEPartLocation side = null; - - public AEBasePart( final ItemStack is ) - { - Preconditions.checkNotNull( is ); - - this.is = is; - this.proxy = new AENetworkProxy( this, "part", is, this instanceof PartCable ); - this.proxy.setValidSides( EnumSet.noneOf( EnumFacing.class ) ); - } - - public IPartHost getHost() - { - return this.host; - } - - public PartType getType() - { - return ItemPart.instance.getTypeByStack( this.is ); - } - - @Override - public IGridNode getGridNode( final AEPartLocation dir ) - { - return this.proxy.getNode(); - } - - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.GLASS; - } - - @Override - public void securityBreak() - { - if( this.getItemStack().getCount() > 0 && this.getGridNode() != null ) - { - final List items = new ArrayList<>(); - items.add( this.is.copy() ); - this.host.removePart( this.side, false ); - Platform.spawnDrops( this.tile.getWorld(), this.tile.getPos(), items ); - this.is.setCount( 0 ); - } - } - - protected AEColor getColor() - { - if( this.host == null ) - { - return AEColor.TRANSPARENT; - } - return this.host.getColor(); - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return 0; - } - - @Override - public TileEntity getTile() - { - return this.tile; - } - - @Override - public AENetworkProxy getProxy() - { - return this.proxy; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this.tile ); - } - - @Override - public void gridChanged() - { - - } - - @Override - public IGridNode getActionableNode() - { - return this.proxy.getNode(); - } - - public void saveChanges() - { - this.host.markForSave(); - } - - @Override - public String getCustomInventoryName() - { - return this.getItemStack().getDisplayName(); - } - - @Override - public boolean hasCustomInventoryName() - { - return this.getItemStack().hasDisplayName(); - } - - @Override - public void setCustomName(String name) { - this.getItemStack().setStackDisplayName(name); - } - - public void addEntityCrashInfo(final CrashReportCategory crashreportcategory ) - { - crashreportcategory.addCrashSection( "Part Side", this.getSide() ); - } - - @Override - public ItemStack getItemStack( final PartItemStack type ) - { - if( type == PartItemStack.NETWORK ) - { - final ItemStack copy = this.is.copy(); - copy.setTagCompound( null ); - return copy; - } - return this.is; - } - - @Override - public boolean isSolid() - { - return false; - } - - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - - } - - @Override - public boolean canConnectRedstone() - { - return false; - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - this.proxy.readFromNBT( data ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - this.proxy.writeToNBT( data ); - } - - @Override - public int isProvidingStrongPower() - { - return 0; - } - - @Override - public int isProvidingWeakPower() - { - return 0; - } - - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - - } - - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - return false; - } - - @Override - public IGridNode getGridNode() - { - return this.proxy.getNode(); - } - - @Override - public void onEntityCollision( final Entity entity ) - { - - } - - @Override - public void removeFromWorld() - { - this.proxy.invalidate(); - } - - @Override - public void addToWorld() - { - this.proxy.onReady(); - } - - @Override - public void setPartHostInfo( final AEPartLocation side, final IPartHost host, final TileEntity tile ) - { - this.setSide( side ); - this.tile = tile; - this.host = host; - } - - @Override - public IGridNode getExternalFacingNode() - { - return null; - } - - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World world, final BlockPos pos, final Random r ) - { - - } - - @Override - public int getLightLevel() - { - return 0; - } - - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - - } - - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 3; - } - - @Override - public boolean isLadder( final EntityLivingBase entity ) - { - return false; - } - - @Override - public IConfigManager getConfigManager() - { - return null; - } - - @Override - public IItemHandler getInventoryByName( final String name ) - { - return null; - } - - /** - * depending on the from, different settings will be accepted, don't call this with null - * - * @param from source of settings - * @param compound compound of source - */ - private void uploadSettings( final SettingsFrom from, final NBTTagCompound compound ) - { - if( compound != null ) - { - final IConfigManager cm = this.getConfigManager(); - if( cm != null ) - { - cm.readFromNBT( compound ); - } - } - - if( this instanceof IPriorityHost ) - { - final IPriorityHost pHost = (IPriorityHost) this; - pHost.setPriority( compound.getInteger( "priority" ) ); - } - - final IItemHandler inv = this.getInventoryByName( "config" ); - if( inv instanceof AppEngInternalAEInventory ) - { - final AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; - final AppEngInternalAEInventory tmp = new AppEngInternalAEInventory( null, target.getSlots() ); - tmp.readFromNBT( compound, "config" ); - for( int x = 0; x < tmp.getSlots(); x++ ) - { - target.setStackInSlot( x, tmp.getStackInSlot( x ) ); - } - if (this instanceof PartLevelEmitter ) { - final PartLevelEmitter partLevelEmitter = (PartLevelEmitter) this; - partLevelEmitter.setReportingValue(compound.getLong("reportingValue")); - } - } - - if (this instanceof IConfigurableFluidInventory) { - final IFluidHandler tank = ((IConfigurableFluidInventory) this).getFluidInventoryByName("config"); - if (tank instanceof AEFluidInventory ) { - final AEFluidInventory target = (AEFluidInventory) tank; - final AEFluidInventory tmp = new AEFluidInventory(null, target.getSlots()); - tmp.readFromNBT(compound, "config"); - for (int x = 0; x < tmp.getSlots(); x++) { - target.setFluidInSlot(x, tmp.getFluidInSlot(x)); - } - } - if (this instanceof PartFluidLevelEmitter ) { - final PartFluidLevelEmitter partFluidLevelEmitter = (PartFluidLevelEmitter) this; - partFluidLevelEmitter.setReportingValue(compound.getLong("reportingValue")); - } - } - } - - /** - * null means nothing to store... - * - * @param from source of settings - * - * @return compound of source - */ - private NBTTagCompound downloadSettings( final SettingsFrom from ) - { - final NBTTagCompound output = new NBTTagCompound(); - - final IConfigManager cm = this.getConfigManager(); - if( cm != null ) - { - cm.writeToNBT( output ); - } - - if( this instanceof IPriorityHost ) - { - final IPriorityHost pHost = (IPriorityHost) this; - output.setInteger( "priority", pHost.getPriority() ); - } - - final IItemHandler inv = this.getInventoryByName( "config" ); - if( inv instanceof AppEngInternalAEInventory ) - { - ( (AppEngInternalAEInventory) inv ).writeToNBT( output, "config" ); - if (this instanceof PartLevelEmitter) { - final PartLevelEmitter partLevelEmitter = (PartLevelEmitter) this; - output.setLong("reportingValue", partLevelEmitter.getReportingValue()); - } - } - - if (this instanceof IConfigurableFluidInventory) { - final IFluidHandler tank = ((IConfigurableFluidInventory) this).getFluidInventoryByName("config"); - if (tank instanceof AEFluidInventory ) { - ((AEFluidInventory) tank).writeToNBT(output, "config"); - } - if (this instanceof PartFluidLevelEmitter) { - final PartFluidLevelEmitter partFluidLevelEmitter = (PartFluidLevelEmitter) this; - output.setLong("reportingValue", partFluidLevelEmitter.getReportingValue()); - } - } - - return output.hasNoTags() ? null : output; - } - - public boolean useStandardMemoryCard() - { - return true; - } - - private boolean useMemoryCard( final EntityPlayer player ) - { - final ItemStack memCardIS = player.inventory.getCurrentItem(); - - if( !memCardIS.isEmpty() && this.useStandardMemoryCard() && memCardIS.getItem() instanceof IMemoryCard ) - { - final IMemoryCard memoryCard = (IMemoryCard) memCardIS.getItem(); - - ItemStack is = this.getItemStack( PartItemStack.NETWORK ); - - // Blocks and parts share the same soul! - final IDefinitions definitions = AEApi.instance().definitions(); - if( definitions.parts().iface().isSameAs( is ) ) - { - Optional iface = definitions.blocks().iface().maybeStack( 1 ); - if( iface.isPresent() ) - { - is = iface.get(); - } - } - - final String name = is.getUnlocalizedName(); - - if( player.isSneaking() ) - { - final NBTTagCompound data = this.downloadSettings( SettingsFrom.MEMORY_CARD ); - if( data != null ) - { - memoryCard.setMemoryCardContents( memCardIS, name, data ); - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_SAVED ); - } - } - else - { - final String storedName = memoryCard.getSettingsName( memCardIS ); - final NBTTagCompound data = memoryCard.getData( memCardIS ); - if( name.equals( storedName ) ) - { - this.uploadSettings( SettingsFrom.MEMORY_CARD, data ); - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_LOADED ); - } - else - { - memoryCard.notifyUser( player, MemoryCardMessages.INVALID_MACHINE ); - } - } - return true; - } - return false; - } - - private boolean useRenamer(final EntityPlayer player) { - final ItemStack stack = player.inventory.getCurrentItem(); - if(stack != null && stack.getItem() instanceof ToolQuartzCuttingKnife) { - if(ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) return false; - Platform.openGUI(player, tile, side, GuiBridge.GUI_RENAMER); - return true; - } - return false; - } - - @Override - public final boolean onActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( this.useMemoryCard( player ) || useRenamer(player) ) - { - return true; - } - - return this.onPartActivate( player, hand, pos ); - } - - @Override - public final boolean onShiftActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( this.useMemoryCard( player ) ) - { - return true; - } - - return this.onPartShiftActivate( player, hand, pos ); - } - - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - return false; - } - - public boolean onPartShiftActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - return false; - } - - @Override - public void onPlacement( final EntityPlayer player, final EnumHand hand, final ItemStack held, final AEPartLocation side ) - { - this.proxy.setOwner( player ); - } - - @Override - public boolean canBePlacedOn( final BusSupport what ) - { - return what == BusSupport.CABLE; - } - - @Override - public boolean requireDynamicRender() - { - return false; - } - - public AEPartLocation getSide() - { - return this.side; - } - - private void setSide( final AEPartLocation side ) - { - this.side = side; - } - - public ItemStack getItemStack() - { - return this.is; - } +import java.io.IOException; +import java.util.*; + + +public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, IUpgradeableHost, ICustomNameObject { + + private final AENetworkProxy proxy; + private final ItemStack is; + private TileEntity tile = null; + private IPartHost host = null; + private AEPartLocation side = null; + + public AEBasePart(final ItemStack is) { + Preconditions.checkNotNull(is); + + this.is = is; + this.proxy = new AENetworkProxy(this, "part", is, this instanceof PartCable); + this.proxy.setValidSides(EnumSet.noneOf(EnumFacing.class)); + } + + public IPartHost getHost() { + return this.host; + } + + public PartType getType() { + return ItemPart.instance.getTypeByStack(this.is); + } + + @Override + public IGridNode getGridNode(final AEPartLocation dir) { + return this.proxy.getNode(); + } + + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.GLASS; + } + + @Override + public void securityBreak() { + if (this.getItemStack().getCount() > 0 && this.getGridNode() != null) { + final List items = new ArrayList<>(); + items.add(this.is.copy()); + this.host.removePart(this.side, false); + Platform.spawnDrops(this.tile.getWorld(), this.tile.getPos(), items); + this.is.setCount(0); + } + } + + protected AEColor getColor() { + if (this.host == null) { + return AEColor.TRANSPARENT; + } + return this.host.getColor(); + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return 0; + } + + @Override + public TileEntity getTile() { + return this.tile; + } + + @Override + public AENetworkProxy getProxy() { + return this.proxy; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this.tile); + } + + @Override + public void gridChanged() { + + } + + @Override + public IGridNode getActionableNode() { + return this.proxy.getNode(); + } + + public void saveChanges() { + this.host.markForSave(); + } + + @Override + public String getCustomInventoryName() { + return this.getItemStack().getDisplayName(); + } + + @Override + public boolean hasCustomInventoryName() { + return this.getItemStack().hasDisplayName(); + } + + @Override + public void setCustomName(String name) { + this.getItemStack().setStackDisplayName(name); + } + + public void addEntityCrashInfo(final CrashReportCategory crashreportcategory) { + crashreportcategory.addCrashSection("Part Side", this.getSide()); + } + + @Override + public ItemStack getItemStack(final PartItemStack type) { + if (type == PartItemStack.NETWORK) { + final ItemStack copy = this.is.copy(); + copy.setTagCompound(null); + return copy; + } + return this.is; + } + + @Override + public boolean isSolid() { + return false; + } + + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + + } + + @Override + public boolean canConnectRedstone() { + return false; + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + this.proxy.readFromNBT(data); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + this.proxy.writeToNBT(data); + } + + @Override + public int isProvidingStrongPower() { + return 0; + } + + @Override + public int isProvidingWeakPower() { + return 0; + } + + @Override + public void writeToStream(final ByteBuf data) throws IOException { + + } + + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + return false; + } + + @Override + public IGridNode getGridNode() { + return this.proxy.getNode(); + } + + @Override + public void onEntityCollision(final Entity entity) { + + } + + @Override + public void removeFromWorld() { + this.proxy.invalidate(); + } + + @Override + public void addToWorld() { + this.proxy.onReady(); + } + + @Override + public void setPartHostInfo(final AEPartLocation side, final IPartHost host, final TileEntity tile) { + this.setSide(side); + this.tile = tile; + this.host = host; + } + + @Override + public IGridNode getExternalFacingNode() { + return null; + } + + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final World world, final BlockPos pos, final Random r) { + + } + + @Override + public int getLightLevel() { + return 0; + } + + @Override + public void getDrops(final List drops, final boolean wrenched) { + + } + + @Override + public float getCableConnectionLength(AECableType cable) { + return 3; + } + + @Override + public boolean isLadder(final EntityLivingBase entity) { + return false; + } + + @Override + public IConfigManager getConfigManager() { + return null; + } + + @Override + public IItemHandler getInventoryByName(final String name) { + return null; + } + + /** + * depending on the from, different settings will be accepted, don't call this with null + * + * @param from source of settings + * @param compound compound of source + */ + private void uploadSettings(final SettingsFrom from, final NBTTagCompound compound) { + if (compound != null) { + final IConfigManager cm = this.getConfigManager(); + if (cm != null) { + cm.readFromNBT(compound); + } + } + + if (this instanceof IPriorityHost) { + final IPriorityHost pHost = (IPriorityHost) this; + pHost.setPriority(compound.getInteger("priority")); + } + + final IItemHandler inv = this.getInventoryByName("config"); + if (inv instanceof AppEngInternalAEInventory) { + final AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; + final AppEngInternalAEInventory tmp = new AppEngInternalAEInventory(null, target.getSlots()); + tmp.readFromNBT(compound, "config"); + for (int x = 0; x < tmp.getSlots(); x++) { + target.setStackInSlot(x, tmp.getStackInSlot(x)); + } + if (this instanceof PartLevelEmitter) { + final PartLevelEmitter partLevelEmitter = (PartLevelEmitter) this; + partLevelEmitter.setReportingValue(compound.getLong("reportingValue")); + } + } + + if (this instanceof IConfigurableFluidInventory) { + final IFluidHandler tank = ((IConfigurableFluidInventory) this).getFluidInventoryByName("config"); + if (tank instanceof AEFluidInventory) { + final AEFluidInventory target = (AEFluidInventory) tank; + final AEFluidInventory tmp = new AEFluidInventory(null, target.getSlots()); + tmp.readFromNBT(compound, "config"); + for (int x = 0; x < tmp.getSlots(); x++) { + target.setFluidInSlot(x, tmp.getFluidInSlot(x)); + } + } + if (this instanceof PartFluidLevelEmitter) { + final PartFluidLevelEmitter partFluidLevelEmitter = (PartFluidLevelEmitter) this; + partFluidLevelEmitter.setReportingValue(compound.getLong("reportingValue")); + } + } + } + + /** + * null means nothing to store... + * + * @param from source of settings + * @return compound of source + */ + private NBTTagCompound downloadSettings(final SettingsFrom from) { + final NBTTagCompound output = new NBTTagCompound(); + + final IConfigManager cm = this.getConfigManager(); + if (cm != null) { + cm.writeToNBT(output); + } + + if (this instanceof IPriorityHost) { + final IPriorityHost pHost = (IPriorityHost) this; + output.setInteger("priority", pHost.getPriority()); + } + + final IItemHandler inv = this.getInventoryByName("config"); + if (inv instanceof AppEngInternalAEInventory) { + ((AppEngInternalAEInventory) inv).writeToNBT(output, "config"); + if (this instanceof PartLevelEmitter) { + final PartLevelEmitter partLevelEmitter = (PartLevelEmitter) this; + output.setLong("reportingValue", partLevelEmitter.getReportingValue()); + } + } + + if (this instanceof IConfigurableFluidInventory) { + final IFluidHandler tank = ((IConfigurableFluidInventory) this).getFluidInventoryByName("config"); + if (tank instanceof AEFluidInventory) { + ((AEFluidInventory) tank).writeToNBT(output, "config"); + } + if (this instanceof PartFluidLevelEmitter) { + final PartFluidLevelEmitter partFluidLevelEmitter = (PartFluidLevelEmitter) this; + output.setLong("reportingValue", partFluidLevelEmitter.getReportingValue()); + } + } + + return output.hasNoTags() ? null : output; + } + + public boolean useStandardMemoryCard() { + return true; + } + + private boolean useMemoryCard(final EntityPlayer player) { + final ItemStack memCardIS = player.inventory.getCurrentItem(); + + if (!memCardIS.isEmpty() && this.useStandardMemoryCard() && memCardIS.getItem() instanceof IMemoryCard) { + final IMemoryCard memoryCard = (IMemoryCard) memCardIS.getItem(); + + ItemStack is = this.getItemStack(PartItemStack.NETWORK); + + // Blocks and parts share the same soul! + final IDefinitions definitions = AEApi.instance().definitions(); + if (definitions.parts().iface().isSameAs(is)) { + Optional iface = definitions.blocks().iface().maybeStack(1); + if (iface.isPresent()) { + is = iface.get(); + } + } + + final String name = is.getUnlocalizedName(); + + if (player.isSneaking()) { + final NBTTagCompound data = this.downloadSettings(SettingsFrom.MEMORY_CARD); + if (data != null) { + memoryCard.setMemoryCardContents(memCardIS, name, data); + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_SAVED); + } + } else { + final String storedName = memoryCard.getSettingsName(memCardIS); + final NBTTagCompound data = memoryCard.getData(memCardIS); + if (name.equals(storedName)) { + this.uploadSettings(SettingsFrom.MEMORY_CARD, data); + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_LOADED); + } else { + memoryCard.notifyUser(player, MemoryCardMessages.INVALID_MACHINE); + } + } + return true; + } + return false; + } + + private boolean useRenamer(final EntityPlayer player) { + final ItemStack stack = player.inventory.getCurrentItem(); + if (stack != null && stack.getItem() instanceof ToolQuartzCuttingKnife) { + if (ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) return false; + Platform.openGUI(player, tile, side, GuiBridge.GUI_RENAMER); + return true; + } + return false; + } + + @Override + public final boolean onActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (this.useMemoryCard(player) || useRenamer(player)) { + return true; + } + + return this.onPartActivate(player, hand, pos); + } + + @Override + public final boolean onShiftActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (this.useMemoryCard(player)) { + return true; + } + + return this.onPartShiftActivate(player, hand, pos); + } + + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + return false; + } + + public boolean onPartShiftActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + return false; + } + + @Override + public void onPlacement(final EntityPlayer player, final EnumHand hand, final ItemStack held, final AEPartLocation side) { + this.proxy.setOwner(player); + } + + @Override + public boolean canBePlacedOn(final BusSupport what) { + return what == BusSupport.CABLE; + } + + @Override + public boolean requireDynamicRender() { + return false; + } + + public AEPartLocation getSide() { + return this.side; + } + + private void setSide(final AEPartLocation side) { + this.side = side; + } + + public ItemStack getItemStack() { + return this.is; + } } \ No newline at end of file diff --git a/src/main/java/appeng/parts/BusCollisionHelper.java b/src/main/java/appeng/parts/BusCollisionHelper.java index c6f138070..58c1d3d98 100644 --- a/src/main/java/appeng/parts/BusCollisionHelper.java +++ b/src/main/java/appeng/parts/BusCollisionHelper.java @@ -19,160 +19,146 @@ package appeng.parts; -import java.util.List; - +import appeng.api.parts.IPartCollisionHelper; +import appeng.api.util.AEPartLocation; import net.minecraft.entity.Entity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; -import appeng.api.parts.IPartCollisionHelper; -import appeng.api.util.AEPartLocation; +import java.util.List; -public class BusCollisionHelper implements IPartCollisionHelper -{ +public class BusCollisionHelper implements IPartCollisionHelper { - private final List boxes; + private final List boxes; - private final EnumFacing x; - private final EnumFacing y; - private final EnumFacing z; + private final EnumFacing x; + private final EnumFacing y; + private final EnumFacing z; - private final Entity entity; - private final boolean isVisual; + private final Entity entity; + private final boolean isVisual; - public BusCollisionHelper( final List boxes, final EnumFacing x, final EnumFacing y, final EnumFacing z, final Entity e, final boolean visual ) - { - this.boxes = boxes; - this.x = x; - this.y = y; - this.z = z; - this.entity = e; - this.isVisual = visual; - } + public BusCollisionHelper(final List boxes, final EnumFacing x, final EnumFacing y, final EnumFacing z, final Entity e, final boolean visual) { + this.boxes = boxes; + this.x = x; + this.y = y; + this.z = z; + this.entity = e; + this.isVisual = visual; + } - public BusCollisionHelper( final List boxes, final AEPartLocation s, final Entity e, final boolean visual ) - { - this.boxes = boxes; - this.entity = e; - this.isVisual = visual; + public BusCollisionHelper(final List boxes, final AEPartLocation s, final Entity e, final boolean visual) { + this.boxes = boxes; + this.entity = e; + this.isVisual = visual; - switch( s ) - { - case DOWN: - this.x = EnumFacing.EAST; - this.y = EnumFacing.NORTH; - this.z = EnumFacing.DOWN; - break; - case UP: - this.x = EnumFacing.EAST; - this.y = EnumFacing.SOUTH; - this.z = EnumFacing.UP; - break; - case EAST: - this.x = EnumFacing.SOUTH; - this.y = EnumFacing.UP; - this.z = EnumFacing.EAST; - break; - case WEST: - this.x = EnumFacing.NORTH; - this.y = EnumFacing.UP; - this.z = EnumFacing.WEST; - break; - case NORTH: - this.x = EnumFacing.WEST; - this.y = EnumFacing.UP; - this.z = EnumFacing.NORTH; - break; - case SOUTH: - this.x = EnumFacing.EAST; - this.y = EnumFacing.UP; - this.z = EnumFacing.SOUTH; - break; - case INTERNAL: - default: - this.x = EnumFacing.EAST; - this.y = EnumFacing.UP; - this.z = EnumFacing.SOUTH; - break; - } - } + switch (s) { + case DOWN: + this.x = EnumFacing.EAST; + this.y = EnumFacing.NORTH; + this.z = EnumFacing.DOWN; + break; + case UP: + this.x = EnumFacing.EAST; + this.y = EnumFacing.SOUTH; + this.z = EnumFacing.UP; + break; + case EAST: + this.x = EnumFacing.SOUTH; + this.y = EnumFacing.UP; + this.z = EnumFacing.EAST; + break; + case WEST: + this.x = EnumFacing.NORTH; + this.y = EnumFacing.UP; + this.z = EnumFacing.WEST; + break; + case NORTH: + this.x = EnumFacing.WEST; + this.y = EnumFacing.UP; + this.z = EnumFacing.NORTH; + break; + case SOUTH: + this.x = EnumFacing.EAST; + this.y = EnumFacing.UP; + this.z = EnumFacing.SOUTH; + break; + case INTERNAL: + default: + this.x = EnumFacing.EAST; + this.y = EnumFacing.UP; + this.z = EnumFacing.SOUTH; + break; + } + } - /** - * pretty much useless... - */ - public Entity getEntity() - { - return this.entity; - } + /** + * pretty much useless... + */ + public Entity getEntity() { + return this.entity; + } - @Override - public void addBox( double minX, double minY, double minZ, double maxX, double maxY, double maxZ ) - { - minX /= 16.0; - minY /= 16.0; - minZ /= 16.0; - maxX /= 16.0; - maxY /= 16.0; - maxZ /= 16.0; + @Override + public void addBox(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + minX /= 16.0; + minY /= 16.0; + minZ /= 16.0; + maxX /= 16.0; + maxY /= 16.0; + maxZ /= 16.0; - double aX = minX * this.x.getFrontOffsetX() + minY * this.y.getFrontOffsetX() + minZ * this.z.getFrontOffsetX(); - double aY = minX * this.x.getFrontOffsetY() + minY * this.y.getFrontOffsetY() + minZ * this.z.getFrontOffsetY(); - double aZ = minX * this.x.getFrontOffsetZ() + minY * this.y.getFrontOffsetZ() + minZ * this.z.getFrontOffsetZ(); + double aX = minX * this.x.getFrontOffsetX() + minY * this.y.getFrontOffsetX() + minZ * this.z.getFrontOffsetX(); + double aY = minX * this.x.getFrontOffsetY() + minY * this.y.getFrontOffsetY() + minZ * this.z.getFrontOffsetY(); + double aZ = minX * this.x.getFrontOffsetZ() + minY * this.y.getFrontOffsetZ() + minZ * this.z.getFrontOffsetZ(); - double bX = maxX * this.x.getFrontOffsetX() + maxY * this.y.getFrontOffsetX() + maxZ * this.z.getFrontOffsetX(); - double bY = maxX * this.x.getFrontOffsetY() + maxY * this.y.getFrontOffsetY() + maxZ * this.z.getFrontOffsetY(); - double bZ = maxX * this.x.getFrontOffsetZ() + maxY * this.y.getFrontOffsetZ() + maxZ * this.z.getFrontOffsetZ(); + double bX = maxX * this.x.getFrontOffsetX() + maxY * this.y.getFrontOffsetX() + maxZ * this.z.getFrontOffsetX(); + double bY = maxX * this.x.getFrontOffsetY() + maxY * this.y.getFrontOffsetY() + maxZ * this.z.getFrontOffsetY(); + double bZ = maxX * this.x.getFrontOffsetZ() + maxY * this.y.getFrontOffsetZ() + maxZ * this.z.getFrontOffsetZ(); - if( this.x.getFrontOffsetX() + this.y.getFrontOffsetX() + this.z.getFrontOffsetX() < 0 ) - { - aX += 1; - bX += 1; - } + if (this.x.getFrontOffsetX() + this.y.getFrontOffsetX() + this.z.getFrontOffsetX() < 0) { + aX += 1; + bX += 1; + } - if( this.x.getFrontOffsetY() + this.y.getFrontOffsetY() + this.z.getFrontOffsetY() < 0 ) - { - aY += 1; - bY += 1; - } + if (this.x.getFrontOffsetY() + this.y.getFrontOffsetY() + this.z.getFrontOffsetY() < 0) { + aY += 1; + bY += 1; + } - if( this.x.getFrontOffsetZ() + this.y.getFrontOffsetZ() + this.z.getFrontOffsetZ() < 0 ) - { - aZ += 1; - bZ += 1; - } + if (this.x.getFrontOffsetZ() + this.y.getFrontOffsetZ() + this.z.getFrontOffsetZ() < 0) { + aZ += 1; + bZ += 1; + } - minX = Math.min( aX, bX ); - minY = Math.min( aY, bY ); - minZ = Math.min( aZ, bZ ); - maxX = Math.max( aX, bX ); - maxY = Math.max( aY, bY ); - maxZ = Math.max( aZ, bZ ); + minX = Math.min(aX, bX); + minY = Math.min(aY, bY); + minZ = Math.min(aZ, bZ); + maxX = Math.max(aX, bX); + maxY = Math.max(aY, bY); + maxZ = Math.max(aZ, bZ); - this.boxes.add( new AxisAlignedBB( minX, minY, minZ, maxX, maxY, maxZ ) ); - } + this.boxes.add(new AxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ)); + } - @Override - public EnumFacing getWorldX() - { - return this.x; - } + @Override + public EnumFacing getWorldX() { + return this.x; + } - @Override - public EnumFacing getWorldY() - { - return this.y; - } + @Override + public EnumFacing getWorldY() { + return this.y; + } - @Override - public EnumFacing getWorldZ() - { - return this.z; - } + @Override + public EnumFacing getWorldZ() { + return this.z; + } - @Override - public boolean isBBCollision() - { - return !this.isVisual; - } + @Override + public boolean isBBCollision() { + return !this.isVisual; + } } diff --git a/src/main/java/appeng/parts/CableBusContainer.java b/src/main/java/appeng/parts/CableBusContainer.java index 070c55014..0dd852a5a 100644 --- a/src/main/java/appeng/parts/CableBusContainer.java +++ b/src/main/java/appeng/parts/CableBusContainer.java @@ -19,17 +19,27 @@ package appeng.parts; -import java.io.IOException; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; -import java.util.Set; - -import javax.annotation.Nullable; - +import appeng.api.AEApi; +import appeng.api.config.YesNo; +import appeng.api.exceptions.FailedConnectionException; +import appeng.api.implementations.parts.IPartCable; +import appeng.api.networking.IGridHost; +import appeng.api.networking.IGridNode; +import appeng.api.parts.*; +import appeng.api.util.AECableType; +import appeng.api.util.AEColor; +import appeng.api.util.AEPartLocation; +import appeng.api.util.DimensionalCoord; +import appeng.client.render.cablebus.CableBusRenderState; +import appeng.client.render.cablebus.CableCoreType; +import appeng.client.render.cablebus.FacadeRenderState; +import appeng.core.AELog; +import appeng.facade.FacadeContainer; +import appeng.helpers.AEMultiTile; +import appeng.me.GridConnection; +import appeng.parts.networking.PartCable; +import appeng.util.Platform; import io.netty.buffer.ByteBuf; - import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -46,1255 +56,996 @@ import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import appeng.api.AEApi; -import appeng.api.config.YesNo; -import appeng.api.exceptions.FailedConnectionException; -import appeng.api.implementations.parts.IPartCable; -import appeng.api.networking.IGridHost; -import appeng.api.networking.IGridNode; -import appeng.api.parts.IFacadeContainer; -import appeng.api.parts.IFacadePart; -import appeng.api.parts.IPart; -import appeng.api.parts.IPartCollisionHelper; -import appeng.api.parts.IPartHost; -import appeng.api.parts.IPartItem; -import appeng.api.parts.LayerFlags; -import appeng.api.parts.PartItemStack; -import appeng.api.parts.SelectedPart; -import appeng.api.util.AECableType; -import appeng.api.util.AEColor; -import appeng.api.util.AEPartLocation; -import appeng.api.util.DimensionalCoord; -import appeng.client.render.cablebus.CableBusRenderState; -import appeng.client.render.cablebus.CableCoreType; -import appeng.client.render.cablebus.FacadeRenderState; -import appeng.core.AELog; -import appeng.facade.FacadeContainer; -import appeng.helpers.AEMultiTile; -import appeng.me.GridConnection; -import appeng.parts.networking.PartCable; -import appeng.util.Platform; - - -public class CableBusContainer extends CableBusStorage implements AEMultiTile, ICableBusContainer -{ - - private static final ThreadLocal IS_LOADING = new ThreadLocal<>(); - private final EnumSet myLayerFlags = EnumSet.noneOf( LayerFlags.class ); - private YesNo hasRedstone = YesNo.UNDECIDED; - private IPartHost tcb; - // TODO 1.10.2-R - does somebody seriously want to make parts TESR??? Hope not. - private boolean requiresDynamicRender = false; - private boolean inWorld = false; - - public CableBusContainer( final IPartHost host ) - { - this.tcb = host; - } - - public static boolean isLoading() - { - final Boolean is = IS_LOADING.get(); - return is != null && is; - } - - public void setHost( final IPartHost host ) - { - this.tcb.clearContainer(); - this.tcb = host; - } - - public void rotateLeft() - { - final IPart[] newSides = new IPart[6]; - - newSides[AEPartLocation.UP.ordinal()] = this.getSide( AEPartLocation.UP ); - newSides[AEPartLocation.DOWN.ordinal()] = this.getSide( AEPartLocation.DOWN ); - - newSides[AEPartLocation.EAST.ordinal()] = this.getSide( AEPartLocation.NORTH ); - newSides[AEPartLocation.SOUTH.ordinal()] = this.getSide( AEPartLocation.EAST ); - newSides[AEPartLocation.WEST.ordinal()] = this.getSide( AEPartLocation.SOUTH ); - newSides[AEPartLocation.NORTH.ordinal()] = this.getSide( AEPartLocation.WEST ); - - for( final AEPartLocation dir : AEPartLocation.SIDE_LOCATIONS ) - { - this.setSide( dir, newSides[dir.ordinal()] ); - } - - this.getFacadeContainer().rotateLeft(); - } - - @Override - public IFacadeContainer getFacadeContainer() - { - return new FacadeContainer( this ); - } - - @Override - public boolean canAddPart( ItemStack is, final AEPartLocation side ) - { - if( PartPlacement.isFacade( is, side ) != null ) - { - return true; - } - - if( is.getItem() instanceof IPartItem ) - { - final IPartItem bi = (IPartItem) is.getItem(); - - is = is.copy(); - is.setCount( 1 ); - - final IPart bp = bi.createPartFromItemStack( is ); - if( bp != null ) - { - if( bp instanceof IPartCable ) - { - boolean canPlace = true; - for( final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS ) - { - if( this.getPart( d ) != null && !this.getPart( d ).canBePlacedOn( ( (IPartCable) bp ).supportsBuses() ) ) - { - canPlace = false; - } - } - - if( !canPlace ) - { - return false; - } - - return this.getPart( AEPartLocation.INTERNAL ) == null; - } - else if( !( bp instanceof IPartCable ) && side != AEPartLocation.INTERNAL ) - { - final IPart cable = this.getPart( AEPartLocation.INTERNAL ); - if( cable != null && !bp.canBePlacedOn( ( (IPartCable) cable ).supportsBuses() ) ) - { - return false; - } - - return this.getPart( side ) == null; - } - } - } - return false; - } - - @Override - public AEPartLocation addPart( ItemStack is, final AEPartLocation side, final @Nullable EntityPlayer player, final @Nullable EnumHand hand ) - { - if( this.canAddPart( is, side ) ) - { - if( is.getItem() instanceof IPartItem ) - { - final IPartItem bi = (IPartItem) is.getItem(); - - is = is.copy(); - is.setCount( 1 ); - - final IPart bp = bi.createPartFromItemStack( is ); - if( bp instanceof IPartCable ) - { - boolean canPlace = true; - for( final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS ) - { - if( this.getPart( d ) != null && !this.getPart( d ).canBePlacedOn( ( (IPartCable) bp ).supportsBuses() ) ) - { - canPlace = false; - } - } - - if( !canPlace ) - { - return null; - } - - if( this.getPart( AEPartLocation.INTERNAL ) != null ) - { - return null; - } - - this.setCenter( (IPartCable) bp ); - bp.setPartHostInfo( AEPartLocation.INTERNAL, this, this.tcb.getTile() ); - - if( player != null ) - { - bp.onPlacement( player, hand, is, side ); - } - - if( this.inWorld ) - { - bp.addToWorld(); - } - - final IGridNode cn = this.getCenter().getGridNode(); - if( cn != null ) - { - for( final AEPartLocation ins : AEPartLocation.SIDE_LOCATIONS ) - { - final IPart sbp = this.getPart( ins ); - if( sbp != null ) - { - final IGridNode sn = sbp.getGridNode(); - if( sn != null ) - { - try - { - GridConnection.create( cn, sn, AEPartLocation.INTERNAL ); - } - catch( final FailedConnectionException e ) - { - AELog.debug( e ); - - bp.removeFromWorld(); - this.setCenter( null ); - return null; - } - } - } - } - } - - this.updateConnections(); - this.markForUpdate(); - this.markForSave(); - this.partChanged(); - return AEPartLocation.INTERNAL; - } - else if( bp != null && !( bp instanceof IPartCable ) && side != AEPartLocation.INTERNAL ) - { - final IPart cable = this.getPart( AEPartLocation.INTERNAL ); - if( cable != null && !bp.canBePlacedOn( ( (IPartCable) cable ).supportsBuses() ) ) - { - return null; - } - - this.setSide( side, bp ); - bp.setPartHostInfo( side, this, this.getTile() ); - - if( player != null ) - { - bp.onPlacement( player, hand, is, side ); - } - - if( this.inWorld ) - { - bp.addToWorld(); - } - - if( this.getCenter() != null ) - { - final IGridNode cn = this.getCenter().getGridNode(); - final IGridNode sn = bp.getGridNode(); - - if( cn != null && sn != null ) - { - try - { - GridConnection.create( cn, sn, AEPartLocation.INTERNAL ); - } - catch( final FailedConnectionException e ) - { - AELog.debug( e ); - - bp.removeFromWorld(); - this.setSide( side, null ); - return null; - } - } - } - - this.updateDynamicRender(); - this.updateConnections(); - this.markForUpdate(); - this.markForSave(); - this.partChanged(); - return side; - } - } - } - return null; - } - - @Override - public IPart getPart( final AEPartLocation partLocation ) - { - if( partLocation == AEPartLocation.INTERNAL ) - { - return this.getCenter(); - } - return this.getSide( partLocation ); - } - - @Override - public IPart getPart( final EnumFacing side ) - { - return this.getSide( AEPartLocation.fromFacing( side ) ); - } - - @Override - public void removePart( final AEPartLocation side, final boolean suppressUpdate ) - { - if( side == AEPartLocation.INTERNAL ) - { - if( this.getCenter() != null ) - { - this.getCenter().removeFromWorld(); - } - this.setCenter( null ); - } - else - { - if( this.getSide( side ) != null ) - { - this.getSide( side ).removeFromWorld(); - } - this.setSide( side, null ); - } - - if( !suppressUpdate ) - { - this.updateDynamicRender(); - this.updateConnections(); - this.markForUpdate(); - this.markForSave(); - this.partChanged(); - } - } - - @Override - public void markForUpdate() - { - this.tcb.markForUpdate(); - } - - @Override - public DimensionalCoord getLocation() - { - return this.tcb.getLocation(); - } - - @Override - public TileEntity getTile() - { - return this.tcb.getTile(); - } - - @Override - public AEColor getColor() - { - if( this.getCenter() != null ) - { - final IPartCable c = this.getCenter(); - return c.getCableColor(); - } - return AEColor.TRANSPARENT; - } - - @Override - public void clearContainer() - { - throw new UnsupportedOperationException( "Now that is silly!" ); - } - - @Override - public boolean isBlocked( final EnumFacing side ) - { - return this.tcb.isBlocked( side ); - } - - @Override - public SelectedPart selectPart( final Vec3d pos ) - { - for( final AEPartLocation side : AEPartLocation.values() ) - { - final IPart p = this.getPart( side ); - if( p != null ) - { - final List boxes = new ArrayList<>(); - - final IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); - p.getBoxes( bch ); - for( AxisAlignedBB bb : boxes ) - { - bb = bb.grow( 0.002, 0.002, 0.002 ); - if( bb.contains( pos ) ) - { - return new SelectedPart( p, side ); - } - } - } - } - - if( AEApi.instance().partHelper().getCableRenderMode().opaqueFacades ) - { - final IFacadeContainer fc = this.getFacadeContainer(); - for( final AEPartLocation side : AEPartLocation.SIDE_LOCATIONS ) - { - final IFacadePart p = fc.getFacade( side ); - if( p != null ) - { - final List boxes = new ArrayList<>(); - - final IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); - p.getBoxes( bch, null ); - for( AxisAlignedBB bb : boxes ) - { - bb = bb.grow( 0.01, 0.01, 0.01 ); - if( bb.contains( pos ) ) - { - return new SelectedPart( p, side ); - } - } - } - } - } - - return new SelectedPart(); - } - - @Override - public void markForSave() - { - this.tcb.markForSave(); - } - - @Override - public void partChanged() - { - if( this.getCenter() == null ) - { - final List facades = new ArrayList<>(); - - final IFacadeContainer fc = this.getFacadeContainer(); - for( final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS ) - { - final IFacadePart fp = fc.getFacade( d ); - if( fp != null ) - { - facades.add( fp.getItemStack() ); - fc.removeFacade( this.tcb, d ); - } - } - - if( !facades.isEmpty() ) - { - final TileEntity te = this.tcb.getTile(); - Platform.spawnDrops( te.getWorld(), te.getPos(), facades ); - } - } - - this.tcb.partChanged(); - } - - @Override - public boolean hasRedstone( final AEPartLocation side ) - { - if( this.hasRedstone == YesNo.UNDECIDED ) - { - this.updateRedstone(); - } - - return this.hasRedstone == YesNo.YES; - } - - @Override - public boolean isEmpty() - { - final IFacadeContainer fc = this.getFacadeContainer(); - for( final AEPartLocation s : AEPartLocation.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - return false; - } - - if( s != AEPartLocation.INTERNAL ) - { - final IFacadePart fp = fc.getFacade( s ); - if( fp != null ) - { - return false; - } - } - } - return true; - } - - @Override - public Set getLayerFlags() - { - return this.myLayerFlags; - } - - @Override - public void cleanup() - { - this.tcb.cleanup(); - } - - @Override - public void notifyNeighbors() - { - this.tcb.notifyNeighbors(); - } - - @Override - public boolean isInWorld() - { - return this.inWorld; - } - - private void updateRedstone() - { - final TileEntity te = this.getTile(); - this.hasRedstone = te.getWorld().isBlockIndirectlyGettingPowered( te.getPos() ) != 0 ? YesNo.YES : YesNo.NO; - } - - private void updateDynamicRender() - { - this.requiresDynamicRender = false; - for( final AEPartLocation s : AEPartLocation.SIDE_LOCATIONS ) - { - final IPart p = this.getPart( s ); - if( p != null ) - { - this.setRequiresDynamicRender( this.isRequiresDynamicRender() || p.requireDynamicRender() ); - } - } - } - - /** - * use for FMP - */ - public void updateConnections() - { - if( this.getCenter() != null ) - { - final EnumSet sides = EnumSet.allOf( EnumFacing.class ); - - for( final EnumFacing s : EnumFacing.VALUES ) - { - if( this.getPart( s ) != null || this.isBlocked( s ) ) - { - sides.remove( s ); - } - } - - this.getCenter().setValidSides( sides ); - final IGridNode n = this.getCenter().getGridNode(); - if( n != null ) - { - n.updateState(); - } - } - } - - public void addToWorld() - { - if( this.inWorld ) - { - return; - } - - this.inWorld = true; - IS_LOADING.set( true ); - - final TileEntity te = this.getTile(); - - // start with the center, then install the side parts into the grid. - for( int x = 6; x >= 0; x-- ) - { - final AEPartLocation s = AEPartLocation.fromOrdinal( x ); - final IPart part = this.getPart( s ); - - if( part != null ) - { - part.setPartHostInfo( s, this, te ); - part.addToWorld(); - - if( s != AEPartLocation.INTERNAL ) - { - final IGridNode sn = part.getGridNode(); - if( sn != null ) - { - // this is a really stupid if statement, why was this - // here? - // if ( !sn.getConnections().iterator().hasNext() ) - - final IPart center = this.getPart( AEPartLocation.INTERNAL ); - if( center != null ) - { - final IGridNode cn = center.getGridNode(); - if( cn != null ) - { - try - { - AEApi.instance().grid().createGridConnection( cn, sn ); - } - catch( final FailedConnectionException e ) - { - // ekk - AELog.debug( e ); - } - } - } - } - } - } - } - - this.partChanged(); - - IS_LOADING.set( false ); - } - - public void removeFromWorld() - { - if( !this.inWorld ) - { - return; - } - - this.inWorld = false; - - for( final AEPartLocation s : AEPartLocation.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - part.removeFromWorld(); - } - } - - this.partChanged(); - } - - @Override - public IGridNode getGridNode( final AEPartLocation side ) - { - final IPart part = this.getPart( side ); - if( part != null ) - { - final IGridNode n = part.getExternalFacingNode(); - if( n != null ) - { - return n; - } - } - - if( this.getCenter() != null ) - { - return this.getCenter().getGridNode(); - } - - return null; - } - - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IGridHost ) - { - final AECableType t = ( (IGridHost) part ).getCableConnectionType( dir ); - if( t != null && t != AECableType.NONE ) - { - return t; - } - } - - if( this.getCenter() != null ) - { - final IPartCable c = this.getCenter(); - return c.getCableConnectionType(); - } - return AECableType.NONE; - } - - @Override - public float getCableConnectionLength( AECableType cable ) - { - return this.getPart( AEPartLocation.INTERNAL ) instanceof IPartCable ? this.getPart( AEPartLocation.INTERNAL ).getCableConnectionLength( cable ) : -1; - } - - @Override - public void securityBreak() - { - for( final AEPartLocation d : AEPartLocation.values() ) - { - final IPart p = this.getPart( d ); - if( p instanceof IGridHost ) - { - ( (IGridHost) p ).securityBreak(); - } - } - } - - public Iterable getSelectedBoundingBoxesFromPool( final boolean ignoreConnections, final boolean includeFacades, final Entity e, final boolean visual ) - { - final List boxes = new ArrayList<>(); - - final IFacadeContainer fc = this.getFacadeContainer(); - for( final AEPartLocation s : AEPartLocation.values() ) - { - final IPartCollisionHelper bch = new BusCollisionHelper( boxes, s, e, visual ); - - final IPart part = this.getPart( s ); - if( part != null ) - { - if( ignoreConnections && part instanceof IPartCable ) - { - bch.addBox( 6.0, 6.0, 6.0, 10.0, 10.0, 10.0 ); - } - else - { - part.getBoxes( bch ); - } - } - - if( AEApi.instance().partHelper().getCableRenderMode().opaqueFacades || !visual ) - { - if( includeFacades && s != null && s != AEPartLocation.INTERNAL ) - { - final IFacadePart fp = fc.getFacade( s ); - if( fp != null ) - { - fp.getBoxes( bch, e ); - } - } - } - } - - return boxes; - } - - @Override - public int isProvidingStrongPower( final EnumFacing side ) - { - final IPart part = this.getPart( side ); - return part != null ? part.isProvidingStrongPower() : 0; - } - - @Override - public int isProvidingWeakPower( final EnumFacing side ) - { - final IPart part = this.getPart( side ); - return part != null ? part.isProvidingWeakPower() : 0; - } - - @Override - public boolean canConnectRedstone( final EnumSet enumSet ) - { - for( final EnumFacing dir : enumSet ) - { - final IPart part = this.getPart( dir ); - if( part != null && part.canConnectRedstone() ) - { - return true; - } - } - return false; - } - - @Override - public void onEntityCollision( final Entity entity ) - { - for( final AEPartLocation s : AEPartLocation.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - part.onEntityCollision( entity ); - } - } - } - - @Override - public boolean activate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - final SelectedPart p = this.selectPart( pos ); - if( p != null && p.part != null ) - { - // forge sends activate even when sneaking in some cases (eg emtpy hand) - // if sneaking try shift activate first. - if( player.isSneaking() && p.part.onShiftActivate( player, hand, pos ) ) - { - return true; - } - return p.part.onActivate( player, hand, pos ); - } - return false; - } - - @Override - public boolean clicked( EntityPlayer player, EnumHand hand, Vec3d hitVec ) - { - final SelectedPart p = this.selectPart( hitVec ); - if( p != null && p.part != null ) - { - if( player.isSneaking() ) - { - return p.part.onShiftClicked( player, hand, hitVec ); - } - else - { - return p.part.onClicked( player, hand, hitVec ); - } - } - return false; - } - - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - this.hasRedstone = YesNo.UNDECIDED; - - for( final AEPartLocation s : AEPartLocation.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - part.onNeighborChanged( w, pos, neighbor ); - } - } - } - - @Override - public boolean isSolidOnSide( final EnumFacing side ) - { - if( side == null ) - { - return false; - } - - // facades are solid.. - final IFacadePart fp = this.getFacadeContainer().getFacade( AEPartLocation.fromFacing( side ) ); - if( fp != null ) - { - return true; - } - - // buses can be too. - final IPart part = this.getPart( side ); - return part != null && part.isSolid(); - } - - @Override - public boolean isLadder( final EntityLivingBase entity ) - { - for( final AEPartLocation side : AEPartLocation.values() ) - { - final IPart p = this.getPart( side ); - if( p != null ) - { - if( p.isLadder( entity ) ) - { - return true; - } - } - } - - return false; - } - - @Override - public void randomDisplayTick( final World world, final BlockPos pos, final Random r ) - { - for( final AEPartLocation side : AEPartLocation.values() ) - { - final IPart p = this.getPart( side ); - if( p != null ) - { - p.randomDisplayTick( world, pos, r ); - } - } - } - - @Override - public int getLightValue() - { - int light = 0; - - for( final AEPartLocation d : AEPartLocation.values() ) - { - final IPart p = this.getPart( d ); - if( p != null ) - { - light = Math.max( p.getLightLevel(), light ); - } - } - - return light; - } - - public void writeToStream( final ByteBuf data ) throws IOException - { - int sides = 0; - for( int x = 0; x < 7; x++ ) - { - final IPart p = this.getPart( AEPartLocation.fromOrdinal( x ) ); - if( p != null ) - { - sides |= ( 1 << x ); - } - } - - data.writeByte( (byte) sides ); - - for( int x = 0; x < 7; x++ ) - { - final IPart p = this.getPart( AEPartLocation.fromOrdinal( x ) ); - if( p != null ) - { - final ItemStack is = p.getItemStack( PartItemStack.NETWORK ); - - data.writeShort( Item.getIdFromItem( is.getItem() ) ); - data.writeShort( is.getItemDamage() ); - - p.writeToStream( data ); - } - } - - this.getFacadeContainer().writeToStream( data ); - } - - public boolean readFromStream( final ByteBuf data ) throws IOException - { - final byte sides = data.readByte(); - - boolean updateBlock = false; - - for( int x = 0; x < 7; x++ ) - { - AEPartLocation side = AEPartLocation.fromOrdinal( x ); - if( ( ( sides & ( 1 << x ) ) == ( 1 << x ) ) ) - { - IPart p = this.getPart( side ); - - final short itemID = data.readShort(); - final short dmgValue = data.readShort(); - - final Item myItem = Item.getItemById( itemID ); - - final ItemStack current = p != null ? p.getItemStack( PartItemStack.NETWORK ) : null; - if( current != null && current.getItem() == myItem && current.getItemDamage() == dmgValue ) - { - if( p.readFromStream( data ) ) - { - updateBlock = true; - } - } - else - { - this.removePart( side, false ); - side = this.addPart( new ItemStack( myItem, 1, dmgValue ), side, null, null ); - if( side != null ) - { - p = this.getPart( side ); - p.readFromStream( data ); - } - else - { - throw new IllegalStateException( "Invalid Stream For CableBus Container." ); - } - } - } - else if( this.getPart( side ) != null ) - { - this.removePart( side, false ); - } - } - - if( this.getFacadeContainer().readFromStream( data ) ) - { - return true; - } - - return updateBlock; - } - - public void writeToNBT( final NBTTagCompound data ) - { - data.setInteger( "hasRedstone", this.hasRedstone.ordinal() ); - - final IFacadeContainer fc = this.getFacadeContainer(); - for( final AEPartLocation s : AEPartLocation.values() ) - { - fc.writeToNBT( data ); - - final IPart part = this.getPart( s ); - if( part != null ) - { - final NBTTagCompound def = new NBTTagCompound(); - part.getItemStack( PartItemStack.WORLD ).writeToNBT( def ); - - final NBTTagCompound extra = new NBTTagCompound(); - part.writeToNBT( extra ); - - data.setTag( "def:" + this.getSide( part ).ordinal(), def ); - data.setTag( "extra:" + this.getSide( part ).ordinal(), extra ); - } - } - } - - private AEPartLocation getSide( final IPart part ) - { - if( this.getCenter() == part ) - { - return AEPartLocation.INTERNAL; - } - else - { - for( final AEPartLocation side : AEPartLocation.SIDE_LOCATIONS ) - { - if( this.getSide( side ) == part ) - { - return side; - } - } - } - - throw new IllegalStateException( "Uhh Bad Part (" + part + ") on Side." ); - } - - public void readFromNBT( final NBTTagCompound data ) - { - if( data.hasKey( "hasRedstone" ) ) - { - this.hasRedstone = YesNo.values()[data.getInteger( "hasRedstone" )]; - } - - for( int x = 0; x < 7; x++ ) - { - AEPartLocation side = AEPartLocation.fromOrdinal( x ); - - final NBTTagCompound def = data.getCompoundTag( "def:" + side.ordinal() ); - final NBTTagCompound extra = data.getCompoundTag( "extra:" + side.ordinal() ); - if( def != null && extra != null ) - { - IPart p = this.getPart( side ); - final ItemStack iss = new ItemStack( def ); - if( iss.isEmpty() ) - { - continue; - } - - final ItemStack current = p == null ? ItemStack.EMPTY : p.getItemStack( PartItemStack.WORLD ); - - if( Platform.itemComparisons().isEqualItemType( iss, current ) ) - { - p.readFromNBT( extra ); - } - else - { - this.removePart( side, true ); - side = this.addPart( iss, side, null, null ); - if( side != null ) - { - p = this.getPart( side ); - p.readFromNBT( extra ); - } - else - { - AELog.warn( "Invalid NBT For CableBus Container: " + iss.getItem().getClass().getName() + " is not a valid part; it was ignored." ); - } - } - } - else - { - this.removePart( side, false ); - } - } - - this.getFacadeContainer().readFromNBT( data ); - } - - public List getDrops( final List drops ) - { - for( final AEPartLocation s : AEPartLocation.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - drops.add( part.getItemStack( PartItemStack.BREAK ) ); - part.getDrops( drops, false ); - } - - if( s != AEPartLocation.INTERNAL ) - { - final IFacadePart fp = this.getFacadeContainer().getFacade( s ); - if( fp != null ) - { - drops.add( fp.getItemStack() ); - } - } - } - - return drops; - } - - public List getNoDrops( final List drops ) - { - for( final AEPartLocation s : AEPartLocation.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - part.getDrops( drops, false ); - } - } - - return drops; - } - - @Override - public boolean recolourBlock( final EnumFacing side, final AEColor colour, final EntityPlayer who ) - { - final IPart cable = this.getPart( AEPartLocation.INTERNAL ); - if( cable != null ) - { - final IPartCable pc = (IPartCable) cable; - return pc.changeColor( colour, who ); - } - return false; - } - - public boolean isRequiresDynamicRender() - { - return this.requiresDynamicRender; - } - - private void setRequiresDynamicRender( final boolean requiresDynamicRender ) - { - this.requiresDynamicRender = requiresDynamicRender; - } - - @Override - public CableBusRenderState getRenderState() - { - final PartCable cable = (PartCable) this.getCenter(); - - final CableBusRenderState renderState = new CableBusRenderState(); - - if( cable != null ) - { - renderState.setCableColor( cable.getCableColor() ); - renderState.setCableType( cable.getCableConnectionType() ); - renderState.setCoreType( CableCoreType.fromCableType( cable.getCableConnectionType() ) ); - - // Check each outgoing connection for the desired characteristics - for( EnumFacing facing : EnumFacing.values() ) - { - // Is there a connection? - if( !cable.isConnected( facing ) ) - { - continue; - } - - // If there is one, check out which type it has, but default to this cable's type - AECableType connectionType = cable.getCableConnectionType(); - - // Only use the incoming cable-type of the adjacent block, if it's not a cable bus itself - // Dense cables however also respect the adjacent cable-type since their outgoing connection - // point would look too big for other cable types - final BlockPos adjacentPos = this.getTile().getPos().offset( facing ); - final TileEntity adjacentTe = this.getTile().getWorld().getTileEntity( adjacentPos ); - - if( adjacentTe instanceof IGridHost ) - { - final IGridHost gridHost = (IGridHost) adjacentTe; - final AECableType adjacentType = gridHost.getCableConnectionType( AEPartLocation.fromFacing( facing.getOpposite() ) ); - - connectionType = AECableType.min( connectionType, adjacentType ); - } - - // Check if the adjacent TE is a cable bus or not - if( adjacentTe instanceof IPartHost ) - { - renderState.getCableBusAdjacent().add( facing ); - } - - renderState.getConnectionTypes().put( facing, connectionType ); - } - - // Collect the number of channels used per side - // We have to do this even for non-smart cables since a glass cable can display a connection as smart if the - // adjacent tile requires it - for( EnumFacing facing : EnumFacing.values() ) - { - int channels = cable.getCableConnectionType().isSmart() ? cable.getChannelsOnSide( facing ) : 0; - renderState.getChannelsOnSide().put( facing, channels ); - } - } - - // Determine attachments and facades - for( EnumFacing facing : EnumFacing.values() ) - { - final FacadeRenderState facadeState = this.getFacadeRenderState( facing ); - - if( facadeState != null ) - { - renderState.getFacades().put( facing, facadeState ); - } - - final IPart part = this.getPart( facing ); - - if( part == null ) - { - continue; - } - - renderState.getPartFlags().put( facing, part.getRenderFlag() ); - - // This will add the part's bounding boxes to the render state, which is required for facades - final AEPartLocation loc = AEPartLocation.fromFacing( facing ); - final IPartCollisionHelper bch = new BusCollisionHelper( renderState.getBoundingBoxes(), loc, null, true ); - - part.getBoxes( bch ); - - if( part instanceof IGridHost ) - { - // Some attachments want a thicker cable than glass, account for that - final IGridHost gridHost = (IGridHost) part; - final AECableType desiredType = gridHost.getCableConnectionType( AEPartLocation.INTERNAL ); - - if( renderState.getCoreType() == CableCoreType.GLASS && ( desiredType == AECableType.SMART || desiredType == AECableType.COVERED ) ) - { - renderState.setCoreType( CableCoreType.COVERED ); - } - - int length = (int) part.getCableConnectionLength( null ); - if( length > 0 && length <= 8 ) - { - renderState.getAttachmentConnections().put( facing, length ); - } - } - - renderState.getAttachments().put( facing, part.getStaticModels() ); - } - - return renderState; - } - - private FacadeRenderState getFacadeRenderState( EnumFacing side ) - { - // Store the "masqueraded" itemstack for the given side, if there is a facade - final IFacadePart facade = this.getFacade( side.ordinal() ); - - if( facade != null ) - { - final ItemStack textureItem = facade.getTextureItem(); - final IBlockState blockState = facade.getBlockState(); - - if( blockState != null && textureItem != null ) - { - return new FacadeRenderState( blockState, !facade.getBlockState().isOpaqueCube() ); - } - } - - return null; - } +import javax.annotation.Nullable; +import java.io.IOException; +import java.util.*; + + +public class CableBusContainer extends CableBusStorage implements AEMultiTile, ICableBusContainer { + + private static final ThreadLocal IS_LOADING = new ThreadLocal<>(); + private final EnumSet myLayerFlags = EnumSet.noneOf(LayerFlags.class); + private YesNo hasRedstone = YesNo.UNDECIDED; + private IPartHost tcb; + // TODO 1.10.2-R - does somebody seriously want to make parts TESR??? Hope not. + private boolean requiresDynamicRender = false; + private boolean inWorld = false; + + public CableBusContainer(final IPartHost host) { + this.tcb = host; + } + + public static boolean isLoading() { + final Boolean is = IS_LOADING.get(); + return is != null && is; + } + + public void setHost(final IPartHost host) { + this.tcb.clearContainer(); + this.tcb = host; + } + + public void rotateLeft() { + final IPart[] newSides = new IPart[6]; + + newSides[AEPartLocation.UP.ordinal()] = this.getSide(AEPartLocation.UP); + newSides[AEPartLocation.DOWN.ordinal()] = this.getSide(AEPartLocation.DOWN); + + newSides[AEPartLocation.EAST.ordinal()] = this.getSide(AEPartLocation.NORTH); + newSides[AEPartLocation.SOUTH.ordinal()] = this.getSide(AEPartLocation.EAST); + newSides[AEPartLocation.WEST.ordinal()] = this.getSide(AEPartLocation.SOUTH); + newSides[AEPartLocation.NORTH.ordinal()] = this.getSide(AEPartLocation.WEST); + + for (final AEPartLocation dir : AEPartLocation.SIDE_LOCATIONS) { + this.setSide(dir, newSides[dir.ordinal()]); + } + + this.getFacadeContainer().rotateLeft(); + } + + @Override + public IFacadeContainer getFacadeContainer() { + return new FacadeContainer(this); + } + + @Override + public boolean canAddPart(ItemStack is, final AEPartLocation side) { + if (PartPlacement.isFacade(is, side) != null) { + return true; + } + + if (is.getItem() instanceof IPartItem) { + final IPartItem bi = (IPartItem) is.getItem(); + + is = is.copy(); + is.setCount(1); + + final IPart bp = bi.createPartFromItemStack(is); + if (bp != null) { + if (bp instanceof IPartCable) { + boolean canPlace = true; + for (final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS) { + if (this.getPart(d) != null && !this.getPart(d).canBePlacedOn(((IPartCable) bp).supportsBuses())) { + canPlace = false; + } + } + + if (!canPlace) { + return false; + } + + return this.getPart(AEPartLocation.INTERNAL) == null; + } else if (!(bp instanceof IPartCable) && side != AEPartLocation.INTERNAL) { + final IPart cable = this.getPart(AEPartLocation.INTERNAL); + if (cable != null && !bp.canBePlacedOn(((IPartCable) cable).supportsBuses())) { + return false; + } + + return this.getPart(side) == null; + } + } + } + return false; + } + + @Override + public AEPartLocation addPart(ItemStack is, final AEPartLocation side, final @Nullable EntityPlayer player, final @Nullable EnumHand hand) { + if (this.canAddPart(is, side)) { + if (is.getItem() instanceof IPartItem) { + final IPartItem bi = (IPartItem) is.getItem(); + + is = is.copy(); + is.setCount(1); + + final IPart bp = bi.createPartFromItemStack(is); + if (bp instanceof IPartCable) { + boolean canPlace = true; + for (final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS) { + if (this.getPart(d) != null && !this.getPart(d).canBePlacedOn(((IPartCable) bp).supportsBuses())) { + canPlace = false; + } + } + + if (!canPlace) { + return null; + } + + if (this.getPart(AEPartLocation.INTERNAL) != null) { + return null; + } + + this.setCenter((IPartCable) bp); + bp.setPartHostInfo(AEPartLocation.INTERNAL, this, this.tcb.getTile()); + + if (player != null) { + bp.onPlacement(player, hand, is, side); + } + + if (this.inWorld) { + bp.addToWorld(); + } + + final IGridNode cn = this.getCenter().getGridNode(); + if (cn != null) { + for (final AEPartLocation ins : AEPartLocation.SIDE_LOCATIONS) { + final IPart sbp = this.getPart(ins); + if (sbp != null) { + final IGridNode sn = sbp.getGridNode(); + if (sn != null) { + try { + GridConnection.create(cn, sn, AEPartLocation.INTERNAL); + } catch (final FailedConnectionException e) { + AELog.debug(e); + + bp.removeFromWorld(); + this.setCenter(null); + return null; + } + } + } + } + } + + this.updateConnections(); + this.markForUpdate(); + this.markForSave(); + this.partChanged(); + return AEPartLocation.INTERNAL; + } else if (bp != null && !(bp instanceof IPartCable) && side != AEPartLocation.INTERNAL) { + final IPart cable = this.getPart(AEPartLocation.INTERNAL); + if (cable != null && !bp.canBePlacedOn(((IPartCable) cable).supportsBuses())) { + return null; + } + + this.setSide(side, bp); + bp.setPartHostInfo(side, this, this.getTile()); + + if (player != null) { + bp.onPlacement(player, hand, is, side); + } + + if (this.inWorld) { + bp.addToWorld(); + } + + if (this.getCenter() != null) { + final IGridNode cn = this.getCenter().getGridNode(); + final IGridNode sn = bp.getGridNode(); + + if (cn != null && sn != null) { + try { + GridConnection.create(cn, sn, AEPartLocation.INTERNAL); + } catch (final FailedConnectionException e) { + AELog.debug(e); + + bp.removeFromWorld(); + this.setSide(side, null); + return null; + } + } + } + + this.updateDynamicRender(); + this.updateConnections(); + this.markForUpdate(); + this.markForSave(); + this.partChanged(); + return side; + } + } + } + return null; + } + + @Override + public IPart getPart(final AEPartLocation partLocation) { + if (partLocation == AEPartLocation.INTERNAL) { + return this.getCenter(); + } + return this.getSide(partLocation); + } + + @Override + public IPart getPart(final EnumFacing side) { + return this.getSide(AEPartLocation.fromFacing(side)); + } + + @Override + public void removePart(final AEPartLocation side, final boolean suppressUpdate) { + if (side == AEPartLocation.INTERNAL) { + if (this.getCenter() != null) { + this.getCenter().removeFromWorld(); + } + this.setCenter(null); + } else { + if (this.getSide(side) != null) { + this.getSide(side).removeFromWorld(); + } + this.setSide(side, null); + } + + if (!suppressUpdate) { + this.updateDynamicRender(); + this.updateConnections(); + this.markForUpdate(); + this.markForSave(); + this.partChanged(); + } + } + + @Override + public void markForUpdate() { + this.tcb.markForUpdate(); + } + + @Override + public DimensionalCoord getLocation() { + return this.tcb.getLocation(); + } + + @Override + public TileEntity getTile() { + return this.tcb.getTile(); + } + + @Override + public AEColor getColor() { + if (this.getCenter() != null) { + final IPartCable c = this.getCenter(); + return c.getCableColor(); + } + return AEColor.TRANSPARENT; + } + + @Override + public void clearContainer() { + throw new UnsupportedOperationException("Now that is silly!"); + } + + @Override + public boolean isBlocked(final EnumFacing side) { + return this.tcb.isBlocked(side); + } + + @Override + public SelectedPart selectPart(final Vec3d pos) { + for (final AEPartLocation side : AEPartLocation.values()) { + final IPart p = this.getPart(side); + if (p != null) { + final List boxes = new ArrayList<>(); + + final IPartCollisionHelper bch = new BusCollisionHelper(boxes, side, null, true); + p.getBoxes(bch); + for (AxisAlignedBB bb : boxes) { + bb = bb.grow(0.002, 0.002, 0.002); + if (bb.contains(pos)) { + return new SelectedPart(p, side); + } + } + } + } + + if (AEApi.instance().partHelper().getCableRenderMode().opaqueFacades) { + final IFacadeContainer fc = this.getFacadeContainer(); + for (final AEPartLocation side : AEPartLocation.SIDE_LOCATIONS) { + final IFacadePart p = fc.getFacade(side); + if (p != null) { + final List boxes = new ArrayList<>(); + + final IPartCollisionHelper bch = new BusCollisionHelper(boxes, side, null, true); + p.getBoxes(bch, null); + for (AxisAlignedBB bb : boxes) { + bb = bb.grow(0.01, 0.01, 0.01); + if (bb.contains(pos)) { + return new SelectedPart(p, side); + } + } + } + } + } + + return new SelectedPart(); + } + + @Override + public void markForSave() { + this.tcb.markForSave(); + } + + @Override + public void partChanged() { + if (this.getCenter() == null) { + final List facades = new ArrayList<>(); + + final IFacadeContainer fc = this.getFacadeContainer(); + for (final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS) { + final IFacadePart fp = fc.getFacade(d); + if (fp != null) { + facades.add(fp.getItemStack()); + fc.removeFacade(this.tcb, d); + } + } + + if (!facades.isEmpty()) { + final TileEntity te = this.tcb.getTile(); + Platform.spawnDrops(te.getWorld(), te.getPos(), facades); + } + } + + this.tcb.partChanged(); + } + + @Override + public boolean hasRedstone(final AEPartLocation side) { + if (this.hasRedstone == YesNo.UNDECIDED) { + this.updateRedstone(); + } + + return this.hasRedstone == YesNo.YES; + } + + @Override + public boolean isEmpty() { + final IFacadeContainer fc = this.getFacadeContainer(); + for (final AEPartLocation s : AEPartLocation.values()) { + final IPart part = this.getPart(s); + if (part != null) { + return false; + } + + if (s != AEPartLocation.INTERNAL) { + final IFacadePart fp = fc.getFacade(s); + if (fp != null) { + return false; + } + } + } + return true; + } + + @Override + public Set getLayerFlags() { + return this.myLayerFlags; + } + + @Override + public void cleanup() { + this.tcb.cleanup(); + } + + @Override + public void notifyNeighbors() { + this.tcb.notifyNeighbors(); + } + + @Override + public boolean isInWorld() { + return this.inWorld; + } + + private void updateRedstone() { + final TileEntity te = this.getTile(); + this.hasRedstone = te.getWorld().isBlockIndirectlyGettingPowered(te.getPos()) != 0 ? YesNo.YES : YesNo.NO; + } + + private void updateDynamicRender() { + this.requiresDynamicRender = false; + for (final AEPartLocation s : AEPartLocation.SIDE_LOCATIONS) { + final IPart p = this.getPart(s); + if (p != null) { + this.setRequiresDynamicRender(this.isRequiresDynamicRender() || p.requireDynamicRender()); + } + } + } + + /** + * use for FMP + */ + public void updateConnections() { + if (this.getCenter() != null) { + final EnumSet sides = EnumSet.allOf(EnumFacing.class); + + for (final EnumFacing s : EnumFacing.VALUES) { + if (this.getPart(s) != null || this.isBlocked(s)) { + sides.remove(s); + } + } + + this.getCenter().setValidSides(sides); + final IGridNode n = this.getCenter().getGridNode(); + if (n != null) { + n.updateState(); + } + } + } + + public void addToWorld() { + if (this.inWorld) { + return; + } + + this.inWorld = true; + IS_LOADING.set(true); + + final TileEntity te = this.getTile(); + + // start with the center, then install the side parts into the grid. + for (int x = 6; x >= 0; x--) { + final AEPartLocation s = AEPartLocation.fromOrdinal(x); + final IPart part = this.getPart(s); + + if (part != null) { + part.setPartHostInfo(s, this, te); + part.addToWorld(); + + if (s != AEPartLocation.INTERNAL) { + final IGridNode sn = part.getGridNode(); + if (sn != null) { + // this is a really stupid if statement, why was this + // here? + // if ( !sn.getConnections().iterator().hasNext() ) + + final IPart center = this.getPart(AEPartLocation.INTERNAL); + if (center != null) { + final IGridNode cn = center.getGridNode(); + if (cn != null) { + try { + AEApi.instance().grid().createGridConnection(cn, sn); + } catch (final FailedConnectionException e) { + // ekk + AELog.debug(e); + } + } + } + } + } + } + } + + this.partChanged(); + + IS_LOADING.set(false); + } + + public void removeFromWorld() { + if (!this.inWorld) { + return; + } + + this.inWorld = false; + + for (final AEPartLocation s : AEPartLocation.values()) { + final IPart part = this.getPart(s); + if (part != null) { + part.removeFromWorld(); + } + } + + this.partChanged(); + } + + @Override + public IGridNode getGridNode(final AEPartLocation side) { + final IPart part = this.getPart(side); + if (part != null) { + final IGridNode n = part.getExternalFacingNode(); + if (n != null) { + return n; + } + } + + if (this.getCenter() != null) { + return this.getCenter().getGridNode(); + } + + return null; + } + + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + final IPart part = this.getPart(dir); + if (part instanceof IGridHost) { + final AECableType t = ((IGridHost) part).getCableConnectionType(dir); + if (t != null && t != AECableType.NONE) { + return t; + } + } + + if (this.getCenter() != null) { + final IPartCable c = this.getCenter(); + return c.getCableConnectionType(); + } + return AECableType.NONE; + } + + @Override + public float getCableConnectionLength(AECableType cable) { + return this.getPart(AEPartLocation.INTERNAL) instanceof IPartCable ? this.getPart(AEPartLocation.INTERNAL).getCableConnectionLength(cable) : -1; + } + + @Override + public void securityBreak() { + for (final AEPartLocation d : AEPartLocation.values()) { + final IPart p = this.getPart(d); + if (p instanceof IGridHost) { + ((IGridHost) p).securityBreak(); + } + } + } + + public Iterable getSelectedBoundingBoxesFromPool(final boolean ignoreConnections, final boolean includeFacades, final Entity e, final boolean visual) { + final List boxes = new ArrayList<>(); + + final IFacadeContainer fc = this.getFacadeContainer(); + for (final AEPartLocation s : AEPartLocation.values()) { + final IPartCollisionHelper bch = new BusCollisionHelper(boxes, s, e, visual); + + final IPart part = this.getPart(s); + if (part != null) { + if (ignoreConnections && part instanceof IPartCable) { + bch.addBox(6.0, 6.0, 6.0, 10.0, 10.0, 10.0); + } else { + part.getBoxes(bch); + } + } + + if (AEApi.instance().partHelper().getCableRenderMode().opaqueFacades || !visual) { + if (includeFacades && s != null && s != AEPartLocation.INTERNAL) { + final IFacadePart fp = fc.getFacade(s); + if (fp != null) { + fp.getBoxes(bch, e); + } + } + } + } + + return boxes; + } + + @Override + public int isProvidingStrongPower(final EnumFacing side) { + final IPart part = this.getPart(side); + return part != null ? part.isProvidingStrongPower() : 0; + } + + @Override + public int isProvidingWeakPower(final EnumFacing side) { + final IPart part = this.getPart(side); + return part != null ? part.isProvidingWeakPower() : 0; + } + + @Override + public boolean canConnectRedstone(final EnumSet enumSet) { + for (final EnumFacing dir : enumSet) { + final IPart part = this.getPart(dir); + if (part != null && part.canConnectRedstone()) { + return true; + } + } + return false; + } + + @Override + public void onEntityCollision(final Entity entity) { + for (final AEPartLocation s : AEPartLocation.values()) { + final IPart part = this.getPart(s); + if (part != null) { + part.onEntityCollision(entity); + } + } + } + + @Override + public boolean activate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + final SelectedPart p = this.selectPart(pos); + if (p != null && p.part != null) { + // forge sends activate even when sneaking in some cases (eg emtpy hand) + // if sneaking try shift activate first. + if (player.isSneaking() && p.part.onShiftActivate(player, hand, pos)) { + return true; + } + return p.part.onActivate(player, hand, pos); + } + return false; + } + + @Override + public boolean clicked(EntityPlayer player, EnumHand hand, Vec3d hitVec) { + final SelectedPart p = this.selectPart(hitVec); + if (p != null && p.part != null) { + if (player.isSneaking()) { + return p.part.onShiftClicked(player, hand, hitVec); + } else { + return p.part.onClicked(player, hand, hitVec); + } + } + return false; + } + + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + this.hasRedstone = YesNo.UNDECIDED; + + for (final AEPartLocation s : AEPartLocation.values()) { + final IPart part = this.getPart(s); + if (part != null) { + part.onNeighborChanged(w, pos, neighbor); + } + } + } + + @Override + public boolean isSolidOnSide(final EnumFacing side) { + if (side == null) { + return false; + } + + // facades are solid.. + final IFacadePart fp = this.getFacadeContainer().getFacade(AEPartLocation.fromFacing(side)); + if (fp != null) { + return true; + } + + // buses can be too. + final IPart part = this.getPart(side); + return part != null && part.isSolid(); + } + + @Override + public boolean isLadder(final EntityLivingBase entity) { + for (final AEPartLocation side : AEPartLocation.values()) { + final IPart p = this.getPart(side); + if (p != null) { + if (p.isLadder(entity)) { + return true; + } + } + } + + return false; + } + + @Override + public void randomDisplayTick(final World world, final BlockPos pos, final Random r) { + for (final AEPartLocation side : AEPartLocation.values()) { + final IPart p = this.getPart(side); + if (p != null) { + p.randomDisplayTick(world, pos, r); + } + } + } + + @Override + public int getLightValue() { + int light = 0; + + for (final AEPartLocation d : AEPartLocation.values()) { + final IPart p = this.getPart(d); + if (p != null) { + light = Math.max(p.getLightLevel(), light); + } + } + + return light; + } + + public void writeToStream(final ByteBuf data) throws IOException { + int sides = 0; + for (int x = 0; x < 7; x++) { + final IPart p = this.getPart(AEPartLocation.fromOrdinal(x)); + if (p != null) { + sides |= (1 << x); + } + } + + data.writeByte((byte) sides); + + for (int x = 0; x < 7; x++) { + final IPart p = this.getPart(AEPartLocation.fromOrdinal(x)); + if (p != null) { + final ItemStack is = p.getItemStack(PartItemStack.NETWORK); + + data.writeShort(Item.getIdFromItem(is.getItem())); + data.writeShort(is.getItemDamage()); + + p.writeToStream(data); + } + } + + this.getFacadeContainer().writeToStream(data); + } + + public boolean readFromStream(final ByteBuf data) throws IOException { + final byte sides = data.readByte(); + + boolean updateBlock = false; + + for (int x = 0; x < 7; x++) { + AEPartLocation side = AEPartLocation.fromOrdinal(x); + if (((sides & (1 << x)) == (1 << x))) { + IPart p = this.getPart(side); + + final short itemID = data.readShort(); + final short dmgValue = data.readShort(); + + final Item myItem = Item.getItemById(itemID); + + final ItemStack current = p != null ? p.getItemStack(PartItemStack.NETWORK) : null; + if (current != null && current.getItem() == myItem && current.getItemDamage() == dmgValue) { + if (p.readFromStream(data)) { + updateBlock = true; + } + } else { + this.removePart(side, false); + side = this.addPart(new ItemStack(myItem, 1, dmgValue), side, null, null); + if (side != null) { + p = this.getPart(side); + p.readFromStream(data); + } else { + throw new IllegalStateException("Invalid Stream For CableBus Container."); + } + } + } else if (this.getPart(side) != null) { + this.removePart(side, false); + } + } + + if (this.getFacadeContainer().readFromStream(data)) { + return true; + } + + return updateBlock; + } + + public void writeToNBT(final NBTTagCompound data) { + data.setInteger("hasRedstone", this.hasRedstone.ordinal()); + + final IFacadeContainer fc = this.getFacadeContainer(); + for (final AEPartLocation s : AEPartLocation.values()) { + fc.writeToNBT(data); + + final IPart part = this.getPart(s); + if (part != null) { + final NBTTagCompound def = new NBTTagCompound(); + part.getItemStack(PartItemStack.WORLD).writeToNBT(def); + + final NBTTagCompound extra = new NBTTagCompound(); + part.writeToNBT(extra); + + data.setTag("def:" + this.getSide(part).ordinal(), def); + data.setTag("extra:" + this.getSide(part).ordinal(), extra); + } + } + } + + private AEPartLocation getSide(final IPart part) { + if (this.getCenter() == part) { + return AEPartLocation.INTERNAL; + } else { + for (final AEPartLocation side : AEPartLocation.SIDE_LOCATIONS) { + if (this.getSide(side) == part) { + return side; + } + } + } + + throw new IllegalStateException("Uhh Bad Part (" + part + ") on Side."); + } + + public void readFromNBT(final NBTTagCompound data) { + if (data.hasKey("hasRedstone")) { + this.hasRedstone = YesNo.values()[data.getInteger("hasRedstone")]; + } + + for (int x = 0; x < 7; x++) { + AEPartLocation side = AEPartLocation.fromOrdinal(x); + + final NBTTagCompound def = data.getCompoundTag("def:" + side.ordinal()); + final NBTTagCompound extra = data.getCompoundTag("extra:" + side.ordinal()); + if (def != null && extra != null) { + IPart p = this.getPart(side); + final ItemStack iss = new ItemStack(def); + if (iss.isEmpty()) { + continue; + } + + final ItemStack current = p == null ? ItemStack.EMPTY : p.getItemStack(PartItemStack.WORLD); + + if (Platform.itemComparisons().isEqualItemType(iss, current)) { + p.readFromNBT(extra); + } else { + this.removePart(side, true); + side = this.addPart(iss, side, null, null); + if (side != null) { + p = this.getPart(side); + p.readFromNBT(extra); + } else { + AELog.warn("Invalid NBT For CableBus Container: " + iss.getItem().getClass().getName() + " is not a valid part; it was ignored."); + } + } + } else { + this.removePart(side, false); + } + } + + this.getFacadeContainer().readFromNBT(data); + } + + public List getDrops(final List drops) { + for (final AEPartLocation s : AEPartLocation.values()) { + final IPart part = this.getPart(s); + if (part != null) { + drops.add(part.getItemStack(PartItemStack.BREAK)); + part.getDrops(drops, false); + } + + if (s != AEPartLocation.INTERNAL) { + final IFacadePart fp = this.getFacadeContainer().getFacade(s); + if (fp != null) { + drops.add(fp.getItemStack()); + } + } + } + + return drops; + } + + public List getNoDrops(final List drops) { + for (final AEPartLocation s : AEPartLocation.values()) { + final IPart part = this.getPart(s); + if (part != null) { + part.getDrops(drops, false); + } + } + + return drops; + } + + @Override + public boolean recolourBlock(final EnumFacing side, final AEColor colour, final EntityPlayer who) { + final IPart cable = this.getPart(AEPartLocation.INTERNAL); + if (cable != null) { + final IPartCable pc = (IPartCable) cable; + return pc.changeColor(colour, who); + } + return false; + } + + public boolean isRequiresDynamicRender() { + return this.requiresDynamicRender; + } + + private void setRequiresDynamicRender(final boolean requiresDynamicRender) { + this.requiresDynamicRender = requiresDynamicRender; + } + + @Override + public CableBusRenderState getRenderState() { + final PartCable cable = (PartCable) this.getCenter(); + + final CableBusRenderState renderState = new CableBusRenderState(); + + if (cable != null) { + renderState.setCableColor(cable.getCableColor()); + renderState.setCableType(cable.getCableConnectionType()); + renderState.setCoreType(CableCoreType.fromCableType(cable.getCableConnectionType())); + + // Check each outgoing connection for the desired characteristics + for (EnumFacing facing : EnumFacing.values()) { + // Is there a connection? + if (!cable.isConnected(facing)) { + continue; + } + + // If there is one, check out which type it has, but default to this cable's type + AECableType connectionType = cable.getCableConnectionType(); + + // Only use the incoming cable-type of the adjacent block, if it's not a cable bus itself + // Dense cables however also respect the adjacent cable-type since their outgoing connection + // point would look too big for other cable types + final BlockPos adjacentPos = this.getTile().getPos().offset(facing); + final TileEntity adjacentTe = this.getTile().getWorld().getTileEntity(adjacentPos); + + if (adjacentTe instanceof IGridHost) { + final IGridHost gridHost = (IGridHost) adjacentTe; + final AECableType adjacentType = gridHost.getCableConnectionType(AEPartLocation.fromFacing(facing.getOpposite())); + + connectionType = AECableType.min(connectionType, adjacentType); + } + + // Check if the adjacent TE is a cable bus or not + if (adjacentTe instanceof IPartHost) { + renderState.getCableBusAdjacent().add(facing); + } + + renderState.getConnectionTypes().put(facing, connectionType); + } + + // Collect the number of channels used per side + // We have to do this even for non-smart cables since a glass cable can display a connection as smart if the + // adjacent tile requires it + for (EnumFacing facing : EnumFacing.values()) { + int channels = cable.getCableConnectionType().isSmart() ? cable.getChannelsOnSide(facing) : 0; + renderState.getChannelsOnSide().put(facing, channels); + } + } + + // Determine attachments and facades + for (EnumFacing facing : EnumFacing.values()) { + final FacadeRenderState facadeState = this.getFacadeRenderState(facing); + + if (facadeState != null) { + renderState.getFacades().put(facing, facadeState); + } + + final IPart part = this.getPart(facing); + + if (part == null) { + continue; + } + + renderState.getPartFlags().put(facing, part.getRenderFlag()); + + // This will add the part's bounding boxes to the render state, which is required for facades + final AEPartLocation loc = AEPartLocation.fromFacing(facing); + final IPartCollisionHelper bch = new BusCollisionHelper(renderState.getBoundingBoxes(), loc, null, true); + + part.getBoxes(bch); + + if (part instanceof IGridHost) { + // Some attachments want a thicker cable than glass, account for that + final IGridHost gridHost = (IGridHost) part; + final AECableType desiredType = gridHost.getCableConnectionType(AEPartLocation.INTERNAL); + + if (renderState.getCoreType() == CableCoreType.GLASS && (desiredType == AECableType.SMART || desiredType == AECableType.COVERED)) { + renderState.setCoreType(CableCoreType.COVERED); + } + + int length = (int) part.getCableConnectionLength(null); + if (length > 0 && length <= 8) { + renderState.getAttachmentConnections().put(facing, length); + } + } + + renderState.getAttachments().put(facing, part.getStaticModels()); + } + + return renderState; + } + + private FacadeRenderState getFacadeRenderState(EnumFacing side) { + // Store the "masqueraded" itemstack for the given side, if there is a facade + final IFacadePart facade = this.getFacade(side.ordinal()); + + if (facade != null) { + final ItemStack textureItem = facade.getTextureItem(); + final IBlockState blockState = facade.getBlockState(); + + if (blockState != null && textureItem != null) { + return new FacadeRenderState(blockState, !facade.getBlockState().isOpaqueCube()); + } + } + + return null; + } } diff --git a/src/main/java/appeng/parts/CableBusStorage.java b/src/main/java/appeng/parts/CableBusStorage.java index ef1f7f7bd..49a2df6a2 100644 --- a/src/main/java/appeng/parts/CableBusStorage.java +++ b/src/main/java/appeng/parts/CableBusStorage.java @@ -19,128 +19,105 @@ package appeng.parts; -import javax.annotation.Nullable; - import appeng.api.implementations.parts.IPartCable; import appeng.api.parts.IFacadePart; import appeng.api.parts.IPart; import appeng.api.util.AEPartLocation; +import javax.annotation.Nullable; + /** * Thin data storage to optimize memory usage for cables. */ -public class CableBusStorage -{ +public class CableBusStorage { - private IPartCable center; - private IPart[] sides; - private IFacadePart[] facades; + private IPartCable center; + private IPart[] sides; + private IFacadePart[] facades; - protected IPartCable getCenter() - { - return this.center; - } + protected IPartCable getCenter() { + return this.center; + } - protected void setCenter( final IPartCable center ) - { - this.center = center; - } + protected void setCenter(final IPartCable center) { + this.center = center; + } - protected IPart getSide( final AEPartLocation side ) - { - final int x = side.ordinal(); - if( this.sides != null && this.sides.length > x ) - { - return this.sides[x]; - } + protected IPart getSide(final AEPartLocation side) { + final int x = side.ordinal(); + if (this.sides != null && this.sides.length > x) { + return this.sides[x]; + } - return null; - } + return null; + } - protected void setSide( final AEPartLocation side, final IPart part ) - { - final int x = side.ordinal(); + protected void setSide(final AEPartLocation side, final IPart part) { + final int x = side.ordinal(); - if( this.sides != null && this.sides.length > x && part == null ) - { - this.sides[x] = null; - this.sides = this.shrink( this.sides, true ); - } - else if( part != null ) - { - this.sides = this.grow( this.sides, x, true ); - this.sides[x] = part; - } - } + if (this.sides != null && this.sides.length > x && part == null) { + this.sides[x] = null; + this.sides = this.shrink(this.sides, true); + } else if (part != null) { + this.sides = this.grow(this.sides, x, true); + this.sides[x] = part; + } + } - private T[] shrink( final T[] in, final boolean parts ) - { - int newSize = -1; - for( int x = 0; x < in.length; x++ ) - { - if( in[x] != null ) - { - newSize = x; - } - } + private T[] shrink(final T[] in, final boolean parts) { + int newSize = -1; + for (int x = 0; x < in.length; x++) { + if (in[x] != null) { + newSize = x; + } + } - if( newSize == -1 ) - { - return null; - } + if (newSize == -1) { + return null; + } - newSize++; - if( newSize == in.length ) - { - return in; - } + newSize++; + if (newSize == in.length) { + return in; + } - final T[] newArray = (T[]) ( parts ? new IPart[newSize] : new IFacadePart[newSize] ); - System.arraycopy( in, 0, newArray, 0, newSize ); + final T[] newArray = (T[]) (parts ? new IPart[newSize] : new IFacadePart[newSize]); + System.arraycopy(in, 0, newArray, 0, newSize); - return newArray; - } + return newArray; + } - private T[] grow( final T[] in, final int newValue, final boolean parts ) - { - if( in != null && in.length > newValue ) - { - return in; - } + private T[] grow(final T[] in, final int newValue, final boolean parts) { + if (in != null && in.length > newValue) { + return in; + } - final int newSize = newValue + 1; + final int newSize = newValue + 1; - final T[] newArray = (T[]) ( parts ? new IPart[newSize] : new IFacadePart[newSize] ); - if( in != null ) - { - System.arraycopy( in, 0, newArray, 0, in.length ); - } + final T[] newArray = (T[]) (parts ? new IPart[newSize] : new IFacadePart[newSize]); + if (in != null) { + System.arraycopy(in, 0, newArray, 0, in.length); + } - return newArray; - } + return newArray; + } - public IFacadePart getFacade( final int x ) - { - if( this.facades != null && this.facades.length > x ) - { - return this.facades[x]; - } + public IFacadePart getFacade(final int x) { + if (this.facades != null && this.facades.length > x) { + return this.facades[x]; + } - return null; - } + return null; + } - public void setFacade( final int x, @Nullable final IFacadePart facade ) - { - if( this.facades != null && this.facades.length > x && facade == null ) - { - this.facades[x] = null; - this.facades = this.shrink( this.facades, false ); - } - else - { - this.facades = this.grow( this.facades, x, false ); - this.facades[x] = facade; - } - } + public void setFacade(final int x, @Nullable final IFacadePart facade) { + if (this.facades != null && this.facades.length > x && facade == null) { + this.facades[x] = null; + this.facades = this.shrink(this.facades, false); + } else { + this.facades = this.grow(this.facades, x, false); + this.facades[x] = facade; + } + } } diff --git a/src/main/java/appeng/parts/ICableBusContainer.java b/src/main/java/appeng/parts/ICableBusContainer.java index 1a399ce20..066ccc69f 100644 --- a/src/main/java/appeng/parts/ICableBusContainer.java +++ b/src/main/java/appeng/parts/ICableBusContainer.java @@ -19,9 +19,9 @@ package appeng.parts; -import java.util.EnumSet; -import java.util.Random; - +import appeng.api.parts.SelectedPart; +import appeng.api.util.AEColor; +import appeng.client.render.cablebus.CableBusRenderState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -34,43 +34,41 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.parts.SelectedPart; -import appeng.api.util.AEColor; -import appeng.client.render.cablebus.CableBusRenderState; +import java.util.EnumSet; +import java.util.Random; -public interface ICableBusContainer -{ +public interface ICableBusContainer { - int isProvidingStrongPower( EnumFacing opposite ); + int isProvidingStrongPower(EnumFacing opposite); - int isProvidingWeakPower( EnumFacing opposite ); + int isProvidingWeakPower(EnumFacing opposite); - boolean canConnectRedstone( EnumSet of ); + boolean canConnectRedstone(EnumSet of); - void onEntityCollision( Entity e ); + void onEntityCollision(Entity e); - boolean activate( EntityPlayer player, EnumHand hand, Vec3d vecFromPool ); + boolean activate(EntityPlayer player, EnumHand hand, Vec3d vecFromPool); - boolean clicked( EntityPlayer player, EnumHand hand, Vec3d hitVec ); + boolean clicked(EntityPlayer player, EnumHand hand, Vec3d hitVec); - void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ); + void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor); - boolean isSolidOnSide( EnumFacing side ); + boolean isSolidOnSide(EnumFacing side); - boolean isEmpty(); + boolean isEmpty(); - SelectedPart selectPart( Vec3d v3 ); + SelectedPart selectPart(Vec3d v3); - boolean recolourBlock( EnumFacing side, AEColor colour, EntityPlayer who ); + boolean recolourBlock(EnumFacing side, AEColor colour, EntityPlayer who); - boolean isLadder( EntityLivingBase entity ); + boolean isLadder(EntityLivingBase entity); - @SideOnly( Side.CLIENT ) - void randomDisplayTick( World world, BlockPos pos, Random r ); + @SideOnly(Side.CLIENT) + void randomDisplayTick(World world, BlockPos pos, Random r); - int getLightValue(); + int getLightValue(); - CableBusRenderState getRenderState(); + CableBusRenderState getRenderState(); } diff --git a/src/main/java/appeng/parts/NullCableBusContainer.java b/src/main/java/appeng/parts/NullCableBusContainer.java index 437736105..03e90cb61 100644 --- a/src/main/java/appeng/parts/NullCableBusContainer.java +++ b/src/main/java/appeng/parts/NullCableBusContainer.java @@ -19,9 +19,9 @@ package appeng.parts; -import java.util.EnumSet; -import java.util.Random; - +import appeng.api.parts.SelectedPart; +import appeng.api.util.AEColor; +import appeng.client.render.cablebus.CableBusRenderState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -32,102 +32,85 @@ import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import appeng.api.parts.SelectedPart; -import appeng.api.util.AEColor; -import appeng.client.render.cablebus.CableBusRenderState; +import java.util.EnumSet; +import java.util.Random; -public class NullCableBusContainer implements ICableBusContainer -{ +public class NullCableBusContainer implements ICableBusContainer { - @Override - public int isProvidingStrongPower( final EnumFacing opposite ) - { - return 0; - } + @Override + public int isProvidingStrongPower(final EnumFacing opposite) { + return 0; + } - @Override - public int isProvidingWeakPower( final EnumFacing opposite ) - { - return 0; - } + @Override + public int isProvidingWeakPower(final EnumFacing opposite) { + return 0; + } - @Override - public boolean canConnectRedstone( final EnumSet of ) - { - return false; - } + @Override + public boolean canConnectRedstone(final EnumSet of) { + return false; + } - @Override - public void onEntityCollision( final Entity e ) - { + @Override + public void onEntityCollision(final Entity e) { - } + } - @Override - public boolean activate( final EntityPlayer player, final EnumHand hand, final Vec3d vecFromPool ) - { - return false; - } + @Override + public boolean activate(final EntityPlayer player, final EnumHand hand, final Vec3d vecFromPool) { + return false; + } - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { - } + } - @Override - public boolean isSolidOnSide( final EnumFacing side ) - { - return false; - } + @Override + public boolean isSolidOnSide(final EnumFacing side) { + return false; + } - @Override - public boolean isEmpty() - { - return true; - } + @Override + public boolean isEmpty() { + return true; + } - @Override - public SelectedPart selectPart( final Vec3d v3 ) - { - return new SelectedPart(); - } + @Override + public SelectedPart selectPart(final Vec3d v3) { + return new SelectedPart(); + } - @Override - public boolean recolourBlock( final EnumFacing side, final AEColor colour, final EntityPlayer who ) - { - return false; - } + @Override + public boolean recolourBlock(final EnumFacing side, final AEColor colour, final EntityPlayer who) { + return false; + } - @Override - public boolean isLadder( final EntityLivingBase entity ) - { - return false; - } + @Override + public boolean isLadder(final EntityLivingBase entity) { + return false; + } - @Override - public void randomDisplayTick( final World world, final BlockPos pos, final Random r ) - { + @Override + public void randomDisplayTick(final World world, final BlockPos pos, final Random r) { - } + } - @Override - public int getLightValue() - { - return 0; - } + @Override + public int getLightValue() { + return 0; + } - @Override - public CableBusRenderState getRenderState() - { - return new CableBusRenderState(); - } + @Override + public CableBusRenderState getRenderState() { + return new CableBusRenderState(); + } - @Override - public boolean clicked( EntityPlayer player, EnumHand hand, Vec3d hitVec ) - { - return false; - } + @Override + public boolean clicked(EntityPlayer player, EnumHand hand, Vec3d hitVec) { + return false; + } } diff --git a/src/main/java/appeng/parts/PartBasicState.java b/src/main/java/appeng/parts/PartBasicState.java index 735008a05..ffec8764a 100644 --- a/src/main/java/appeng/parts/PartBasicState.java +++ b/src/main/java/appeng/parts/PartBasicState.java @@ -19,12 +19,6 @@ package appeng.parts; -import java.io.IOException; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.item.ItemStack; - import appeng.api.implementations.IPowerChannelState; import appeng.api.networking.GridFlags; import appeng.api.networking.events.MENetworkBootingStatusChange; @@ -32,104 +26,91 @@ import appeng.api.networking.events.MENetworkChannelsChanged; import appeng.api.networking.events.MENetworkEventSubscribe; import appeng.api.networking.events.MENetworkPowerStatusChange; import appeng.me.GridAccessException; +import io.netty.buffer.ByteBuf; +import net.minecraft.item.ItemStack; + +import java.io.IOException; -public abstract class PartBasicState extends AEBasePart implements IPowerChannelState -{ +public abstract class PartBasicState extends AEBasePart implements IPowerChannelState { - protected static final int POWERED_FLAG = 1; - protected static final int CHANNEL_FLAG = 2; + protected static final int POWERED_FLAG = 1; + protected static final int CHANNEL_FLAG = 2; - private int clientFlags = 0; // sent as byte. + private int clientFlags = 0; // sent as byte. - public PartBasicState( final ItemStack is ) - { - super( is ); - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - } + public PartBasicState(final ItemStack is) { + super(is); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + } - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - this.getHost().markForUpdate(); - } + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + this.getHost().markForUpdate(); + } - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } - @MENetworkEventSubscribe - public void bootingRender( final MENetworkBootingStatusChange bs ) - { - this.getHost().markForUpdate(); - } + @MENetworkEventSubscribe + public void bootingRender(final MENetworkBootingStatusChange bs) { + this.getHost().markForUpdate(); + } - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); + @Override + public void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); - this.setClientFlags( 0 ); + this.setClientFlags(0); - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - this.setClientFlags( this.getClientFlags() | POWERED_FLAG ); - } + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + this.setClientFlags(this.getClientFlags() | POWERED_FLAG); + } - if( this.getProxy().getNode().meetsChannelRequirements() ) - { - this.setClientFlags( this.getClientFlags() | CHANNEL_FLAG ); - } + if (this.getProxy().getNode().meetsChannelRequirements()) { + this.setClientFlags(this.getClientFlags() | CHANNEL_FLAG); + } - this.setClientFlags( this.populateFlags( this.getClientFlags() ) ); - } - catch( final GridAccessException e ) - { - // meh - } + this.setClientFlags(this.populateFlags(this.getClientFlags())); + } catch (final GridAccessException e) { + // meh + } - data.writeByte( (byte) this.getClientFlags() ); - } + data.writeByte((byte) this.getClientFlags()); + } - protected int populateFlags( final int cf ) - { - return cf; - } + protected int populateFlags(final int cf) { + return cf; + } - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean eh = super.readFromStream( data ); + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + final boolean eh = super.readFromStream(data); - final int old = this.getClientFlags(); - this.setClientFlags( data.readByte() ); + final int old = this.getClientFlags(); + this.setClientFlags(data.readByte()); - return eh || old != this.getClientFlags(); - } + return eh || old != this.getClientFlags(); + } - @Override - public boolean isPowered() - { - return ( this.getClientFlags() & POWERED_FLAG ) == POWERED_FLAG; - } + @Override + public boolean isPowered() { + return (this.getClientFlags() & POWERED_FLAG) == POWERED_FLAG; + } - @Override - public boolean isActive() - { - return ( this.getClientFlags() & CHANNEL_FLAG ) == CHANNEL_FLAG; - } + @Override + public boolean isActive() { + return (this.getClientFlags() & CHANNEL_FLAG) == CHANNEL_FLAG; + } - public int getClientFlags() - { - return this.clientFlags; - } + public int getClientFlags() { + return this.clientFlags; + } - private void setClientFlags( final int clientFlags ) - { - this.clientFlags = clientFlags; - } + private void setClientFlags(final int clientFlags) { + this.clientFlags = clientFlags; + } } diff --git a/src/main/java/appeng/parts/PartModel.java b/src/main/java/appeng/parts/PartModel.java index 727984f88..7735efae7 100644 --- a/src/main/java/appeng/parts/PartModel.java +++ b/src/main/java/appeng/parts/PartModel.java @@ -19,62 +19,51 @@ package appeng.parts; -import java.util.List; - +import appeng.api.parts.IPartModel; import com.google.common.collect.ImmutableList; - import net.minecraft.util.ResourceLocation; -import appeng.api.parts.IPartModel; +import java.util.List; -public class PartModel implements IPartModel -{ - private final boolean isSolid; +public class PartModel implements IPartModel { + private final boolean isSolid; - private final List resources; + private final List resources; - public PartModel( ResourceLocation resource ) - { - this( true, resource ); - } + public PartModel(ResourceLocation resource) { + this(true, resource); + } - public PartModel( ResourceLocation... resources ) - { - this( true, resources ); - } + public PartModel(ResourceLocation... resources) { + this(true, resources); + } - public PartModel( boolean isSolid, ResourceLocation resource ) - { - this( isSolid, ImmutableList.of( resource ) ); - } + public PartModel(boolean isSolid, ResourceLocation resource) { + this(isSolid, ImmutableList.of(resource)); + } - public PartModel( boolean isSolid, ResourceLocation... resources ) - { - this( isSolid, ImmutableList.copyOf( resources ) ); - } + public PartModel(boolean isSolid, ResourceLocation... resources) { + this(isSolid, ImmutableList.copyOf(resources)); + } - public PartModel( List resources ) - { - this( true, resources ); - } + public PartModel(List resources) { + this(true, resources); + } - public PartModel( boolean isSolid, List resources ) - { - this.isSolid = isSolid; - this.resources = resources; - } + public PartModel(boolean isSolid, List resources) { + this.isSolid = isSolid; + this.resources = resources; + } - @Override - public boolean requireCableConnection() - { - return this.isSolid; - } + @Override + public boolean requireCableConnection() { + return this.isSolid; + } - @Override - public List getModels() - { - return this.resources; - } + @Override + public List getModels() { + return this.resources; + } } diff --git a/src/main/java/appeng/parts/PartPlacement.java b/src/main/java/appeng/parts/PartPlacement.java index 3679023bc..4d7373e42 100644 --- a/src/main/java/appeng/parts/PartPlacement.java +++ b/src/main/java/appeng/parts/PartPlacement.java @@ -19,10 +19,19 @@ package appeng.parts; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - +import appeng.api.AEApi; +import appeng.api.definitions.IBlockDefinition; +import appeng.api.definitions.IItems; +import appeng.api.parts.*; +import appeng.api.util.AEPartLocation; +import appeng.api.util.DimensionalCoord; +import appeng.core.AppEng; +import appeng.core.sync.network.NetworkHandler; +import appeng.core.sync.packets.PacketClick; +import appeng.core.sync.packets.PacketPartPlacement; +import appeng.facade.IFacadeItem; +import appeng.util.LookDirection; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.state.IBlockState; @@ -45,436 +54,341 @@ import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; -import appeng.api.AEApi; -import appeng.api.definitions.IBlockDefinition; -import appeng.api.definitions.IItems; -import appeng.api.parts.IFacadePart; -import appeng.api.parts.IPartHost; -import appeng.api.parts.IPartItem; -import appeng.api.parts.PartItemStack; -import appeng.api.parts.SelectedPart; -import appeng.api.util.AEPartLocation; -import appeng.api.util.DimensionalCoord; -import appeng.core.AppEng; -import appeng.core.sync.network.NetworkHandler; -import appeng.core.sync.packets.PacketClick; -import appeng.core.sync.packets.PacketPartPlacement; -import appeng.facade.IFacadeItem; -import appeng.util.LookDirection; -import appeng.util.Platform; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; -public class PartPlacement -{ +public class PartPlacement { - private static float eyeHeight = 0.0f; - private final ThreadLocal placing = new ThreadLocal<>(); - private boolean wasCanceled = false; + private static float eyeHeight = 0.0f; + private final ThreadLocal placing = new ThreadLocal<>(); + private boolean wasCanceled = false; - public static EnumActionResult place( final ItemStack held, final BlockPos pos, EnumFacing side, final EntityPlayer player, final EnumHand hand, final World world, PlaceType pass, final int depth ) - { - if( depth > 3 ) - { - return EnumActionResult.FAIL; - } + public static EnumActionResult place(final ItemStack held, final BlockPos pos, EnumFacing side, final EntityPlayer player, final EnumHand hand, final World world, PlaceType pass, final int depth) { + if (depth > 3) { + return EnumActionResult.FAIL; + } - if( !held.isEmpty() && Platform.isWrench( player, held, pos ) && player.isSneaking() ) - { - if( !Platform.hasPermissions( new DimensionalCoord( world, pos ), player ) ) - { - return EnumActionResult.FAIL; - } + if (!held.isEmpty() && Platform.isWrench(player, held, pos) && player.isSneaking()) { + if (!Platform.hasPermissions(new DimensionalCoord(world, pos), player)) { + return EnumActionResult.FAIL; + } - final Block block = world.getBlockState( pos ).getBlock(); - final TileEntity tile = world.getTileEntity( pos ); - IPartHost host = null; + final Block block = world.getBlockState(pos).getBlock(); + final TileEntity tile = world.getTileEntity(pos); + IPartHost host = null; - if( tile instanceof IPartHost ) - { - host = (IPartHost) tile; - } + if (tile instanceof IPartHost) { + host = (IPartHost) tile; + } - if( host != null ) - { - if( !world.isRemote ) - { - final LookDirection dir = Platform.getPlayerRay( player, getEyeOffset( player ) ); - final RayTraceResult mop = block.collisionRayTrace( world.getBlockState( pos ), world, pos, dir.getA(), dir.getB() ); + if (host != null) { + if (!world.isRemote) { + final LookDirection dir = Platform.getPlayerRay(player, getEyeOffset(player)); + final RayTraceResult mop = block.collisionRayTrace(world.getBlockState(pos), world, pos, dir.getA(), dir.getB()); - if( mop != null ) - { - final List is = new ArrayList<>(); - final SelectedPart sp = selectPart( player, host, - mop.hitVec.addVector( -mop.getBlockPos().getX(), -mop.getBlockPos().getY(), -mop.getBlockPos().getZ() ) ); + if (mop != null) { + final List is = new ArrayList<>(); + final SelectedPart sp = selectPart(player, host, + mop.hitVec.addVector(-mop.getBlockPos().getX(), -mop.getBlockPos().getY(), -mop.getBlockPos().getZ())); - if( sp.part != null ) - { - is.add( sp.part.getItemStack( PartItemStack.WRENCH ) ); - sp.part.getDrops( is, true ); - host.removePart( sp.side, false ); - } + if (sp.part != null) { + is.add(sp.part.getItemStack(PartItemStack.WRENCH)); + sp.part.getDrops(is, true); + host.removePart(sp.side, false); + } - if( sp.facade != null ) - { - is.add( sp.facade.getItemStack() ); - host.getFacadeContainer().removeFacade( host, sp.side ); - Platform.notifyBlocksOfNeighbors( world, pos ); - } + if (sp.facade != null) { + is.add(sp.facade.getItemStack()); + host.getFacadeContainer().removeFacade(host, sp.side); + Platform.notifyBlocksOfNeighbors(world, pos); + } - if( host.isEmpty() ) - { - host.cleanup(); - } + if (host.isEmpty()) { + host.cleanup(); + } - if( !is.isEmpty() ) - { - Platform.spawnDrops( world, pos, is ); - } - } - } - else - { - player.swingArm( hand ); - NetworkHandler.instance().sendToServer( new PacketPartPlacement( pos, side, getEyeOffset( player ), hand ) ); - } - return EnumActionResult.SUCCESS; - } + if (!is.isEmpty()) { + Platform.spawnDrops(world, pos, is); + } + } + } else { + player.swingArm(hand); + NetworkHandler.instance().sendToServer(new PacketPartPlacement(pos, side, getEyeOffset(player), hand)); + } + return EnumActionResult.SUCCESS; + } - return EnumActionResult.PASS; - } + return EnumActionResult.PASS; + } - TileEntity tile = world.getTileEntity( pos ); - IPartHost host = null; + TileEntity tile = world.getTileEntity(pos); + IPartHost host = null; - if( tile instanceof IPartHost ) - { - host = (IPartHost) tile; - } + if (tile instanceof IPartHost) { + host = (IPartHost) tile; + } - if( !held.isEmpty() ) - { - final IFacadePart fp = isFacade( held, AEPartLocation.fromFacing( side ) ); - if( fp != null ) - { - if( host != null ) - { - if( !world.isRemote ) - { - if( host.getPart( AEPartLocation.INTERNAL ) == null ) - { - return EnumActionResult.FAIL; - } + if (!held.isEmpty()) { + final IFacadePart fp = isFacade(held, AEPartLocation.fromFacing(side)); + if (fp != null) { + if (host != null) { + if (!world.isRemote) { + if (host.getPart(AEPartLocation.INTERNAL) == null) { + return EnumActionResult.FAIL; + } - if( host.canAddPart( held, AEPartLocation.fromFacing( side ) ) ) - { - if( host.getFacadeContainer().addFacade( fp ) ) - { - host.markForSave(); - host.markForUpdate(); - if( !player.capabilities.isCreativeMode ) - { - held.grow( -1 ); - ; - if( held.getCount() == 0 ) - { - player.setHeldItem( hand, ItemStack.EMPTY ); - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( player, held, hand ) ); - } - } - return EnumActionResult.SUCCESS; - } - } - } - else - { - player.swingArm( hand ); - NetworkHandler.instance().sendToServer( new PacketPartPlacement( pos, side, getEyeOffset( player ), hand ) ); - return EnumActionResult.SUCCESS; - } - } - return EnumActionResult.FAIL; - } - } + if (host.canAddPart(held, AEPartLocation.fromFacing(side))) { + if (host.getFacadeContainer().addFacade(fp)) { + host.markForSave(); + host.markForUpdate(); + if (!player.capabilities.isCreativeMode) { + held.grow(-1); + if (held.getCount() == 0) { + player.setHeldItem(hand, ItemStack.EMPTY); + MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, held, hand)); + } + } + return EnumActionResult.SUCCESS; + } + } + } else { + player.swingArm(hand); + NetworkHandler.instance().sendToServer(new PacketPartPlacement(pos, side, getEyeOffset(player), hand)); + return EnumActionResult.SUCCESS; + } + } + return EnumActionResult.FAIL; + } + } - if( held.isEmpty() ) - { - final Block block = world.getBlockState( pos ).getBlock(); - if( host != null && player.isSneaking() && block != null ) - { - final LookDirection dir = Platform.getPlayerRay( player, getEyeOffset( player ) ); - final RayTraceResult mop = block.collisionRayTrace( world.getBlockState( pos ), world, pos, dir.getA(), dir.getB() ); + if (held.isEmpty()) { + final Block block = world.getBlockState(pos).getBlock(); + if (host != null && player.isSneaking() && block != null) { + final LookDirection dir = Platform.getPlayerRay(player, getEyeOffset(player)); + final RayTraceResult mop = block.collisionRayTrace(world.getBlockState(pos), world, pos, dir.getA(), dir.getB()); - if( mop != null ) - { - mop.hitVec = mop.hitVec.addVector( -mop.getBlockPos().getX(), -mop.getBlockPos().getY(), -mop.getBlockPos().getZ() ); - final SelectedPart sPart = selectPart( player, host, mop.hitVec ); - if( sPart != null && sPart.part != null ) - { - if( sPart.part.onShiftActivate( player, hand, mop.hitVec ) ) - { - if( world.isRemote ) - { - NetworkHandler.instance().sendToServer( new PacketPartPlacement( pos, side, getEyeOffset( player ), hand ) ); - } - return EnumActionResult.SUCCESS; - } - } - } - } - } + if (mop != null) { + mop.hitVec = mop.hitVec.addVector(-mop.getBlockPos().getX(), -mop.getBlockPos().getY(), -mop.getBlockPos().getZ()); + final SelectedPart sPart = selectPart(player, host, mop.hitVec); + if (sPart != null && sPart.part != null) { + if (sPart.part.onShiftActivate(player, hand, mop.hitVec)) { + if (world.isRemote) { + NetworkHandler.instance().sendToServer(new PacketPartPlacement(pos, side, getEyeOffset(player), hand)); + } + return EnumActionResult.SUCCESS; + } + } + } + } + } - if( held.isEmpty() || !( held.getItem() instanceof IPartItem ) ) - { - return EnumActionResult.PASS; - } + if (held.isEmpty() || !(held.getItem() instanceof IPartItem)) { + return EnumActionResult.PASS; + } - BlockPos te_pos = pos; + BlockPos te_pos = pos; - final IBlockDefinition multiPart = AEApi.instance().definitions().blocks().multiPart(); - if( host == null && pass == PlaceType.PLACE_ITEM ) - { - EnumFacing offset = null; + final IBlockDefinition multiPart = AEApi.instance().definitions().blocks().multiPart(); + if (host == null && pass == PlaceType.PLACE_ITEM) { + EnumFacing offset = null; - final Block blkID = world.getBlockState( pos ).getBlock(); - if( blkID != null && !blkID.isReplaceable( world, pos ) ) - { - offset = side; - if( Platform.isServer() ) - { - side = side.getOpposite(); - } - } + final Block blkID = world.getBlockState(pos).getBlock(); + if (blkID != null && !blkID.isReplaceable(world, pos)) { + offset = side; + if (Platform.isServer()) { + side = side.getOpposite(); + } + } - te_pos = offset == null ? pos : pos.offset( offset ); + te_pos = offset == null ? pos : pos.offset(offset); - tile = world.getTileEntity( te_pos ); - if( tile instanceof IPartHost ) - { - host = (IPartHost) tile; - } + tile = world.getTileEntity(te_pos); + if (tile instanceof IPartHost) { + host = (IPartHost) tile; + } - final Optional maybeMultiPartStack = multiPart.maybeStack( 1 ); - final Optional maybeMultiPartBlock = multiPart.maybeBlock(); - final Optional maybeMultiPartItemBlock = multiPart.maybeItemBlock(); + final Optional maybeMultiPartStack = multiPart.maybeStack(1); + final Optional maybeMultiPartBlock = multiPart.maybeBlock(); + final Optional maybeMultiPartItemBlock = multiPart.maybeItemBlock(); - final boolean hostIsNotPresent = host == null; - final boolean multiPartPresent = maybeMultiPartBlock.isPresent() && maybeMultiPartStack.isPresent() && maybeMultiPartItemBlock.isPresent(); - final boolean canMultiPartBePlaced = maybeMultiPartBlock.get().canPlaceBlockAt( world, te_pos ); + final boolean hostIsNotPresent = host == null; + final boolean multiPartPresent = maybeMultiPartBlock.isPresent() && maybeMultiPartStack.isPresent() && maybeMultiPartItemBlock.isPresent(); + final boolean canMultiPartBePlaced = maybeMultiPartBlock.get().canPlaceBlockAt(world, te_pos); - if( hostIsNotPresent && multiPartPresent && canMultiPartBePlaced && maybeMultiPartItemBlock.get() - .placeBlockAt( maybeMultiPartStack.get(), player, - world, te_pos, side, 0.5f, 0.5f, 0.5f, maybeMultiPartBlock.get().getDefaultState() ) ) - { - if( !world.isRemote ) - { - tile = world.getTileEntity( te_pos ); + if (hostIsNotPresent && multiPartPresent && canMultiPartBePlaced && maybeMultiPartItemBlock.get() + .placeBlockAt(maybeMultiPartStack.get(), player, + world, te_pos, side, 0.5f, 0.5f, 0.5f, maybeMultiPartBlock.get().getDefaultState())) { + if (!world.isRemote) { + tile = world.getTileEntity(te_pos); - if( tile instanceof IPartHost ) - { - host = (IPartHost) tile; - } + if (tile instanceof IPartHost) { + host = (IPartHost) tile; + } - pass = PlaceType.INTERACT_SECOND_PASS; - } - else - { - player.swingArm( hand ); - NetworkHandler.instance().sendToServer( new PacketPartPlacement( pos, side, getEyeOffset( player ), hand ) ); - return EnumActionResult.SUCCESS; - } - } - else if( host != null && !host.canAddPart( held, AEPartLocation.fromFacing( side ) ) ) - { - return EnumActionResult.FAIL; - } - } + pass = PlaceType.INTERACT_SECOND_PASS; + } else { + player.swingArm(hand); + NetworkHandler.instance().sendToServer(new PacketPartPlacement(pos, side, getEyeOffset(player), hand)); + return EnumActionResult.SUCCESS; + } + } else if (host != null && !host.canAddPart(held, AEPartLocation.fromFacing(side))) { + return EnumActionResult.FAIL; + } + } - if( host == null ) - { - return EnumActionResult.PASS; - } + if (host == null) { + return EnumActionResult.PASS; + } - if( !host.canAddPart( held, AEPartLocation.fromFacing( side ) ) ) - { - if( pass == PlaceType.INTERACT_FIRST_PASS || pass == PlaceType.PLACE_ITEM ) - { - te_pos = pos.offset( side ); + if (!host.canAddPart(held, AEPartLocation.fromFacing(side))) { + if (pass == PlaceType.INTERACT_FIRST_PASS || pass == PlaceType.PLACE_ITEM) { + te_pos = pos.offset(side); - final Block blkID = world.getBlockState( te_pos ).getBlock(); + final Block blkID = world.getBlockState(te_pos).getBlock(); - if( blkID == null || blkID.isReplaceable( world, te_pos ) || host != null ) - { - return place( held, te_pos, side.getOpposite(), player, hand, world, - pass == PlaceType.INTERACT_FIRST_PASS ? PlaceType.INTERACT_SECOND_PASS : PlaceType.PLACE_ITEM, depth + 1 ); - } - } - return EnumActionResult.PASS; - } + if (blkID == null || blkID.isReplaceable(world, te_pos) || host != null) { + return place(held, te_pos, side.getOpposite(), player, hand, world, + pass == PlaceType.INTERACT_FIRST_PASS ? PlaceType.INTERACT_SECOND_PASS : PlaceType.PLACE_ITEM, depth + 1); + } + } + return EnumActionResult.PASS; + } - if( !world.isRemote ) - { - final IBlockState state = world.getBlockState( pos ); - final LookDirection dir = Platform.getPlayerRay( player, getEyeOffset( player ) ); - final RayTraceResult mop = state.getBlock().collisionRayTrace( state, world, pos, dir.getA(), dir.getB() ); + if (!world.isRemote) { + final IBlockState state = world.getBlockState(pos); + final LookDirection dir = Platform.getPlayerRay(player, getEyeOffset(player)); + final RayTraceResult mop = state.getBlock().collisionRayTrace(state, world, pos, dir.getA(), dir.getB()); - if( mop != null ) - { - final SelectedPart sp = selectPart( player, host, - mop.hitVec.addVector( -mop.getBlockPos().getX(), -mop.getBlockPos().getY(), -mop.getBlockPos().getZ() ) ); + if (mop != null) { + final SelectedPart sp = selectPart(player, host, + mop.hitVec.addVector(-mop.getBlockPos().getX(), -mop.getBlockPos().getY(), -mop.getBlockPos().getZ())); - if( sp.part != null ) - { - if( !player.isSneaking() && sp.part.onActivate( player, hand, mop.hitVec ) ) - { - return EnumActionResult.FAIL; - } - } - } + if (sp.part != null) { + if (!player.isSneaking() && sp.part.onActivate(player, hand, mop.hitVec)) { + return EnumActionResult.FAIL; + } + } + } - final DimensionalCoord dc = host.getLocation(); - if( !Platform.hasPermissions( dc, player ) ) - { - return EnumActionResult.FAIL; - } + final DimensionalCoord dc = host.getLocation(); + if (!Platform.hasPermissions(dc, player)) { + return EnumActionResult.FAIL; + } - final AEPartLocation mySide = host.addPart( held, AEPartLocation.fromFacing( side ), player, hand ); - if( mySide != null ) - { - multiPart.maybeBlock().ifPresent( multiPartBlock -> - { - final SoundType ss = multiPartBlock.getSoundType( state, world, pos, player ); + final AEPartLocation mySide = host.addPart(held, AEPartLocation.fromFacing(side), player, hand); + if (mySide != null) { + multiPart.maybeBlock().ifPresent(multiPartBlock -> + { + final SoundType ss = multiPartBlock.getSoundType(state, world, pos, player); - world.playSound( null, pos, ss.getPlaceSound(), SoundCategory.BLOCKS, ( ss.getVolume() + 1.0F ) / 2.0F, ss.getPitch() * 0.8F ); - } ); + world.playSound(null, pos, ss.getPlaceSound(), SoundCategory.BLOCKS, (ss.getVolume() + 1.0F) / 2.0F, ss.getPitch() * 0.8F); + }); - if( !player.capabilities.isCreativeMode ) - { - held.grow( -1 ); - if( held.getCount() == 0 ) - { - player.setHeldItem( hand, ItemStack.EMPTY ); - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( player, held, hand ) ); - } - } - } - } - else - { - player.swingArm( hand ); - } - return EnumActionResult.SUCCESS; - } + if (!player.capabilities.isCreativeMode) { + held.grow(-1); + if (held.getCount() == 0) { + player.setHeldItem(hand, ItemStack.EMPTY); + MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, held, hand)); + } + } + } + } else { + player.swingArm(hand); + } + return EnumActionResult.SUCCESS; + } - private static float getEyeOffset( final EntityPlayer p ) - { - if( p.world.isRemote ) - { - return Platform.getEyeOffset( p ); - } + private static float getEyeOffset(final EntityPlayer p) { + if (p.world.isRemote) { + return Platform.getEyeOffset(p); + } - return getEyeHeight(); - } + return getEyeHeight(); + } - private static SelectedPart selectPart( final EntityPlayer player, final IPartHost host, final Vec3d pos ) - { - AppEng.proxy.updateRenderMode( player ); - final SelectedPart sp = host.selectPart( pos ); - AppEng.proxy.updateRenderMode( null ); + private static SelectedPart selectPart(final EntityPlayer player, final IPartHost host, final Vec3d pos) { + AppEng.proxy.updateRenderMode(player); + final SelectedPart sp = host.selectPart(pos); + AppEng.proxy.updateRenderMode(null); - return sp; - } + return sp; + } - public static IFacadePart isFacade( final ItemStack held, final AEPartLocation side ) - { - if( held.getItem() instanceof IFacadeItem ) - { - return ( (IFacadeItem) held.getItem() ).createPartFromItemStack( held, side ); - } + public static IFacadePart isFacade(final ItemStack held, final AEPartLocation side) { + if (held.getItem() instanceof IFacadeItem) { + return ((IFacadeItem) held.getItem()).createPartFromItemStack(held, side); + } - return null; - } + return null; + } - @SubscribeEvent - public void playerInteract( final TickEvent.ClientTickEvent event ) - { - this.wasCanceled = false; - } + @SubscribeEvent + public void playerInteract(final TickEvent.ClientTickEvent event) { + this.wasCanceled = false; + } - @SubscribeEvent - public void playerInteract( final PlayerInteractEvent event ) - { - // Only handle the main hand event - if( event.getHand() != EnumHand.MAIN_HAND ) - { - return; - } + @SubscribeEvent + public void playerInteract(final PlayerInteractEvent event) { + // Only handle the main hand event + if (event.getHand() != EnumHand.MAIN_HAND) { + return; + } - if( event instanceof PlayerInteractEvent.RightClickEmpty && event.getEntityPlayer().world.isRemote ) - { - // re-check to see if this event was already channeled, cause these two events are really stupid... - final RayTraceResult mop = Platform.rayTrace( event.getEntityPlayer(), true, false ); - final Minecraft mc = Minecraft.getMinecraft(); + if (event instanceof PlayerInteractEvent.RightClickEmpty && event.getEntityPlayer().world.isRemote) { + // re-check to see if this event was already channeled, cause these two events are really stupid... + final RayTraceResult mop = Platform.rayTrace(event.getEntityPlayer(), true, false); + final Minecraft mc = Minecraft.getMinecraft(); - final float f = 1.0F; - final double d0 = mc.playerController.getBlockReachDistance(); - final Vec3d vec3 = mc.getRenderViewEntity().getPositionEyes( f ); + final float f = 1.0F; + final double d0 = mc.playerController.getBlockReachDistance(); + final Vec3d vec3 = mc.getRenderViewEntity().getPositionEyes(f); - if( mop != null && mop.hitVec.distanceTo( vec3 ) < d0 ) - { - final World w = event.getEntity().world; - final TileEntity te = w.getTileEntity( mop.getBlockPos() ); - if( te instanceof IPartHost && this.wasCanceled ) - { - event.setCanceled( true ); - } - } - else - { - final ItemStack held = event.getEntityPlayer().getHeldItem( event.getHand() ); - final IItems items = AEApi.instance().definitions().items(); + if (mop != null && mop.hitVec.distanceTo(vec3) < d0) { + final World w = event.getEntity().world; + final TileEntity te = w.getTileEntity(mop.getBlockPos()); + if (te instanceof IPartHost && this.wasCanceled) { + event.setCanceled(true); + } + } else { + final ItemStack held = event.getEntityPlayer().getHeldItem(event.getHand()); + final IItems items = AEApi.instance().definitions().items(); - boolean supportedItem = items.memoryCard().isSameAs( held ); - supportedItem |= items.colorApplicator().isSameAs( held ); + boolean supportedItem = items.memoryCard().isSameAs(held); + supportedItem |= items.colorApplicator().isSameAs(held); - if( event.getEntityPlayer().isSneaking() && !held.isEmpty() && supportedItem ) - { - NetworkHandler.instance().sendToServer( new PacketClick( event.getPos(), event.getFace(), 0, 0, 0, event.getHand() ) ); - } - } - } - else if( event instanceof PlayerInteractEvent.RightClickBlock && !event.getEntityPlayer().world.isRemote ) - { - if( this.placing.get() != null ) - { - return; - } + if (event.getEntityPlayer().isSneaking() && !held.isEmpty() && supportedItem) { + NetworkHandler.instance().sendToServer(new PacketClick(event.getPos(), event.getFace(), 0, 0, 0, event.getHand())); + } + } + } else if (event instanceof PlayerInteractEvent.RightClickBlock && !event.getEntityPlayer().world.isRemote) { + if (this.placing.get() != null) { + return; + } - this.placing.set( event ); + this.placing.set(event); - final ItemStack held = event.getEntityPlayer().getHeldItem( event.getHand() ); - if( place( held, event.getPos(), event.getFace(), event.getEntityPlayer(), event.getHand(), event.getEntityPlayer().world, - PlaceType.INTERACT_FIRST_PASS, 0 ) == EnumActionResult.SUCCESS ) - { - event.setCanceled( true ); - this.wasCanceled = true; - } + final ItemStack held = event.getEntityPlayer().getHeldItem(event.getHand()); + if (place(held, event.getPos(), event.getFace(), event.getEntityPlayer(), event.getHand(), event.getEntityPlayer().world, + PlaceType.INTERACT_FIRST_PASS, 0) == EnumActionResult.SUCCESS) { + event.setCanceled(true); + this.wasCanceled = true; + } - this.placing.set( null ); - } - } + this.placing.set(null); + } + } - private static float getEyeHeight() - { - return eyeHeight; - } + private static float getEyeHeight() { + return eyeHeight; + } - public static void setEyeHeight( final float eyeHeight ) - { - PartPlacement.eyeHeight = eyeHeight; - } + public static void setEyeHeight(final float eyeHeight) { + PartPlacement.eyeHeight = eyeHeight; + } - public enum PlaceType - { - PLACE_ITEM, INTERACT_FIRST_PASS, INTERACT_SECOND_PASS - } + public enum PlaceType { + PLACE_ITEM, INTERACT_FIRST_PASS, INTERACT_SECOND_PASS + } } \ No newline at end of file diff --git a/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java b/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java index fbdd32227..c67f77686 100644 --- a/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java @@ -19,41 +19,35 @@ package appeng.parts.automation; +import appeng.api.config.Upgrades; +import appeng.util.inv.IAEAppEngInventory; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; -import appeng.api.config.Upgrades; -import appeng.util.inv.IAEAppEngInventory; +public class BlockUpgradeInventory extends UpgradeInventory { + private final Block block; -public class BlockUpgradeInventory extends UpgradeInventory -{ - private final Block block; + public BlockUpgradeInventory(final Block block, final IAEAppEngInventory parent, final int s) { + super(parent, s); + this.block = block; + } - public BlockUpgradeInventory( final Block block, final IAEAppEngInventory parent, final int s ) - { - super( parent, s ); - this.block = block; - } + @Override + public int getMaxInstalled(final Upgrades upgrades) { + int max = 0; - @Override - public int getMaxInstalled( final Upgrades upgrades ) - { - int max = 0; + for (final ItemStack is : upgrades.getSupported().keySet()) { + final Item encodedItem = is.getItem(); - for( final ItemStack is : upgrades.getSupported().keySet() ) - { - final Item encodedItem = is.getItem(); + if (encodedItem instanceof ItemBlock && Block.getBlockFromItem(encodedItem) == this.block) { + max = upgrades.getSupported().get(is); + break; + } + } - if( encodedItem instanceof ItemBlock && Block.getBlockFromItem( encodedItem ) == this.block ) - { - max = upgrades.getSupported().get( is ); - break; - } - } - - return max; - } + return max; + } } diff --git a/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java b/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java index 1f065e4d6..236cb2d87 100644 --- a/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java @@ -19,38 +19,32 @@ package appeng.parts.automation; -import net.minecraft.item.ItemStack; - import appeng.api.config.Upgrades; import appeng.api.definitions.IItemDefinition; import appeng.util.inv.IAEAppEngInventory; +import net.minecraft.item.ItemStack; -public final class DefinitionUpgradeInventory extends UpgradeInventory -{ - private final IItemDefinition definition; +public final class DefinitionUpgradeInventory extends UpgradeInventory { + private final IItemDefinition definition; - public DefinitionUpgradeInventory( final IItemDefinition definition, final IAEAppEngInventory parent, final int s ) - { - super( parent, s ); + public DefinitionUpgradeInventory(final IItemDefinition definition, final IAEAppEngInventory parent, final int s) { + super(parent, s); - this.definition = definition; - } + this.definition = definition; + } - @Override - public int getMaxInstalled( final Upgrades upgrades ) - { - int max = 0; + @Override + public int getMaxInstalled(final Upgrades upgrades) { + int max = 0; - for( final ItemStack stack : upgrades.getSupported().keySet() ) - { - if( this.definition.isSameAs( stack ) ) - { - max = upgrades.getSupported().get( stack ); - break; - } - } + for (final ItemStack stack : upgrades.getSupported().keySet()) { + if (this.definition.isSameAs(stack)) { + max = upgrades.getSupported().get(stack); + break; + } + } - return max; - } + return max; + } } diff --git a/src/main/java/appeng/parts/automation/PartAbstractFormationPlane.java b/src/main/java/appeng/parts/automation/PartAbstractFormationPlane.java index ca2429bb6..63eb3bc46 100644 --- a/src/main/java/appeng/parts/automation/PartAbstractFormationPlane.java +++ b/src/main/java/appeng/parts/automation/PartAbstractFormationPlane.java @@ -1,14 +1,6 @@ - package appeng.parts.automation; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; - import appeng.api.config.Actionable; import appeng.api.networking.security.IActionSource; import appeng.api.parts.IPart; @@ -23,243 +15,216 @@ import appeng.api.util.AECableType; import appeng.api.util.AEPartLocation; import appeng.api.util.IConfigManager; import appeng.helpers.IPriorityHost; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; -public abstract class PartAbstractFormationPlane> extends PartUpgradeable implements ICellContainer, IPriorityHost, IMEInventory -{ +public abstract class PartAbstractFormationPlane> extends PartUpgradeable implements ICellContainer, IPriorityHost, IMEInventory { - private boolean wasActive = false; - private int priority = 0; - protected boolean blocked = false; + private boolean wasActive = false; + private int priority = 0; + protected boolean blocked = false; - public PartAbstractFormationPlane( ItemStack is ) - { - super( is ); - } + public PartAbstractFormationPlane(ItemStack is) { + super(is); + } - protected abstract void updateHandler(); + protected abstract void updateHandler(); - @Override - protected int getUpgradeSlots() - { - return 5; - } + @Override + protected int getUpgradeSlots() { + return 5; + } - @Override - public void upgradesChanged() - { - this.updateHandler(); - } + @Override + public void upgradesChanged() { + this.updateHandler(); + } - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.updateHandler(); - this.getHost().markForSave(); - } + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + this.updateHandler(); + this.getHost().markForSave(); + } - public void stateChanged() - { - final boolean currentActive = this.getProxy().isActive(); - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - this.updateHandler(); - this.getHost().markForUpdate(); - } - } + public void stateChanged() { + final boolean currentActive = this.getProxy().isActive(); + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + this.updateHandler(); + this.getHost().markForUpdate(); + } + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - int minX = 1; - int minY = 1; - int maxX = 15; - int maxY = 15; + @Override + public void getBoxes(final IPartCollisionHelper bch) { + int minX = 1; + int minY = 1; + int maxX = 15; + int maxY = 15; - final IPartHost host = this.getHost(); - if( host != null ) - { - final TileEntity te = host.getTile(); + final IPartHost host = this.getHost(); + if (host != null) { + final TileEntity te = host.getTile(); - final BlockPos pos = te.getPos(); + final BlockPos pos = te.getPos(); - final EnumFacing e = bch.getWorldX(); - final EnumFacing u = bch.getWorldY(); + final EnumFacing e = bch.getWorldX(); + final EnumFacing u = bch.getWorldY(); - if( this.isTransitionPlane( te.getWorld().getTileEntity( pos.offset( e.getOpposite() ) ), this.getSide() ) ) - { - minX = 0; - } + if (this.isTransitionPlane(te.getWorld().getTileEntity(pos.offset(e.getOpposite())), this.getSide())) { + minX = 0; + } - if( this.isTransitionPlane( te.getWorld().getTileEntity( pos.offset( e ) ), this.getSide() ) ) - { - maxX = 16; - } + if (this.isTransitionPlane(te.getWorld().getTileEntity(pos.offset(e)), this.getSide())) { + maxX = 16; + } - if( this.isTransitionPlane( te.getWorld().getTileEntity( pos.offset( u.getOpposite() ) ), this.getSide() ) ) - { - minY = 0; - } + if (this.isTransitionPlane(te.getWorld().getTileEntity(pos.offset(u.getOpposite())), this.getSide())) { + minY = 0; + } - if( this.isTransitionPlane( te.getWorld().getTileEntity( pos.offset( u ) ), this.getSide() ) ) - { - maxY = 16; - } - } + if (this.isTransitionPlane(te.getWorld().getTileEntity(pos.offset(u)), this.getSide())) { + maxY = 16; + } + } - bch.addBox( 5, 5, 14, 11, 11, 15 ); - bch.addBox( minX, minY, 15, maxX, maxY, 16 ); - } + bch.addBox(5, 5, 14, 11, 11, 15); + bch.addBox(minX, minY, 15, maxX, maxY, 16); + } - public PlaneConnections getConnections() - { + public PlaneConnections getConnections() { - final EnumFacing facingRight, facingUp; - AEPartLocation location = this.getSide(); - switch( location ) - { - case UP: - facingRight = EnumFacing.EAST; - facingUp = EnumFacing.NORTH; - break; - case DOWN: - facingRight = EnumFacing.WEST; - facingUp = EnumFacing.NORTH; - break; - case NORTH: - facingRight = EnumFacing.WEST; - facingUp = EnumFacing.UP; - break; - case SOUTH: - facingRight = EnumFacing.EAST; - facingUp = EnumFacing.UP; - break; - case WEST: - facingRight = EnumFacing.SOUTH; - facingUp = EnumFacing.UP; - break; - case EAST: - facingRight = EnumFacing.NORTH; - facingUp = EnumFacing.UP; - break; - default: - case INTERNAL: - return PlaneConnections.of( false, false, false, false ); - } + final EnumFacing facingRight, facingUp; + AEPartLocation location = this.getSide(); + switch (location) { + case UP: + facingRight = EnumFacing.EAST; + facingUp = EnumFacing.NORTH; + break; + case DOWN: + facingRight = EnumFacing.WEST; + facingUp = EnumFacing.NORTH; + break; + case NORTH: + facingRight = EnumFacing.WEST; + facingUp = EnumFacing.UP; + break; + case SOUTH: + facingRight = EnumFacing.EAST; + facingUp = EnumFacing.UP; + break; + case WEST: + facingRight = EnumFacing.SOUTH; + facingUp = EnumFacing.UP; + break; + case EAST: + facingRight = EnumFacing.NORTH; + facingUp = EnumFacing.UP; + break; + default: + case INTERNAL: + return PlaneConnections.of(false, false, false, false); + } - boolean left = false, right = false, down = false, up = false; + boolean left = false, right = false, down = false, up = false; - final IPartHost host = this.getHost(); - if( host != null ) - { - final TileEntity te = host.getTile(); + final IPartHost host = this.getHost(); + if (host != null) { + final TileEntity te = host.getTile(); - final BlockPos pos = te.getPos(); + final BlockPos pos = te.getPos(); - if( this.isTransitionPlane( te.getWorld().getTileEntity( pos.offset( facingRight.getOpposite() ) ), this.getSide() ) ) - { - left = true; - } + if (this.isTransitionPlane(te.getWorld().getTileEntity(pos.offset(facingRight.getOpposite())), this.getSide())) { + left = true; + } - if( this.isTransitionPlane( te.getWorld().getTileEntity( pos.offset( facingRight ) ), this.getSide() ) ) - { - right = true; - } + if (this.isTransitionPlane(te.getWorld().getTileEntity(pos.offset(facingRight)), this.getSide())) { + right = true; + } - if( this.isTransitionPlane( te.getWorld().getTileEntity( pos.offset( facingUp.getOpposite() ) ), this.getSide() ) ) - { - down = true; - } + if (this.isTransitionPlane(te.getWorld().getTileEntity(pos.offset(facingUp.getOpposite())), this.getSide())) { + down = true; + } - if( this.isTransitionPlane( te.getWorld().getTileEntity( pos.offset( facingUp ) ), this.getSide() ) ) - { - up = true; - } - } + if (this.isTransitionPlane(te.getWorld().getTileEntity(pos.offset(facingUp)), this.getSide())) { + up = true; + } + } - return PlaneConnections.of( up, right, down, left ); - } + return PlaneConnections.of(up, right, down, left); + } - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - if( pos.offset( this.getSide().getFacing() ).equals( neighbor ) ) - { - final TileEntity te = this.getHost().getTile(); - final AEPartLocation side = this.getSide(); + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + if (pos.offset(this.getSide().getFacing()).equals(neighbor)) { + final TileEntity te = this.getHost().getTile(); + final AEPartLocation side = this.getSide(); - final BlockPos tePos = te.getPos().offset( side.getFacing() ); + final BlockPos tePos = te.getPos().offset(side.getFacing()); - this.blocked = !w.getBlockState( tePos ).getBlock().isReplaceable( w, tePos ); - } - } + this.blocked = !w.getBlockState(tePos).getBlock().isReplaceable(w, tePos); + } + } - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 1; - } + @Override + public float getCableConnectionLength(AECableType cable) { + return 1; + } - protected boolean isTransitionPlane( final TileEntity blockTileEntity, final AEPartLocation side ) - { - if( blockTileEntity instanceof IPartHost ) - { - final IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); - return p != null && this.getClass() == p.getClass(); - } - return false; - } + protected boolean isTransitionPlane(final TileEntity blockTileEntity, final AEPartLocation side) { + if (blockTileEntity instanceof IPartHost) { + final IPart p = ((IPartHost) blockTileEntity).getPart(side); + return p != null && this.getClass() == p.getClass(); + } + return false; + } - @Override - public T extractItems( final T request, final Actionable mode, final IActionSource src ) - { - return null; - } + @Override + public T extractItems(final T request, final Actionable mode, final IActionSource src) { + return null; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return out; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return out; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.priority = data.getInteger( "priority" ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.priority = data.getInteger("priority"); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setInteger( "priority", this.getPriority() ); - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setInteger("priority", this.getPriority()); + } - @Override - public int getPriority() - { - return this.priority; - } + @Override + public int getPriority() { + return this.priority; + } - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - this.getHost().markForSave(); - this.updateHandler(); - } + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + this.getHost().markForSave(); + this.updateHandler(); + } - @Override - public void blinkCell( final int slot ) - { - // :P - } + @Override + public void blinkCell(final int slot) { + // :P + } - @Override - public void saveChanges( final ICellInventory cell ) - { - // nope! - } + @Override + public void saveChanges(final ICellInventory cell) { + // nope! + } } diff --git a/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java b/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java index c582f36d0..48daee9fc 100644 --- a/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java +++ b/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java @@ -19,24 +19,6 @@ package appeng.parts.automation; -import java.util.List; - -import com.google.common.collect.Lists; - -import net.minecraft.block.material.Material; -import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.Entity; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; -import net.minecraft.world.WorldServer; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -69,515 +51,451 @@ import appeng.parts.PartBasicState; import appeng.util.IWorldCallable; import appeng.util.Platform; import appeng.util.item.AEItemStack; - - -public class PartAnnihilationPlane extends PartBasicState implements IGridTickable, IWorldCallable -{ - - private static final PlaneModels MODELS = new PlaneModels( "part/annihilation_plane_", "part/annihilation_plane_on_" ); - - @PartModels - public static List getModels() - { - return MODELS.getModels(); - } - - private final IActionSource mySrc = new MachineSource( this ); - private boolean isAccepting = true; - private boolean breaking = false; - - public PartAnnihilationPlane( final ItemStack is ) - { - super( is ); - } - - @Override - public TickRateModulation call( final World world ) throws Exception - { - this.breaking = false; - return this.breakBlock( true ); - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - int minX = 1; - int minY = 1; - int maxX = 15; - int maxY = 15; - - final IPartHost host = this.getHost(); - if( host != null ) - { - final TileEntity te = host.getTile(); - - final BlockPos pos = te.getPos(); - - final EnumFacing e = bch.getWorldX(); - final EnumFacing u = bch.getWorldY(); - - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( e.getOpposite() ) ), this.getSide() ) ) - { - minX = 0; - } - - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( e ) ), this.getSide() ) ) - { - maxX = 16; - } - - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( u.getOpposite() ) ), this.getSide() ) ) - { - minY = 0; - } - - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( e ) ), this.getSide() ) ) - { - maxY = 16; - } - } - - bch.addBox( 5, 5, 14, 11, 11, 15 ); - // The smaller collision hitbox here is needed to allow for the entity collision event - bch.addBox( minX, minY, 15, maxX, maxY, bch.isBBCollision() ? 15 : 16 ); - } - - /** - * @return An object describing which adjacent planes this plane connects to visually. - */ - public PlaneConnections getConnections() - { - - final EnumFacing facingRight, facingUp; - AEPartLocation location = this.getSide(); - switch( location ) - { - case UP: - facingRight = EnumFacing.EAST; - facingUp = EnumFacing.NORTH; - break; - case DOWN: - facingRight = EnumFacing.WEST; - facingUp = EnumFacing.NORTH; - break; - case NORTH: - facingRight = EnumFacing.WEST; - facingUp = EnumFacing.UP; - break; - case SOUTH: - facingRight = EnumFacing.EAST; - facingUp = EnumFacing.UP; - break; - case WEST: - facingRight = EnumFacing.SOUTH; - facingUp = EnumFacing.UP; - break; - case EAST: - facingRight = EnumFacing.NORTH; - facingUp = EnumFacing.UP; - break; - default: - case INTERNAL: - return PlaneConnections.of( false, false, false, false ); - } - - boolean left = false, right = false, down = false, up = false; - - final IPartHost host = this.getHost(); - if( host != null ) - { - final TileEntity te = host.getTile(); - - final BlockPos pos = te.getPos(); - - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( facingRight.getOpposite() ) ), this.getSide() ) ) - { - left = true; - } - - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( facingRight ) ), this.getSide() ) ) - { - right = true; - } - - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( facingUp.getOpposite() ) ), this.getSide() ) ) - { - down = true; - } - - if( this.isAnnihilationPlane( te.getWorld().getTileEntity( pos.offset( facingUp ) ), this.getSide() ) ) - { - up = true; - } - } - - return PlaneConnections.of( up, right, down, left ); - } - - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - if( pos.offset( this.getSide().getFacing() ).equals( neighbor ) ) - { - this.refresh(); - } - } - - @Override - public void onEntityCollision( final Entity entity ) - { - if( this.isAccepting && entity instanceof EntityItem && !entity.isDead && Platform.isServer() && this.getProxy().isActive() ) - { - boolean capture = false; - final BlockPos pos = this.getTile().getPos(); - - // This is the middle point of the entities BB, which is better suited for comparisons that don't rely on it - // "touching" the plane - double posYMiddle = ( entity.getEntityBoundingBox().minY + entity.getEntityBoundingBox().maxY ) / 2.0D; - - switch( this.getSide() ) - { - case DOWN: - case UP: - if( entity.posX > pos.getX() && entity.posX < pos.getX() + 1 ) - { - if( entity.posZ > pos.getZ() && entity.posZ < pos.getZ() + 1 ) - { - if( ( entity.posY > pos.getY() + 0.9 && this.getSide() == AEPartLocation.UP ) || ( entity.posY < pos.getY() + 0.1 && this - .getSide() == AEPartLocation.DOWN ) ) - { - capture = true; - } - } - } - break; - case SOUTH: - case NORTH: - if( entity.posX > pos.getX() && entity.posX < pos.getX() + 1 ) - { - if( posYMiddle > pos.getY() && posYMiddle < pos.getY() + 1 ) - { - if( ( entity.posZ > pos.getZ() + 0.9 && this.getSide() == AEPartLocation.SOUTH ) || ( entity.posZ < pos.getZ() + 0.1 && this - .getSide() == AEPartLocation.NORTH ) ) - { - capture = true; - } - } - } - break; - case EAST: - case WEST: - if( entity.posZ > pos.getZ() && entity.posZ < pos.getZ() + 1 ) - { - if( posYMiddle > pos.getY() && posYMiddle < pos.getY() + 1 ) - { - if( ( entity.posX > pos.getX() + 0.9 && this.getSide() == AEPartLocation.EAST ) || ( entity.posX < pos.getX() + 0.1 && this - .getSide() == AEPartLocation.WEST ) ) - { - capture = true; - } - } - } - break; - default: - // umm? - break; - } - - if( capture ) - { - final boolean changed = this.storeEntityItem( (EntityItem) entity ); - - if( changed ) - { - AppEng.proxy.sendToAllNearExcept( null, pos.getX(), pos.getY(), pos.getZ(), 64, this.getTile().getWorld(), - new PacketTransitionEffect( entity.posX, entity.posY, entity.posZ, this.getSide(), false ) ); - } - } - } - } - - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 1; - } - - /** - * Stores an {@link EntityItem} inside the network and either marks it as dead or sets it to the leftover stackSize. - * - * @param entityItem {@link EntityItem} to store - */ - private boolean storeEntityItem( final EntityItem entityItem ) - { - if( !entityItem.isDead ) - { - final IAEItemStack overflow = this.storeItemStack( entityItem.getItem() ); - - return this.handleOverflow( entityItem, overflow ); - } - - return false; - } - - /** - * Stores an {@link ItemStack} inside the network. - * - * @param item {@link ItemStack} to store - * - * @return the leftover items, which could not be stored inside the network - */ - private IAEItemStack storeItemStack( final ItemStack item ) - { - final IAEItemStack itemToStore = AEItemStack.fromItemStack( item ); - try - { - final IStorageGrid storage = this.getProxy().getStorage(); - final IEnergyGrid energy = this.getProxy().getEnergy(); - final IAEItemStack overflow = Platform.poweredInsert( energy, - storage.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ), itemToStore, this.mySrc ); - - this.isAccepting = overflow == null; - - return overflow; - } - catch( final GridAccessException e1 ) - { - // :P - } - - return null; - } - - /** - * Handles a possible overflow or none at all. - * It will update the entity to match the leftover stack size as well as mark it as dead without any leftover - * amount. - * - * @param entityItem the entity to update or destroy - * @param overflow the leftover {@link IAEItemStack} - * - * @return true, if the entity was changed otherwise false. - */ - private boolean handleOverflow( final EntityItem entityItem, final IAEItemStack overflow ) - { - if( overflow == null || overflow.getStackSize() == 0 ) - { - entityItem.setDead(); - return true; - } - - final int oldStackSize = entityItem.getItem().getCount(); - final int newStackSize = (int) overflow.getStackSize(); - final boolean changed = oldStackSize != newStackSize; - - entityItem.getItem().setCount( newStackSize ); - - return changed; - } - - protected boolean isAnnihilationPlane( final TileEntity blockTileEntity, final AEPartLocation side ) - { - if( blockTileEntity instanceof IPartHost ) - { - final IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); - return p != null && p.getClass() == this.getClass(); - } - return false; - } - - @Override - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - this.refresh(); - this.getHost().markForUpdate(); - } - - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.refresh(); - this.getHost().markForUpdate(); - } - - private TickRateModulation breakBlock( final boolean modulate ) - { - if( this.isAccepting && this.getProxy().isActive() ) - { - try - { - final TileEntity te = this.getTile(); - final WorldServer w = (WorldServer) te.getWorld(); - - final BlockPos pos = te.getPos().offset( this.getSide().getFacing() ); - final IEnergyGrid energy = this.getProxy().getEnergy(); - - if( this.canHandleBlock( w, pos ) ) - { - final List items = this.obtainBlockDrops( w, pos ); - final float requiredPower = this.calculateEnergyUsage( w, pos, items ); - - final boolean hasPower = energy.extractAEPower( requiredPower, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > requiredPower - 0.1; - final boolean canStore = this.canStoreItemStacks( items ); - - if( hasPower && canStore ) - { - if( modulate ) - { - energy.extractAEPower( requiredPower, Actionable.MODULATE, PowerMultiplier.CONFIG ); - this.breakBlockAndStoreItems( w, pos ); - AppEng.proxy.sendToAllNearExcept( null, pos.getX(), pos.getY(), pos.getZ(), 64, w, - new PacketTransitionEffect( pos.getX(), pos.getY(), pos.getZ(), this.getSide(), true ) ); - } - else - { - this.breaking = true; - TickHandler.INSTANCE.addCallable( this.getTile().getWorld(), this ); - } - return TickRateModulation.URGENT; - } - } - } - catch( final GridAccessException e1 ) - { - // :P - } - } - - // nothing to do here :) - return TickRateModulation.IDLE; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.AnnihilationPlane.getMin(), TickRates.AnnihilationPlane.getMax(), false, true ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( this.breaking ) - { - return TickRateModulation.URGENT; - } - - this.isAccepting = true; - return this.breakBlock( false ); - } - - /** - * Checks if this plane can handle the block at the specific coordinates. - */ - private boolean canHandleBlock( final WorldServer w, final BlockPos pos ) - { - final IBlockState state = w.getBlockState( pos ); - final Material material = state.getMaterial(); - final float hardness = state.getBlockHardness( w, pos ); - final boolean ignoreMaterials = material == Material.AIR || material == Material.LAVA || material == Material.WATER || material.isLiquid(); - final boolean ignoreBlocks = state.getBlock() == Blocks.BEDROCK || state.getBlock() == Blocks.END_PORTAL || state - .getBlock() == Blocks.END_PORTAL_FRAME || state.getBlock() == Blocks.COMMAND_BLOCK; - - return !ignoreMaterials && !ignoreBlocks && hardness >= 0f && !w.isAirBlock( pos ) && w.isBlockLoaded( pos ) && w.canMineBlockBody( - Platform.getPlayer( w ), - pos ); - } - - protected List obtainBlockDrops( final WorldServer w, final BlockPos pos ) - { - final ItemStack[] out = Platform.getBlockDrops( w, pos ); - return Lists.newArrayList( out ); - } - - /** - * Checks if this plane can handle the block at the specific coordinates. - */ - protected float calculateEnergyUsage( final WorldServer w, final BlockPos pos, final List items ) - { - final IBlockState state = w.getBlockState( pos ); - final float hardness = state.getBlockHardness( w, pos ); - - float requiredEnergy = 1 + hardness; - for( final ItemStack is : items ) - { - requiredEnergy += is.getCount(); - } - - return requiredEnergy; - } - - /** - * Checks if the network can store the possible drops. - * - * It also sets isAccepting to false, if the item can not be stored. - * - * @param itemStacks an array of {@link ItemStack} to test - * - * @return true, if the network can store at least a single item of all drops or no drops are reported - */ - private boolean canStoreItemStacks( final List itemStacks ) - { - boolean canStore = itemStacks.isEmpty(); - - try - { - final IStorageGrid storage = this.getProxy().getStorage(); - - for( final ItemStack itemStack : itemStacks ) - { - final IAEItemStack itemToTest = AEItemStack.fromItemStack( itemStack ); - final IAEItemStack overflow = storage.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - .injectItems( itemToTest, Actionable.SIMULATE, this.mySrc ); - if( overflow == null || itemToTest.getStackSize() > overflow.getStackSize() ) - { - canStore = true; - } - } - } - catch( final GridAccessException e ) - { - // :P - } - - this.isAccepting = canStore; - return canStore; - } - - private void breakBlockAndStoreItems( final WorldServer w, final BlockPos pos ) - { - w.destroyBlock( pos, true ); - - final AxisAlignedBB box = new AxisAlignedBB( pos ).grow( 0.2 ); - for( final Object ei : w.getEntitiesWithinAABB( EntityItem.class, box ) ) - { - if( ei instanceof EntityItem ) - { - final EntityItem entityItem = (EntityItem) ei; - this.storeEntityItem( entityItem ); - } - } - } - - private void refresh() - { - this.isAccepting = true; - - try - { - this.getProxy().getTick().alertDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - public IPartModel getStaticModels() - { - return MODELS.getModel( this.getConnections(), this.isPowered(), this.isActive() ); - } +import com.google.common.collect.Lists; +import net.minecraft.block.material.Material; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.Entity; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraft.world.WorldServer; + +import java.util.List; + + +public class PartAnnihilationPlane extends PartBasicState implements IGridTickable, IWorldCallable { + + private static final PlaneModels MODELS = new PlaneModels("part/annihilation_plane_", "part/annihilation_plane_on_"); + + @PartModels + public static List getModels() { + return MODELS.getModels(); + } + + private final IActionSource mySrc = new MachineSource(this); + private boolean isAccepting = true; + private boolean breaking = false; + + public PartAnnihilationPlane(final ItemStack is) { + super(is); + } + + @Override + public TickRateModulation call(final World world) throws Exception { + this.breaking = false; + return this.breakBlock(true); + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + int minX = 1; + int minY = 1; + int maxX = 15; + int maxY = 15; + + final IPartHost host = this.getHost(); + if (host != null) { + final TileEntity te = host.getTile(); + + final BlockPos pos = te.getPos(); + + final EnumFacing e = bch.getWorldX(); + final EnumFacing u = bch.getWorldY(); + + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(e.getOpposite())), this.getSide())) { + minX = 0; + } + + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(e)), this.getSide())) { + maxX = 16; + } + + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(u.getOpposite())), this.getSide())) { + minY = 0; + } + + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(e)), this.getSide())) { + maxY = 16; + } + } + + bch.addBox(5, 5, 14, 11, 11, 15); + // The smaller collision hitbox here is needed to allow for the entity collision event + bch.addBox(minX, minY, 15, maxX, maxY, bch.isBBCollision() ? 15 : 16); + } + + /** + * @return An object describing which adjacent planes this plane connects to visually. + */ + public PlaneConnections getConnections() { + + final EnumFacing facingRight, facingUp; + AEPartLocation location = this.getSide(); + switch (location) { + case UP: + facingRight = EnumFacing.EAST; + facingUp = EnumFacing.NORTH; + break; + case DOWN: + facingRight = EnumFacing.WEST; + facingUp = EnumFacing.NORTH; + break; + case NORTH: + facingRight = EnumFacing.WEST; + facingUp = EnumFacing.UP; + break; + case SOUTH: + facingRight = EnumFacing.EAST; + facingUp = EnumFacing.UP; + break; + case WEST: + facingRight = EnumFacing.SOUTH; + facingUp = EnumFacing.UP; + break; + case EAST: + facingRight = EnumFacing.NORTH; + facingUp = EnumFacing.UP; + break; + default: + case INTERNAL: + return PlaneConnections.of(false, false, false, false); + } + + boolean left = false, right = false, down = false, up = false; + + final IPartHost host = this.getHost(); + if (host != null) { + final TileEntity te = host.getTile(); + + final BlockPos pos = te.getPos(); + + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(facingRight.getOpposite())), this.getSide())) { + left = true; + } + + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(facingRight)), this.getSide())) { + right = true; + } + + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(facingUp.getOpposite())), this.getSide())) { + down = true; + } + + if (this.isAnnihilationPlane(te.getWorld().getTileEntity(pos.offset(facingUp)), this.getSide())) { + up = true; + } + } + + return PlaneConnections.of(up, right, down, left); + } + + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + if (pos.offset(this.getSide().getFacing()).equals(neighbor)) { + this.refresh(); + } + } + + @Override + public void onEntityCollision(final Entity entity) { + if (this.isAccepting && entity instanceof EntityItem && !entity.isDead && Platform.isServer() && this.getProxy().isActive()) { + boolean capture = false; + final BlockPos pos = this.getTile().getPos(); + + // This is the middle point of the entities BB, which is better suited for comparisons that don't rely on it + // "touching" the plane + double posYMiddle = (entity.getEntityBoundingBox().minY + entity.getEntityBoundingBox().maxY) / 2.0D; + + switch (this.getSide()) { + case DOWN: + case UP: + if (entity.posX > pos.getX() && entity.posX < pos.getX() + 1) { + if (entity.posZ > pos.getZ() && entity.posZ < pos.getZ() + 1) { + if ((entity.posY > pos.getY() + 0.9 && this.getSide() == AEPartLocation.UP) || (entity.posY < pos.getY() + 0.1 && this + .getSide() == AEPartLocation.DOWN)) { + capture = true; + } + } + } + break; + case SOUTH: + case NORTH: + if (entity.posX > pos.getX() && entity.posX < pos.getX() + 1) { + if (posYMiddle > pos.getY() && posYMiddle < pos.getY() + 1) { + if ((entity.posZ > pos.getZ() + 0.9 && this.getSide() == AEPartLocation.SOUTH) || (entity.posZ < pos.getZ() + 0.1 && this + .getSide() == AEPartLocation.NORTH)) { + capture = true; + } + } + } + break; + case EAST: + case WEST: + if (entity.posZ > pos.getZ() && entity.posZ < pos.getZ() + 1) { + if (posYMiddle > pos.getY() && posYMiddle < pos.getY() + 1) { + if ((entity.posX > pos.getX() + 0.9 && this.getSide() == AEPartLocation.EAST) || (entity.posX < pos.getX() + 0.1 && this + .getSide() == AEPartLocation.WEST)) { + capture = true; + } + } + } + break; + default: + // umm? + break; + } + + if (capture) { + final boolean changed = this.storeEntityItem((EntityItem) entity); + + if (changed) { + AppEng.proxy.sendToAllNearExcept(null, pos.getX(), pos.getY(), pos.getZ(), 64, this.getTile().getWorld(), + new PacketTransitionEffect(entity.posX, entity.posY, entity.posZ, this.getSide(), false)); + } + } + } + } + + @Override + public float getCableConnectionLength(AECableType cable) { + return 1; + } + + /** + * Stores an {@link EntityItem} inside the network and either marks it as dead or sets it to the leftover stackSize. + * + * @param entityItem {@link EntityItem} to store + */ + private boolean storeEntityItem(final EntityItem entityItem) { + if (!entityItem.isDead) { + final IAEItemStack overflow = this.storeItemStack(entityItem.getItem()); + + return this.handleOverflow(entityItem, overflow); + } + + return false; + } + + /** + * Stores an {@link ItemStack} inside the network. + * + * @param item {@link ItemStack} to store + * @return the leftover items, which could not be stored inside the network + */ + private IAEItemStack storeItemStack(final ItemStack item) { + final IAEItemStack itemToStore = AEItemStack.fromItemStack(item); + try { + final IStorageGrid storage = this.getProxy().getStorage(); + final IEnergyGrid energy = this.getProxy().getEnergy(); + final IAEItemStack overflow = Platform.poweredInsert(energy, + storage.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)), itemToStore, this.mySrc); + + this.isAccepting = overflow == null; + + return overflow; + } catch (final GridAccessException e1) { + // :P + } + + return null; + } + + /** + * Handles a possible overflow or none at all. + * It will update the entity to match the leftover stack size as well as mark it as dead without any leftover + * amount. + * + * @param entityItem the entity to update or destroy + * @param overflow the leftover {@link IAEItemStack} + * @return true, if the entity was changed otherwise false. + */ + private boolean handleOverflow(final EntityItem entityItem, final IAEItemStack overflow) { + if (overflow == null || overflow.getStackSize() == 0) { + entityItem.setDead(); + return true; + } + + final int oldStackSize = entityItem.getItem().getCount(); + final int newStackSize = (int) overflow.getStackSize(); + final boolean changed = oldStackSize != newStackSize; + + entityItem.getItem().setCount(newStackSize); + + return changed; + } + + protected boolean isAnnihilationPlane(final TileEntity blockTileEntity, final AEPartLocation side) { + if (blockTileEntity instanceof IPartHost) { + final IPart p = ((IPartHost) blockTileEntity).getPart(side); + return p != null && p.getClass() == this.getClass(); + } + return false; + } + + @Override + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + this.refresh(); + this.getHost().markForUpdate(); + } + + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.refresh(); + this.getHost().markForUpdate(); + } + + private TickRateModulation breakBlock(final boolean modulate) { + if (this.isAccepting && this.getProxy().isActive()) { + try { + final TileEntity te = this.getTile(); + final WorldServer w = (WorldServer) te.getWorld(); + + final BlockPos pos = te.getPos().offset(this.getSide().getFacing()); + final IEnergyGrid energy = this.getProxy().getEnergy(); + + if (this.canHandleBlock(w, pos)) { + final List items = this.obtainBlockDrops(w, pos); + final float requiredPower = this.calculateEnergyUsage(w, pos, items); + + final boolean hasPower = energy.extractAEPower(requiredPower, Actionable.SIMULATE, PowerMultiplier.CONFIG) > requiredPower - 0.1; + final boolean canStore = this.canStoreItemStacks(items); + + if (hasPower && canStore) { + if (modulate) { + energy.extractAEPower(requiredPower, Actionable.MODULATE, PowerMultiplier.CONFIG); + this.breakBlockAndStoreItems(w, pos); + AppEng.proxy.sendToAllNearExcept(null, pos.getX(), pos.getY(), pos.getZ(), 64, w, + new PacketTransitionEffect(pos.getX(), pos.getY(), pos.getZ(), this.getSide(), true)); + } else { + this.breaking = true; + TickHandler.INSTANCE.addCallable(this.getTile().getWorld(), this); + } + return TickRateModulation.URGENT; + } + } + } catch (final GridAccessException e1) { + // :P + } + } + + // nothing to do here :) + return TickRateModulation.IDLE; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.AnnihilationPlane.getMin(), TickRates.AnnihilationPlane.getMax(), false, true); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (this.breaking) { + return TickRateModulation.URGENT; + } + + this.isAccepting = true; + return this.breakBlock(false); + } + + /** + * Checks if this plane can handle the block at the specific coordinates. + */ + private boolean canHandleBlock(final WorldServer w, final BlockPos pos) { + final IBlockState state = w.getBlockState(pos); + final Material material = state.getMaterial(); + final float hardness = state.getBlockHardness(w, pos); + final boolean ignoreMaterials = material == Material.AIR || material == Material.LAVA || material == Material.WATER || material.isLiquid(); + final boolean ignoreBlocks = state.getBlock() == Blocks.BEDROCK || state.getBlock() == Blocks.END_PORTAL || state + .getBlock() == Blocks.END_PORTAL_FRAME || state.getBlock() == Blocks.COMMAND_BLOCK; + + return !ignoreMaterials && !ignoreBlocks && hardness >= 0f && !w.isAirBlock(pos) && w.isBlockLoaded(pos) && w.canMineBlockBody( + Platform.getPlayer(w), + pos); + } + + protected List obtainBlockDrops(final WorldServer w, final BlockPos pos) { + final ItemStack[] out = Platform.getBlockDrops(w, pos); + return Lists.newArrayList(out); + } + + /** + * Checks if this plane can handle the block at the specific coordinates. + */ + protected float calculateEnergyUsage(final WorldServer w, final BlockPos pos, final List items) { + final IBlockState state = w.getBlockState(pos); + final float hardness = state.getBlockHardness(w, pos); + + float requiredEnergy = 1 + hardness; + for (final ItemStack is : items) { + requiredEnergy += is.getCount(); + } + + return requiredEnergy; + } + + /** + * Checks if the network can store the possible drops. + *

+ * It also sets isAccepting to false, if the item can not be stored. + * + * @param itemStacks an array of {@link ItemStack} to test + * @return true, if the network can store at least a single item of all drops or no drops are reported + */ + private boolean canStoreItemStacks(final List itemStacks) { + boolean canStore = itemStacks.isEmpty(); + + try { + final IStorageGrid storage = this.getProxy().getStorage(); + + for (final ItemStack itemStack : itemStacks) { + final IAEItemStack itemToTest = AEItemStack.fromItemStack(itemStack); + final IAEItemStack overflow = storage.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) + .injectItems(itemToTest, Actionable.SIMULATE, this.mySrc); + if (overflow == null || itemToTest.getStackSize() > overflow.getStackSize()) { + canStore = true; + } + } + } catch (final GridAccessException e) { + // :P + } + + this.isAccepting = canStore; + return canStore; + } + + private void breakBlockAndStoreItems(final WorldServer w, final BlockPos pos) { + w.destroyBlock(pos, true); + + final AxisAlignedBB box = new AxisAlignedBB(pos).grow(0.2); + for (final Object ei : w.getEntitiesWithinAABB(EntityItem.class, box)) { + if (ei instanceof EntityItem) { + final EntityItem entityItem = (EntityItem) ei; + this.storeEntityItem(entityItem); + } + } + } + + private void refresh() { + this.isAccepting = true; + + try { + this.getProxy().getTick().alertDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // :P + } + } + + @Override + public IPartModel getStaticModels() { + return MODELS.getModel(this.getConnections(), this.isPowered(), this.isActive()); + } } diff --git a/src/main/java/appeng/parts/automation/PartExportBus.java b/src/main/java/appeng/parts/automation/PartExportBus.java index 538947933..8cdff15e4 100644 --- a/src/main/java/appeng/parts/automation/PartExportBus.java +++ b/src/main/java/appeng/parts/automation/PartExportBus.java @@ -19,26 +19,8 @@ package appeng.parts.automation; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -import com.google.common.primitives.Ints; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumHand; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.Vec3d; - import appeng.api.AEApi; -import appeng.api.config.Actionable; -import appeng.api.config.FuzzyMode; -import appeng.api.config.PowerMultiplier; -import appeng.api.config.RedstoneMode; -import appeng.api.config.SchedulingMode; -import appeng.api.config.Settings; -import appeng.api.config.Upgrades; -import appeng.api.config.YesNo; +import appeng.api.config.*; import appeng.api.networking.IGridNode; import appeng.api.networking.crafting.ICraftingGrid; import appeng.api.networking.crafting.ICraftingLink; @@ -67,344 +49,287 @@ import appeng.parts.PartModel; import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.item.AEItemStack; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import com.google.common.primitives.Ints; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumHand; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.Vec3d; -public class PartExportBus extends PartSharedItemBus implements ICraftingRequester -{ - public static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "part/export_bus_base" ); +public class PartExportBus extends PartSharedItemBus implements ICraftingRequester { + public static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "part/export_bus_base"); - @PartModels - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/export_bus_off" ) ); + @PartModels + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/export_bus_off")); - @PartModels - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/export_bus_on" ) ); + @PartModels + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/export_bus_on")); - @PartModels - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/export_bus_has_channel" ) ); + @PartModels + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/export_bus_has_channel")); - private final MultiCraftingTracker craftingTracker = new MultiCraftingTracker( this, 9 ); - private final IActionSource mySrc; - private long itemToSend = 1; - private boolean didSomething = false; - private int nextSlot = 0; + private final MultiCraftingTracker craftingTracker = new MultiCraftingTracker(this, 9); + private final IActionSource mySrc; + private long itemToSend = 1; + private boolean didSomething = false; + private int nextSlot = 0; - @Reflected - public PartExportBus( final ItemStack is ) - { - super( is ); + @Reflected + public PartExportBus(final ItemStack is) { + super(is); - this.getConfigManager().registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.CRAFT_ONLY, YesNo.NO ); - this.getConfigManager().registerSetting( Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT ); - this.mySrc = new MachineSource( this ); - } + this.getConfigManager().registerSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.getConfigManager().registerSetting(Settings.CRAFT_ONLY, YesNo.NO); + this.getConfigManager().registerSetting(Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT); + this.mySrc = new MachineSource(this); + } - @Override - public void readFromNBT( final NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.craftingTracker.readFromNBT( extra ); - this.nextSlot = extra.getInteger( "nextSlot" ); - } + @Override + public void readFromNBT(final NBTTagCompound extra) { + super.readFromNBT(extra); + this.craftingTracker.readFromNBT(extra); + this.nextSlot = extra.getInteger("nextSlot"); + } - @Override - public void writeToNBT( final NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.craftingTracker.writeToNBT( extra ); - extra.setInteger( "nextSlot", this.nextSlot ); - } + @Override + public void writeToNBT(final NBTTagCompound extra) { + super.writeToNBT(extra); + this.craftingTracker.writeToNBT(extra); + extra.setInteger("nextSlot", this.nextSlot); + } - @Override - protected TickRateModulation doBusWork() - { - if( !this.getProxy().isActive() || !this.canDoBusWork() ) - { - return TickRateModulation.IDLE; - } + @Override + protected TickRateModulation doBusWork() { + if (!this.getProxy().isActive() || !this.canDoBusWork()) { + return TickRateModulation.IDLE; + } - this.itemToSend = this.calculateItemsToSend(); - this.didSomething = false; + this.itemToSend = this.calculateItemsToSend(); + this.didSomething = false; - try - { - final InventoryAdaptor destination = this.getHandler(); - final IMEMonitor inv = this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - final IEnergyGrid energy = this.getProxy().getEnergy(); - final ICraftingGrid cg = this.getProxy().getCrafting(); - final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ); - final SchedulingMode schedulingMode = (SchedulingMode) this.getConfigManager().getSetting( Settings.SCHEDULING_MODE ); + try { + final InventoryAdaptor destination = this.getHandler(); + final IMEMonitor inv = this.getProxy().getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + final IEnergyGrid energy = this.getProxy().getEnergy(); + final ICraftingGrid cg = this.getProxy().getCrafting(); + final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE); + final SchedulingMode schedulingMode = (SchedulingMode) this.getConfigManager().getSetting(Settings.SCHEDULING_MODE); - if( destination != null ) - { - int x = 0; + if (destination != null) { + int x = 0; - for( x = 0; x < this.availableSlots() && this.itemToSend > 0; x++ ) - { - final int slotToExport = this.getStartingSlot( schedulingMode, x ); + for (x = 0; x < this.availableSlots() && this.itemToSend > 0; x++) { + final int slotToExport = this.getStartingSlot(schedulingMode, x); - final IAEItemStack ais = this.getConfig().getAEStackInSlot( slotToExport ); + final IAEItemStack ais = this.getConfig().getAEStackInSlot(slotToExport); - if( ais == null || this.itemToSend <= 0 ) - { - continue; - } + if (ais == null || this.itemToSend <= 0) { + continue; + } - if( this.craftOnly() ) - { - this.didSomething = this.craftingTracker.handleCrafting( slotToExport, this.itemToSend, ais, destination, this.getTile().getWorld(), this.getProxy().getGrid(), cg, this.mySrc ) || this.didSomething; + if (this.craftOnly()) { + this.didSomething = this.craftingTracker.handleCrafting(slotToExport, this.itemToSend, ais, destination, this.getTile().getWorld(), this.getProxy().getGrid(), cg, this.mySrc) || this.didSomething; - } + } - final long before = this.itemToSend; + final long before = this.itemToSend; - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - for( final IAEItemStack o : ImmutableList.copyOf( inv.getStorageList().findFuzzy( ais, fzMode ) ) ) - { - this.pushItemIntoTarget( destination, energy, inv, o ); - if( this.itemToSend <= 0 ) - { - break; - } - } - } - else - { - if( inv.getStorageList().findPrecise( ais ) != null ) - { - this.pushItemIntoTarget( destination, energy, inv, ais ); - } - } + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + for (final IAEItemStack o : ImmutableList.copyOf(inv.getStorageList().findFuzzy(ais, fzMode))) { + this.pushItemIntoTarget(destination, energy, inv, o); + if (this.itemToSend <= 0) { + break; + } + } + } else { + if (inv.getStorageList().findPrecise(ais) != null) { + this.pushItemIntoTarget(destination, energy, inv, ais); + } + } - if( this.itemToSend == before && this.isCraftingEnabled() ) - { - this.didSomething = this.craftingTracker.handleCrafting( slotToExport, this.itemToSend, ais, destination, this.getTile().getWorld(), this.getProxy().getGrid(), cg, this.mySrc ) || this.didSomething; - } - } + if (this.itemToSend == before && this.isCraftingEnabled()) { + this.didSomething = this.craftingTracker.handleCrafting(slotToExport, this.itemToSend, ais, destination, this.getTile().getWorld(), this.getProxy().getGrid(), cg, this.mySrc) || this.didSomething; + } + } - this.updateSchedulingMode( schedulingMode, x ); - } - else - { - return TickRateModulation.SLEEP; - } - } - catch( final GridAccessException e ) - { - // :P - } + this.updateSchedulingMode(schedulingMode, x); + } else { + return TickRateModulation.SLEEP; + } + } catch (final GridAccessException e) { + // :P + } - return this.didSomething ? TickRateModulation.FASTER : TickRateModulation.SLOWER; - } + return this.didSomething ? TickRateModulation.FASTER : TickRateModulation.SLOWER; + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 4, 4, 12, 12, 12, 14 ); - bch.addBox( 5, 5, 14, 11, 11, 15 ); - bch.addBox( 6, 6, 15, 10, 10, 16 ); - bch.addBox( 6, 6, 11, 10, 10, 12 ); - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(4, 4, 12, 12, 12, 14); + bch.addBox(5, 5, 14, 11, 11, 15); + bch.addBox(6, 6, 15, 10, 10, 16); + bch.addBox(6, 6, 11, 10, 10, 12); + } - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 5; - } + @Override + public float getCableConnectionLength(AECableType cable) { + return 5; + } - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS ); - } - return true; - } + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS); + } + return true; + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.ExportBus.getMin(), TickRates.ExportBus.getMax(), this.isSleeping(), false ); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.ExportBus.getMin(), TickRates.ExportBus.getMax(), this.isSleeping(), false); + } - @Override - public RedstoneMode getRSMode() - { - return (RedstoneMode) this.getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ); - } + @Override + public RedstoneMode getRSMode() { + return (RedstoneMode) this.getConfigManager().getSetting(Settings.REDSTONE_CONTROLLED); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.doBusWork(); - } + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.doBusWork(); + } - @Override - public ImmutableSet getRequestedJobs() - { - return this.craftingTracker.getRequestedJobs(); - } + @Override + public ImmutableSet getRequestedJobs() { + return this.craftingTracker.getRequestedJobs(); + } - @Override - public IAEItemStack injectCraftedItems( final ICraftingLink link, final IAEItemStack items, final Actionable mode ) - { - final InventoryAdaptor d = this.getHandler(); + @Override + public IAEItemStack injectCraftedItems(final ICraftingLink link, final IAEItemStack items, final Actionable mode) { + final InventoryAdaptor d = this.getHandler(); - try - { - if( d != null && this.getProxy().isActive() ) - { - final IEnergyGrid energy = this.getProxy().getEnergy(); - final double power = items.getStackSize(); + try { + if (d != null && this.getProxy().isActive()) { + final IEnergyGrid energy = this.getProxy().getEnergy(); + final double power = items.getStackSize(); - if( energy.extractAEPower( power, mode, PowerMultiplier.CONFIG ) > power - 0.01 ) - { - ItemStack inputStack = items.getCachedItemStack( items.getStackSize() ); + if (energy.extractAEPower(power, mode, PowerMultiplier.CONFIG) > power - 0.01) { + ItemStack inputStack = items.getCachedItemStack(items.getStackSize()); - ItemStack remaining; + ItemStack remaining; - if( mode == Actionable.SIMULATE ) - { - remaining = d.simulateAdd( inputStack ); - items.setCachedItemStack( inputStack ); - } - else - { - remaining = d.addItems( inputStack ); - if( !remaining.isEmpty() ) - { - items.setCachedItemStack( remaining ); - } - } + if (mode == Actionable.SIMULATE) { + remaining = d.simulateAdd(inputStack); + items.setCachedItemStack(inputStack); + } else { + remaining = d.addItems(inputStack); + if (!remaining.isEmpty()) { + items.setCachedItemStack(remaining); + } + } - if( remaining == inputStack ) - { - return items; - } + if (remaining == inputStack) { + return items; + } - return AEItemStack.fromItemStack( remaining ); - } - } - } - catch( final GridAccessException e ) - { - AELog.debug( e ); - } + return AEItemStack.fromItemStack(remaining); + } + } + } catch (final GridAccessException e) { + AELog.debug(e); + } - return items; - } + return items; + } - @Override - public void jobStateChange( final ICraftingLink link ) - { - this.craftingTracker.jobStateChange( link ); - } + @Override + public void jobStateChange(final ICraftingLink link) { + this.craftingTracker.jobStateChange(link); + } - @Override - protected boolean isSleeping() - { - return this.getHandler() == null || super.isSleeping(); - } + @Override + protected boolean isSleeping() { + return this.getHandler() == null || super.isSleeping(); + } - private boolean craftOnly() - { - return this.getConfigManager().getSetting( Settings.CRAFT_ONLY ) == YesNo.YES; - } + private boolean craftOnly() { + return this.getConfigManager().getSetting(Settings.CRAFT_ONLY) == YesNo.YES; + } - private boolean isCraftingEnabled() - { - return this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0; - } + private boolean isCraftingEnabled() { + return this.getInstalledUpgrades(Upgrades.CRAFTING) > 0; + } - private void pushItemIntoTarget( final InventoryAdaptor d, final IEnergyGrid energy, final IMEInventory inv, IAEItemStack org ) - { - ItemStack inputStack = org.getCachedItemStack( org.getStackSize() ); + private void pushItemIntoTarget(final InventoryAdaptor d, final IEnergyGrid energy, final IMEInventory inv, IAEItemStack org) { + ItemStack inputStack = org.getCachedItemStack(org.getStackSize()); - ItemStack remaining = d.simulateAdd( inputStack ); + ItemStack remaining = d.simulateAdd(inputStack); - // Store the stack in the cache for next time. - if( !remaining.isEmpty() ) - { - org.setCachedItemStack( remaining ); - if( remaining == inputStack ) - { - return; - } - } + // Store the stack in the cache for next time. + if (!remaining.isEmpty()) { + org.setCachedItemStack(remaining); + if (remaining == inputStack) { + return; + } + } - final long canFit = remaining.isEmpty() ? this.itemToSend : this.itemToSend - remaining.getCount(); + final long canFit = remaining.isEmpty() ? this.itemToSend : this.itemToSend - remaining.getCount(); - if( canFit > 0 ) - { - IAEItemStack ais = org.copy(); - ais.setStackSize( canFit ); - final IAEItemStack itemsToAdd = Platform.poweredExtraction( energy, inv, ais, this.mySrc ); + if (canFit > 0) { + IAEItemStack ais = org.copy(); + ais.setStackSize(canFit); + final IAEItemStack itemsToAdd = Platform.poweredExtraction(energy, inv, ais, this.mySrc); - if( itemsToAdd != null ) - { - this.itemToSend -= itemsToAdd.getStackSize(); + if (itemsToAdd != null) { + this.itemToSend -= itemsToAdd.getStackSize(); - inputStack.setCount( Ints.saturatedCast( itemsToAdd.getStackSize() ) ); + inputStack.setCount(Ints.saturatedCast(itemsToAdd.getStackSize())); - final ItemStack failed = d.addItems( inputStack ); - if( !failed.isEmpty() ) - { - ais.setStackSize( failed.getCount() ); - inv.injectItems( ais, Actionable.MODULATE, this.mySrc ); - } - else - { - this.didSomething = true; - } - } - else - { - org.setCachedItemStack( inputStack ); - } - } - } + final ItemStack failed = d.addItems(inputStack); + if (!failed.isEmpty()) { + ais.setStackSize(failed.getCount()); + inv.injectItems(ais, Actionable.MODULATE, this.mySrc); + } else { + this.didSomething = true; + } + } else { + org.setCachedItemStack(inputStack); + } + } + } - private int getStartingSlot( final SchedulingMode schedulingMode, final int x ) - { - if( schedulingMode == SchedulingMode.RANDOM ) - { - return Platform.getRandom().nextInt( this.availableSlots() ); - } + private int getStartingSlot(final SchedulingMode schedulingMode, final int x) { + if (schedulingMode == SchedulingMode.RANDOM) { + return Platform.getRandom().nextInt(this.availableSlots()); + } - if( schedulingMode == SchedulingMode.ROUNDROBIN ) - { - return ( this.nextSlot + x ) % this.availableSlots(); - } + if (schedulingMode == SchedulingMode.ROUNDROBIN) { + return (this.nextSlot + x) % this.availableSlots(); + } - return x; - } + return x; + } - private void updateSchedulingMode( final SchedulingMode schedulingMode, final int x ) - { - if( schedulingMode == SchedulingMode.ROUNDROBIN ) - { - this.nextSlot = ( this.nextSlot + x ) % this.availableSlots(); - } - } + private void updateSchedulingMode(final SchedulingMode schedulingMode, final int x) { + if (schedulingMode == SchedulingMode.ROUNDROBIN) { + this.nextSlot = (this.nextSlot + x) % this.availableSlots(); + } + } - @Override - public IPartModel getStaticModels() - { - if( this.isActive() && this.isPowered() ) - { - return MODELS_HAS_CHANNEL; - } - else if( this.isPowered() ) - { - return MODELS_ON; - } - else - { - return MODELS_OFF; - } - } + @Override + public IPartModel getStaticModels() { + if (this.isActive() && this.isPowered()) { + return MODELS_HAS_CHANNEL; + } else if (this.isPowered()) { + return MODELS_ON; + } else { + return MODELS_OFF; + } + } } diff --git a/src/main/java/appeng/parts/automation/PartFormationPlane.java b/src/main/java/appeng/parts/automation/PartFormationPlane.java index 83365d6a0..f5f12083b 100644 --- a/src/main/java/appeng/parts/automation/PartFormationPlane.java +++ b/src/main/java/appeng/parts/automation/PartFormationPlane.java @@ -19,41 +19,8 @@ package appeng.parts.automation; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.item.Item; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemBlockSpecial; -import net.minecraft.item.ItemFirework; -import net.minecraft.item.ItemSkull; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; -import net.minecraft.world.WorldServer; -import net.minecraftforge.common.IPlantable; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; -import appeng.api.config.AccessRestriction; -import appeng.api.config.Actionable; -import appeng.api.config.FuzzyMode; -import appeng.api.config.IncludeExclude; -import appeng.api.config.Settings; -import appeng.api.config.Upgrades; -import appeng.api.config.YesNo; +import appeng.api.config.*; import appeng.api.networking.events.MENetworkCellArrayUpdate; import appeng.api.networking.events.MENetworkChannelsChanged; import appeng.api.networking.events.MENetworkEventSubscribe; @@ -77,319 +44,284 @@ import appeng.util.Platform; import appeng.util.inv.InvOperation; import appeng.util.prioritylist.FuzzyPriorityList; import appeng.util.prioritylist.PrecisePriorityList; +import net.minecraft.entity.Entity; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.item.*; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; +import net.minecraft.world.World; +import net.minecraft.world.WorldServer; +import net.minecraftforge.common.IPlantable; +import net.minecraftforge.items.IItemHandler; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; -public class PartFormationPlane extends PartAbstractFormationPlane -{ +public class PartFormationPlane extends PartAbstractFormationPlane { - private static final PlaneModels MODELS = new PlaneModels( "part/formation_plane_", "part/formation_plane_on_" ); + private static final PlaneModels MODELS = new PlaneModels("part/formation_plane_", "part/formation_plane_on_"); - @PartModels - public static List getModels() - { - return MODELS.getModels(); - } + @PartModels + public static List getModels() { + return MODELS.getModels(); + } - private final MEInventoryHandler myHandler = new MEInventoryHandler<>( this, AEApi.instance() - .storage() - .getStorageChannel( IItemStorageChannel.class ) ); - private final AppEngInternalAEInventory Config = new AppEngInternalAEInventory( this, 63 ); + private final MEInventoryHandler myHandler = new MEInventoryHandler<>(this, AEApi.instance() + .storage() + .getStorageChannel(IItemStorageChannel.class)); + private final AppEngInternalAEInventory Config = new AppEngInternalAEInventory(this, 63); - public PartFormationPlane( final ItemStack is ) - { - super( is ); + public PartFormationPlane(final ItemStack is) { + super(is); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.PLACE_BLOCK, YesNo.YES ); - this.updateHandler(); - } + this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.getConfigManager().registerSetting(Settings.PLACE_BLOCK, YesNo.YES); + this.updateHandler(); + } - @Override - protected void updateHandler() - { - this.myHandler.setBaseAccess( AccessRestriction.WRITE ); - this.myHandler.setWhitelist( this.getInstalledUpgrades( Upgrades.INVERTER ) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST ); - this.myHandler.setPriority( this.getPriority() ); + @Override + protected void updateHandler() { + this.myHandler.setBaseAccess(AccessRestriction.WRITE); + this.myHandler.setWhitelist(this.getInstalledUpgrades(Upgrades.INVERTER) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST); + this.myHandler.setPriority(this.getPriority()); - final IItemList priorityList = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); + final IItemList priorityList = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); - final int slotsToUse = 18 + this.getInstalledUpgrades( Upgrades.CAPACITY ) * 9; - for( int x = 0; x < this.Config.getSlots() && x < slotsToUse; x++ ) - { - final IAEItemStack is = this.Config.getAEStackInSlot( x ); - if( is != null ) - { - priorityList.add( is ); - } - } + final int slotsToUse = 18 + this.getInstalledUpgrades(Upgrades.CAPACITY) * 9; + for (int x = 0; x < this.Config.getSlots() && x < slotsToUse; x++) { + final IAEItemStack is = this.Config.getAEStackInSlot(x); + if (is != null) { + priorityList.add(is); + } + } - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - this.myHandler.setPartitionList( - new FuzzyPriorityList( priorityList, (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ) ) ); - } - else - { - this.myHandler.setPartitionList( new PrecisePriorityList( priorityList ) ); - } + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + this.myHandler.setPartitionList( + new FuzzyPriorityList(priorityList, (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE))); + } else { + this.myHandler.setPartitionList(new PrecisePriorityList(priorityList)); + } - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - super.onChangeInventory( inv, slot, mc, removedStack, newStack ); + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { + super.onChangeInventory(inv, slot, mc, removedStack, newStack); - if( inv == this.Config ) - { - this.updateHandler(); - } - } + if (inv == this.Config) { + this.updateHandler(); + } + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.Config.readFromNBT( data, "config" ); - this.updateHandler(); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.Config.readFromNBT(data, "config"); + this.updateHandler(); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.Config.writeToNBT( data, "config" ); - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.Config.writeToNBT(data, "config"); + } - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.Config; - } + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("config")) { + return this.Config; + } - return super.getInventoryByName( name ); - } + return super.getInventoryByName(name); + } - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.stateChanged(); - } + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.stateChanged(); + } - @Override - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged changedChannels ) - { - this.stateChanged(); - } + @Override + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged changedChannels) { + this.stateChanged(); + } - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_FORMATION_PLANE ); - } - return true; - } + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_FORMATION_PLANE); + } + return true; + } - @Override - public List getCellArray( final IStorageChannel channel ) - { - if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - final List handler = new ArrayList<>( 1 ); - handler.add( this.myHandler ); - return handler; - } - return Collections.emptyList(); - } + @Override + public List getCellArray(final IStorageChannel channel) { + if (channel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + final List handler = new ArrayList<>(1); + handler.add(this.myHandler); + return handler; + } + return Collections.emptyList(); + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final IActionSource src ) - { - if( this.blocked || input == null || input.getStackSize() <= 0 ) - { - return input; - } + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable type, final IActionSource src) { + if (this.blocked || input == null || input.getStackSize() <= 0) { + return input; + } - final YesNo placeBlock = (YesNo) this.getConfigManager().getSetting( Settings.PLACE_BLOCK ); + final YesNo placeBlock = (YesNo) this.getConfigManager().getSetting(Settings.PLACE_BLOCK); - final ItemStack is = input.createItemStack(); - final Item i = is.getItem(); + final ItemStack is = input.createItemStack(); + final Item i = is.getItem(); - long maxStorage = Math.min( input.getStackSize(), is.getMaxStackSize() ); - boolean worked = false; + long maxStorage = Math.min(input.getStackSize(), is.getMaxStackSize()); + boolean worked = false; - final TileEntity te = this.getHost().getTile(); - final World w = te.getWorld(); - final AEPartLocation side = this.getSide(); + final TileEntity te = this.getHost().getTile(); + final World w = te.getWorld(); + final AEPartLocation side = this.getSide(); - final BlockPos tePos = te.getPos().offset( side.getFacing() ); + final BlockPos tePos = te.getPos().offset(side.getFacing()); - if( w.getBlockState( tePos ).getBlock().isReplaceable( w, tePos ) ) - { - if( placeBlock == YesNo.YES && ( i instanceof ItemBlock || i instanceof ItemBlockSpecial || i instanceof IPlantable || i instanceof ItemSkull || i instanceof ItemFirework || i instanceof IPartItem || i == Item - .getItemFromBlock( Blocks.REEDS ) ) ) - { - final EntityPlayer player = Platform.getPlayer( (WorldServer) w ); - Platform.configurePlayer( player, side, this.getTile() ); - EnumHand hand = player.getActiveHand(); - player.setHeldItem( hand, is ); + if (w.getBlockState(tePos).getBlock().isReplaceable(w, tePos)) { + if (placeBlock == YesNo.YES && (i instanceof ItemBlock || i instanceof ItemBlockSpecial || i instanceof IPlantable || i instanceof ItemSkull || i instanceof ItemFirework || i instanceof IPartItem || i == Item + .getItemFromBlock(Blocks.REEDS))) { + final EntityPlayer player = Platform.getPlayer((WorldServer) w); + Platform.configurePlayer(player, side, this.getTile()); + EnumHand hand = player.getActiveHand(); + player.setHeldItem(hand, is); - maxStorage = is.getCount(); - worked = true; - if( type == Actionable.MODULATE ) - { - if( i instanceof IPlantable || i instanceof ItemSkull || i == Item.getItemFromBlock( Blocks.REEDS ) ) - { - boolean Worked = false; + maxStorage = is.getCount(); + worked = true; + if (type == Actionable.MODULATE) { + if (i instanceof IPlantable || i instanceof ItemSkull || i == Item.getItemFromBlock(Blocks.REEDS)) { + boolean Worked = false; - if( side.xOffset == 0 && side.zOffset == 0 ) - { - Worked = i.onItemUse( player, w, tePos.offset( side.getFacing() ), hand, side.getFacing().getOpposite(), side.xOffset, - side.yOffset, side.zOffset ) == EnumActionResult.SUCCESS; - } + if (side.xOffset == 0 && side.zOffset == 0) { + Worked = i.onItemUse(player, w, tePos.offset(side.getFacing()), hand, side.getFacing().getOpposite(), side.xOffset, + side.yOffset, side.zOffset) == EnumActionResult.SUCCESS; + } - if( !Worked && side.xOffset == 0 && side.zOffset == 0 ) - { - Worked = i.onItemUse( player, w, tePos.offset( side.getFacing().getOpposite() ), hand, side.getFacing(), side.xOffset, - side.yOffset, side.zOffset ) == EnumActionResult.SUCCESS; - } + if (!Worked && side.xOffset == 0 && side.zOffset == 0) { + Worked = i.onItemUse(player, w, tePos.offset(side.getFacing().getOpposite()), hand, side.getFacing(), side.xOffset, + side.yOffset, side.zOffset) == EnumActionResult.SUCCESS; + } - if( !Worked && side.yOffset == 0 ) - { - Worked = i.onItemUse( player, w, tePos.offset( EnumFacing.DOWN ), hand, EnumFacing.UP, side.xOffset, side.yOffset, - side.zOffset ) == EnumActionResult.SUCCESS; - } + if (!Worked && side.yOffset == 0) { + Worked = i.onItemUse(player, w, tePos.offset(EnumFacing.DOWN), hand, EnumFacing.UP, side.xOffset, side.yOffset, + side.zOffset) == EnumActionResult.SUCCESS; + } - if( !Worked ) - { - i.onItemUse( player, w, tePos, hand, side.getFacing().getOpposite(), side.xOffset, side.yOffset, side.zOffset ); - } + if (!Worked) { + i.onItemUse(player, w, tePos, hand, side.getFacing().getOpposite(), side.xOffset, side.yOffset, side.zOffset); + } - maxStorage -= is.getCount(); - } - else - { - i.onItemUse( player, w, tePos, hand, side.getFacing().getOpposite(), side.xOffset, side.yOffset, side.zOffset ); - maxStorage -= is.getCount(); - } - } - else - { - maxStorage = 1; - } + maxStorage -= is.getCount(); + } else { + i.onItemUse(player, w, tePos, hand, side.getFacing().getOpposite(), side.xOffset, side.yOffset, side.zOffset); + maxStorage -= is.getCount(); + } + } else { + maxStorage = 1; + } - // Safe keeping - player.setHeldItem( hand, ItemStack.EMPTY ); - } - else - { - worked = true; + // Safe keeping + player.setHeldItem(hand, ItemStack.EMPTY); + } else { + worked = true; - final int sum = this.countEntitesAround( w, tePos ); + final int sum = this.countEntitesAround(w, tePos); - if( sum < AEConfig.instance().getFormationPlaneEntityLimit() ) - { - if( type == Actionable.MODULATE ) - { - is.setCount( (int) maxStorage ); - final double x = ( side.xOffset != 0 ? 0 : .7 * ( Platform.getRandomFloat() - .5 ) ) + side.xOffset + .5 + te.getPos().getX(); - final double y = ( side.yOffset != 0 ? 0 : .7 * ( Platform.getRandomFloat() - .5 ) ) + side.yOffset + .5 + te.getPos().getY(); - final double z = ( side.zOffset != 0 ? 0 : .7 * ( Platform.getRandomFloat() - .5 ) ) + side.zOffset + .5 + te.getPos().getZ(); + if (sum < AEConfig.instance().getFormationPlaneEntityLimit()) { + if (type == Actionable.MODULATE) { + is.setCount((int) maxStorage); + final double x = (side.xOffset != 0 ? 0 : .7 * (Platform.getRandomFloat() - .5)) + side.xOffset + .5 + te.getPos().getX(); + final double y = (side.yOffset != 0 ? 0 : .7 * (Platform.getRandomFloat() - .5)) + side.yOffset + .5 + te.getPos().getY(); + final double z = (side.zOffset != 0 ? 0 : .7 * (Platform.getRandomFloat() - .5)) + side.zOffset + .5 + te.getPos().getZ(); - final EntityItem ei = new EntityItem( w, x, y, z, is.copy() ); + final EntityItem ei = new EntityItem(w, x, y, z, is.copy()); - Entity result = ei; + Entity result = ei; - ei.motionX = side.xOffset * 0.2; - ei.motionY = side.yOffset * 0.2; - ei.motionZ = side.zOffset * 0.2; + ei.motionX = side.xOffset * 0.2; + ei.motionY = side.yOffset * 0.2; + ei.motionZ = side.zOffset * 0.2; - if( is.getItem().hasCustomEntity( is ) ) - { - result = is.getItem().createEntity( w, ei, is ); - if( result != null ) - { - ei.setDead(); - } - else - { - result = ei; - } - } + if (is.getItem().hasCustomEntity(is)) { + result = is.getItem().createEntity(w, ei, is); + if (result != null) { + ei.setDead(); + } else { + result = ei; + } + } - if( !w.spawnEntity( result ) ) - { - result.setDead(); - worked = false; - } - } - } - else - { - worked = false; - } - } - } + if (!w.spawnEntity(result)) { + result.setDead(); + worked = false; + } + } + } else { + worked = false; + } + } + } - this.blocked = !w.getBlockState( tePos ).getBlock().isReplaceable( w, tePos ); + this.blocked = !w.getBlockState(tePos).getBlock().isReplaceable(w, tePos); - if( worked ) - { - final IAEItemStack out = input.copy(); - out.decStackSize( maxStorage ); - if( out.getStackSize() == 0 ) - { - return null; - } - return out; - } + if (worked) { + final IAEItemStack out = input.copy(); + out.decStackSize(maxStorage); + if (out.getStackSize() == 0) { + return null; + } + return out; + } - return input; - } + return input; + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } - @Override - public IPartModel getStaticModels() - { - return MODELS.getModel( this.getConnections(), this.isPowered(), this.isActive() ); - } + @Override + public IPartModel getStaticModels() { + return MODELS.getModel(this.getConnections(), this.isPowered(), this.isActive()); + } - @Override - public ItemStack getItemStackRepresentation() - { - return AEApi.instance().definitions().parts().formationPlane().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - } + @Override + public ItemStack getItemStackRepresentation() { + return AEApi.instance().definitions().parts().formationPlane().maybeStack(1).orElse(ItemStack.EMPTY); + } - @Override - public GuiBridge getGuiBridge() - { - return GuiBridge.GUI_FORMATION_PLANE; - } + @Override + public GuiBridge getGuiBridge() { + return GuiBridge.GUI_FORMATION_PLANE; + } - private int countEntitesAround( World world, BlockPos pos ) - { - final AxisAlignedBB t = new AxisAlignedBB( pos ).grow( 8 ); - final List list = world.getEntitiesWithinAABB( Entity.class, t ); + private int countEntitesAround(World world, BlockPos pos) { + final AxisAlignedBB t = new AxisAlignedBB(pos).grow(8); + final List list = world.getEntitiesWithinAABB(Entity.class, t); - return list.size(); - } + return list.size(); + } } diff --git a/src/main/java/appeng/parts/automation/PartIdentityAnnihilationPlane.java b/src/main/java/appeng/parts/automation/PartIdentityAnnihilationPlane.java index a987537d5..13170a863 100644 --- a/src/main/java/appeng/parts/automation/PartIdentityAnnihilationPlane.java +++ b/src/main/java/appeng/parts/automation/PartIdentityAnnihilationPlane.java @@ -19,9 +19,11 @@ package appeng.parts.automation; -import java.util.ArrayList; -import java.util.List; - +import appeng.api.parts.IPart; +import appeng.api.parts.IPartHost; +import appeng.api.parts.IPartModel; +import appeng.api.util.AEPartLocation; +import appeng.items.parts.PartModels; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Items; import net.minecraft.item.Item; @@ -32,83 +34,67 @@ import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.common.util.FakePlayerFactory; -import appeng.api.parts.IPart; -import appeng.api.parts.IPartHost; -import appeng.api.parts.IPartModel; -import appeng.api.util.AEPartLocation; -import appeng.items.parts.PartModels; +import java.util.ArrayList; +import java.util.List; -public class PartIdentityAnnihilationPlane extends PartAnnihilationPlane -{ +public class PartIdentityAnnihilationPlane extends PartAnnihilationPlane { - private static final PlaneModels MODELS = new PlaneModels( "part/identity_annihilation_plane_", "part/identity_annihilation_plane_on_" ); + private static final PlaneModels MODELS = new PlaneModels("part/identity_annihilation_plane_", "part/identity_annihilation_plane_on_"); - @PartModels - public static List getModels() - { - return MODELS.getModels(); - } + @PartModels + public static List getModels() { + return MODELS.getModels(); + } - private static final float SILK_TOUCH_FACTOR = 16; + private static final float SILK_TOUCH_FACTOR = 16; - public PartIdentityAnnihilationPlane( final ItemStack is ) - { - super( is ); - } + public PartIdentityAnnihilationPlane(final ItemStack is) { + super(is); + } - @Override - protected boolean isAnnihilationPlane( final TileEntity blockTileEntity, final AEPartLocation side ) - { - if( blockTileEntity instanceof IPartHost ) - { - final IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); - return p != null && p.getClass() == this.getClass(); - } - return false; - } + @Override + protected boolean isAnnihilationPlane(final TileEntity blockTileEntity, final AEPartLocation side) { + if (blockTileEntity instanceof IPartHost) { + final IPart p = ((IPartHost) blockTileEntity).getPart(side); + return p != null && p.getClass() == this.getClass(); + } + return false; + } - @Override - protected float calculateEnergyUsage( final WorldServer w, final BlockPos pos, final List items ) - { - final float requiredEnergy = super.calculateEnergyUsage( w, pos, items ); + @Override + protected float calculateEnergyUsage(final WorldServer w, final BlockPos pos, final List items) { + final float requiredEnergy = super.calculateEnergyUsage(w, pos, items); - return requiredEnergy * SILK_TOUCH_FACTOR; - } + return requiredEnergy * SILK_TOUCH_FACTOR; + } - @Override - protected List obtainBlockDrops( final WorldServer w, final BlockPos pos ) - { - final FakePlayer fakePlayer = FakePlayerFactory.getMinecraft( w ); - final IBlockState state = w.getBlockState( pos ); + @Override + protected List obtainBlockDrops(final WorldServer w, final BlockPos pos) { + final FakePlayer fakePlayer = FakePlayerFactory.getMinecraft(w); + final IBlockState state = w.getBlockState(pos); - if( state.getBlock().canSilkHarvest( w, pos, state, fakePlayer ) ) - { - final List out = new ArrayList<>( 1 ); - final Item item = Item.getItemFromBlock( state.getBlock() ); + if (state.getBlock().canSilkHarvest(w, pos, state, fakePlayer)) { + final List out = new ArrayList<>(1); + final Item item = Item.getItemFromBlock(state.getBlock()); - if( item != Items.AIR ) - { - int meta = 0; - if( item.getHasSubtypes() ) - { - meta = state.getBlock().getMetaFromState( state ); - } - final ItemStack itemstack = new ItemStack( item, 1, meta ); - out.add( itemstack ); - } - return out; - } - else - { - return super.obtainBlockDrops( w, pos ); - } - } + if (item != Items.AIR) { + int meta = 0; + if (item.getHasSubtypes()) { + meta = state.getBlock().getMetaFromState(state); + } + final ItemStack itemstack = new ItemStack(item, 1, meta); + out.add(itemstack); + } + return out; + } else { + return super.obtainBlockDrops(w, pos); + } + } - @Override - public IPartModel getStaticModels() - { - return MODELS.getModel( this.getConnections(), this.isPowered(), this.isActive() ); - } + @Override + public IPartModel getStaticModels() { + return MODELS.getModel(this.getConnections(), this.isPowered(), this.isActive()); + } } diff --git a/src/main/java/appeng/parts/automation/PartImportBus.java b/src/main/java/appeng/parts/automation/PartImportBus.java index 128cef3f8..06e99fcb0 100644 --- a/src/main/java/appeng/parts/automation/PartImportBus.java +++ b/src/main/java/appeng/parts/automation/PartImportBus.java @@ -19,19 +19,8 @@ package appeng.parts.automation; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumHand; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.Vec3d; - import appeng.api.AEApi; -import appeng.api.config.Actionable; -import appeng.api.config.FuzzyMode; -import appeng.api.config.RedstoneMode; -import appeng.api.config.Settings; -import appeng.api.config.Upgrades; +import appeng.api.config.*; import appeng.api.networking.IGridNode; import appeng.api.networking.energy.IEnergyGrid; import appeng.api.networking.energy.IEnergySource; @@ -56,286 +45,233 @@ import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.inv.IInventoryDestination; import appeng.util.item.AEItemStack; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumHand; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.Vec3d; -public class PartImportBus extends PartSharedItemBus implements IInventoryDestination -{ +public class PartImportBus extends PartSharedItemBus implements IInventoryDestination { - public static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "part/import_bus_base" ); - @PartModels - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/import_bus_off" ) ); - @PartModels - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/import_bus_on" ) ); - @PartModels - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/import_bus_has_channel" ) ); + public static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "part/import_bus_base"); + @PartModels + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/import_bus_off")); + @PartModels + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/import_bus_on")); + @PartModels + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/import_bus_has_channel")); - private final IActionSource source; - private int itemsToSend; // used in tickingRequest - private boolean worked; // used in tickingRequest + private final IActionSource source; + private int itemsToSend; // used in tickingRequest + private boolean worked; // used in tickingRequest - @Reflected - public PartImportBus( final ItemStack is ) - { - super( is ); + @Reflected + public PartImportBus(final ItemStack is) { + super(is); - this.getConfigManager().registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.source = new MachineSource( this ); - } + this.getConfigManager().registerSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.source = new MachineSource(this); + } - @Override - public boolean canInsert( final ItemStack stack ) - { - if( stack.isEmpty() || stack.getItem() == Items.AIR ) - { - return false; - } + @Override + public boolean canInsert(final ItemStack stack) { + if (stack.isEmpty() || stack.getItem() == Items.AIR) { + return false; + } - try - { - final IMEMonitor inv = this.getProxy() - .getStorage() - .getInventory( - AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); + try { + final IMEMonitor inv = this.getProxy() + .getStorage() + .getInventory( + AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); - final IAEItemStack out = inv.injectItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( stack ), - Actionable.SIMULATE, - this.source ); - if( out == null ) - { - return true; - } - return out.getStackSize() != stack.getCount(); - } - catch( GridAccessException ex ) - { - return false; - } - } + final IAEItemStack out = inv.injectItems(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(stack), + Actionable.SIMULATE, + this.source); + if (out == null) { + return true; + } + return out.getStackSize() != stack.getCount(); + } catch (GridAccessException ex) { + return false; + } + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 6, 6, 11, 10, 10, 13 ); - bch.addBox( 5, 5, 13, 11, 11, 14 ); - bch.addBox( 4, 4, 14, 12, 12, 16 ); - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(6, 6, 11, 10, 10, 13); + bch.addBox(5, 5, 13, 11, 11, 14); + bch.addBox(4, 4, 14, 12, 12, 16); + } - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 5; - } + @Override + public float getCableConnectionLength(AECableType cable) { + return 5; + } - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS ); - } - return true; - } + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS); + } + return true; + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.ImportBus.getMin(), TickRates.ImportBus.getMax(), this.isSleeping(), false ); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.ImportBus.getMin(), TickRates.ImportBus.getMax(), this.isSleeping(), false); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.doBusWork(); - } + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.doBusWork(); + } - @Override - protected TickRateModulation doBusWork() - { - if( !this.getProxy().isActive() || !this.canDoBusWork() ) - { - return TickRateModulation.IDLE; - } + @Override + protected TickRateModulation doBusWork() { + if (!this.getProxy().isActive() || !this.canDoBusWork()) { + return TickRateModulation.IDLE; + } - this.worked = false; + this.worked = false; - final InventoryAdaptor myAdaptor = this.getHandler(); - final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ); + final InventoryAdaptor myAdaptor = this.getHandler(); + final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE); - if( myAdaptor != null ) - { - try - { - this.itemsToSend = this.calculateItemsToSend(); + if (myAdaptor != null) { + try { + this.itemsToSend = this.calculateItemsToSend(); - final IMEMonitor inv = this.getProxy() - .getStorage() - .getInventory( - AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - final IEnergyGrid energy = this.getProxy().getEnergy(); + final IMEMonitor inv = this.getProxy() + .getStorage() + .getInventory( + AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + final IEnergyGrid energy = this.getProxy().getEnergy(); - boolean Configured = false; - for( int x = 0; x < this.availableSlots(); x++ ) - { - final IAEItemStack ais = this.getConfig().getAEStackInSlot( x ); - if( ais != null && this.itemsToSend > 0 ) - { - Configured = true; - while( this.itemsToSend > 0 ) - { - if( this.importStuff( myAdaptor, ais, inv, energy, fzMode ) ) - { - break; - } - } - } - } + boolean Configured = false; + for (int x = 0; x < this.availableSlots(); x++) { + final IAEItemStack ais = this.getConfig().getAEStackInSlot(x); + if (ais != null && this.itemsToSend > 0) { + Configured = true; + while (this.itemsToSend > 0) { + if (this.importStuff(myAdaptor, ais, inv, energy, fzMode)) { + break; + } + } + } + } - if( !Configured ) - { - while( this.itemsToSend > 0 ) - { - if( this.importStuff( myAdaptor, null, inv, energy, fzMode ) ) - { - break; - } - } - } - } - catch( final GridAccessException e ) - { - // :3 - } - } - else - { - return TickRateModulation.SLEEP; - } + if (!Configured) { + while (this.itemsToSend > 0) { + if (this.importStuff(myAdaptor, null, inv, energy, fzMode)) { + break; + } + } + } + } catch (final GridAccessException e) { + // :3 + } + } else { + return TickRateModulation.SLEEP; + } - return this.worked ? TickRateModulation.FASTER : TickRateModulation.SLOWER; - } + return this.worked ? TickRateModulation.FASTER : TickRateModulation.SLOWER; + } - private boolean importStuff( final InventoryAdaptor myAdaptor, final IAEItemStack whatToImport, final IMEMonitor inv, final IEnergySource energy, final FuzzyMode fzMode ) - { - final int toSend = this.calculateMaximumAmountToImport( myAdaptor, whatToImport, inv, fzMode ); + private boolean importStuff(final InventoryAdaptor myAdaptor, final IAEItemStack whatToImport, final IMEMonitor inv, final IEnergySource energy, final FuzzyMode fzMode) { + final int toSend = this.calculateMaximumAmountToImport(myAdaptor, whatToImport, inv, fzMode); - if( toSend == 0 ) - { - return true; - } + if (toSend == 0) { + return true; + } - final ItemStack newItems; + final ItemStack newItems; - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - newItems = myAdaptor.removeSimilarItems( toSend, whatToImport == null ? ItemStack.EMPTY : whatToImport.getDefinition(), fzMode, this ); - } - else - { - newItems = myAdaptor.removeItems( toSend, whatToImport == null ? ItemStack.EMPTY : whatToImport.getDefinition(), this ); - } + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + newItems = myAdaptor.removeSimilarItems(toSend, whatToImport == null ? ItemStack.EMPTY : whatToImport.getDefinition(), fzMode, this); + } else { + newItems = myAdaptor.removeItems(toSend, whatToImport == null ? ItemStack.EMPTY : whatToImport.getDefinition(), this); + } - if( !newItems.isEmpty() ) - { - final IAEItemStack aeStack = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( newItems ); - final IAEItemStack failed = Platform.poweredInsert( energy, inv, aeStack, this.source ); + if (!newItems.isEmpty()) { + final IAEItemStack aeStack = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(newItems); + final IAEItemStack failed = Platform.poweredInsert(energy, inv, aeStack, this.source); - if( failed != null ) - { - // try unpowered insert, better be a bit lenient then void items - final IAEItemStack spill = inv.injectItems( failed, Actionable.MODULATE, this.source ); - if( spill != null ) - { - // last resort try to put it back .. lets hope it's a chest type of thing - myAdaptor.addItems( spill.createItemStack() ); - } - return true; - } - else - { - this.itemsToSend -= newItems.getCount(); - this.worked = true; - } - } - else - { - return true; - } + if (failed != null) { + // try unpowered insert, better be a bit lenient then void items + final IAEItemStack spill = inv.injectItems(failed, Actionable.MODULATE, this.source); + if (spill != null) { + // last resort try to put it back .. lets hope it's a chest type of thing + myAdaptor.addItems(spill.createItemStack()); + } + return true; + } else { + this.itemsToSend -= newItems.getCount(); + this.worked = true; + } + } else { + return true; + } - return false; - } + return false; + } - private int calculateMaximumAmountToImport( final InventoryAdaptor myAdaptor, final IAEItemStack whatToImport, final IMEMonitor inv, final FuzzyMode fzMode ) - { - final int toSend = Math.min( this.itemsToSend, 64 ); - final ItemStack itemStackToImport; + private int calculateMaximumAmountToImport(final InventoryAdaptor myAdaptor, final IAEItemStack whatToImport, final IMEMonitor inv, final FuzzyMode fzMode) { + final int toSend = Math.min(this.itemsToSend, 64); + final ItemStack itemStackToImport; - if( whatToImport == null ) - { - itemStackToImport = ItemStack.EMPTY; - } - else - { - itemStackToImport = whatToImport.getDefinition(); - } + if (whatToImport == null) { + itemStackToImport = ItemStack.EMPTY; + } else { + itemStackToImport = whatToImport.getDefinition(); + } - final IAEItemStack itemAmountNotStorable; - final ItemStack simResult; - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - simResult = myAdaptor.simulateSimilarRemove( toSend, itemStackToImport, fzMode, null ); - itemAmountNotStorable = inv.injectItems( AEItemStack.fromItemStack( simResult ), Actionable.SIMULATE, this.source ); - } - else - { - simResult = myAdaptor.simulateRemove( toSend, itemStackToImport, null ); - itemAmountNotStorable = inv.injectItems( AEItemStack.fromItemStack( simResult ), Actionable.SIMULATE, this.source ); - } + final IAEItemStack itemAmountNotStorable; + final ItemStack simResult; + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + simResult = myAdaptor.simulateSimilarRemove(toSend, itemStackToImport, fzMode, null); + itemAmountNotStorable = inv.injectItems(AEItemStack.fromItemStack(simResult), Actionable.SIMULATE, this.source); + } else { + simResult = myAdaptor.simulateRemove(toSend, itemStackToImport, null); + itemAmountNotStorable = inv.injectItems(AEItemStack.fromItemStack(simResult), Actionable.SIMULATE, this.source); + } - if( simResult.isEmpty() ) - { - return 0; - } + if (simResult.isEmpty()) { + return 0; + } - if( itemAmountNotStorable != null ) - { - if( simResult.getCount() == itemAmountNotStorable.getStackSize() ) - { - return 0; - } - return (int) Math.min( simResult.getCount() - itemAmountNotStorable.getStackSize(), toSend ); - } + if (itemAmountNotStorable != null) { + if (simResult.getCount() == itemAmountNotStorable.getStackSize()) { + return 0; + } + return (int) Math.min(simResult.getCount() - itemAmountNotStorable.getStackSize(), toSend); + } - return toSend; - } + return toSend; + } - @Override - protected boolean isSleeping() - { - return this.getHandler() == null || super.isSleeping(); - } + @Override + protected boolean isSleeping() { + return this.getHandler() == null || super.isSleeping(); + } - @Override - public RedstoneMode getRSMode() - { - return (RedstoneMode) this.getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ); - } + @Override + public RedstoneMode getRSMode() { + return (RedstoneMode) this.getConfigManager().getSetting(Settings.REDSTONE_CONTROLLED); + } - @Override - public IPartModel getStaticModels() - { - if( this.isActive() && this.isPowered() ) - { - return MODELS_HAS_CHANNEL; - } - else if( this.isPowered() ) - { - return MODELS_ON; - } - else - { - return MODELS_OFF; - } - } + @Override + public IPartModel getStaticModels() { + if (this.isActive() && this.isPowered()) { + return MODELS_HAS_CHANNEL; + } else if (this.isPowered()) { + return MODELS_ON; + } else { + return MODELS_OFF; + } + } } diff --git a/src/main/java/appeng/parts/automation/PartLevelEmitter.java b/src/main/java/appeng/parts/automation/PartLevelEmitter.java index f1dae7bca..17db631cf 100644 --- a/src/main/java/appeng/parts/automation/PartLevelEmitter.java +++ b/src/main/java/appeng/parts/automation/PartLevelEmitter.java @@ -55,8 +55,6 @@ import appeng.parts.PartModel; import appeng.tile.inventory.AppEngInternalAEInventory; import appeng.util.Platform; import appeng.util.inv.InvOperation; -import appeng.util.item.OreHelper; -import appeng.util.item.OreReference; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; @@ -70,503 +68,406 @@ import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.items.IItemHandler; -import java.util.Optional; import java.util.Random; -public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherHost, IStackWatcherHost, ICraftingWatcherHost, IMEMonitorHandlerReceiver, ICraftingProvider -{ - - @PartModels - public static final ResourceLocation MODEL_BASE_OFF = new ResourceLocation( AppEng.MOD_ID, "part/level_emitter_base_off" ); - @PartModels - public static final ResourceLocation MODEL_BASE_ON = new ResourceLocation( AppEng.MOD_ID, "part/level_emitter_base_on" ); - @PartModels - public static final ResourceLocation MODEL_STATUS_OFF = new ResourceLocation( AppEng.MOD_ID, "part/level_emitter_status_off" ); - @PartModels - public static final ResourceLocation MODEL_STATUS_ON = new ResourceLocation( AppEng.MOD_ID, "part/level_emitter_status_on" ); - @PartModels - public static final ResourceLocation MODEL_STATUS_HAS_CHANNEL = new ResourceLocation( AppEng.MOD_ID, "part/level_emitter_status_has_channel" ); - - public static final PartModel MODEL_OFF_OFF = new PartModel( MODEL_BASE_OFF, MODEL_STATUS_OFF ); - public static final PartModel MODEL_OFF_ON = new PartModel( MODEL_BASE_OFF, MODEL_STATUS_ON ); - public static final PartModel MODEL_OFF_HAS_CHANNEL = new PartModel( MODEL_BASE_OFF, MODEL_STATUS_HAS_CHANNEL ); - public static final PartModel MODEL_ON_OFF = new PartModel( MODEL_BASE_ON, MODEL_STATUS_OFF ); - public static final PartModel MODEL_ON_ON = new PartModel( MODEL_BASE_ON, MODEL_STATUS_ON ); - public static final PartModel MODEL_ON_HAS_CHANNEL = new PartModel( MODEL_BASE_ON, MODEL_STATUS_HAS_CHANNEL ); - - private static final int FLAG_ON = 4; - - private final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, 1 ); - - private boolean prevState = false; - - private long lastReportedValue = 0; - private long reportingValue = 0; - - private IStackWatcher myWatcher; - private IEnergyWatcher myEnergyWatcher; - private ICraftingWatcher myCraftingWatcher; - private double centerX; - private double centerY; - private double centerZ; - - @Reflected - public PartLevelEmitter( final ItemStack is ) - { - super( is ); - - this.getConfigManager().registerSetting( Settings.REDSTONE_EMITTER, RedstoneMode.HIGH_SIGNAL ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL ); - this.getConfigManager().registerSetting( Settings.CRAFT_VIA_REDSTONE, YesNo.NO ); - } - - public long getReportingValue() - { - return this.reportingValue; - } - - public void setReportingValue( final long v ) - { - this.reportingValue = v; - if( this.getConfigManager().getSetting( Settings.LEVEL_TYPE ) == LevelType.ENERGY_LEVEL ) - { - this.configureWatchers(); - } - else - { - this.updateState(); - } - } - - private void updateState() - { - final boolean isOn = this.isLevelEmitterOn(); - if( this.prevState != isOn ) - { - this.getHost().markForUpdate(); - final TileEntity te = this.getHost().getTile(); - this.prevState = isOn; - Platform.notifyBlocksOfNeighbors( te.getWorld(), te.getPos() ); - Platform.notifyBlocksOfNeighbors( te.getWorld(), te.getPos().offset( this.getSide().getFacing() ) ); - } - } - - // TODO: Make private again - public boolean isLevelEmitterOn() - { - if( Platform.isClient() ) - { - return ( this.getClientFlags() & FLAG_ON ) == FLAG_ON; - } - - if( !this.getProxy().isActive() ) - { - return false; - } - - if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) - { - try - { - return this.getProxy().getCrafting().isRequesting( this.config.getAEStackInSlot( 0 ) ); - } - catch( final GridAccessException e ) - { - // :P - } - - return this.prevState; - } - - final boolean flipState = this.getConfigManager().getSetting( Settings.REDSTONE_EMITTER ) == RedstoneMode.LOW_SIGNAL; - return flipState ? this.reportingValue >= this.lastReportedValue + 1 : this.reportingValue < this.lastReportedValue + 1; - } - - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange powerEvent ) - { - if (this.getProxy().isActive()) - { - onListUpdate(); - } - this.updateState(); - } - - @Override - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - if (this.getProxy().isActive()) - { - onListUpdate(); - } - this.updateState(); - } - - @Override - protected int populateFlags( final int cf ) - { - return cf | ( this.prevState ? FLAG_ON : 0 ); - } - - @Override - public void updateWatcher( final ICraftingWatcher newWatcher ) - { - this.myCraftingWatcher = newWatcher; - this.configureWatchers(); - } - - @Override - public void onRequestChange( final ICraftingGrid craftingGrid, final IAEItemStack what ) - { - this.updateState(); - } - - // update the system... - private void configureWatchers() - { - final IAEItemStack myStack = this.config.getAEStackInSlot( 0 ); - - if( this.myWatcher != null ) - { - this.myWatcher.reset(); - } - - if( this.myEnergyWatcher != null ) - { - this.myEnergyWatcher.reset(); - } - - if( this.myCraftingWatcher != null ) - { - this.myCraftingWatcher.reset(); - } - - try - { - this.getProxy().getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.getProxy().getNode() ) ); - } - catch( final GridAccessException e1 ) - { - // :/ - } - - if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) - { - if( this.myCraftingWatcher != null && myStack != null ) - { - this.myCraftingWatcher.add( myStack ); - } - - return; - } - - if( this.getConfigManager().getSetting( Settings.LEVEL_TYPE ) == LevelType.ENERGY_LEVEL ) - { - if( this.myEnergyWatcher != null ) - { - this.myEnergyWatcher.add( this.reportingValue ); - } - - try - { - // update to power... - this.lastReportedValue = (long) this.getProxy().getEnergy().getStoredPower(); - this.updateState(); - - // no more item stuff.. - this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).removeListener( this ); - } - catch( final GridAccessException e ) - { - // :P - } - - return; - } - - try - { - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 || myStack == null ) - { - this.getProxy() - .getStorage() - .getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - .addListener( this, - this.getProxy().getGrid() ); - } - else - { - this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).removeListener( this ); - - if( this.myWatcher != null ) - { - this.myWatcher.add( myStack ); - } - } - - this.updateReportingValue( this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) ); - } - catch( final GridAccessException e ) - { - // >.> - } - } - - private void updateReportingValue( final IMEMonitor monitor ) - { - final IAEItemStack myStack = this.config.getAEStackInSlot( 0 ); - - if( myStack == null ) - { - if( monitor instanceof NetworkMonitor ) - { - this.lastReportedValue = ( (NetworkMonitor) monitor ).getGridCurrentCount(); - } - } - - else if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ); - - this.lastReportedValue = 0; - monitor.getStorageList().findFuzzy( myStack, fzMode ).forEach( iaeItemStack -> lastReportedValue += iaeItemStack.getStackSize() ); - } - else - { - this.lastReportedValue = 0; - IAEItemStack precise = monitor.getStorageList().findPrecise( myStack ); - if( precise != null ) lastReportedValue = precise.getStackSize(); - } - this.updateState(); - } - - @Override - public void updateWatcher( final IStackWatcher newWatcher ) - { - this.myWatcher = newWatcher; - this.configureWatchers(); - } - - @Override - public void onStackChange( final IItemList o, final IAEStack fullStack, final IAEStack diffStack, final IActionSource src, final IStorageChannel chan ) - { - if( chan == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) && fullStack.equals( this.config.getAEStackInSlot( 0 ) ) && this.getInstalledUpgrades( Upgrades.FUZZY ) == 0 ) - { - this.lastReportedValue = fullStack.getStackSize(); - this.updateState(); - } - } - - @Override - public void updateWatcher( final IEnergyWatcher newWatcher ) - { - this.myEnergyWatcher = newWatcher; - this.configureWatchers(); - } - - @Override - public void onThresholdPass( final IEnergyGrid energyGrid ) - { - this.lastReportedValue = (long) energyGrid.getStoredPower(); - this.updateState(); - } - - @Override - public boolean isValid( final Object effectiveGrid ) - { - try - { - return this.getProxy().getGrid() == effectiveGrid; - } - catch( final GridAccessException e ) - { - return false; - } - } - - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final IActionSource actionSource ) - { - this.updateReportingValue( (IMEMonitor) monitor ); - } - - @Override - public void onListUpdate() - { - try - { - this.updateReportingValue( this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) ); - } - catch( final GridAccessException e ) - { - // ;P - } - } - - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.SMART; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 7, 7, 11, 9, 9, 16 ); - } - - @Override - public int isProvidingStrongPower() - { - return this.prevState ? 15 : 0; - } - - @Override - public int isProvidingWeakPower() - { - return this.prevState ? 15 : 0; - } - - @Override - public void randomDisplayTick( final World world, final BlockPos pos, final Random r ) - { - if( this.isLevelEmitterOn() ) - { - final AEPartLocation d = this.getSide(); - - final double d0 = d.xOffset * 0.45F + ( r.nextFloat() - 0.5F ) * 0.2D; - final double d1 = d.yOffset * 0.45F + ( r.nextFloat() - 0.5F ) * 0.2D; - final double d2 = d.zOffset * 0.45F + ( r.nextFloat() - 0.5F ) * 0.2D; - - world.spawnParticle( EnumParticleTypes.REDSTONE, 0.5 + pos.getX() + d0, 0.5 + pos.getY() + d1, 0.5 + pos.getZ() + d2, 0.0D, 0.0D, 0.0D, - new int[0] ); - } - } - - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 16; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_LEVEL_EMITTER ); - } - return true; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.configureWatchers(); - } - - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( inv == this.config ) - { - this.configureWatchers(); - } - - super.onChangeInventory( inv, slot, mc, removedStack, newStack ); - } - - @Override - public void upgradesChanged() - { - this.configureWatchers(); - this.updateState(); - } - - @Override - public boolean canConnectRedstone() - { - return true; - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.lastReportedValue = data.getLong( "lastReportedValue" ); - this.reportingValue = data.getLong( "reportingValue" ); - this.prevState = data.getBoolean( "prevState" ); - this.config.readFromNBT( data, "config" ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setLong( "lastReportedValue", this.lastReportedValue ); - data.setLong( "reportingValue", this.reportingValue ); - data.setBoolean( "prevState", this.prevState ); - this.config.writeToNBT( data, "config" ); - } - - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.config; - } - - return super.getInventoryByName( name ); - } - - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) - { - return false; - } - - @Override - public boolean isBusy() - { - return true; - } - - @Override - public void provideCrafting( final ICraftingProviderHelper craftingTracker ) - { - if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) - { - if( this.getConfigManager().getSetting( Settings.CRAFT_VIA_REDSTONE ) == YesNo.YES ) - { - final IAEItemStack what = this.config.getAEStackInSlot( 0 ); - if( what != null ) - { - craftingTracker.setEmitable( what ); - } - } - } - } - - @Override - public IPartModel getStaticModels() - { - if( this.isActive() && this.isPowered() ) - { - return this.isLevelEmitterOn() ? MODEL_ON_HAS_CHANNEL : MODEL_OFF_HAS_CHANNEL; - } - else if( this.isPowered() ) - { - return this.isLevelEmitterOn() ? MODEL_ON_ON : MODEL_OFF_ON; - } - else - { - return this.isLevelEmitterOn() ? MODEL_ON_OFF : MODEL_OFF_OFF; - } - } +public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherHost, IStackWatcherHost, ICraftingWatcherHost, IMEMonitorHandlerReceiver, ICraftingProvider { + + @PartModels + public static final ResourceLocation MODEL_BASE_OFF = new ResourceLocation(AppEng.MOD_ID, "part/level_emitter_base_off"); + @PartModels + public static final ResourceLocation MODEL_BASE_ON = new ResourceLocation(AppEng.MOD_ID, "part/level_emitter_base_on"); + @PartModels + public static final ResourceLocation MODEL_STATUS_OFF = new ResourceLocation(AppEng.MOD_ID, "part/level_emitter_status_off"); + @PartModels + public static final ResourceLocation MODEL_STATUS_ON = new ResourceLocation(AppEng.MOD_ID, "part/level_emitter_status_on"); + @PartModels + public static final ResourceLocation MODEL_STATUS_HAS_CHANNEL = new ResourceLocation(AppEng.MOD_ID, "part/level_emitter_status_has_channel"); + + public static final PartModel MODEL_OFF_OFF = new PartModel(MODEL_BASE_OFF, MODEL_STATUS_OFF); + public static final PartModel MODEL_OFF_ON = new PartModel(MODEL_BASE_OFF, MODEL_STATUS_ON); + public static final PartModel MODEL_OFF_HAS_CHANNEL = new PartModel(MODEL_BASE_OFF, MODEL_STATUS_HAS_CHANNEL); + public static final PartModel MODEL_ON_OFF = new PartModel(MODEL_BASE_ON, MODEL_STATUS_OFF); + public static final PartModel MODEL_ON_ON = new PartModel(MODEL_BASE_ON, MODEL_STATUS_ON); + public static final PartModel MODEL_ON_HAS_CHANNEL = new PartModel(MODEL_BASE_ON, MODEL_STATUS_HAS_CHANNEL); + + private static final int FLAG_ON = 4; + + private final AppEngInternalAEInventory config = new AppEngInternalAEInventory(this, 1); + + private boolean prevState = false; + + private long lastReportedValue = 0; + private long reportingValue = 0; + + private IStackWatcher myWatcher; + private IEnergyWatcher myEnergyWatcher; + private ICraftingWatcher myCraftingWatcher; + private double centerX; + private double centerY; + private double centerZ; + + @Reflected + public PartLevelEmitter(final ItemStack is) { + super(is); + + this.getConfigManager().registerSetting(Settings.REDSTONE_EMITTER, RedstoneMode.HIGH_SIGNAL); + this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.getConfigManager().registerSetting(Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL); + this.getConfigManager().registerSetting(Settings.CRAFT_VIA_REDSTONE, YesNo.NO); + } + + public long getReportingValue() { + return this.reportingValue; + } + + public void setReportingValue(final long v) { + this.reportingValue = v; + if (this.getConfigManager().getSetting(Settings.LEVEL_TYPE) == LevelType.ENERGY_LEVEL) { + this.configureWatchers(); + } else { + this.updateState(); + } + } + + private void updateState() { + final boolean isOn = this.isLevelEmitterOn(); + if (this.prevState != isOn) { + this.getHost().markForUpdate(); + final TileEntity te = this.getHost().getTile(); + this.prevState = isOn; + Platform.notifyBlocksOfNeighbors(te.getWorld(), te.getPos()); + Platform.notifyBlocksOfNeighbors(te.getWorld(), te.getPos().offset(this.getSide().getFacing())); + } + } + + // TODO: Make private again + public boolean isLevelEmitterOn() { + if (Platform.isClient()) { + return (this.getClientFlags() & FLAG_ON) == FLAG_ON; + } + + if (!this.getProxy().isActive()) { + return false; + } + + if (this.getInstalledUpgrades(Upgrades.CRAFTING) > 0) { + try { + return this.getProxy().getCrafting().isRequesting(this.config.getAEStackInSlot(0)); + } catch (final GridAccessException e) { + // :P + } + + return this.prevState; + } + + final boolean flipState = this.getConfigManager().getSetting(Settings.REDSTONE_EMITTER) == RedstoneMode.LOW_SIGNAL; + return flipState == (this.reportingValue >= this.lastReportedValue + 1); + } + + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange powerEvent) { + if (this.getProxy().isActive()) { + onListUpdate(); + } + this.updateState(); + } + + @Override + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + if (this.getProxy().isActive()) { + onListUpdate(); + } + this.updateState(); + } + + @Override + protected int populateFlags(final int cf) { + return cf | (this.prevState ? FLAG_ON : 0); + } + + @Override + public void updateWatcher(final ICraftingWatcher newWatcher) { + this.myCraftingWatcher = newWatcher; + this.configureWatchers(); + } + + @Override + public void onRequestChange(final ICraftingGrid craftingGrid, final IAEItemStack what) { + this.updateState(); + } + + // update the system... + private void configureWatchers() { + final IAEItemStack myStack = this.config.getAEStackInSlot(0); + + if (this.myWatcher != null) { + this.myWatcher.reset(); + } + + if (this.myEnergyWatcher != null) { + this.myEnergyWatcher.reset(); + } + + if (this.myCraftingWatcher != null) { + this.myCraftingWatcher.reset(); + } + + try { + this.getProxy().getGrid().postEvent(new MENetworkCraftingPatternChange(this, this.getProxy().getNode())); + } catch (final GridAccessException e1) { + // :/ + } + + if (this.getInstalledUpgrades(Upgrades.CRAFTING) > 0) { + if (this.myCraftingWatcher != null && myStack != null) { + this.myCraftingWatcher.add(myStack); + } + + return; + } + + if (this.getConfigManager().getSetting(Settings.LEVEL_TYPE) == LevelType.ENERGY_LEVEL) { + if (this.myEnergyWatcher != null) { + this.myEnergyWatcher.add(this.reportingValue); + } + + try { + // update to power... + this.lastReportedValue = (long) this.getProxy().getEnergy().getStoredPower(); + this.updateState(); + + // no more item stuff.. + this.getProxy().getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)).removeListener(this); + } catch (final GridAccessException e) { + // :P + } + + return; + } + + try { + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0 || myStack == null) { + this.getProxy() + .getStorage() + .getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) + .addListener(this, + this.getProxy().getGrid()); + } else { + this.getProxy().getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)).removeListener(this); + + if (this.myWatcher != null) { + this.myWatcher.add(myStack); + } + } + + this.updateReportingValue(this.getProxy().getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class))); + } catch (final GridAccessException e) { + // >.> + } + } + + private void updateReportingValue(final IMEMonitor monitor) { + final IAEItemStack myStack = this.config.getAEStackInSlot(0); + + if (myStack == null) { + if (monitor instanceof NetworkMonitor) { + this.lastReportedValue = ((NetworkMonitor) monitor).getGridCurrentCount(); + } + } else if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE); + + this.lastReportedValue = 0; + monitor.getStorageList().findFuzzy(myStack, fzMode).forEach(iaeItemStack -> lastReportedValue += iaeItemStack.getStackSize()); + } else { + this.lastReportedValue = 0; + IAEItemStack precise = monitor.getStorageList().findPrecise(myStack); + if (precise != null) lastReportedValue = precise.getStackSize(); + } + this.updateState(); + } + + @Override + public void updateWatcher(final IStackWatcher newWatcher) { + this.myWatcher = newWatcher; + this.configureWatchers(); + } + + @Override + public void onStackChange(final IItemList o, final IAEStack fullStack, final IAEStack diffStack, final IActionSource src, final IStorageChannel chan) { + if (chan == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class) && fullStack.equals(this.config.getAEStackInSlot(0)) && this.getInstalledUpgrades(Upgrades.FUZZY) == 0) { + this.lastReportedValue = fullStack.getStackSize(); + this.updateState(); + } + } + + @Override + public void updateWatcher(final IEnergyWatcher newWatcher) { + this.myEnergyWatcher = newWatcher; + this.configureWatchers(); + } + + @Override + public void onThresholdPass(final IEnergyGrid energyGrid) { + this.lastReportedValue = (long) energyGrid.getStoredPower(); + this.updateState(); + } + + @Override + public boolean isValid(final Object effectiveGrid) { + try { + return this.getProxy().getGrid() == effectiveGrid; + } catch (final GridAccessException e) { + return false; + } + } + + @Override + public void postChange(final IBaseMonitor monitor, final Iterable change, final IActionSource actionSource) { + this.updateReportingValue((IMEMonitor) monitor); + } + + @Override + public void onListUpdate() { + try { + this.updateReportingValue(this.getProxy().getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class))); + } catch (final GridAccessException e) { + // ;P + } + } + + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.SMART; + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(7, 7, 11, 9, 9, 16); + } + + @Override + public int isProvidingStrongPower() { + return this.prevState ? 15 : 0; + } + + @Override + public int isProvidingWeakPower() { + return this.prevState ? 15 : 0; + } + + @Override + public void randomDisplayTick(final World world, final BlockPos pos, final Random r) { + if (this.isLevelEmitterOn()) { + final AEPartLocation d = this.getSide(); + + final double d0 = d.xOffset * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; + final double d1 = d.yOffset * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; + final double d2 = d.zOffset * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; + + world.spawnParticle(EnumParticleTypes.REDSTONE, 0.5 + pos.getX() + d0, 0.5 + pos.getY() + d1, 0.5 + pos.getZ() + d2, 0.0D, 0.0D, 0.0D + ); + } + } + + @Override + public float getCableConnectionLength(AECableType cable) { + return 16; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_LEVEL_EMITTER); + } + return true; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + this.configureWatchers(); + } + + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { + if (inv == this.config) { + this.configureWatchers(); + } + + super.onChangeInventory(inv, slot, mc, removedStack, newStack); + } + + @Override + public void upgradesChanged() { + this.configureWatchers(); + this.updateState(); + } + + @Override + public boolean canConnectRedstone() { + return true; + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.lastReportedValue = data.getLong("lastReportedValue"); + this.reportingValue = data.getLong("reportingValue"); + this.prevState = data.getBoolean("prevState"); + this.config.readFromNBT(data, "config"); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setLong("lastReportedValue", this.lastReportedValue); + data.setLong("reportingValue", this.reportingValue); + data.setBoolean("prevState", this.prevState); + this.config.writeToNBT(data, "config"); + } + + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("config")) { + return this.config; + } + + return super.getInventoryByName(name); + } + + @Override + public boolean pushPattern(final ICraftingPatternDetails patternDetails, final InventoryCrafting table) { + return false; + } + + @Override + public boolean isBusy() { + return true; + } + + @Override + public void provideCrafting(final ICraftingProviderHelper craftingTracker) { + if (this.getInstalledUpgrades(Upgrades.CRAFTING) > 0) { + if (this.getConfigManager().getSetting(Settings.CRAFT_VIA_REDSTONE) == YesNo.YES) { + final IAEItemStack what = this.config.getAEStackInSlot(0); + if (what != null) { + craftingTracker.setEmitable(what); + } + } + } + } + + @Override + public IPartModel getStaticModels() { + if (this.isActive() && this.isPowered()) { + return this.isLevelEmitterOn() ? MODEL_ON_HAS_CHANNEL : MODEL_OFF_HAS_CHANNEL; + } else if (this.isPowered()) { + return this.isLevelEmitterOn() ? MODEL_ON_ON : MODEL_OFF_ON; + } else { + return this.isLevelEmitterOn() ? MODEL_ON_OFF : MODEL_OFF_OFF; + } + } } diff --git a/src/main/java/appeng/parts/automation/PartSharedItemBus.java b/src/main/java/appeng/parts/automation/PartSharedItemBus.java index 782579fb9..3671816fa 100644 --- a/src/main/java/appeng/parts/automation/PartSharedItemBus.java +++ b/src/main/java/appeng/parts/automation/PartSharedItemBus.java @@ -19,13 +19,6 @@ package appeng.parts.automation; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.RedstoneMode; import appeng.api.config.Upgrades; import appeng.api.networking.ticking.IGridTickable; @@ -33,148 +26,129 @@ import appeng.api.networking.ticking.TickRateModulation; import appeng.me.GridAccessException; import appeng.tile.inventory.AppEngInternalAEInventory; import appeng.util.InventoryAdaptor; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.items.IItemHandler; -public abstract class PartSharedItemBus extends PartUpgradeable implements IGridTickable -{ +public abstract class PartSharedItemBus extends PartUpgradeable implements IGridTickable { - private final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, 9 ); - private boolean lastRedstone = false; + private final AppEngInternalAEInventory config = new AppEngInternalAEInventory(this, 9); + private boolean lastRedstone = false; - public PartSharedItemBus( final ItemStack is ) - { - super( is ); - } + public PartSharedItemBus(final ItemStack is) { + super(is); + } - @Override - public void upgradesChanged() - { - this.updateState(); - } + @Override + public void upgradesChanged() { + this.updateState(); + } - @Override - public void readFromNBT( final net.minecraft.nbt.NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.getConfig().readFromNBT( extra, "config" ); - } + @Override + public void readFromNBT(final net.minecraft.nbt.NBTTagCompound extra) { + super.readFromNBT(extra); + this.getConfig().readFromNBT(extra, "config"); + } - @Override - public void writeToNBT( final net.minecraft.nbt.NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.getConfig().writeToNBT( extra, "config" ); - } + @Override + public void writeToNBT(final net.minecraft.nbt.NBTTagCompound extra) { + super.writeToNBT(extra); + this.getConfig().writeToNBT(extra, "config"); + } - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.getConfig(); - } + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("config")) { + return this.getConfig(); + } - return super.getInventoryByName( name ); - } + return super.getInventoryByName(name); + } - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - this.updateState(); - if( this.lastRedstone != this.getHost().hasRedstone( this.getSide() ) ) - { - this.lastRedstone = !this.lastRedstone; - if( this.lastRedstone && this.getRSMode() == RedstoneMode.SIGNAL_PULSE ) - { - this.doBusWork(); - } - } - } + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + this.updateState(); + if (this.lastRedstone != this.getHost().hasRedstone(this.getSide())) { + this.lastRedstone = !this.lastRedstone; + if (this.lastRedstone && this.getRSMode() == RedstoneMode.SIGNAL_PULSE) { + this.doBusWork(); + } + } + } - protected InventoryAdaptor getHandler() - { - final TileEntity self = this.getHost().getTile(); - final TileEntity target = this.getTileEntity( self, self.getPos().offset( this.getSide().getFacing() ) ); + protected InventoryAdaptor getHandler() { + final TileEntity self = this.getHost().getTile(); + final TileEntity target = this.getTileEntity(self, self.getPos().offset(this.getSide().getFacing())); - return InventoryAdaptor.getAdaptor( target, this.getSide().getFacing().getOpposite() ); - } + return InventoryAdaptor.getAdaptor(target, this.getSide().getFacing().getOpposite()); + } - private TileEntity getTileEntity( final TileEntity self, final BlockPos pos ) - { - final World w = self.getWorld(); + private TileEntity getTileEntity(final TileEntity self, final BlockPos pos) { + final World w = self.getWorld(); - if( w.getChunkProvider().getLoadedChunk( pos.getX() >> 4, pos.getZ() >> 4 ) != null ) - { - return w.getTileEntity( pos ); - } + if (w.getChunkProvider().getLoadedChunk(pos.getX() >> 4, pos.getZ() >> 4) != null) { + return w.getTileEntity(pos); + } - return null; - } + return null; + } - protected int availableSlots() - { - return Math.min( 1 + this.getInstalledUpgrades( Upgrades.CAPACITY ) * 4, this.getConfig().getSlots() ); - } + protected int availableSlots() { + return Math.min(1 + this.getInstalledUpgrades(Upgrades.CAPACITY) * 4, this.getConfig().getSlots()); + } - protected int calculateItemsToSend() - { - switch( this.getInstalledUpgrades( Upgrades.SPEED ) ) - { - default: - case 0: - return 1; - case 1: - return 8; - case 2: - return 32; - case 3: - return 64; - case 4: - return 96; - } - } + protected int calculateItemsToSend() { + switch (this.getInstalledUpgrades(Upgrades.SPEED)) { + default: + case 0: + return 1; + case 1: + return 8; + case 2: + return 32; + case 3: + return 64; + case 4: + return 96; + } + } - /** - * Checks if the bus can actually do something. - * - * Currently this tests if the chunk for the target is actually loaded. - * - * @return true, if the the bus should do its work. - */ - protected boolean canDoBusWork() - { - final TileEntity self = this.getHost().getTile(); - final BlockPos selfPos = self.getPos().offset( this.getSide().getFacing() ); - final int xCoordinate = selfPos.getX(); - final int zCoordinate = selfPos.getZ(); - final World world = self.getWorld(); + /** + * Checks if the bus can actually do something. + *

+ * Currently this tests if the chunk for the target is actually loaded. + * + * @return true, if the the bus should do its work. + */ + protected boolean canDoBusWork() { + final TileEntity self = this.getHost().getTile(); + final BlockPos selfPos = self.getPos().offset(this.getSide().getFacing()); + final int xCoordinate = selfPos.getX(); + final int zCoordinate = selfPos.getZ(); + final World world = self.getWorld(); - return world != null && world.getChunkProvider().getLoadedChunk( xCoordinate >> 4, zCoordinate >> 4 ) != null; - } + return world != null && world.getChunkProvider().getLoadedChunk(xCoordinate >> 4, zCoordinate >> 4) != null; + } - private void updateState() - { - try - { - if( !this.isSleeping() ) - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - else - { - this.getProxy().getTick().sleepDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } + private void updateState() { + try { + if (!this.isSleeping()) { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } else { + this.getProxy().getTick().sleepDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } - protected abstract TickRateModulation doBusWork(); + protected abstract TickRateModulation doBusWork(); - AppEngInternalAEInventory getConfig() - { - return this.config; - } + AppEngInternalAEInventory getConfig() { + return this.config; + } } diff --git a/src/main/java/appeng/parts/automation/PartUpgradeable.java b/src/main/java/appeng/parts/automation/PartUpgradeable.java index 42a5776fc..b2d10819b 100644 --- a/src/main/java/appeng/parts/automation/PartUpgradeable.java +++ b/src/main/java/appeng/parts/automation/PartUpgradeable.java @@ -19,11 +19,6 @@ package appeng.parts.automation; -import java.util.List; - -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.RedstoneMode; import appeng.api.config.Upgrades; import appeng.api.util.IConfigManager; @@ -32,140 +27,121 @@ import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; import appeng.util.inv.IAEAppEngInventory; import appeng.util.inv.InvOperation; +import net.minecraft.item.ItemStack; +import net.minecraftforge.items.IItemHandler; + +import java.util.List; -public abstract class PartUpgradeable extends PartBasicState implements IAEAppEngInventory, IConfigManagerHost -{ - private final IConfigManager manager; - private final UpgradeInventory upgrades; +public abstract class PartUpgradeable extends PartBasicState implements IAEAppEngInventory, IConfigManagerHost { + private final IConfigManager manager; + private final UpgradeInventory upgrades; - public PartUpgradeable( final ItemStack is ) - { - super( is ); - this.upgrades = new StackUpgradeInventory( this.getItemStack(), this, this.getUpgradeSlots() ); - this.manager = new ConfigManager( this ); - } + public PartUpgradeable(final ItemStack is) { + super(is); + this.upgrades = new StackUpgradeInventory(this.getItemStack(), this, this.getUpgradeSlots()); + this.manager = new ConfigManager(this); + } - protected int getUpgradeSlots() - { - return 4; - } + protected int getUpgradeSlots() { + return 4; + } - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { - } + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( inv == this.upgrades ) - { - this.upgradesChanged(); - } - } + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { + if (inv == this.upgrades) { + this.upgradesChanged(); + } + } - public void upgradesChanged() - { + public void upgradesChanged() { - } + } - protected boolean isSleeping() - { - if( this.getInstalledUpgrades( Upgrades.REDSTONE ) > 0 ) - { - switch( this.getRSMode() ) - { - case IGNORE: - return false; + protected boolean isSleeping() { + if (this.getInstalledUpgrades(Upgrades.REDSTONE) > 0) { + switch (this.getRSMode()) { + case IGNORE: + return false; - case HIGH_SIGNAL: - if( this.getHost().hasRedstone( this.getSide() ) ) - { - return false; - } + case HIGH_SIGNAL: + if (this.getHost().hasRedstone(this.getSide())) { + return false; + } - break; + break; - case LOW_SIGNAL: - if( !this.getHost().hasRedstone( this.getSide() ) ) - { - return false; - } + case LOW_SIGNAL: + if (!this.getHost().hasRedstone(this.getSide())) { + return false; + } - break; + break; - case SIGNAL_PULSE: - default: - break; - } + case SIGNAL_PULSE: + default: + break; + } - return true; - } + return true; + } - return false; - } + return false; + } - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.upgrades.getInstalledUpgrades( u ); - } + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.upgrades.getInstalledUpgrades(u); + } - @Override - public boolean canConnectRedstone() - { - return this.upgrades.getMaxInstalled( Upgrades.REDSTONE ) > 0; - } + @Override + public boolean canConnectRedstone() { + return this.upgrades.getMaxInstalled(Upgrades.REDSTONE) > 0; + } - @Override - public void readFromNBT( final net.minecraft.nbt.NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.manager.readFromNBT( extra ); - this.upgrades.readFromNBT( extra, "upgrades" ); - } + @Override + public void readFromNBT(final net.minecraft.nbt.NBTTagCompound extra) { + super.readFromNBT(extra); + this.manager.readFromNBT(extra); + this.upgrades.readFromNBT(extra, "upgrades"); + } - @Override - public void writeToNBT( final net.minecraft.nbt.NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.manager.writeToNBT( extra ); - this.upgrades.writeToNBT( extra, "upgrades" ); - } + @Override + public void writeToNBT(final net.minecraft.nbt.NBTTagCompound extra) { + super.writeToNBT(extra); + this.manager.writeToNBT(extra); + this.upgrades.writeToNBT(extra, "upgrades"); + } - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - for( final ItemStack is : this.upgrades ) - { - if( !is.isEmpty() ) - { - drops.add( is ); - } - } - } + @Override + public void getDrops(final List drops, final boolean wrenched) { + for (final ItemStack is : this.upgrades) { + if (!is.isEmpty()) { + drops.add(is); + } + } + } - @Override - public IConfigManager getConfigManager() - { - return this.manager; - } + @Override + public IConfigManager getConfigManager() { + return this.manager; + } - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("upgrades")) { + return this.upgrades; + } - return null; - } + return null; + } - public RedstoneMode getRSMode() - { - return null; - } + public RedstoneMode getRSMode() { + return null; + } } diff --git a/src/main/java/appeng/parts/automation/PlaneBakedModel.java b/src/main/java/appeng/parts/automation/PlaneBakedModel.java index 62a04236b..782b47695 100644 --- a/src/main/java/appeng/parts/automation/PlaneBakedModel.java +++ b/src/main/java/appeng/parts/automation/PlaneBakedModel.java @@ -19,14 +19,8 @@ package appeng.parts.automation; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nullable; - +import appeng.client.render.cablebus.CubeBuilder; import com.google.common.collect.ImmutableList; - import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -36,87 +30,78 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.EnumFacing; -import appeng.client.render.cablebus.CubeBuilder; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; /** * Built-in model for annihilation planes that supports connected textures. */ -public class PlaneBakedModel implements IBakedModel -{ +public class PlaneBakedModel implements IBakedModel { - private final TextureAtlasSprite frontTexture; + private final TextureAtlasSprite frontTexture; - private final List quads; + private final List quads; - PlaneBakedModel( VertexFormat format, TextureAtlasSprite frontTexture, TextureAtlasSprite sidesTexture, TextureAtlasSprite backTexture, PlaneConnections connections ) - { - this.frontTexture = frontTexture; + PlaneBakedModel(VertexFormat format, TextureAtlasSprite frontTexture, TextureAtlasSprite sidesTexture, TextureAtlasSprite backTexture, PlaneConnections connections) { + this.frontTexture = frontTexture; - List quads = new ArrayList<>( 4 * 6 ); + List quads = new ArrayList<>(4 * 6); - CubeBuilder builder = new CubeBuilder( format, quads ); + CubeBuilder builder = new CubeBuilder(format, quads); - builder.setTextures( sidesTexture, sidesTexture, frontTexture, backTexture, sidesTexture, sidesTexture ); + builder.setTextures(sidesTexture, sidesTexture, frontTexture, backTexture, sidesTexture, sidesTexture); - // Keep the orientation of the X axis in mind here. When looking at a quad facing north from the front, - // The X-axis points left - int minX = connections.isRight() ? 0 : 1; - int maxX = connections.isLeft() ? 16 : 15; - int minY = connections.isDown() ? 0 : 1; - int maxY = connections.isUp() ? 16 : 15; + // Keep the orientation of the X axis in mind here. When looking at a quad facing north from the front, + // The X-axis points left + int minX = connections.isRight() ? 0 : 1; + int maxX = connections.isLeft() ? 16 : 15; + int minY = connections.isDown() ? 0 : 1; + int maxY = connections.isUp() ? 16 : 15; - builder.addCube( minX, minY, 0, maxX, maxY, 1 ); + builder.addCube(minX, minY, 0, maxX, maxY, 1); - this.quads = ImmutableList.copyOf( quads ); - } + this.quads = ImmutableList.copyOf(quads); + } - @Override - public List getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) - { - if( side == null ) - { - return this.quads; - } - else - { - return Collections.emptyList(); - } - } + @Override + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + if (side == null) { + return this.quads; + } else { + return Collections.emptyList(); + } + } - @Override - public boolean isAmbientOcclusion() - { - return false; - } + @Override + public boolean isAmbientOcclusion() { + return false; + } - @Override - public boolean isGui3d() - { - return false; - } + @Override + public boolean isGui3d() { + return false; + } - @Override - public boolean isBuiltInRenderer() - { - return false; - } + @Override + public boolean isBuiltInRenderer() { + return false; + } - @Override - public TextureAtlasSprite getParticleTexture() - { - return this.frontTexture; - } + @Override + public TextureAtlasSprite getParticleTexture() { + return this.frontTexture; + } - @Override - public ItemCameraTransforms getItemCameraTransforms() - { - return ItemCameraTransforms.DEFAULT; - } + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return ItemCameraTransforms.DEFAULT; + } - @Override - public ItemOverrideList getOverrides() - { - return ItemOverrideList.NONE; - } + @Override + public ItemOverrideList getOverrides() { + return ItemOverrideList.NONE; + } } diff --git a/src/main/java/appeng/parts/automation/PlaneConnections.java b/src/main/java/appeng/parts/automation/PlaneConnections.java index a5b294815..276505b6b 100644 --- a/src/main/java/appeng/parts/automation/PlaneConnections.java +++ b/src/main/java/appeng/parts/automation/PlaneConnections.java @@ -19,122 +19,106 @@ package appeng.parts.automation; +import com.google.common.base.Strings; + import java.util.ArrayList; import java.util.List; -import com.google.common.base.Strings; - /** * Models in which directions - looking at the front face - a plane (annihilation, formation, etc.) is connected to * other planes of the same type. */ -public final class PlaneConnections -{ +public final class PlaneConnections { - private final boolean up; - private final boolean right; - private final boolean down; - private final boolean left; + private final boolean up; + private final boolean right; + private final boolean down; + private final boolean left; - private static final int BITMASK_UP = 8; - private static final int BITMASK_RIGHT = 4; - private static final int BITMASK_DOWN = 2; - private static final int BITMASK_LEFT = 1; + private static final int BITMASK_UP = 8; + private static final int BITMASK_RIGHT = 4; + private static final int BITMASK_DOWN = 2; + private static final int BITMASK_LEFT = 1; - public static final List PERMUTATIONS = generatePermutations(); + public static final List PERMUTATIONS = generatePermutations(); - private static List generatePermutations() - { - List connections = new ArrayList<>( 16 ); + private static List generatePermutations() { + List connections = new ArrayList<>(16); - for( int i = 0; i < 16; i++ ) - { - boolean up = ( i & BITMASK_UP ) != 0; - boolean right = ( i & BITMASK_RIGHT ) != 0; - boolean down = ( i & BITMASK_DOWN ) != 0; - boolean left = ( i & BITMASK_LEFT ) != 0; + for (int i = 0; i < 16; i++) { + boolean up = (i & BITMASK_UP) != 0; + boolean right = (i & BITMASK_RIGHT) != 0; + boolean down = (i & BITMASK_DOWN) != 0; + boolean left = (i & BITMASK_LEFT) != 0; - connections.add( new PlaneConnections( up, right, down, left ) ); - } + connections.add(new PlaneConnections(up, right, down, left)); + } - return connections; - } + return connections; + } - private PlaneConnections( boolean up, boolean right, boolean down, boolean left ) - { - this.up = up; - this.right = right; - this.down = down; - this.left = left; - } + private PlaneConnections(boolean up, boolean right, boolean down, boolean left) { + this.up = up; + this.right = right; + this.down = down; + this.left = left; + } - public static PlaneConnections of( boolean up, boolean right, boolean down, boolean left ) - { - return PERMUTATIONS.get( getIndex( up, right, down, left ) ); - } + public static PlaneConnections of(boolean up, boolean right, boolean down, boolean left) { + return PERMUTATIONS.get(getIndex(up, right, down, left)); + } - public boolean isUp() - { - return this.up; - } + public boolean isUp() { + return this.up; + } - public boolean isRight() - { - return this.right; - } + public boolean isRight() { + return this.right; + } - public boolean isDown() - { - return this.down; - } + public boolean isDown() { + return this.down; + } - public boolean isLeft() - { - return this.left; - } + public boolean isLeft() { + return this.left; + } - // The combination of connections expressed as a number ranging from [0,15] - public int getIndex() - { - return getIndex( this.up, this.right, this.down, this.left ); - } + // The combination of connections expressed as a number ranging from [0,15] + public int getIndex() { + return getIndex(this.up, this.right, this.down, this.left); + } - private static int getIndex( boolean up, boolean right, boolean down, boolean left ) - { - return ( up ? BITMASK_UP : 0 ) + ( right ? BITMASK_RIGHT : 0 ) + ( left ? BITMASK_LEFT : 0 ) + ( down ? BITMASK_DOWN : 0 ); - } + private static int getIndex(boolean up, boolean right, boolean down, boolean left) { + return (up ? BITMASK_UP : 0) + (right ? BITMASK_RIGHT : 0) + (left ? BITMASK_LEFT : 0) + (down ? BITMASK_DOWN : 0); + } - // Returns a suffix that expresses the connection states as a string - public String getFilenameSuffix() - { - String suffix = Integer.toBinaryString( this.getIndex() ); - return Strings.padStart( suffix, 4, '0' ); - } + // Returns a suffix that expresses the connection states as a string + public String getFilenameSuffix() { + String suffix = Integer.toBinaryString(this.getIndex()); + return Strings.padStart(suffix, 4, '0'); + } - @Override - public boolean equals( Object o ) - { - if( this == o ) - { - return true; - } - if( o == null || this.getClass() != o.getClass() ) - { - return false; - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || this.getClass() != o.getClass()) { + return false; + } - PlaneConnections that = (PlaneConnections) o; - return this.up == that.up && this.right == that.right && this.down == that.down && this.left == that.left; - } + PlaneConnections that = (PlaneConnections) o; + return this.up == that.up && this.right == that.right && this.down == that.down && this.left == that.left; + } - @Override - public int hashCode() - { - int result = ( this.up ? 1 : 0 ); - result = 31 * result + ( this.right ? 1 : 0 ); - result = 31 * result + ( this.down ? 1 : 0 ); - result = 31 * result + ( this.left ? 1 : 0 ); - return result; - } + @Override + public int hashCode() { + int result = (this.up ? 1 : 0); + result = 31 * result + (this.right ? 1 : 0); + result = 31 * result + (this.down ? 1 : 0); + result = 31 * result + (this.left ? 1 : 0); + return result; + } } diff --git a/src/main/java/appeng/parts/automation/PlaneModel.java b/src/main/java/appeng/parts/automation/PlaneModel.java index 43bf6047a..08b230859 100644 --- a/src/main/java/appeng/parts/automation/PlaneModel.java +++ b/src/main/java/appeng/parts/automation/PlaneModel.java @@ -19,12 +19,7 @@ package appeng.parts.automation; -import java.util.Collection; -import java.util.Collections; -import java.util.function.Function; - import com.google.common.collect.Lists; - import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -33,52 +28,50 @@ import net.minecraftforge.client.model.IModel; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; +import java.util.Collection; +import java.util.Collections; +import java.util.function.Function; + /** * Built-in model for annihilation planes that supports connected textures. */ -public class PlaneModel implements IModel -{ +public class PlaneModel implements IModel { - private final ResourceLocation frontTexture; - private final ResourceLocation sidesTexture; - private final ResourceLocation backTexture; - private final PlaneConnections connections; + private final ResourceLocation frontTexture; + private final ResourceLocation sidesTexture; + private final ResourceLocation backTexture; + private final PlaneConnections connections; - public PlaneModel( ResourceLocation frontTexture, ResourceLocation sidesTexture, ResourceLocation backTexture, PlaneConnections connections ) - { - this.frontTexture = frontTexture; - this.sidesTexture = sidesTexture; - this.backTexture = backTexture; - this.connections = connections; - } + public PlaneModel(ResourceLocation frontTexture, ResourceLocation sidesTexture, ResourceLocation backTexture, PlaneConnections connections) { + this.frontTexture = frontTexture; + this.sidesTexture = sidesTexture; + this.backTexture = backTexture; + this.connections = connections; + } - @Override - public Collection getDependencies() - { - return Collections.emptyList(); - } + @Override + public Collection getDependencies() { + return Collections.emptyList(); + } - @Override - public Collection getTextures() - { - return Lists.newArrayList( this.frontTexture, this.sidesTexture, this.backTexture ); - } + @Override + public Collection getTextures() { + return Lists.newArrayList(this.frontTexture, this.sidesTexture, this.backTexture); + } - @Override - public IBakedModel bake( IModelState state, VertexFormat format, Function bakedTextureGetter ) - { - TextureAtlasSprite frontSprite = bakedTextureGetter.apply( this.frontTexture ); - TextureAtlasSprite sidesSprite = bakedTextureGetter.apply( this.sidesTexture ); - TextureAtlasSprite backSprite = bakedTextureGetter.apply( this.backTexture ); + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + TextureAtlasSprite frontSprite = bakedTextureGetter.apply(this.frontTexture); + TextureAtlasSprite sidesSprite = bakedTextureGetter.apply(this.sidesTexture); + TextureAtlasSprite backSprite = bakedTextureGetter.apply(this.backTexture); - return new PlaneBakedModel( format, frontSprite, sidesSprite, backSprite, this.connections ); - } + return new PlaneBakedModel(format, frontSprite, sidesSprite, backSprite, this.connections); + } - @Override - public IModelState getDefaultState() - { - return TRSRTransformation.identity(); - } + @Override + public IModelState getDefaultState() { + return TRSRTransformation.identity(); + } } diff --git a/src/main/java/appeng/parts/automation/PlaneModels.java b/src/main/java/appeng/parts/automation/PlaneModels.java index 9da759be9..615204754 100644 --- a/src/main/java/appeng/parts/automation/PlaneModels.java +++ b/src/main/java/appeng/parts/automation/PlaneModels.java @@ -19,80 +19,68 @@ package appeng.parts.automation; +import appeng.api.parts.IPartModel; +import appeng.core.AppEng; +import appeng.parts.PartModel; +import com.google.common.collect.ImmutableMap; +import net.minecraft.util.ResourceLocation; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import com.google.common.collect.ImmutableMap; - -import net.minecraft.util.ResourceLocation; - -import appeng.api.parts.IPartModel; -import appeng.core.AppEng; -import appeng.parts.PartModel; - /** * Contains a mapping from a Plane's connections to the models to use for that state. */ -public class PlaneModels -{ +public class PlaneModels { - public static final ResourceLocation MODEL_CHASSIS_OFF = new ResourceLocation( AppEng.MOD_ID, "part/transition_plane_off" ); - public static final ResourceLocation MODEL_CHASSIS_ON = new ResourceLocation( AppEng.MOD_ID, "part/transition_plane_on" ); - public static final ResourceLocation MODEL_CHASSIS_HAS_CHANNEL = new ResourceLocation( AppEng.MOD_ID, "part/transition_plane_has_channel" ); + public static final ResourceLocation MODEL_CHASSIS_OFF = new ResourceLocation(AppEng.MOD_ID, "part/transition_plane_off"); + public static final ResourceLocation MODEL_CHASSIS_ON = new ResourceLocation(AppEng.MOD_ID, "part/transition_plane_on"); + public static final ResourceLocation MODEL_CHASSIS_HAS_CHANNEL = new ResourceLocation(AppEng.MOD_ID, "part/transition_plane_has_channel"); - private final Map modelsOff; + private final Map modelsOff; - private final Map modelsOn; + private final Map modelsOn; - private final Map modelsHasChannel; + private final Map modelsHasChannel; - public PlaneModels( String prefixOff, String prefixOn ) - { - Map modelsOff = new HashMap<>(); - Map modelsOn = new HashMap<>(); - Map modelsHasChannel = new HashMap<>(); + public PlaneModels(String prefixOff, String prefixOn) { + Map modelsOff = new HashMap<>(); + Map modelsOn = new HashMap<>(); + Map modelsHasChannel = new HashMap<>(); - for( PlaneConnections permutation : PlaneConnections.PERMUTATIONS ) - { - ResourceLocation planeOff = new ResourceLocation( AppEng.MOD_ID, prefixOff + permutation.getFilenameSuffix() ); - ResourceLocation planeOn = new ResourceLocation( AppEng.MOD_ID, prefixOn + permutation.getFilenameSuffix() ); + for (PlaneConnections permutation : PlaneConnections.PERMUTATIONS) { + ResourceLocation planeOff = new ResourceLocation(AppEng.MOD_ID, prefixOff + permutation.getFilenameSuffix()); + ResourceLocation planeOn = new ResourceLocation(AppEng.MOD_ID, prefixOn + permutation.getFilenameSuffix()); - modelsOff.put( permutation, new PartModel( MODEL_CHASSIS_OFF, planeOff ) ); - modelsOn.put( permutation, new PartModel( MODEL_CHASSIS_ON, planeOff ) ); - modelsHasChannel.put( permutation, new PartModel( MODEL_CHASSIS_HAS_CHANNEL, planeOn ) ); - } + modelsOff.put(permutation, new PartModel(MODEL_CHASSIS_OFF, planeOff)); + modelsOn.put(permutation, new PartModel(MODEL_CHASSIS_ON, planeOff)); + modelsHasChannel.put(permutation, new PartModel(MODEL_CHASSIS_HAS_CHANNEL, planeOn)); + } - this.modelsOff = ImmutableMap.copyOf( modelsOff ); - this.modelsOn = ImmutableMap.copyOf( modelsOn ); - this.modelsHasChannel = ImmutableMap.copyOf( modelsHasChannel ); - } + this.modelsOff = ImmutableMap.copyOf(modelsOff); + this.modelsOn = ImmutableMap.copyOf(modelsOn); + this.modelsHasChannel = ImmutableMap.copyOf(modelsHasChannel); + } - public IPartModel getModel( PlaneConnections connections, boolean hasPower, boolean hasChannel ) - { - if( hasPower && hasChannel ) - { - return this.modelsHasChannel.get( connections ); - } - else if( hasPower ) - { - return this.modelsOn.get( connections ); - } - else - { - return this.modelsOff.get( connections ); - } - } + public IPartModel getModel(PlaneConnections connections, boolean hasPower, boolean hasChannel) { + if (hasPower && hasChannel) { + return this.modelsHasChannel.get(connections); + } else if (hasPower) { + return this.modelsOn.get(connections); + } else { + return this.modelsOff.get(connections); + } + } - public List getModels() - { - List result = new ArrayList<>(); - this.modelsOff.values().forEach( result::add ); - this.modelsOn.values().forEach( result::add ); - this.modelsHasChannel.values().forEach( result::add ); - return result; - } + public List getModels() { + List result = new ArrayList<>(); + this.modelsOff.values().forEach(result::add); + this.modelsOn.values().forEach(result::add); + this.modelsHasChannel.values().forEach(result::add); + return result; + } } diff --git a/src/main/java/appeng/parts/automation/StackUpgradeInventory.java b/src/main/java/appeng/parts/automation/StackUpgradeInventory.java index c99afda08..64b0ead6a 100644 --- a/src/main/java/appeng/parts/automation/StackUpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/StackUpgradeInventory.java @@ -19,36 +19,30 @@ package appeng.parts.automation; -import net.minecraft.item.ItemStack; - import appeng.api.config.Upgrades; import appeng.util.inv.IAEAppEngInventory; +import net.minecraft.item.ItemStack; -public class StackUpgradeInventory extends UpgradeInventory -{ - private final ItemStack stack; +public class StackUpgradeInventory extends UpgradeInventory { + private final ItemStack stack; - public StackUpgradeInventory( final ItemStack stack, final IAEAppEngInventory inventory, final int s ) - { - super( inventory, s ); - this.stack = stack; - } + public StackUpgradeInventory(final ItemStack stack, final IAEAppEngInventory inventory, final int s) { + super(inventory, s); + this.stack = stack; + } - @Override - public int getMaxInstalled( final Upgrades upgrades ) - { - int max = 0; + @Override + public int getMaxInstalled(final Upgrades upgrades) { + int max = 0; - for( final ItemStack is : upgrades.getSupported().keySet() ) - { - if( ItemStack.areItemsEqual( this.stack, is ) ) - { - max = upgrades.getSupported().get( is ); - break; - } - } + for (final ItemStack is : upgrades.getSupported().keySet()) { + if (ItemStack.areItemsEqual(this.stack, is)) { + max = upgrades.getSupported().get(is); + break; + } + } - return max; - } + return max; + } } diff --git a/src/main/java/appeng/parts/automation/UpgradeInventory.java b/src/main/java/appeng/parts/automation/UpgradeInventory.java index e75af7c4b..27d579546 100644 --- a/src/main/java/appeng/parts/automation/UpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/UpgradeInventory.java @@ -19,22 +19,6 @@ package appeng.parts.automation; -import javax.annotation.Nonnull; -import appeng.api.AEApi; -import appeng.container.slot.SlotRestrictedInput; -import appeng.core.Api; -import appeng.helpers.DualityInterface; -import appeng.util.inv.ItemHandlerIterator; -import net.minecraft.client.Minecraft; -import net.minecraft.init.Items; -import net.minecraft.inventory.Slot; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.Upgrades; import appeng.api.implementations.items.IUpgradeModule; import appeng.tile.inventory.AppEngInternalInventory; @@ -42,177 +26,159 @@ import appeng.util.Platform; import appeng.util.inv.IAEAppEngInventory; import appeng.util.inv.InvOperation; import appeng.util.inv.filter.IAEItemFilter; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.items.IItemHandler; -import java.util.ArrayList; -import java.util.List; +import javax.annotation.Nonnull; -public abstract class UpgradeInventory extends AppEngInternalInventory implements IAEAppEngInventory -{ - private final IAEAppEngInventory parent; +public abstract class UpgradeInventory extends AppEngInternalInventory implements IAEAppEngInventory { + private final IAEAppEngInventory parent; - private boolean cached = false; - private int fuzzyUpgrades = 0; - private int speedUpgrades = 0; - private int redstoneUpgrades = 0; - private int capacityUpgrades = 0; - private int inverterUpgrades = 0; - private int craftingUpgrades = 0; - private int patternExpansionUpgrades = 0; + private boolean cached = false; + private int fuzzyUpgrades = 0; + private int speedUpgrades = 0; + private int redstoneUpgrades = 0; + private int capacityUpgrades = 0; + private int inverterUpgrades = 0; + private int craftingUpgrades = 0; + private int patternExpansionUpgrades = 0; - public UpgradeInventory( final IAEAppEngInventory parent, final int s ) - { - super( null, s, 1 ); - this.setTileEntity( this ); - this.parent = parent; - this.setFilter( new UpgradeInvFilter() ); - } + public UpgradeInventory(final IAEAppEngInventory parent, final int s) { + super(null, s, 1); + this.setTileEntity(this); + this.parent = parent; + this.setFilter(new UpgradeInvFilter()); + } - @Override - protected boolean eventsEnabled() - { - return true; - } + @Override + protected boolean eventsEnabled() { + return true; + } - public int getInstalledUpgrades( final Upgrades u ) - { - if( !this.cached ) - { - this.updateUpgradeInfo(); - } + public int getInstalledUpgrades(final Upgrades u) { + if (!this.cached) { + this.updateUpgradeInfo(); + } - switch( u ) - { - case CAPACITY: - return this.capacityUpgrades; - case FUZZY: - return this.fuzzyUpgrades; - case REDSTONE: - return this.redstoneUpgrades; - case SPEED: - return this.speedUpgrades; - case INVERTER: - return this.inverterUpgrades; - case CRAFTING: - return this.craftingUpgrades; - case PATTERN_EXPANSION: - return this.patternExpansionUpgrades; - default: - return 0; - } - } + switch (u) { + case CAPACITY: + return this.capacityUpgrades; + case FUZZY: + return this.fuzzyUpgrades; + case REDSTONE: + return this.redstoneUpgrades; + case SPEED: + return this.speedUpgrades; + case INVERTER: + return this.inverterUpgrades; + case CRAFTING: + return this.craftingUpgrades; + case PATTERN_EXPANSION: + return this.patternExpansionUpgrades; + default: + return 0; + } + } - public abstract int getMaxInstalled( Upgrades upgrades ); + public abstract int getMaxInstalled(Upgrades upgrades); - private void updateUpgradeInfo() - { - this.cached = true; - this.patternExpansionUpgrades = this.inverterUpgrades = this.capacityUpgrades = this.redstoneUpgrades = this.speedUpgrades = this.fuzzyUpgrades = this.craftingUpgrades = 0; + private void updateUpgradeInfo() { + this.cached = true; + this.patternExpansionUpgrades = this.inverterUpgrades = this.capacityUpgrades = this.redstoneUpgrades = this.speedUpgrades = this.fuzzyUpgrades = this.craftingUpgrades = 0; - for( final ItemStack is : this ) - { - if( is == null || is.getItem() == Items.AIR || !( is.getItem() instanceof IUpgradeModule ) ) - { - continue; - } + for (final ItemStack is : this) { + if (is == null || is.getItem() == Items.AIR || !(is.getItem() instanceof IUpgradeModule)) { + continue; + } - final Upgrades myUpgrade = ( (IUpgradeModule) is.getItem() ).getType( is ); - switch( myUpgrade ) - { - case CAPACITY: - this.capacityUpgrades++; - break; - case FUZZY: - this.fuzzyUpgrades++; - break; - case REDSTONE: - this.redstoneUpgrades++; - break; - case SPEED: - this.speedUpgrades++; - break; - case INVERTER: - this.inverterUpgrades++; - break; - case CRAFTING: - this.craftingUpgrades++; - break; - case PATTERN_EXPANSION: - this.patternExpansionUpgrades++; - break; - default: - break; - } - } + final Upgrades myUpgrade = ((IUpgradeModule) is.getItem()).getType(is); + switch (myUpgrade) { + case CAPACITY: + this.capacityUpgrades++; + break; + case FUZZY: + this.fuzzyUpgrades++; + break; + case REDSTONE: + this.redstoneUpgrades++; + break; + case SPEED: + this.speedUpgrades++; + break; + case INVERTER: + this.inverterUpgrades++; + break; + case CRAFTING: + this.craftingUpgrades++; + break; + case PATTERN_EXPANSION: + this.patternExpansionUpgrades++; + break; + default: + break; + } + } - this.capacityUpgrades = Math.min( this.capacityUpgrades, this.getMaxInstalled( Upgrades.CAPACITY ) ); - this.fuzzyUpgrades = Math.min( this.fuzzyUpgrades, this.getMaxInstalled( Upgrades.FUZZY ) ); - this.redstoneUpgrades = Math.min( this.redstoneUpgrades, this.getMaxInstalled( Upgrades.REDSTONE ) ); - this.speedUpgrades = Math.min( this.speedUpgrades, this.getMaxInstalled( Upgrades.SPEED ) ); - this.inverterUpgrades = Math.min( this.inverterUpgrades, this.getMaxInstalled( Upgrades.INVERTER ) ); - this.craftingUpgrades = Math.min( this.craftingUpgrades, this.getMaxInstalled( Upgrades.CRAFTING ) ); - this.patternExpansionUpgrades = Math.min( this.patternExpansionUpgrades, this.getMaxInstalled( Upgrades.PATTERN_EXPANSION ) ); - } + this.capacityUpgrades = Math.min(this.capacityUpgrades, this.getMaxInstalled(Upgrades.CAPACITY)); + this.fuzzyUpgrades = Math.min(this.fuzzyUpgrades, this.getMaxInstalled(Upgrades.FUZZY)); + this.redstoneUpgrades = Math.min(this.redstoneUpgrades, this.getMaxInstalled(Upgrades.REDSTONE)); + this.speedUpgrades = Math.min(this.speedUpgrades, this.getMaxInstalled(Upgrades.SPEED)); + this.inverterUpgrades = Math.min(this.inverterUpgrades, this.getMaxInstalled(Upgrades.INVERTER)); + this.craftingUpgrades = Math.min(this.craftingUpgrades, this.getMaxInstalled(Upgrades.CRAFTING)); + this.patternExpansionUpgrades = Math.min(this.patternExpansionUpgrades, this.getMaxInstalled(Upgrades.PATTERN_EXPANSION)); + } - @Override - public void readFromNBT( final NBTTagCompound target ) - { - super.readFromNBT( target ); - this.updateUpgradeInfo(); - } + @Override + public void readFromNBT(final NBTTagCompound target) { + super.readFromNBT(target); + this.updateUpgradeInfo(); + } - @Override - public void saveChanges() - { - if( this.parent != null ) - { - this.parent.saveChanges(); - } - } + @Override + public void saveChanges() { + if (this.parent != null) { + this.parent.saveChanges(); + } + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - this.cached = false; - if( this.parent != null && Platform.isServer() ) - { - this.parent.onChangeInventory( inv, slot, mc, removedStack, newStack ); - } - } + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { + this.cached = false; + if (this.parent != null && Platform.isServer()) { + this.parent.onChangeInventory(inv, slot, mc, removedStack, newStack); + } + } - @Nonnull - @Override - public ItemStack extractItem( int slot, int amount, boolean simulate ) - { - return super.extractItem( slot, amount, simulate ); - } + @Nonnull + @Override + public ItemStack extractItem(int slot, int amount, boolean simulate) { + return super.extractItem(slot, amount, simulate); + } - private class UpgradeInvFilter implements IAEItemFilter - { + private class UpgradeInvFilter implements IAEItemFilter { - @Override - public boolean allowExtract( IItemHandler inv, int slot, int amount ) - { - return true; - } + @Override + public boolean allowExtract(IItemHandler inv, int slot, int amount) { + return true; + } - @Override - public boolean allowInsert( IItemHandler inv, int slot, ItemStack itemstack ) - { - if( itemstack.isEmpty() ) - { - return false; - } - final Item it = itemstack.getItem(); - if( it instanceof IUpgradeModule ) - { - final Upgrades u = ( (IUpgradeModule) it ).getType( itemstack ); - if( u != null ) - { - return UpgradeInventory.this.getInstalledUpgrades( u ) < UpgradeInventory.this.getMaxInstalled( u ); - } - } - return false; - } - } + @Override + public boolean allowInsert(IItemHandler inv, int slot, ItemStack itemstack) { + if (itemstack.isEmpty()) { + return false; + } + final Item it = itemstack.getItem(); + if (it instanceof IUpgradeModule) { + final Upgrades u = ((IUpgradeModule) it).getType(itemstack); + if (u != null) { + return UpgradeInventory.this.getInstalledUpgrades(u) < UpgradeInventory.this.getMaxInstalled(u); + } + } + return false; + } + } } diff --git a/src/main/java/appeng/parts/misc/ItemHandlerAdapter.java b/src/main/java/appeng/parts/misc/ItemHandlerAdapter.java index 77267e07f..ca4da5c81 100644 --- a/src/main/java/appeng/parts/misc/ItemHandlerAdapter.java +++ b/src/main/java/appeng/parts/misc/ItemHandlerAdapter.java @@ -51,312 +51,254 @@ import java.util.*; /** * Wraps an Item Handler in such a way that it can be used as an IMEInventory for items. */ -class ItemHandlerAdapter implements IMEInventory, IBaseMonitor, ITickingMonitor -{ - private final Object2ObjectMap, Object> listeners = new Object2ObjectOpenHashMap<>(); - private IActionSource mySource; - private final IItemHandler itemHandler; - private final IGridProxyable proxyable; - private final InventoryCache cache; - private StorageFilter mode; - private AccessRestriction access; +class ItemHandlerAdapter implements IMEInventory, IBaseMonitor, ITickingMonitor { + private final Object2ObjectMap, Object> listeners = new Object2ObjectOpenHashMap<>(); + private IActionSource mySource; + private final IItemHandler itemHandler; + private final IGridProxyable proxyable; + private final InventoryCache cache; + private StorageFilter mode; + private AccessRestriction access; - ItemHandlerAdapter( IItemHandler itemHandler, IGridProxyable proxy ) - { - this.itemHandler = itemHandler; - this.proxyable = proxy; - if( this.proxyable instanceof PartStorageBus ) - { - PartStorageBus partStorageBus = (PartStorageBus) this.proxyable; - this.mode = ( (StorageFilter) partStorageBus.getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); - this.access = ( (AccessRestriction) partStorageBus.getConfigManager().getSetting( Settings.ACCESS ) ); - } - this.cache = new InventoryCache( this.itemHandler, this.mode ); - this.cache.update(); - } + ItemHandlerAdapter(IItemHandler itemHandler, IGridProxyable proxy) { + this.itemHandler = itemHandler; + this.proxyable = proxy; + if (this.proxyable instanceof PartStorageBus) { + PartStorageBus partStorageBus = (PartStorageBus) this.proxyable; + this.mode = ((StorageFilter) partStorageBus.getConfigManager().getSetting(Settings.STORAGE_FILTER)); + this.access = ((AccessRestriction) partStorageBus.getConfigManager().getSetting(Settings.ACCESS)); + } + this.cache = new InventoryCache(this.itemHandler, this.mode); + this.cache.update(); + } - @Override - public IAEItemStack injectItems( IAEItemStack iox, Actionable type, IActionSource src ) - { - // Try to reuse the cached stack - ItemStack inputStack = iox.getCachedItemStack( iox.getStackSize() ); + @Override + public IAEItemStack injectItems(IAEItemStack iox, Actionable type, IActionSource src) { + // Try to reuse the cached stack + ItemStack inputStack = iox.getCachedItemStack(iox.getStackSize()); - ItemStack remaining = inputStack; + ItemStack remaining = inputStack; - int slotCount = this.itemHandler.getSlots(); - for( int i = 0; i < slotCount && !remaining.isEmpty(); i++ ) - { - remaining = this.itemHandler.insertItem( i, remaining, type == Actionable.SIMULATE ); - } + int slotCount = this.itemHandler.getSlots(); + for (int i = 0; i < slotCount && !remaining.isEmpty(); i++) { + remaining = this.itemHandler.insertItem(i, remaining, type == Actionable.SIMULATE); + } - // Store the stack in the cache for next time. - if( type == Actionable.SIMULATE ) - { - iox.setCachedItemStack( inputStack ); - } - else - { - if( !remaining.isEmpty() ) - { - iox.setCachedItemStack( remaining ); - } - } + // Store the stack in the cache for next time. + if (type == Actionable.SIMULATE) { + iox.setCachedItemStack(inputStack); + } else { + if (!remaining.isEmpty()) { + iox.setCachedItemStack(remaining); + } + } - // At this point, we still have some items left... - if( remaining == inputStack ) - { - // The stack remained unmodified, target inventory is full - return iox; - } + // At this point, we still have some items left... + if (remaining == inputStack) { + // The stack remained unmodified, target inventory is full + return iox; + } - if( type == Actionable.MODULATE ) - { - IAEItemStack added = iox.copy().setStackSize( iox.getStackSize() - remaining.getCount() ); - this.cache.currentlyCached.add( added ); - this.postDifference( Collections.singletonList( added ) ); - try - { - this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() ); - } - catch( GridAccessException ex ) - { - // meh - } - } + if (type == Actionable.MODULATE) { + IAEItemStack added = iox.copy().setStackSize(iox.getStackSize() - remaining.getCount()); + this.cache.currentlyCached.add(added); + this.postDifference(Collections.singletonList(added)); + try { + this.proxyable.getProxy().getTick().alertDevice(this.proxyable.getProxy().getNode()); + } catch (GridAccessException ex) { + // meh + } + } - return AEItemStack.fromItemStack( remaining ); - } + return AEItemStack.fromItemStack(remaining); + } - @Override - public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src ) - { - int remainingSize = Ints.saturatedCast( request.getStackSize() ); + @Override + public IAEItemStack extractItems(IAEItemStack request, Actionable mode, IActionSource src) { + int remainingSize = Ints.saturatedCast(request.getStackSize()); - // Use this to gather the requested items - ItemStack gathered = ItemStack.EMPTY; + // Use this to gather the requested items + ItemStack gathered = ItemStack.EMPTY; - final boolean simulate = ( mode == Actionable.SIMULATE ); - for( int i = 0; i < this.itemHandler.getSlots(); i++ ) - { - ItemStack stackInInventorySlot = this.itemHandler.getStackInSlot( i ); + final boolean simulate = (mode == Actionable.SIMULATE); + for (int i = 0; i < this.itemHandler.getSlots(); i++) { + ItemStack stackInInventorySlot = this.itemHandler.getStackInSlot(i); - if( !request.isSameType( stackInInventorySlot ) ) - { - continue; - } + if (!request.isSameType(stackInInventorySlot)) { + continue; + } - ItemStack extracted; + ItemStack extracted; - int stackSizeCurrentSlot = stackInInventorySlot.getCount(); - int remainingCurrentSlot = Math.min( remainingSize, stackSizeCurrentSlot ); + int stackSizeCurrentSlot = stackInInventorySlot.getCount(); + int remainingCurrentSlot = Math.min(remainingSize, stackSizeCurrentSlot); - // We have to loop here because according to the docs, the handler shouldn't return a stack with size > - // maxSize, even if we request more. So even if it returns a valid stack, it might have more stuff. - do - { - extracted = this.itemHandler.extractItem( i, remainingCurrentSlot, simulate ); - if( !extracted.isEmpty() ) - { - // In order to guard against broken IItemHandler implementations, we'll try to guess if the returned - // stack (especially in simulate mode) is the same that was returned by getStackInSlot. This is - // obviously not a precise science, but it would catch the previous Forge bug: - // https://github.com/MinecraftForge/MinecraftForge/pull/6580 - if( extracted == stackInInventorySlot ) - { - extracted = extracted.copy(); - } + // We have to loop here because according to the docs, the handler shouldn't return a stack with size > + // maxSize, even if we request more. So even if it returns a valid stack, it might have more stuff. + do { + extracted = this.itemHandler.extractItem(i, remainingCurrentSlot, simulate); + if (!extracted.isEmpty()) { + // In order to guard against broken IItemHandler implementations, we'll try to guess if the returned + // stack (especially in simulate mode) is the same that was returned by getStackInSlot. This is + // obviously not a precise science, but it would catch the previous Forge bug: + // https://github.com/MinecraftForge/MinecraftForge/pull/6580 + if (extracted == stackInInventorySlot) { + extracted = extracted.copy(); + } - if( extracted.getCount() > remainingCurrentSlot ) - { - // Something broke. It should never return more than we requested... - // We're going to silently eat the remainder - AELog.warn( "Mod that provided item handler %s is broken. Returned %s items while only requesting %d.", this.itemHandler.getClass().getName(), extracted.toString(), remainingCurrentSlot ); - extracted.setCount( remainingCurrentSlot ); - } + if (extracted.getCount() > remainingCurrentSlot) { + // Something broke. It should never return more than we requested... + // We're going to silently eat the remainder + AELog.warn("Mod that provided item handler %s is broken. Returned %s items while only requesting %d.", this.itemHandler.getClass().getName(), extracted.toString(), remainingCurrentSlot); + extracted.setCount(remainingCurrentSlot); + } - // Heuristic for simulation: looping in case of simulations is pointless, since the state of the - // underlying inventory does not change after a simulated extraction. To still support inventories - // that report stacks that are larger than maxStackSize, we use this heuristic - if( simulate && extracted.getCount() == extracted.getMaxStackSize() && remainingCurrentSlot > extracted.getMaxStackSize() ) - { - extracted.setCount( remainingCurrentSlot ); - } + // Heuristic for simulation: looping in case of simulations is pointless, since the state of the + // underlying inventory does not change after a simulated extraction. To still support inventories + // that report stacks that are larger than maxStackSize, we use this heuristic + if (simulate && extracted.getCount() == extracted.getMaxStackSize() && remainingCurrentSlot > extracted.getMaxStackSize()) { + extracted.setCount(remainingCurrentSlot); + } - if( gathered.isEmpty() ) - { - gathered = extracted; - } - else - { - gathered.grow( extracted.getCount() ); - } - remainingCurrentSlot -= extracted.getCount(); - } - } while ( !simulate && !extracted.isEmpty() && remainingCurrentSlot > 0 ); + if (gathered.isEmpty()) { + gathered = extracted; + } else { + gathered.grow(extracted.getCount()); + } + remainingCurrentSlot -= extracted.getCount(); + } + } while (!simulate && !extracted.isEmpty() && remainingCurrentSlot > 0); - remainingSize -= stackSizeCurrentSlot - remainingCurrentSlot; - if( remainingSize <= 0 ) - { - break; - } - } + remainingSize -= stackSizeCurrentSlot - remainingCurrentSlot; + if (remainingSize <= 0) { + break; + } + } - if( !gathered.isEmpty() ) - { - IAEItemStack gatheredAEItemStack = AEItemStack.fromItemStack( gathered ); - if( mode == Actionable.MODULATE ) - { - IAEItemStack cachedStack = this.cache.currentlyCached.findPrecise( request ); - if( cachedStack != null ) - { - cachedStack.decStackSize( gatheredAEItemStack.getStackSize() ); - this.postDifference( Collections.singletonList( gatheredAEItemStack.copy().setStackSize( -gatheredAEItemStack.getStackSize() ) ) ); - } - try - { - this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() ); - } - catch( GridAccessException ex ) - { - // meh - } - } + if (!gathered.isEmpty()) { + IAEItemStack gatheredAEItemStack = AEItemStack.fromItemStack(gathered); + if (mode == Actionable.MODULATE) { + IAEItemStack cachedStack = this.cache.currentlyCached.findPrecise(request); + if (cachedStack != null) { + cachedStack.decStackSize(gatheredAEItemStack.getStackSize()); + this.postDifference(Collections.singletonList(gatheredAEItemStack.copy().setStackSize(-gatheredAEItemStack.getStackSize()))); + } + try { + this.proxyable.getProxy().getTick().alertDevice(this.proxyable.getProxy().getNode()); + } catch (GridAccessException ex) { + // meh + } + } - return gatheredAEItemStack; - } + return gatheredAEItemStack; + } - return null; - } + return null; + } - @Override - public TickRateModulation onTick() - { - List changes = this.cache.update(); - if( !changes.isEmpty() && access.hasPermission( AccessRestriction.READ ) ) - { - this.postDifference( changes ); - return TickRateModulation.URGENT; - } - else - { - return TickRateModulation.SLOWER; - } - } + @Override + public TickRateModulation onTick() { + List changes = this.cache.update(); + if (!changes.isEmpty() && access.hasPermission(AccessRestriction.READ)) { + this.postDifference(changes); + return TickRateModulation.URGENT; + } else { + return TickRateModulation.SLOWER; + } + } - @Override - public void setActionSource( final IActionSource mySource ) - { - this.mySource = mySource; - } + @Override + public void setActionSource(final IActionSource mySource) { + this.mySource = mySource; + } - @Override - public IItemList getAvailableItems( IItemList out ) - { - return this.cache.getAvailableItems( out ); - } + @Override + public IItemList getAvailableItems(IItemList out) { + return this.cache.getAvailableItems(out); + } - @Override - public IItemStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IItemStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } - private void postDifference( Iterable a ) - { - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while ( i.hasNext() ) - { - final Map.Entry, Object> l = i.next(); - final IMEMonitorHandlerReceiver key = l.getKey(); - if( key.isValid( l.getValue() ) ) - { - key.postChange( this, a, this.mySource ); - } - else - { - i.remove(); - } - } - } + private void postDifference(Iterable a) { + final Iterator, Object>> i = this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Map.Entry, Object> l = i.next(); + final IMEMonitorHandlerReceiver key = l.getKey(); + if (key.isValid(l.getValue())) { + key.postChange(this, a, this.mySource); + } else { + i.remove(); + } + } + } - private static class InventoryCache implements Iterable - { - private final IItemHandler itemHandler; - private final StorageFilter mode; - IItemList currentlyCached = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); + private static class InventoryCache implements Iterable { + private final IItemHandler itemHandler; + private final StorageFilter mode; + IItemList currentlyCached = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); - public InventoryCache( IItemHandler itemHandler, StorageFilter mode ) - { - this.mode = mode; - this.itemHandler = itemHandler; - } + public InventoryCache(IItemHandler itemHandler, StorageFilter mode) { + this.mode = mode; + this.itemHandler = itemHandler; + } - public IItemList getAvailableItems( IItemList out ) - { - currentlyCached.iterator().forEachRemaining( out::add ); - return out; - } + public IItemList getAvailableItems(IItemList out) { + currentlyCached.iterator().forEachRemaining(out::add); + return out; + } - private StorageFilter getMode() - { - return this.mode; - } + private StorageFilter getMode() { + return this.mode; + } - public List update() - { - final List changes = new ArrayList<>(); + public List update() { + final List changes = new ArrayList<>(); - IItemList currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); + IItemList currentlyOnStorage = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); - for( final ItemSlot is : this ) - { - if( this.mode == StorageFilter.EXTRACTABLE_ONLY && !is.isExtractable() ) - { - continue; - } - currentlyOnStorage.add( is.getAEItemStack() ); - } + for (final ItemSlot is : this) { + if (this.mode == StorageFilter.EXTRACTABLE_ONLY && !is.isExtractable()) { + continue; + } + currentlyOnStorage.add(is.getAEItemStack()); + } - for( final IAEItemStack is : currentlyCached ) - { - is.setStackSize( -is.getStackSize() ); - } + for (final IAEItemStack is : currentlyCached) { + is.setStackSize(-is.getStackSize()); + } - for( final IAEItemStack is : currentlyOnStorage ) - { - currentlyCached.add( is ); - } + for (final IAEItemStack is : currentlyOnStorage) { + currentlyCached.add(is); + } - for( final IAEItemStack is : currentlyCached ) - { - if( is.getStackSize() != 0 ) - { - changes.add( is ); - } - } + for (final IAEItemStack is : currentlyCached) { + if (is.getStackSize() != 0) { + changes.add(is); + } + } - currentlyCached = currentlyOnStorage; + currentlyCached = currentlyOnStorage; - return changes; - } + return changes; + } - @Override - public Iterator iterator() - { - return new ItemHandlerIterator( this.itemHandler ); - } + @Override + public Iterator iterator() { + return new ItemHandlerIterator(this.itemHandler); + } - } + } } diff --git a/src/main/java/appeng/parts/misc/ItemRepositoryAdapter.java b/src/main/java/appeng/parts/misc/ItemRepositoryAdapter.java index 196aa0eab..d68345cb2 100644 --- a/src/main/java/appeng/parts/misc/ItemRepositoryAdapter.java +++ b/src/main/java/appeng/parts/misc/ItemRepositoryAdapter.java @@ -1,6 +1,5 @@ package appeng.parts.misc; -import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -33,227 +32,184 @@ import java.util.*; * Used by the Storage Bus */ -class ItemRepositoryAdapter implements IMEInventory, IBaseMonitor, ITickingMonitor -{ - private final Object2ObjectMap, Object> listeners = new Object2ObjectOpenHashMap<>(); - private IActionSource mySource; - private final IItemRepository itemRepository; - private final IGridProxyable proxyable; - private final InventoryCache cache; - private AccessRestriction access; +class ItemRepositoryAdapter implements IMEInventory, IBaseMonitor, ITickingMonitor { + private final Object2ObjectMap, Object> listeners = new Object2ObjectOpenHashMap<>(); + private IActionSource mySource; + private final IItemRepository itemRepository; + private final IGridProxyable proxyable; + private final InventoryCache cache; + private AccessRestriction access; - ItemRepositoryAdapter( IItemRepository itemRepository, IGridProxyable proxy ) - { - this.itemRepository = itemRepository; - this.proxyable = proxy; - this.cache = new InventoryCache( this.itemRepository ); - if( this.proxyable instanceof PartStorageBus ) - { - PartStorageBus partStorageBus = (PartStorageBus) this.proxyable; - this.access = ( (AccessRestriction) partStorageBus.getConfigManager().getSetting( Settings.ACCESS ) ); - } - this.cache.update(); - } + ItemRepositoryAdapter(IItemRepository itemRepository, IGridProxyable proxy) { + this.itemRepository = itemRepository; + this.proxyable = proxy; + this.cache = new InventoryCache(this.itemRepository); + if (this.proxyable instanceof PartStorageBus) { + PartStorageBus partStorageBus = (PartStorageBus) this.proxyable; + this.access = ((AccessRestriction) partStorageBus.getConfigManager().getSetting(Settings.ACCESS)); + } + this.cache.update(); + } - @Override - public IAEItemStack injectItems( IAEItemStack iox, Actionable type, IActionSource src ) - { - // Try to reuse the cached stack - ItemStack inputStack = iox.getCachedItemStack( iox.getStackSize() ); + @Override + public IAEItemStack injectItems(IAEItemStack iox, Actionable type, IActionSource src) { + // Try to reuse the cached stack + ItemStack inputStack = iox.getCachedItemStack(iox.getStackSize()); - ItemStack remaining; + ItemStack remaining; - remaining = this.itemRepository.insertItem( inputStack, type == Actionable.SIMULATE ); + remaining = this.itemRepository.insertItem(inputStack, type == Actionable.SIMULATE); - // Store the stack in the cache for next time. - if( type == Actionable.SIMULATE ) - { - iox.setCachedItemStack( inputStack ); - } - else - { - if( !remaining.isEmpty() ) - { - iox.setCachedItemStack( remaining ); - } - } + // Store the stack in the cache for next time. + if (type == Actionable.SIMULATE) { + iox.setCachedItemStack(inputStack); + } else { + if (!remaining.isEmpty()) { + iox.setCachedItemStack(remaining); + } + } - // At this point, we still have some items left... - if( remaining == inputStack ) - { - // The stack remained unmodified, target inventory is full - return iox; - } + // At this point, we still have some items left... + if (remaining == inputStack) { + // The stack remained unmodified, target inventory is full + return iox; + } - if( type == Actionable.MODULATE ) - { - IAEItemStack added = iox.copy().setStackSize( iox.getStackSize() - remaining.getCount() ); - this.cache.currentlyCached.add( added ); - this.postDifference( Collections.singletonList( added ) ); - try - { - this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() ); - } - catch( GridAccessException ex ) - { - // meh - } - } + if (type == Actionable.MODULATE) { + IAEItemStack added = iox.copy().setStackSize(iox.getStackSize() - remaining.getCount()); + this.cache.currentlyCached.add(added); + this.postDifference(Collections.singletonList(added)); + try { + this.proxyable.getProxy().getTick().alertDevice(this.proxyable.getProxy().getNode()); + } catch (GridAccessException ex) { + // meh + } + } - return AEItemStack.fromItemStack( remaining ); + return AEItemStack.fromItemStack(remaining); - } + } - @Override - public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src ) - { - int remainingSize = Ints.saturatedCast( request.getStackSize() ); + @Override + public IAEItemStack extractItems(IAEItemStack request, Actionable mode, IActionSource src) { + int remainingSize = Ints.saturatedCast(request.getStackSize()); - final boolean simulate = ( mode == Actionable.SIMULATE ); + final boolean simulate = (mode == Actionable.SIMULATE); - ItemStack extracted = this.itemRepository.extractItem( request.getDefinition(), remainingSize, simulate ); + ItemStack extracted = this.itemRepository.extractItem(request.getDefinition(), remainingSize, simulate); - if( extracted.getCount() > remainingSize ) - { - // Something broke. It should never return more than we requested... - // We're going to silently eat the remainder - AELog.warn( "Mod that provided item handler %s is broken. Returned %s items while only requesting %d.", this.itemRepository.getClass().getName(), extracted.toString(), remainingSize ); - extracted.setCount( remainingSize ); - } + if (extracted.getCount() > remainingSize) { + // Something broke. It should never return more than we requested... + // We're going to silently eat the remainder + AELog.warn("Mod that provided item handler %s is broken. Returned %s items while only requesting %d.", this.itemRepository.getClass().getName(), extracted.toString(), remainingSize); + extracted.setCount(remainingSize); + } - if( !extracted.isEmpty() ) - { - IAEItemStack extractedAEItemStack = AEItemStack.fromItemStack( extracted ); - if( mode == Actionable.MODULATE ) - { - IAEItemStack cachedStack = this.cache.currentlyCached.findPrecise( request ); - if( cachedStack != null ) - { - cachedStack.decStackSize( extractedAEItemStack.getStackSize() ); - this.postDifference( Collections.singletonList( extractedAEItemStack.copy().setStackSize( -extractedAEItemStack.getStackSize() ) ) ); - } - try - { - this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() ); - } - catch( GridAccessException ex ) - { - // meh - } - } - return extractedAEItemStack; - } - return null; - } + if (!extracted.isEmpty()) { + IAEItemStack extractedAEItemStack = AEItemStack.fromItemStack(extracted); + if (mode == Actionable.MODULATE) { + IAEItemStack cachedStack = this.cache.currentlyCached.findPrecise(request); + if (cachedStack != null) { + cachedStack.decStackSize(extractedAEItemStack.getStackSize()); + this.postDifference(Collections.singletonList(extractedAEItemStack.copy().setStackSize(-extractedAEItemStack.getStackSize()))); + } + try { + this.proxyable.getProxy().getTick().alertDevice(this.proxyable.getProxy().getNode()); + } catch (GridAccessException ex) { + // meh + } + } + return extractedAEItemStack; + } + return null; + } - @Override - public IItemList getAvailableItems( IItemList out ) - { - return this.cache.getAvailableItems( out ); - } + @Override + public IItemList getAvailableItems(IItemList out) { + return this.cache.getAvailableItems(out); + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } - @Override - public void addListener( IMEMonitorHandlerReceiver l, Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } + @Override + public void addListener(IMEMonitorHandlerReceiver l, Object verificationToken) { + this.listeners.put(l, verificationToken); + } - @Override - public void removeListener( IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } + @Override + public void removeListener(IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } - private void postDifference( Iterable a ) - { - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while ( i.hasNext() ) - { - final Map.Entry, Object> l = i.next(); - final IMEMonitorHandlerReceiver key = l.getKey(); - if( key.isValid( l.getValue() ) ) - { - key.postChange( this, a, this.mySource ); - } - else - { - i.remove(); - } - } - } + private void postDifference(Iterable a) { + final Iterator, Object>> i = this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Map.Entry, Object> l = i.next(); + final IMEMonitorHandlerReceiver key = l.getKey(); + if (key.isValid(l.getValue())) { + key.postChange(this, a, this.mySource); + } else { + i.remove(); + } + } + } - @Override - public TickRateModulation onTick() - { - List changes = this.cache.update(); - if( !changes.isEmpty() && access.hasPermission( AccessRestriction.READ ) ) - { - this.postDifference( changes ); - return TickRateModulation.URGENT; - } - else - { - return TickRateModulation.SLOWER; - } - } + @Override + public TickRateModulation onTick() { + List changes = this.cache.update(); + if (!changes.isEmpty() && access.hasPermission(AccessRestriction.READ)) { + this.postDifference(changes); + return TickRateModulation.URGENT; + } else { + return TickRateModulation.SLOWER; + } + } - @Override - public void setActionSource( final IActionSource mySource ) - { - this.mySource = mySource; - } + @Override + public void setActionSource(final IActionSource mySource) { + this.mySource = mySource; + } - private static class InventoryCache - { - private IItemList currentlyCached = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - private final IItemRepository iItemRepository; + private static class InventoryCache { + private IItemList currentlyCached = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + private final IItemRepository iItemRepository; - public InventoryCache( IItemRepository iItemRepository ) - { - this.iItemRepository = iItemRepository; - } + public InventoryCache(IItemRepository iItemRepository) { + this.iItemRepository = iItemRepository; + } - public IItemList getAvailableItems( IItemList out ) - { - currentlyCached.iterator().forEachRemaining( out::add ); - return out; - } + public IItemList getAvailableItems(IItemList out) { + currentlyCached.iterator().forEachRemaining(out::add); + return out; + } - public List update() - { - final List changes = new ArrayList<>(); + public List update() { + final List changes = new ArrayList<>(); - IItemList currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - this.iItemRepository.getAllItems().stream().map( s -> AEItemStack.fromItemStack( s.itemPrototype ).setStackSize( s.count ) ).forEach( currentlyOnStorage::add ); + IItemList currentlyOnStorage = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + this.iItemRepository.getAllItems().stream().map(s -> AEItemStack.fromItemStack(s.itemPrototype).setStackSize(s.count)).forEach(currentlyOnStorage::add); - for( final IAEItemStack is : currentlyCached ) - { - is.setStackSize( -is.getStackSize() ); - } + for (final IAEItemStack is : currentlyCached) { + is.setStackSize(-is.getStackSize()); + } - for( final IAEItemStack is : currentlyOnStorage ) - { - currentlyCached.add( is ); - } + for (final IAEItemStack is : currentlyOnStorage) { + currentlyCached.add(is); + } - for( final IAEItemStack is : currentlyCached ) - { - if( is.getStackSize() != 0 ) - { - changes.add( is ); - } - } + for (final IAEItemStack is : currentlyCached) { + if (is.getStackSize() != 0) { + changes.add(is); + } + } - currentlyCached = currentlyOnStorage; + currentlyCached = currentlyOnStorage; - return changes; - } + return changes; + } - } + } } diff --git a/src/main/java/appeng/parts/misc/PartCableAnchor.java b/src/main/java/appeng/parts/misc/PartCableAnchor.java index a77201714..4e677ea63 100644 --- a/src/main/java/appeng/parts/misc/PartCableAnchor.java +++ b/src/main/java/appeng/parts/misc/PartCableAnchor.java @@ -19,12 +19,14 @@ package appeng.parts.misc; -import java.io.IOException; -import java.util.List; -import java.util.Random; - +import appeng.api.networking.IGridNode; +import appeng.api.parts.*; +import appeng.api.util.AECableType; +import appeng.api.util.AEPartLocation; +import appeng.core.AppEng; +import appeng.items.parts.PartModels; +import appeng.parts.PartModel; import io.netty.buffer.ByteBuf; - import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -38,219 +40,174 @@ import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import appeng.api.networking.IGridNode; -import appeng.api.parts.BusSupport; -import appeng.api.parts.IPart; -import appeng.api.parts.IPartCollisionHelper; -import appeng.api.parts.IPartHost; -import appeng.api.parts.IPartModel; -import appeng.api.parts.PartItemStack; -import appeng.api.util.AECableType; -import appeng.api.util.AEPartLocation; -import appeng.core.AppEng; -import appeng.items.parts.PartModels; -import appeng.parts.PartModel; +import java.io.IOException; +import java.util.List; +import java.util.Random; -public class PartCableAnchor implements IPart -{ +public class PartCableAnchor implements IPart { - @PartModels - public static final PartModel DEFAULT_MODELS = new PartModel( false, new ResourceLocation( AppEng.MOD_ID, "part/cable_anchor" ) ); + @PartModels + public static final PartModel DEFAULT_MODELS = new PartModel(false, new ResourceLocation(AppEng.MOD_ID, "part/cable_anchor")); - @PartModels - public static final PartModel FACADE_MODELS = new PartModel( false, new ResourceLocation( AppEng.MOD_ID, "part/cable_anchor_short" ) ); + @PartModels + public static final PartModel FACADE_MODELS = new PartModel(false, new ResourceLocation(AppEng.MOD_ID, "part/cable_anchor_short")); - private ItemStack is = ItemStack.EMPTY; - private IPartHost host = null; - private AEPartLocation mySide = AEPartLocation.UP; + private ItemStack is = ItemStack.EMPTY; + private IPartHost host = null; + private AEPartLocation mySide = AEPartLocation.UP; - public PartCableAnchor( final ItemStack is ) - { - this.is = is; - } + public PartCableAnchor(final ItemStack is) { + this.is = is; + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - if( this.host != null && this.host.getFacadeContainer().getFacade( this.mySide ) != null ) - { - bch.addBox( 7, 7, 10, 9, 9, 14 ); - } - else - { - bch.addBox( 7, 7, 10, 9, 9, 16 ); - } - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + if (this.host != null && this.host.getFacadeContainer().getFacade(this.mySide) != null) { + bch.addBox(7, 7, 10, 9, 9, 14); + } else { + bch.addBox(7, 7, 10, 9, 9, 16); + } + } - @Override - public ItemStack getItemStack( final PartItemStack wrenched ) - { - return this.is; - } + @Override + public ItemStack getItemStack(final PartItemStack wrenched) { + return this.is; + } - @Override - public boolean requireDynamicRender() - { - return false; - } + @Override + public boolean requireDynamicRender() { + return false; + } - @Override - public boolean isSolid() - { - return false; - } + @Override + public boolean isSolid() { + return false; + } - @Override - public boolean canConnectRedstone() - { - return false; - } + @Override + public boolean canConnectRedstone() { + return false; + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { + @Override + public void writeToNBT(final NBTTagCompound data) { - } + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { + @Override + public void readFromNBT(final NBTTagCompound data) { - } + } - @Override - public int getLightLevel() - { - return 0; - } + @Override + public int getLightLevel() { + return 0; + } - @Override - public boolean isLadder( final EntityLivingBase entity ) - { - return this.mySide.yOffset == 0 && ( entity.collidedHorizontally || !entity.onGround ); - } + @Override + public boolean isLadder(final EntityLivingBase entity) { + return this.mySide.yOffset == 0 && (entity.collidedHorizontally || !entity.onGround); + } - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { - } + } - @Override - public int isProvidingStrongPower() - { - return 0; - } + @Override + public int isProvidingStrongPower() { + return 0; + } - @Override - public int isProvidingWeakPower() - { - return 0; - } + @Override + public int isProvidingWeakPower() { + return 0; + } - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { + @Override + public void writeToStream(final ByteBuf data) throws IOException { - } + } - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - return false; - } + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + return false; + } - @Override - public IGridNode getGridNode() - { - return null; - } + @Override + public IGridNode getGridNode() { + return null; + } - @Override - public void onEntityCollision( final Entity entity ) - { + @Override + public void onEntityCollision(final Entity entity) { - } + } - @Override - public void removeFromWorld() - { + @Override + public void removeFromWorld() { - } + } - @Override - public void addToWorld() - { + @Override + public void addToWorld() { - } + } - @Override - public IGridNode getExternalFacingNode() - { - return null; - } + @Override + public IGridNode getExternalFacingNode() { + return null; + } - @Override - public void setPartHostInfo( final AEPartLocation side, final IPartHost host, final TileEntity tile ) - { - this.host = host; - this.mySide = side; - } + @Override + public void setPartHostInfo(final AEPartLocation side, final IPartHost host, final TileEntity tile) { + this.host = host; + this.mySide = side; + } - @Override - public boolean onActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - return false; - } + @Override + public boolean onActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + return false; + } - @Override - public boolean onShiftActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - return false; - } + @Override + public boolean onShiftActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + return false; + } - @Override - public void getDrops( final List drops, final boolean wrenched ) - { + @Override + public void getDrops(final List drops, final boolean wrenched) { - } + } - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 0; - } + @Override + public float getCableConnectionLength(AECableType cable) { + return 0; + } - @Override - public void randomDisplayTick( final World world, final BlockPos pos, final Random r ) - { + @Override + public void randomDisplayTick(final World world, final BlockPos pos, final Random r) { - } + } - @Override - public void onPlacement( final EntityPlayer player, final EnumHand hand, final ItemStack held, final AEPartLocation side ) - { + @Override + public void onPlacement(final EntityPlayer player, final EnumHand hand, final ItemStack held, final AEPartLocation side) { - } + } - @Override - public boolean canBePlacedOn( final BusSupport what ) - { - return what == BusSupport.CABLE || what == BusSupport.DENSE_CABLE; - } + @Override + public boolean canBePlacedOn(final BusSupport what) { + return what == BusSupport.CABLE || what == BusSupport.DENSE_CABLE; + } - @Override - public IPartModel getStaticModels() - { - if( this.host != null && this.host.getFacadeContainer().getFacade( this.mySide ) != null ) - { - return FACADE_MODELS; - } - else - { - return DEFAULT_MODELS; - } - } + @Override + public IPartModel getStaticModels() { + if (this.host != null && this.host.getFacadeContainer().getFacade(this.mySide) != null) { + return FACADE_MODELS; + } else { + return DEFAULT_MODELS; + } + } } diff --git a/src/main/java/appeng/parts/misc/PartInterface.java b/src/main/java/appeng/parts/misc/PartInterface.java index 05f18f826..1e9e6f61f 100644 --- a/src/main/java/appeng/parts/misc/PartInterface.java +++ b/src/main/java/appeng/parts/misc/PartInterface.java @@ -19,23 +19,6 @@ package appeng.parts.misc; -import java.util.EnumSet; -import java.util.List; - -import com.google.common.collect.ImmutableSet; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.Vec3d; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.Upgrades; @@ -71,252 +54,225 @@ import appeng.util.Platform; import appeng.util.inv.IAEAppEngInventory; import appeng.util.inv.IInventoryDestination; import appeng.util.inv.InvOperation; +import com.google.common.collect.ImmutableSet; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.Vec3d; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.items.IItemHandler; + +import java.util.EnumSet; +import java.util.List; -public class PartInterface extends PartBasicState implements IGridTickable, IStorageMonitorable, IInventoryDestination, IInterfaceHost, IAEAppEngInventory, IPriorityHost -{ +public class PartInterface extends PartBasicState implements IGridTickable, IStorageMonitorable, IInventoryDestination, IInterfaceHost, IAEAppEngInventory, IPriorityHost { - public static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "part/interface_base" ); + public static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "part/interface_base"); - @PartModels - public static final PartModel MODELS_OFF = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/interface_off" ) ); + @PartModels + public static final PartModel MODELS_OFF = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/interface_off")); - @PartModels - public static final PartModel MODELS_ON = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/interface_on" ) ); + @PartModels + public static final PartModel MODELS_ON = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/interface_on")); - @PartModels - public static final PartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/interface_has_channel" ) ); + @PartModels + public static final PartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/interface_has_channel")); - private final DualityInterface duality = new DualityInterface( this.getProxy(), this ); + private final DualityInterface duality = new DualityInterface(this.getProxy(), this); - @Reflected - public PartInterface( final ItemStack is ) - { - super( is ); - } + @Reflected + public PartInterface(final ItemStack is) { + super(is); + } - @Override - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - this.duality.notifyNeighbors(); - } + @Override + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + this.duality.notifyNeighbors(); + } - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.duality.notifyNeighbors(); - } + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.duality.notifyNeighbors(); + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 2, 2, 14, 14, 14, 16 ); - bch.addBox( 5, 5, 12, 11, 11, 14 ); - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + bch.addBox(5, 5, 12, 11, 11, 14); + } - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.duality.getInstalledUpgrades( u ); - } + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.duality.getInstalledUpgrades(u); + } - @Override - public void gridChanged() - { - this.duality.gridChanged(); - } + @Override + public void gridChanged() { + this.duality.gridChanged(); + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.duality.readFromNBT( data ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.duality.readFromNBT(data); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.duality.writeToNBT( data ); - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.duality.writeToNBT(data); + } - @Override - public void addToWorld() - { - super.addToWorld(); - this.duality.initialize(); - } + @Override + public void addToWorld() { + super.addToWorld(); + this.duality.initialize(); + } - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - this.duality.addDrops( drops ); - } + @Override + public void getDrops(final List drops, final boolean wrenched) { + this.duality.addDrops(drops); + } - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 4; - } + @Override + public float getCableConnectionLength(AECableType cable) { + return 4; + } - @Override - public IConfigManager getConfigManager() - { - return this.duality.getConfigManager(); - } + @Override + public IConfigManager getConfigManager() { + return this.duality.getConfigManager(); + } - @Override - public IItemHandler getInventoryByName( final String name ) - { - return this.duality.getInventoryByName( name ); - } + @Override + public IItemHandler getInventoryByName(final String name) { + return this.duality.getInventoryByName(name); + } - @Override - public boolean onPartActivate( final EntityPlayer p, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, this.getTileEntity(), this.getSide(), GuiBridge.GUI_INTERFACE ); - } - return true; - } + @Override + public boolean onPartActivate(final EntityPlayer p, final EnumHand hand, final Vec3d pos) { + if (Platform.isServer()) { + Platform.openGUI(p, this.getTileEntity(), this.getSide(), GuiBridge.GUI_INTERFACE); + } + return true; + } - @Override - public boolean canInsert( final ItemStack stack ) - { - return this.duality.canInsert( stack ); - } + @Override + public boolean canInsert(final ItemStack stack) { + return this.duality.canInsert(stack); + } - @Override - public > IMEMonitor getInventory( IStorageChannel channel ) - { - return this.duality.getInventory( channel ); - } + @Override + public > IMEMonitor getInventory(IStorageChannel channel) { + return this.duality.getInventory(channel); + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return this.duality.getTickingRequest( node ); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return this.duality.getTickingRequest(node); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.duality.tickingRequest( node, ticksSinceLastCall ); - } + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.duality.tickingRequest(node, ticksSinceLastCall); + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - this.duality.onChangeInventory( inv, slot, mc, removedStack, newStack ); - } + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { + this.duality.onChangeInventory(inv, slot, mc, removedStack, newStack); + } - @Override - public DualityInterface getInterfaceDuality() - { - return this.duality; - } + @Override + public DualityInterface getInterfaceDuality() { + return this.duality; + } - @Override - public EnumSet getTargets() - { - return EnumSet.of( this.getSide().getFacing() ); - } + @Override + public EnumSet getTargets() { + return EnumSet.of(this.getSide().getFacing()); + } - @Override - public TileEntity getTileEntity() - { - return super.getHost().getTile(); - } + @Override + public TileEntity getTileEntity() { + return super.getHost().getTile(); + } - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) - { - return this.duality.pushPattern( patternDetails, table ); - } + @Override + public boolean pushPattern(final ICraftingPatternDetails patternDetails, final InventoryCrafting table) { + return this.duality.pushPattern(patternDetails, table); + } - @Override - public boolean isBusy() - { - return this.duality.isBusy(); - } + @Override + public boolean isBusy() { + return this.duality.isBusy(); + } - @Override - public void provideCrafting( final ICraftingProviderHelper craftingTracker ) - { - this.duality.provideCrafting( craftingTracker ); - } + @Override + public void provideCrafting(final ICraftingProviderHelper craftingTracker) { + this.duality.provideCrafting(craftingTracker); + } - @Override - public ImmutableSet getRequestedJobs() - { - return this.duality.getRequestedJobs(); - } + @Override + public ImmutableSet getRequestedJobs() { + return this.duality.getRequestedJobs(); + } - @Override - public IAEItemStack injectCraftedItems( final ICraftingLink link, final IAEItemStack items, final Actionable mode ) - { - return this.duality.injectCraftedItems( link, items, mode ); - } + @Override + public IAEItemStack injectCraftedItems(final ICraftingLink link, final IAEItemStack items, final Actionable mode) { + return this.duality.injectCraftedItems(link, items, mode); + } - @Override - public void jobStateChange( final ICraftingLink link ) - { - this.duality.jobStateChange( link ); - } + @Override + public void jobStateChange(final ICraftingLink link) { + this.duality.jobStateChange(link); + } - @Override - public int getPriority() - { - return this.duality.getPriority(); - } + @Override + public int getPriority() { + return this.duality.getPriority(); + } - @Override - public void setPriority( final int newValue ) - { - this.duality.setPriority( newValue ); - } + @Override + public void setPriority(final int newValue) { + this.duality.setPriority(newValue); + } - @Override - public IPartModel getStaticModels() - { - if( this.isActive() && this.isPowered() ) - { - return MODELS_HAS_CHANNEL; - } - else if( this.isPowered() ) - { - return MODELS_ON; - } - else - { - return MODELS_OFF; - } - } + @Override + public IPartModel getStaticModels() { + if (this.isActive() && this.isPowered()) { + return MODELS_HAS_CHANNEL; + } else if (this.isPowered()) { + return MODELS_ON; + } else { + return MODELS_OFF; + } + } - @Override - public boolean hasCapability( Capability capabilityClass ) - { - return this.duality.hasCapability( capabilityClass, this.getSide().getFacing() ); - } + @Override + public boolean hasCapability(Capability capabilityClass) { + return this.duality.hasCapability(capabilityClass, this.getSide().getFacing()); + } - @Override - public T getCapability( Capability capabilityClass ) - { - return this.duality.getCapability( capabilityClass, this.getSide().getFacing() ); - } + @Override + public T getCapability(Capability capabilityClass) { + return this.duality.getCapability(capabilityClass, this.getSide().getFacing()); + } - @Override - public ItemStack getItemStackRepresentation() - { - return AEApi.instance().definitions().parts().iface().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - } + @Override + public ItemStack getItemStackRepresentation() { + return AEApi.instance().definitions().parts().iface().maybeStack(1).orElse(ItemStack.EMPTY); + } - @Override - public GuiBridge getGuiBridge() - { - return GuiBridge.GUI_INTERFACE; - } + @Override + public GuiBridge getGuiBridge() { + return GuiBridge.GUI_INTERFACE; + } } diff --git a/src/main/java/appeng/parts/misc/PartInvertedToggleBus.java b/src/main/java/appeng/parts/misc/PartInvertedToggleBus.java index 9614318c1..d9276c34b 100644 --- a/src/main/java/appeng/parts/misc/PartInvertedToggleBus.java +++ b/src/main/java/appeng/parts/misc/PartInvertedToggleBus.java @@ -19,56 +19,46 @@ package appeng.parts.misc; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - import appeng.api.parts.IPartModel; import appeng.core.AppEng; import appeng.helpers.Reflected; import appeng.items.parts.PartModels; import appeng.parts.PartModel; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; -public class PartInvertedToggleBus extends PartToggleBus -{ - @PartModels - public static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "part/inverted_toggle_bus_base" ); +public class PartInvertedToggleBus extends PartToggleBus { + @PartModels + public static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "part/inverted_toggle_bus_base"); - public static final PartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_STATUS_OFF ); - public static final PartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_STATUS_ON ); - public static final PartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, MODEL_STATUS_HAS_CHANNEL ); + public static final PartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_STATUS_OFF); + public static final PartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_STATUS_ON); + public static final PartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, MODEL_STATUS_HAS_CHANNEL); - @Reflected - public PartInvertedToggleBus( final ItemStack is ) - { - super( is ); - this.getProxy().setIdlePowerUsage( 0.0 ); - this.getOuterProxy().setIdlePowerUsage( 0.0 ); - this.getProxy().setFlags(); - this.getOuterProxy().setFlags(); - } + @Reflected + public PartInvertedToggleBus(final ItemStack is) { + super(is); + this.getProxy().setIdlePowerUsage(0.0); + this.getOuterProxy().setIdlePowerUsage(0.0); + this.getProxy().setFlags(); + this.getOuterProxy().setFlags(); + } - @Override - protected boolean getIntention() - { - return !super.getIntention(); - } + @Override + protected boolean getIntention() { + return !super.getIntention(); + } - @Override - public IPartModel getStaticModels() - { - if( this.hasRedstoneFlag() && this.isActive() && this.isPowered() ) - { - return MODELS_HAS_CHANNEL; - } - else if( this.hasRedstoneFlag() && this.isPowered() ) - { - return MODELS_ON; - } - else - { - return MODELS_OFF; - } - } + @Override + public IPartModel getStaticModels() { + if (this.hasRedstoneFlag() && this.isActive() && this.isPowered()) { + return MODELS_HAS_CHANNEL; + } else if (this.hasRedstoneFlag() && this.isPowered()) { + return MODELS_ON; + } else { + return MODELS_OFF; + } + } } diff --git a/src/main/java/appeng/parts/misc/PartOreDicStorageBus.java b/src/main/java/appeng/parts/misc/PartOreDicStorageBus.java index 61a7993d5..c1af86c77 100644 --- a/src/main/java/appeng/parts/misc/PartOreDicStorageBus.java +++ b/src/main/java/appeng/parts/misc/PartOreDicStorageBus.java @@ -31,60 +31,51 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.Vec3d; -public class PartOreDicStorageBus extends PartStorageBus -{ - public static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "part/oredict_storage_bus_base" ); +public class PartOreDicStorageBus extends PartStorageBus { + public static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "part/oredict_storage_bus_base"); @PartModels - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/storage_bus_off" ) ); + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/storage_bus_off")); @PartModels - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/storage_bus_on" ) ); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/storage_bus_on")); @PartModels - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/storage_bus_has_channel" ) ); + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/storage_bus_has_channel")); public String oreExp = ""; OreDictPriorityList priorityList; - public PartOreDicStorageBus( ItemStack is ) - { - super( is ); + public PartOreDicStorageBus(ItemStack is) { + super(is); } @Override - public void readFromNBT( NBTTagCompound data ) - { - super.readFromNBT( data ); - this.oreExp = data.getString( "oreMatch" ); - this.priorityList = new OreDictPriorityList<>( OreHelper.INSTANCE.getMatchingOre( oreExp ), oreExp ); + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + this.oreExp = data.getString("oreMatch"); + this.priorityList = new OreDictPriorityList<>(OreHelper.INSTANCE.getMatchingOre(oreExp), oreExp); } @Override - public void writeToNBT( NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setString( "oreMatch", getOreExp() ); + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + data.setString("oreMatch", getOreExp()); } @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_OREDICTSTORAGEBUS ); + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_OREDICTSTORAGEBUS); } return true; } @Override - public GuiBridge getGuiBridge() - { + public GuiBridge getGuiBridge() { return GuiBridge.GUI_OREDICTSTORAGEBUS; } @Override - public MEInventoryHandler getInternalHandler() - { - if( this.cached ) - { + public MEInventoryHandler getInternalHandler() { + if (this.cached) { return this.handler; } @@ -92,132 +83,102 @@ public class PartOreDicStorageBus extends PartStorageBus this.cached = true; final TileEntity self = this.getHost().getTile(); - final TileEntity target = self.getWorld().getTileEntity( self.getPos().offset( this.getSide().getFacing() ) ); - final int newHandlerHash = this.createHandlerHash( target ); + final TileEntity target = self.getWorld().getTileEntity(self.getPos().offset(this.getSide().getFacing())); + final int newHandlerHash = this.createHandlerHash(target); - if( newHandlerHash != 0 && newHandlerHash == this.handlerHash ) - { + if (newHandlerHash != 0 && newHandlerHash == this.handlerHash) { return this.handler; } this.handlerHash = newHandlerHash; this.handler = null; - if( this.monitor != null ) - { - ( (IBaseMonitor) monitor ).removeListener( this ); + if (this.monitor != null) { + ((IBaseMonitor) monitor).removeListener(this); } this.monitor = null; - if( target != null ) - { - IMEInventory inv = this.getInventoryWrapper( target ); + if (target != null) { + IMEInventory inv = this.getInventoryWrapper(target); - if( inv instanceof ITickingMonitor ) - { + if (inv instanceof ITickingMonitor) { this.monitor = (ITickingMonitor) inv; - this.monitor.setActionSource( mySrc ); - this.monitor.setMode( (StorageFilter) this.getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); + this.monitor.setActionSource(mySrc); + this.monitor.setMode((StorageFilter) this.getConfigManager().getSetting(Settings.STORAGE_FILTER)); } - if( inv != null ) - { - this.handler = new MEInventoryHandler<>( inv, AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); + if (inv != null) { + this.handler = new MEInventoryHandler<>(inv, AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); - this.handler.setBaseAccess( (AccessRestriction) this.getConfigManager().getSetting( Settings.ACCESS ) ); - this.handler.setWhitelist( this.getInstalledUpgrades( Upgrades.INVERTER ) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST ); - this.handler.setPriority( this.priority ); + this.handler.setBaseAccess((AccessRestriction) this.getConfigManager().getSetting(Settings.ACCESS)); + this.handler.setWhitelist(this.getInstalledUpgrades(Upgrades.INVERTER) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST); + this.handler.setPriority(this.priority); - this.handler.setPartitionList( this.getPriorityList() ); + this.handler.setPartitionList(this.getPriorityList()); - if( inv instanceof IBaseMonitor ) - { - if( ( (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getSetting( Settings.ACCESS ) ).hasPermission( AccessRestriction.READ ) ) - { - ( (IBaseMonitor) inv ).addListener( this, this.handler ); + if (inv instanceof IBaseMonitor) { + if (((AccessRestriction) ((ConfigManager) this.getConfigManager()).getSetting(Settings.ACCESS)).hasPermission(AccessRestriction.READ)) { + ((IBaseMonitor) inv).addListener(this, this.handler); } } } } // update sleep state... - if( wasSleeping != ( this.monitor == null ) ) - { - try - { + if (wasSleeping != (this.monitor == null)) { + try { final ITickManager tm = this.getProxy().getTick(); - if( this.monitor == null ) - { - tm.sleepDevice( this.getProxy().getNode() ); + if (this.monitor == null) { + tm.sleepDevice(this.getProxy().getNode()); + } else { + tm.wakeDevice(this.getProxy().getNode()); } - else - { - tm.wakeDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { + } catch (final GridAccessException e) { // :( } } - try - { + try { // force grid to update handlers... - ( (GridStorageCache) this.getProxy().getGrid().getCache( IStorageGrid.class ) ).cellUpdate( null ); - } - catch( final GridAccessException e ) - { + ((GridStorageCache) this.getProxy().getGrid().getCache(IStorageGrid.class)).cellUpdate(null); + } catch (final GridAccessException e) { // :3 } return this.handler; } - private IPartitionList getPriorityList() - { - if( priorityList == null ) - { - this.priorityList = new OreDictPriorityList<>( OreHelper.INSTANCE.getMatchingOre( oreExp ), oreExp ); + private IPartitionList getPriorityList() { + if (priorityList == null) { + this.priorityList = new OreDictPriorityList<>(OreHelper.INSTANCE.getMatchingOre(oreExp), oreExp); } return priorityList; } - public String getOreExp() - { - if( this.oreExp == null ) - { + public String getOreExp() { + if (this.oreExp == null) { return ""; } return oreExp; } - public void saveOreMatch( String oreMatch ) - { - if( !this.oreExp.equals( oreMatch ) ) - { + public void saveOreMatch(String oreMatch) { + if (!this.oreExp.equals(oreMatch)) { this.oreExp = oreMatch; - this.priorityList = new OreDictPriorityList<>( OreHelper.INSTANCE.getMatchingOre( oreExp ), oreExp ); - if( this.handler != null ) - { - handler.setPartitionList( this.priorityList ); + this.priorityList = new OreDictPriorityList<>(OreHelper.INSTANCE.getMatchingOre(oreExp), oreExp); + if (this.handler != null) { + handler.setPartitionList(this.priorityList); } this.getHost().markForSave(); } } @Override - public IPartModel getStaticModels() - { - if( this.isActive() && this.isPowered() ) - { + public IPartModel getStaticModels() { + if (this.isActive() && this.isPowered()) { return MODELS_HAS_CHANNEL; - } - else if( this.isPowered() ) - { + } else if (this.isPowered()) { return MODELS_ON; - } - else - { + } else { return MODELS_OFF; } } diff --git a/src/main/java/appeng/parts/misc/PartStorageBus.java b/src/main/java/appeng/parts/misc/PartStorageBus.java index 52eeec768..b782e1f77 100644 --- a/src/main/java/appeng/parts/misc/PartStorageBus.java +++ b/src/main/java/appeng/parts/misc/PartStorageBus.java @@ -85,606 +85,485 @@ import java.util.List; import java.util.Objects; -public class PartStorageBus extends PartUpgradeable implements IGridTickable, ICellContainer, IMEMonitorHandlerReceiver, IPriorityHost -{ - public static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "part/storage_bus_base" ); - @PartModels - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/storage_bus_off" ) ); - @PartModels - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/storage_bus_on" ) ); - @PartModels - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, new ResourceLocation( AppEng.MOD_ID, "part/storage_bus_has_channel" ) ); - @CapabilityInject( IItemRepository.class ) - public static Capability ITEM_REPOSITORY_CAPABILITY = null; - protected final IActionSource mySrc; - protected final AppEngInternalAEInventory Config = new AppEngInternalAEInventory( this, 63 ); - protected int priority = 0; - protected boolean cached = false; - protected ITickingMonitor monitor = null; - protected MEInventoryHandler handler = null; - protected int handlerHash = 0; - private boolean wasActive = false; - private byte resetCacheLogic = 0; - private boolean accessChanged; - private boolean readOncePass; - - @Reflected - public PartStorageBus( final ItemStack is ) - { - super( is ); - this.getConfigManager().registerSetting( Settings.ACCESS, AccessRestriction.READ_WRITE ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY ); - this.mySrc = new MachineSource( this ); - } - - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.updateStatus(); - } - - private void updateStatus() - { - final boolean currentActive = this.getProxy().isActive(); - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - this.getHost().markForUpdate(); - } - catch( final GridAccessException e ) - { - // :P - } - } - } - - @Override - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged changedChannels ) - { - this.updateStatus(); - } - - @Override - protected int getUpgradeSlots() - { - return 5; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - if( settingName.name().equals( "ACCESS" ) ) - { - this.accessChanged = true; - } - this.resetCache( true ); - this.getHost().markForSave(); - } - - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - super.onChangeInventory( inv, slot, mc, removedStack, newStack ); - - if( inv == this.Config ) - { - this.resetCache( true ); - } - } - - @Override - public void upgradesChanged() - { - super.upgradesChanged(); - this.resetCache( true ); - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.Config.readFromNBT( data, "config" ); - this.priority = data.getInteger( "priority" ); - this.accessChanged = false; - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.Config.writeToNBT( data, "config" ); - data.setInteger( "priority", this.priority ); - } - - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.Config; - } - - return super.getInventoryByName( name ); - } - - private void resetCache( final boolean fullReset ) - { - if( this.getHost() == null || this.getHost().getTile() == null || this.getHost().getTile().getWorld() == null || this.getHost().getTile().getWorld().isRemote ) - { - return; - } - - if( fullReset ) - { - this.resetCacheLogic = 2; - } - else if( this.resetCacheLogic < 2 ) - { - this.resetCacheLogic = 1; - } - - try - { - this.getProxy().getTick().alertDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - public boolean isValid( final Object verificationToken ) - { - return this.handler == verificationToken; - } - - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final IActionSource source ) - { - if( this.getProxy().isActive() ) - { - AccessRestriction currentAccess = (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getSetting( Settings.ACCESS ); - if( readOncePass ) - { - readOncePass = false; - try - { - this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), change, mySrc ); - } - catch( final GridAccessException e ) - { - // :( - } - return; - } - if( !currentAccess.hasPermission( AccessRestriction.READ ) ) - { - return; - } - try - { - this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), change, source ); - } - catch( final GridAccessException e ) - { - // :( - } - } - } - - @Override - public void onListUpdate() - { - // not used here. - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 3, 3, 15, 13, 13, 16 ); - bch.addBox( 2, 2, 14, 14, 14, 15 ); - bch.addBox( 5, 5, 12, 11, 11, 14 ); - } - - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - if( pos.offset( this.getSide().getFacing() ).equals( neighbor ) ) - { - final TileEntity te = w.getTileEntity( neighbor ); - - // In case the TE was destroyed, we have to do a full reset immediately. - if( te instanceof TileCableBus ) - { - IPart iPart = ( (TileCableBus) te ).getPart( this.getSide().getOpposite() ); - if( iPart == null ) - { - this.resetCache( true ); - this.resetCache(); - } - else if( iPart instanceof PartInterface ) - { - if( createHandlerHash( te ) != handlerHash ) - { - this.resetCache( true ); - this.resetCache(); - } - } - } - else if( te == null ) - { - this.resetCache( true ); - this.resetCache(); - } - else if( te instanceof TileInterface ) - { - if( createHandlerHash( te ) != handlerHash ) - { - this.resetCache( true ); - this.resetCache(); - } - } - else - { - this.resetCache( false ); - } - } - } - - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 4; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_STORAGEBUS ); - } - return true; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.StorageBus.getMin(), TickRates.StorageBus.getMax(), this.monitor == null, true ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( this.resetCacheLogic != 0 ) - { - this.resetCache(); - } - - if( this.monitor != null ) - { - return this.monitor.onTick(); - } - - return TickRateModulation.SLEEP; - } - - private void resetCache() - { - final boolean fullReset = this.resetCacheLogic == 2; - this.resetCacheLogic = 0; - - final MEInventoryHandler in = this.getInternalHandler(); - - IItemList before = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - if( in != null ) - { - if( accessChanged ) - { - AccessRestriction currentAccess = (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getSetting( Settings.ACCESS ); - AccessRestriction oldAccess = (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getOldSetting( Settings.ACCESS ); - if( oldAccess.hasPermission( AccessRestriction.READ ) && !currentAccess.hasPermission( AccessRestriction.READ ) ) - { - readOncePass = true; - } - in.setBaseAccess( oldAccess ); - before = in.getAvailableItems( before ); - in.setBaseAccess( currentAccess ); - accessChanged = false; - } - else - { - before = in.getAvailableItems( before ); - } - } - - this.cached = false; - if( fullReset ) - { - this.handlerHash = 0; - } - - final MEInventoryHandler out = this.getInternalHandler(); - - IItemList after = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - - if( in != out ) - { - if( out != null ) - { - after = out.getAvailableItems( after ); - } - Platform.postListChanges( before, after, this, this.mySrc ); - } - } - - IMEInventory getInventoryWrapper( TileEntity target ) - { - - EnumFacing targetSide = this.getSide().getFacing().getOpposite(); - - // Prioritize a handler to directly link to another ME network - IStorageMonitorableAccessor accessor = target.getCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide ); - - if( accessor != null ) - { - IStorageMonitorable inventory = accessor.getInventory( this.mySrc ); - if( inventory != null ) - { - return inventory.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - } - - // So this could / can be a design decision. If the tile does support our custom capability, - // but it does not return an inventory for the action source, we do NOT fall back to using - // IItemHandler's, as that might circumvent the security setings, and might also cause - // performance issues. - return null; - } - - // Check via cap for IItemRepository - if( ITEM_REPOSITORY_CAPABILITY != null && target.hasCapability( ITEM_REPOSITORY_CAPABILITY, targetSide ) ) - { - IItemRepository handlerRepo = target.getCapability( ITEM_REPOSITORY_CAPABILITY, targetSide ); - if( handlerRepo != null ) - { - return new ItemRepositoryAdapter( handlerRepo, this ); - } - } - // Check via cap for IItemHandler - IItemHandler handlerExt = target.getCapability( CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, targetSide ); - if( handlerExt != null ) - { - return new ItemHandlerAdapter( handlerExt, this ); - } - - return null; - - } - - int createHandlerHash( TileEntity target ) - { - if( target == null ) - { - return 0; - } - - final EnumFacing targetSide = this.getSide().getFacing().getOpposite(); - - if( target.hasCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide ) ) - { - IStorageMonitorableAccessor accessor = target.getCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide ); - if( accessor != null ) - { - IStorageMonitorable inventory = accessor.getInventory( this.mySrc ); - if( inventory != null ) - { - return Objects.hash( target, inventory.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) ); - } - } - return Objects.hash( target, target.getCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide ) ); - } - - final IItemHandler itemHandler = target.getCapability( CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, targetSide ); - - if( itemHandler != null ) - { - return Objects.hash( target, itemHandler, itemHandler.getSlots() ); - } - - return 0; - } - - public MEInventoryHandler getInternalHandler() - { - if( this.cached ) - { - return this.handler; - } - - final boolean wasSleeping = this.monitor == null; - - this.cached = true; - final TileEntity self = this.getHost().getTile(); - final TileEntity target = self.getWorld().getTileEntity( self.getPos().offset( this.getSide().getFacing() ) ); - final int newHandlerHash = this.createHandlerHash( target ); - - if( newHandlerHash != 0 && newHandlerHash == this.handlerHash ) - { - return this.handler; - } - - this.handlerHash = newHandlerHash; - this.handler = null; - if( this.monitor != null ) - { - ( (IBaseMonitor) monitor ).removeListener( this ); - } - this.monitor = null; - if( target != null ) - { - IMEInventory inv = this.getInventoryWrapper( target ); - - if( inv instanceof ITickingMonitor ) - { - this.monitor = (ITickingMonitor) inv; - this.monitor.setActionSource( mySrc ); - this.monitor.setMode( (StorageFilter) this.getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); - } - - if( inv != null ) - { - this.handler = new MEInventoryHandler<>( inv, AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - - this.handler.setBaseAccess( (AccessRestriction) this.getConfigManager().getSetting( Settings.ACCESS ) ); - this.handler.setWhitelist( this.getInstalledUpgrades( Upgrades.INVERTER ) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST ); - this.handler.setPriority( this.priority ); - - final IItemList priorityList = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); - - final int slotsToUse = 18 + this.getInstalledUpgrades( Upgrades.CAPACITY ) * 9; - for( int x = 0; x < this.Config.getSlots() && x < slotsToUse; x++ ) - { - final IAEItemStack is = this.Config.getAEStackInSlot( x ); - if( is != null ) - { - priorityList.add( is ); - } - } - - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - this.handler.setPartitionList( new FuzzyPriorityList<>( priorityList, (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ) ) ); - } - else - { - this.handler.setPartitionList( new PrecisePriorityList<>( priorityList ) ); - } - - if( inv instanceof IBaseMonitor ) - { - if( ( (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getSetting( Settings.ACCESS ) ).hasPermission( AccessRestriction.READ ) ) - { - ( (IBaseMonitor) inv ).addListener( this, this.handler ); - } - } - } - } - - // update sleep state... - if( wasSleeping != ( this.monitor == null ) ) - { - try - { - final ITickManager tm = this.getProxy().getTick(); - if( this.monitor == null ) - { - tm.sleepDevice( this.getProxy().getNode() ); - } - else - { - tm.wakeDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :( - } - } - - try - { - // force grid to update handlers... - ( (GridStorageCache) this.getProxy().getGrid().getCache( IStorageGrid.class ) ).cellUpdate( null ); - } - catch( final GridAccessException e ) - { - // :3 - } - - return this.handler; - } - - @Override - public List getCellArray( final IStorageChannel channel ) - { - if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - final IMEInventoryHandler out = this.getInternalHandler(); - if( out != null ) - { - return Collections.singletonList( out ); - } - } - return Collections.emptyList(); - } - - @Override - public int getPriority() - { - return this.priority; - } - - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - this.getHost().markForSave(); - this.resetCache( true ); - } - - @Override - public void blinkCell( final int slot ) - { - } - - // TODO: BC PIPE INTEGRATION - /* - * @Override - * @Method( iname = IntegrationType.BuildCraftTransport ) - * public ConnectOverride overridePipeConnection( PipeType type, ForgeDirection with ) - * { - * return type == PipeType.ITEM && with == this.getSide() ? ConnectOverride.CONNECT : ConnectOverride.DISCONNECT; - * } - */ - @Override - public void saveChanges( final ICellInventory cellInventory ) - { - // nope! - } - - @Override - public IPartModel getStaticModels() - { - if( this.isActive() && this.isPowered() ) - { - return MODELS_HAS_CHANNEL; - } - else if( this.isPowered() ) - { - return MODELS_ON; - } - else - { - return MODELS_OFF; - } - } - - @Override - public ItemStack getItemStackRepresentation() - { - return AEApi.instance().definitions().parts().storageBus().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - } - - @Override - public GuiBridge getGuiBridge() - { - return GuiBridge.GUI_STORAGEBUS; - } +public class PartStorageBus extends PartUpgradeable implements IGridTickable, ICellContainer, IMEMonitorHandlerReceiver, IPriorityHost { + public static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "part/storage_bus_base"); + @PartModels + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/storage_bus_off")); + @PartModels + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/storage_bus_on")); + @PartModels + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, new ResourceLocation(AppEng.MOD_ID, "part/storage_bus_has_channel")); + @CapabilityInject(IItemRepository.class) + public static Capability ITEM_REPOSITORY_CAPABILITY = null; + protected final IActionSource mySrc; + protected final AppEngInternalAEInventory Config = new AppEngInternalAEInventory(this, 63); + protected int priority = 0; + protected boolean cached = false; + protected ITickingMonitor monitor = null; + protected MEInventoryHandler handler = null; + protected int handlerHash = 0; + private boolean wasActive = false; + private byte resetCacheLogic = 0; + private boolean accessChanged; + private boolean readOncePass; + + @Reflected + public PartStorageBus(final ItemStack is) { + super(is); + this.getConfigManager().registerSetting(Settings.ACCESS, AccessRestriction.READ_WRITE); + this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.getConfigManager().registerSetting(Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY); + this.mySrc = new MachineSource(this); + } + + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.updateStatus(); + } + + private void updateStatus() { + final boolean currentActive = this.getProxy().isActive(); + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + this.getHost().markForUpdate(); + } catch (final GridAccessException e) { + // :P + } + } + } + + @Override + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged changedChannels) { + this.updateStatus(); + } + + @Override + protected int getUpgradeSlots() { + return 5; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + if (settingName.name().equals("ACCESS")) { + this.accessChanged = true; + } + this.resetCache(true); + this.getHost().markForSave(); + } + + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { + super.onChangeInventory(inv, slot, mc, removedStack, newStack); + + if (inv == this.Config) { + this.resetCache(true); + } + } + + @Override + public void upgradesChanged() { + super.upgradesChanged(); + this.resetCache(true); + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.Config.readFromNBT(data, "config"); + this.priority = data.getInteger("priority"); + this.accessChanged = false; + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.Config.writeToNBT(data, "config"); + data.setInteger("priority", this.priority); + } + + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("config")) { + return this.Config; + } + + return super.getInventoryByName(name); + } + + private void resetCache(final boolean fullReset) { + if (this.getHost() == null || this.getHost().getTile() == null || this.getHost().getTile().getWorld() == null || this.getHost().getTile().getWorld().isRemote) { + return; + } + + if (fullReset) { + this.resetCacheLogic = 2; + } else if (this.resetCacheLogic < 2) { + this.resetCacheLogic = 1; + } + + try { + this.getProxy().getTick().alertDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // :P + } + } + + @Override + public boolean isValid(final Object verificationToken) { + return this.handler == verificationToken; + } + + @Override + public void postChange(final IBaseMonitor monitor, final Iterable change, final IActionSource source) { + if (this.getProxy().isActive()) { + AccessRestriction currentAccess = (AccessRestriction) ((ConfigManager) this.getConfigManager()).getSetting(Settings.ACCESS); + if (readOncePass) { + readOncePass = false; + try { + this.getProxy().getStorage().postAlterationOfStoredItems(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class), change, mySrc); + } catch (final GridAccessException e) { + // :( + } + return; + } + if (!currentAccess.hasPermission(AccessRestriction.READ)) { + return; + } + try { + this.getProxy().getStorage().postAlterationOfStoredItems(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class), change, source); + } catch (final GridAccessException e) { + // :( + } + } + } + + @Override + public void onListUpdate() { + // not used here. + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(3, 3, 15, 13, 13, 16); + bch.addBox(2, 2, 14, 14, 14, 15); + bch.addBox(5, 5, 12, 11, 11, 14); + } + + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + if (pos.offset(this.getSide().getFacing()).equals(neighbor)) { + final TileEntity te = w.getTileEntity(neighbor); + + // In case the TE was destroyed, we have to do a full reset immediately. + if (te instanceof TileCableBus) { + IPart iPart = ((TileCableBus) te).getPart(this.getSide().getOpposite()); + if (iPart == null) { + this.resetCache(true); + this.resetCache(); + } else if (iPart instanceof PartInterface) { + if (createHandlerHash(te) != handlerHash) { + this.resetCache(true); + this.resetCache(); + } + } + } else if (te == null) { + this.resetCache(true); + this.resetCache(); + } else if (te instanceof TileInterface) { + if (createHandlerHash(te) != handlerHash) { + this.resetCache(true); + this.resetCache(); + } + } else { + this.resetCache(false); + } + } + } + + @Override + public float getCableConnectionLength(AECableType cable) { + return 4; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_STORAGEBUS); + } + return true; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.StorageBus.getMin(), TickRates.StorageBus.getMax(), this.monitor == null, true); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (this.resetCacheLogic != 0) { + this.resetCache(); + } + + if (this.monitor != null) { + return this.monitor.onTick(); + } + + return TickRateModulation.SLEEP; + } + + private void resetCache() { + final boolean fullReset = this.resetCacheLogic == 2; + this.resetCacheLogic = 0; + + final MEInventoryHandler in = this.getInternalHandler(); + + IItemList before = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + if (in != null) { + if (accessChanged) { + AccessRestriction currentAccess = (AccessRestriction) ((ConfigManager) this.getConfigManager()).getSetting(Settings.ACCESS); + AccessRestriction oldAccess = (AccessRestriction) ((ConfigManager) this.getConfigManager()).getOldSetting(Settings.ACCESS); + if (oldAccess.hasPermission(AccessRestriction.READ) && !currentAccess.hasPermission(AccessRestriction.READ)) { + readOncePass = true; + } + in.setBaseAccess(oldAccess); + before = in.getAvailableItems(before); + in.setBaseAccess(currentAccess); + accessChanged = false; + } else { + before = in.getAvailableItems(before); + } + } + + this.cached = false; + if (fullReset) { + this.handlerHash = 0; + } + + final MEInventoryHandler out = this.getInternalHandler(); + + IItemList after = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + + if (in != out) { + if (out != null) { + after = out.getAvailableItems(after); + } + Platform.postListChanges(before, after, this, this.mySrc); + } + } + + IMEInventory getInventoryWrapper(TileEntity target) { + + EnumFacing targetSide = this.getSide().getFacing().getOpposite(); + + // Prioritize a handler to directly link to another ME network + IStorageMonitorableAccessor accessor = target.getCapability(Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide); + + if (accessor != null) { + IStorageMonitorable inventory = accessor.getInventory(this.mySrc); + if (inventory != null) { + return inventory.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + } + + // So this could / can be a design decision. If the tile does support our custom capability, + // but it does not return an inventory for the action source, we do NOT fall back to using + // IItemHandler's, as that might circumvent the security setings, and might also cause + // performance issues. + return null; + } + + // Check via cap for IItemRepository + if (ITEM_REPOSITORY_CAPABILITY != null && target.hasCapability(ITEM_REPOSITORY_CAPABILITY, targetSide)) { + IItemRepository handlerRepo = target.getCapability(ITEM_REPOSITORY_CAPABILITY, targetSide); + if (handlerRepo != null) { + return new ItemRepositoryAdapter(handlerRepo, this); + } + } + // Check via cap for IItemHandler + IItemHandler handlerExt = target.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, targetSide); + if (handlerExt != null) { + return new ItemHandlerAdapter(handlerExt, this); + } + + return null; + + } + + int createHandlerHash(TileEntity target) { + if (target == null) { + return 0; + } + + final EnumFacing targetSide = this.getSide().getFacing().getOpposite(); + + if (target.hasCapability(Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide)) { + IStorageMonitorableAccessor accessor = target.getCapability(Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide); + if (accessor != null) { + IStorageMonitorable inventory = accessor.getInventory(this.mySrc); + if (inventory != null) { + return Objects.hash(target, inventory.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class))); + } + } + return Objects.hash(target, target.getCapability(Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide)); + } + + final IItemHandler itemHandler = target.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, targetSide); + + if (itemHandler != null) { + return Objects.hash(target, itemHandler, itemHandler.getSlots()); + } + + return 0; + } + + public MEInventoryHandler getInternalHandler() { + if (this.cached) { + return this.handler; + } + + final boolean wasSleeping = this.monitor == null; + + this.cached = true; + final TileEntity self = this.getHost().getTile(); + final TileEntity target = self.getWorld().getTileEntity(self.getPos().offset(this.getSide().getFacing())); + final int newHandlerHash = this.createHandlerHash(target); + + if (newHandlerHash != 0 && newHandlerHash == this.handlerHash) { + return this.handler; + } + + this.handlerHash = newHandlerHash; + this.handler = null; + if (this.monitor != null) { + ((IBaseMonitor) monitor).removeListener(this); + } + this.monitor = null; + if (target != null) { + IMEInventory inv = this.getInventoryWrapper(target); + + if (inv instanceof ITickingMonitor) { + this.monitor = (ITickingMonitor) inv; + this.monitor.setActionSource(mySrc); + this.monitor.setMode((StorageFilter) this.getConfigManager().getSetting(Settings.STORAGE_FILTER)); + } + + if (inv != null) { + this.handler = new MEInventoryHandler<>(inv, AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + + this.handler.setBaseAccess((AccessRestriction) this.getConfigManager().getSetting(Settings.ACCESS)); + this.handler.setWhitelist(this.getInstalledUpgrades(Upgrades.INVERTER) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST); + this.handler.setPriority(this.priority); + + final IItemList priorityList = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); + + final int slotsToUse = 18 + this.getInstalledUpgrades(Upgrades.CAPACITY) * 9; + for (int x = 0; x < this.Config.getSlots() && x < slotsToUse; x++) { + final IAEItemStack is = this.Config.getAEStackInSlot(x); + if (is != null) { + priorityList.add(is); + } + } + + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + this.handler.setPartitionList(new FuzzyPriorityList<>(priorityList, (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE))); + } else { + this.handler.setPartitionList(new PrecisePriorityList<>(priorityList)); + } + + if (inv instanceof IBaseMonitor) { + if (((AccessRestriction) ((ConfigManager) this.getConfigManager()).getSetting(Settings.ACCESS)).hasPermission(AccessRestriction.READ)) { + ((IBaseMonitor) inv).addListener(this, this.handler); + } + } + } + } + + // update sleep state... + if (wasSleeping != (this.monitor == null)) { + try { + final ITickManager tm = this.getProxy().getTick(); + if (this.monitor == null) { + tm.sleepDevice(this.getProxy().getNode()); + } else { + tm.wakeDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :( + } + } + + try { + // force grid to update handlers... + ((GridStorageCache) this.getProxy().getGrid().getCache(IStorageGrid.class)).cellUpdate(null); + } catch (final GridAccessException e) { + // :3 + } + + return this.handler; + } + + @Override + public List getCellArray(final IStorageChannel channel) { + if (channel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + final IMEInventoryHandler out = this.getInternalHandler(); + if (out != null) { + return Collections.singletonList(out); + } + } + return Collections.emptyList(); + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + this.getHost().markForSave(); + this.resetCache(true); + } + + @Override + public void blinkCell(final int slot) { + } + + // TODO: BC PIPE INTEGRATION + /* + * @Override + * @Method( iname = IntegrationType.BuildCraftTransport ) + * public ConnectOverride overridePipeConnection( PipeType type, ForgeDirection with ) + * { + * return type == PipeType.ITEM && with == this.getSide() ? ConnectOverride.CONNECT : ConnectOverride.DISCONNECT; + * } + */ + @Override + public void saveChanges(final ICellInventory cellInventory) { + // nope! + } + + @Override + public IPartModel getStaticModels() { + if (this.isActive() && this.isPowered()) { + return MODELS_HAS_CHANNEL; + } else if (this.isPowered()) { + return MODELS_ON; + } else { + return MODELS_OFF; + } + } + + @Override + public ItemStack getItemStackRepresentation() { + return AEApi.instance().definitions().parts().storageBus().maybeStack(1).orElse(ItemStack.EMPTY); + } + + @Override + public GuiBridge getGuiBridge() { + return GuiBridge.GUI_STORAGEBUS; + } } diff --git a/src/main/java/appeng/parts/misc/PartToggleBus.java b/src/main/java/appeng/parts/misc/PartToggleBus.java index 128031bf5..8e7202be2 100644 --- a/src/main/java/appeng/parts/misc/PartToggleBus.java +++ b/src/main/java/appeng/parts/misc/PartToggleBus.java @@ -19,17 +19,6 @@ package appeng.parts.misc; -import java.util.EnumSet; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumHand; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; - import appeng.api.AEApi; import appeng.api.exceptions.FailedConnectionException; import appeng.api.networking.IGridConnection; @@ -46,184 +35,161 @@ import appeng.items.parts.PartModels; import appeng.me.helpers.AENetworkProxy; import appeng.parts.PartBasicState; import appeng.parts.PartModel; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumHand; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; + +import java.util.EnumSet; -public class PartToggleBus extends PartBasicState -{ +public class PartToggleBus extends PartBasicState { - @PartModels - public static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "part/toggle_bus_base" ); - @PartModels - public static final ResourceLocation MODEL_STATUS_OFF = new ResourceLocation( AppEng.MOD_ID, "part/toggle_bus_status_off" ); - @PartModels - public static final ResourceLocation MODEL_STATUS_ON = new ResourceLocation( AppEng.MOD_ID, "part/toggle_bus_status_on" ); - @PartModels - public static final ResourceLocation MODEL_STATUS_HAS_CHANNEL = new ResourceLocation( AppEng.MOD_ID, "part/toggle_bus_status_has_channel" ); + @PartModels + public static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "part/toggle_bus_base"); + @PartModels + public static final ResourceLocation MODEL_STATUS_OFF = new ResourceLocation(AppEng.MOD_ID, "part/toggle_bus_status_off"); + @PartModels + public static final ResourceLocation MODEL_STATUS_ON = new ResourceLocation(AppEng.MOD_ID, "part/toggle_bus_status_on"); + @PartModels + public static final ResourceLocation MODEL_STATUS_HAS_CHANNEL = new ResourceLocation(AppEng.MOD_ID, "part/toggle_bus_status_has_channel"); - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_STATUS_OFF ); - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_STATUS_ON ); - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, MODEL_STATUS_HAS_CHANNEL ); + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_STATUS_OFF); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_STATUS_ON); + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, MODEL_STATUS_HAS_CHANNEL); - private static final int REDSTONE_FLAG = 4; - private final AENetworkProxy outerProxy = new AENetworkProxy( this, "outer", ItemStack.EMPTY, true ); - private IGridConnection connection; - private boolean hasRedstone = false; + private static final int REDSTONE_FLAG = 4; + private final AENetworkProxy outerProxy = new AENetworkProxy(this, "outer", ItemStack.EMPTY, true); + private IGridConnection connection; + private boolean hasRedstone = false; - @Reflected - public PartToggleBus( final ItemStack is ) - { - super( is ); + @Reflected + public PartToggleBus(final ItemStack is) { + super(is); - this.getProxy().setIdlePowerUsage( 0.0 ); - this.getOuterProxy().setIdlePowerUsage( 0.0 ); - this.getProxy().setFlags(); - this.getOuterProxy().setFlags(); - } + this.getProxy().setIdlePowerUsage(0.0); + this.getOuterProxy().setIdlePowerUsage(0.0); + this.getProxy().setFlags(); + this.getOuterProxy().setFlags(); + } - @Override - protected int populateFlags( final int cf ) - { - return cf | ( this.getIntention() ? REDSTONE_FLAG : 0 ); - } + @Override + protected int populateFlags(final int cf) { + return cf | (this.getIntention() ? REDSTONE_FLAG : 0); + } - public boolean hasRedstoneFlag() - { - return ( this.getClientFlags() & REDSTONE_FLAG ) == REDSTONE_FLAG; - } + public boolean hasRedstoneFlag() { + return (this.getClientFlags() & REDSTONE_FLAG) == REDSTONE_FLAG; + } - protected boolean getIntention() - { - return this.getHost().hasRedstone( this.getSide() ); - } + protected boolean getIntention() { + return this.getHost().hasRedstone(this.getSide()); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.GLASS; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.GLASS; + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 6, 6, 11, 10, 10, 16 ); - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(6, 6, 11, 10, 10, 16); + } - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - final boolean oldHasRedstone = this.hasRedstone; - this.hasRedstone = this.getHost().hasRedstone( this.getSide() ); + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + final boolean oldHasRedstone = this.hasRedstone; + this.hasRedstone = this.getHost().hasRedstone(this.getSide()); - if( this.hasRedstone != oldHasRedstone ) - { - this.updateInternalState(); - this.getHost().markForUpdate(); - } - } + if (this.hasRedstone != oldHasRedstone) { + this.updateInternalState(); + this.getHost().markForUpdate(); + } + } - @Override - public void readFromNBT( final NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.getOuterProxy().readFromNBT( extra ); - } + @Override + public void readFromNBT(final NBTTagCompound extra) { + super.readFromNBT(extra); + this.getOuterProxy().readFromNBT(extra); + } - @Override - public void writeToNBT( final NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.getOuterProxy().writeToNBT( extra ); - } + @Override + public void writeToNBT(final NBTTagCompound extra) { + super.writeToNBT(extra); + this.getOuterProxy().writeToNBT(extra); + } - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - this.getOuterProxy().invalidate(); - } + @Override + public void removeFromWorld() { + super.removeFromWorld(); + this.getOuterProxy().invalidate(); + } - @Override - public void addToWorld() - { - super.addToWorld(); - this.getOuterProxy().onReady(); - this.hasRedstone = this.getHost().hasRedstone( this.getSide() ); - this.updateInternalState(); - } + @Override + public void addToWorld() { + super.addToWorld(); + this.getOuterProxy().onReady(); + this.hasRedstone = this.getHost().hasRedstone(this.getSide()); + this.updateInternalState(); + } - @Override - public void setPartHostInfo( final AEPartLocation side, final IPartHost host, final TileEntity tile ) - { - super.setPartHostInfo( side, host, tile ); - this.outerProxy.setValidSides( EnumSet.of( side.getFacing() ) ); - } + @Override + public void setPartHostInfo(final AEPartLocation side, final IPartHost host, final TileEntity tile) { + super.setPartHostInfo(side, host, tile); + this.outerProxy.setValidSides(EnumSet.of(side.getFacing())); + } - @Override - public IGridNode getExternalFacingNode() - { - return this.getOuterProxy().getNode(); - } + @Override + public IGridNode getExternalFacingNode() { + return this.getOuterProxy().getNode(); + } - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 5; - } + @Override + public float getCableConnectionLength(AECableType cable) { + return 5; + } - @Override - public void onPlacement( final EntityPlayer player, final EnumHand hand, final ItemStack held, final AEPartLocation side ) - { - super.onPlacement( player, hand, held, side ); - this.getOuterProxy().setOwner( player ); - } + @Override + public void onPlacement(final EntityPlayer player, final EnumHand hand, final ItemStack held, final AEPartLocation side) { + super.onPlacement(player, hand, held, side); + this.getOuterProxy().setOwner(player); + } - private void updateInternalState() - { - final boolean intention = this.getIntention(); - if( intention == ( this.connection == null ) ) - { - if( this.getProxy().getNode() != null && this.getOuterProxy().getNode() != null ) - { - if( intention ) - { - try - { - this.connection = AEApi.instance().grid().createGridConnection( this.getProxy().getNode(), this.getOuterProxy().getNode() ); - } - catch( final FailedConnectionException e ) - { - // :( - AELog.debug( e ); - } - } - else - { - this.connection.destroy(); - this.connection = null; - } - } - } - } + private void updateInternalState() { + final boolean intention = this.getIntention(); + if (intention == (this.connection == null)) { + if (this.getProxy().getNode() != null && this.getOuterProxy().getNode() != null) { + if (intention) { + try { + this.connection = AEApi.instance().grid().createGridConnection(this.getProxy().getNode(), this.getOuterProxy().getNode()); + } catch (final FailedConnectionException e) { + // :( + AELog.debug(e); + } + } else { + this.connection.destroy(); + this.connection = null; + } + } + } + } - AENetworkProxy getOuterProxy() - { - return this.outerProxy; - } + AENetworkProxy getOuterProxy() { + return this.outerProxy; + } - @Override - public IPartModel getStaticModels() - { - if( this.hasRedstoneFlag() && this.isActive() && this.isPowered() ) - { - return MODELS_HAS_CHANNEL; - } - else if( this.hasRedstoneFlag() && this.isPowered() ) - { - return MODELS_ON; - } - else - { - return MODELS_OFF; - } - } + @Override + public IPartModel getStaticModels() { + if (this.hasRedstoneFlag() && this.isActive() && this.isPowered()) { + return MODELS_HAS_CHANNEL; + } else if (this.hasRedstoneFlag() && this.isPowered()) { + return MODELS_ON; + } else { + return MODELS_OFF; + } + } } diff --git a/src/main/java/appeng/parts/networking/PartCable.java b/src/main/java/appeng/parts/networking/PartCable.java index 7834a4765..be3e1653c 100644 --- a/src/main/java/appeng/parts/networking/PartCable.java +++ b/src/main/java/appeng/parts/networking/PartCable.java @@ -19,18 +19,6 @@ package appeng.parts.networking; -import java.io.IOException; -import java.util.EnumSet; - -import com.google.common.collect.ImmutableSet; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; - import appeng.api.AEApi; import appeng.api.config.SecurityPermissions; import appeng.api.definitions.IParts; @@ -51,386 +39,318 @@ import appeng.items.parts.ItemPart; import appeng.me.GridAccessException; import appeng.parts.AEBasePart; import appeng.util.Platform; +import com.google.common.collect.ImmutableSet; +import io.netty.buffer.ByteBuf; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; + +import java.io.IOException; +import java.util.EnumSet; -public class PartCable extends AEBasePart implements IPartCable -{ +public class PartCable extends AEBasePart implements IPartCable { - private static final ImmutableSet STRAIGHT_PART_LOCATIONS = ImmutableSet.of( AEPartLocation.DOWN, AEPartLocation.NORTH, - AEPartLocation.EAST ); + private static final ImmutableSet STRAIGHT_PART_LOCATIONS = ImmutableSet.of(AEPartLocation.DOWN, AEPartLocation.NORTH, + AEPartLocation.EAST); - private final int[] channelsOnSide = { 0, 0, 0, 0, 0, 0 }; + private final int[] channelsOnSide = {0, 0, 0, 0, 0, 0}; - private EnumSet connections = EnumSet.noneOf( AEPartLocation.class ); - private boolean powered = false; + private EnumSet connections = EnumSet.noneOf(AEPartLocation.class); + private boolean powered = false; - public PartCable( final ItemStack is ) - { - super( is ); - this.getProxy().setFlags( GridFlags.PREFERRED ); - this.getProxy().setIdlePowerUsage( 0.0 ); - this.getProxy().setColor( AEColor.values()[( (ItemPart) is.getItem() ).variantOf( is.getItemDamage() )] ); - } + public PartCable(final ItemStack is) { + super(is); + this.getProxy().setFlags(GridFlags.PREFERRED); + this.getProxy().setIdlePowerUsage(0.0); + this.getProxy().setColor(AEColor.values()[((ItemPart) is.getItem()).variantOf(is.getItemDamage())]); + } - @Override - public BusSupport supportsBuses() - { - return BusSupport.CABLE; - } + @Override + public BusSupport supportsBuses() { + return BusSupport.CABLE; + } - @Override - public AEColor getCableColor() - { - return this.getProxy().getColor(); - } + @Override + public AEColor getCableColor() { + return this.getProxy().getColor(); + } - @Override - public AECableType getCableConnectionType() - { - return AECableType.GLASS; - } + @Override + public AECableType getCableConnectionType() { + return AECableType.GLASS; + } - @Override - public float getCableConnectionLength( AECableType cable ) - { - if( cable == this.getCableConnectionType() ) - { - return 4; - } - else if( cable.ordinal() >= this.getCableConnectionType().ordinal() ) - { - return -1; - } - else - { - return 8; - } - } + @Override + public float getCableConnectionLength(AECableType cable) { + if (cable == this.getCableConnectionType()) { + return 4; + } else if (cable.ordinal() >= this.getCableConnectionType().ordinal()) { + return -1; + } else { + return 8; + } + } - @Override - public boolean changeColor( final AEColor newColor, final EntityPlayer who ) - { - if( this.getCableColor() != newColor ) - { - ItemStack newPart = null; + @Override + public boolean changeColor(final AEColor newColor, final EntityPlayer who) { + if (this.getCableColor() != newColor) { + ItemStack newPart = null; - final IParts parts = AEApi.instance().definitions().parts(); + final IParts parts = AEApi.instance().definitions().parts(); - if( this.getCableConnectionType() == AECableType.GLASS ) - { - newPart = parts.cableGlass().stack( newColor, 1 ); - } - else if( this.getCableConnectionType() == AECableType.COVERED ) - { - newPart = parts.cableCovered().stack( newColor, 1 ); - } - else if( this.getCableConnectionType() == AECableType.SMART ) - { - newPart = parts.cableSmart().stack( newColor, 1 ); - } - else if( this.getCableConnectionType() == AECableType.DENSE_COVERED ) - { - newPart = parts.cableDenseCovered().stack( newColor, 1 ); - } - else if( this.getCableConnectionType() == AECableType.DENSE_SMART ) - { - newPart = parts.cableDenseSmart().stack( newColor, 1 ); - } + if (this.getCableConnectionType() == AECableType.GLASS) { + newPart = parts.cableGlass().stack(newColor, 1); + } else if (this.getCableConnectionType() == AECableType.COVERED) { + newPart = parts.cableCovered().stack(newColor, 1); + } else if (this.getCableConnectionType() == AECableType.SMART) { + newPart = parts.cableSmart().stack(newColor, 1); + } else if (this.getCableConnectionType() == AECableType.DENSE_COVERED) { + newPart = parts.cableDenseCovered().stack(newColor, 1); + } else if (this.getCableConnectionType() == AECableType.DENSE_SMART) { + newPart = parts.cableDenseSmart().stack(newColor, 1); + } - boolean hasPermission = true; + boolean hasPermission = true; - try - { - hasPermission = this.getProxy().getSecurity().hasPermission( who, SecurityPermissions.BUILD ); - } - catch( final GridAccessException e ) - { - // :P - } + try { + hasPermission = this.getProxy().getSecurity().hasPermission(who, SecurityPermissions.BUILD); + } catch (final GridAccessException e) { + // :P + } - if( newPart != null && hasPermission ) - { - if( Platform.isClient() ) - { - return true; - } + if (newPart != null && hasPermission) { + if (Platform.isClient()) { + return true; + } - this.getHost().removePart( AEPartLocation.INTERNAL, true ); - this.getHost().addPart( newPart, AEPartLocation.INTERNAL, who, null ); - return true; - } - } - return false; - } + this.getHost().removePart(AEPartLocation.INTERNAL, true); + this.getHost().addPart(newPart, AEPartLocation.INTERNAL, who, null); + return true; + } + } + return false; + } - @Override - public void setValidSides( final EnumSet sides ) - { - this.getProxy().setValidSides( sides ); - } + @Override + public void setValidSides(final EnumSet sides) { + this.getProxy().setValidSides(sides); + } - @Override - public boolean isConnected( final EnumFacing side ) - { - return this.getConnections().contains( AEPartLocation.fromFacing( side ) ); - } + @Override + public boolean isConnected(final EnumFacing side) { + return this.getConnections().contains(AEPartLocation.fromFacing(side)); + } - public void markForUpdate() - { - this.getHost().markForUpdate(); - } + public void markForUpdate() { + this.getHost().markForUpdate(); + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 6.0, 6.0, 6.0, 10.0, 10.0, 10.0 ); + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(6.0, 6.0, 6.0, 10.0, 10.0, 10.0); - if( Platform.isServer() ) - { - final IGridNode n = this.getGridNode(); - if( n != null ) - { - this.setConnections( n.getConnectedSides() ); - } - else - { - this.getConnections().clear(); - } - } + if (Platform.isServer()) { + final IGridNode n = this.getGridNode(); + if (n != null) { + this.setConnections(n.getConnectedSides()); + } else { + this.getConnections().clear(); + } + } - final IPartHost ph = this.getHost(); - if( ph != null ) - { - for( final AEPartLocation dir : AEPartLocation.SIDE_LOCATIONS ) - { - final IPart p = ph.getPart( dir ); - if( p instanceof IGridHost ) - { - final double dist = p.getCableConnectionLength( this.getCableConnectionType() ); + final IPartHost ph = this.getHost(); + if (ph != null) { + for (final AEPartLocation dir : AEPartLocation.SIDE_LOCATIONS) { + final IPart p = ph.getPart(dir); + if (p instanceof IGridHost) { + final double dist = p.getCableConnectionLength(this.getCableConnectionType()); - if( dist > 8 ) - { - continue; - } + if (dist > 8) { + continue; + } - switch( dir ) - { - case DOWN: - bch.addBox( 6.0, dist, 6.0, 10.0, 6.0, 10.0 ); - break; - case EAST: - bch.addBox( 10.0, 6.0, 6.0, 16.0 - dist, 10.0, 10.0 ); - break; - case NORTH: - bch.addBox( 6.0, 6.0, dist, 10.0, 10.0, 6.0 ); - break; - case SOUTH: - bch.addBox( 6.0, 6.0, 10.0, 10.0, 10.0, 16.0 - dist ); - break; - case UP: - bch.addBox( 6.0, 10.0, 6.0, 10.0, 16.0 - dist, 10.0 ); - break; - case WEST: - bch.addBox( dist, 6.0, 6.0, 6.0, 10.0, 10.0 ); - break; - default: - } - } - } - } + switch (dir) { + case DOWN: + bch.addBox(6.0, dist, 6.0, 10.0, 6.0, 10.0); + break; + case EAST: + bch.addBox(10.0, 6.0, 6.0, 16.0 - dist, 10.0, 10.0); + break; + case NORTH: + bch.addBox(6.0, 6.0, dist, 10.0, 10.0, 6.0); + break; + case SOUTH: + bch.addBox(6.0, 6.0, 10.0, 10.0, 10.0, 16.0 - dist); + break; + case UP: + bch.addBox(6.0, 10.0, 6.0, 10.0, 16.0 - dist, 10.0); + break; + case WEST: + bch.addBox(dist, 6.0, 6.0, 6.0, 10.0, 10.0); + break; + default: + } + } + } + } - for( final AEPartLocation of : this.getConnections() ) - { - switch( of ) - { - case DOWN: - bch.addBox( 6.0, 0.0, 6.0, 10.0, 6.0, 10.0 ); - break; - case EAST: - bch.addBox( 10.0, 6.0, 6.0, 16.0, 10.0, 10.0 ); - break; - case NORTH: - bch.addBox( 6.0, 6.0, 0.0, 10.0, 10.0, 6.0 ); - break; - case SOUTH: - bch.addBox( 6.0, 6.0, 10.0, 10.0, 10.0, 16.0 ); - break; - case UP: - bch.addBox( 6.0, 10.0, 6.0, 10.0, 16.0, 10.0 ); - break; - case WEST: - bch.addBox( 0.0, 6.0, 6.0, 6.0, 10.0, 10.0 ); - break; - default: - } - } - } + for (final AEPartLocation of : this.getConnections()) { + switch (of) { + case DOWN: + bch.addBox(6.0, 0.0, 6.0, 10.0, 6.0, 10.0); + break; + case EAST: + bch.addBox(10.0, 6.0, 6.0, 16.0, 10.0, 10.0); + break; + case NORTH: + bch.addBox(6.0, 6.0, 0.0, 10.0, 10.0, 6.0); + break; + case SOUTH: + bch.addBox(6.0, 6.0, 10.0, 10.0, 10.0, 16.0); + break; + case UP: + bch.addBox(6.0, 10.0, 6.0, 10.0, 16.0, 10.0); + break; + case WEST: + bch.addBox(0.0, 6.0, 6.0, 6.0, 10.0, 10.0); + break; + default: + } + } + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); - if( Platform.isServer() ) - { - final IGridNode node = this.getGridNode(); + if (Platform.isServer()) { + final IGridNode node = this.getGridNode(); - if( node != null ) - { - int howMany = 0; - for( final IGridConnection gc : node.getConnections() ) - { - howMany = Math.max( gc.getUsedChannels(), howMany ); - } + if (node != null) { + int howMany = 0; + for (final IGridConnection gc : node.getConnections()) { + howMany = Math.max(gc.getUsedChannels(), howMany); + } - data.setByte( "usedChannels", (byte) howMany ); - } - } - } + data.setByte("usedChannels", (byte) howMany); + } + } + } - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - int flags = 0; - boolean[] writeSide = new boolean[EnumFacing.values().length]; - int[] channelsPerSide = new int[EnumFacing.values().length]; + @Override + public void writeToStream(final ByteBuf data) throws IOException { + int flags = 0; + boolean[] writeSide = new boolean[EnumFacing.values().length]; + int[] channelsPerSide = new int[EnumFacing.values().length]; - for( EnumFacing thisSide : EnumFacing.values() ) - { - final IPart part = this.getHost().getPart( thisSide ); - if( part != null ) - { - writeSide[thisSide.ordinal()] = true; - int channels = 0; - if( part.getGridNode() != null ) - { - final IReadOnlyCollection set = part.getGridNode().getConnections(); - for( final IGridConnection gc : set ) - { - channels = Math.max( channels, gc.getUsedChannels() ); - } - } - channelsPerSide[thisSide.ordinal()] = channels; - } - } + for (EnumFacing thisSide : EnumFacing.values()) { + final IPart part = this.getHost().getPart(thisSide); + if (part != null) { + writeSide[thisSide.ordinal()] = true; + int channels = 0; + if (part.getGridNode() != null) { + final IReadOnlyCollection set = part.getGridNode().getConnections(); + for (final IGridConnection gc : set) { + channels = Math.max(channels, gc.getUsedChannels()); + } + } + channelsPerSide[thisSide.ordinal()] = channels; + } + } - IGridNode n = this.getGridNode(); - if( n != null ) - { - for( final IGridConnection gc : n.getConnections() ) - { - final AEPartLocation side = gc.getDirection( n ); - if( side != AEPartLocation.INTERNAL ) - { - writeSide[side.ordinal()] = true; - channelsPerSide[side.ordinal()] = gc.getUsedChannels(); - flags |= ( 1 << side.ordinal() ); - } - } - } + IGridNode n = this.getGridNode(); + if (n != null) { + for (final IGridConnection gc : n.getConnections()) { + final AEPartLocation side = gc.getDirection(n); + if (side != AEPartLocation.INTERNAL) { + writeSide[side.ordinal()] = true; + channelsPerSide[side.ordinal()] = gc.getUsedChannels(); + flags |= (1 << side.ordinal()); + } + } + } - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - flags |= ( 1 << AEPartLocation.INTERNAL.ordinal() ); - } - } - catch( final GridAccessException e ) - { - // aww... - } + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + flags |= (1 << AEPartLocation.INTERNAL.ordinal()); + } + } catch (final GridAccessException e) { + // aww... + } - data.writeByte( (byte) flags ); - // Only write the used channels for sides where we have a part or another cable - for( int i = 0; i < writeSide.length; i++ ) - { - if( writeSide[i] ) - { - data.writeByte( channelsPerSide[i] ); - } - } - } + data.writeByte((byte) flags); + // Only write the used channels for sides where we have a part or another cable + for (int i = 0; i < writeSide.length; i++) { + if (writeSide[i]) { + data.writeByte(channelsPerSide[i]); + } + } + } - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - int cs = data.readByte(); - final EnumSet myC = this.getConnections().clone(); - final boolean wasPowered = this.powered; - this.powered = false; - boolean channelsChanged = false; + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + int cs = data.readByte(); + final EnumSet myC = this.getConnections().clone(); + final boolean wasPowered = this.powered; + this.powered = false; + boolean channelsChanged = false; - for( final AEPartLocation d : AEPartLocation.values() ) - { - if( d == AEPartLocation.INTERNAL ) - { - final int id = 1 << d.ordinal(); - if( id == ( cs & id ) ) - { - this.powered = true; - } - } - else - { - boolean conOnSide = ( cs & ( 1 << d.ordinal() ) ) != 0; - if( conOnSide ) - { - this.getConnections().add( d ); - } - else - { - this.getConnections().remove( d ); - } + for (final AEPartLocation d : AEPartLocation.values()) { + if (d == AEPartLocation.INTERNAL) { + final int id = 1 << d.ordinal(); + if (id == (cs & id)) { + this.powered = true; + } + } else { + boolean conOnSide = (cs & (1 << d.ordinal())) != 0; + if (conOnSide) { + this.getConnections().add(d); + } else { + this.getConnections().remove(d); + } - int ch = 0; + int ch = 0; - // Only read channels if there's a part on this side or a cable connection - // This works only because cables are always read *last* from the packet update for - // a cable bus - if( conOnSide || this.getHost().getPart( d ) != null ) - { - ch = ( data.readByte() ) & 0xFF; - } + // Only read channels if there's a part on this side or a cable connection + // This works only because cables are always read *last* from the packet update for + // a cable bus + if (conOnSide || this.getHost().getPart(d) != null) { + ch = (data.readByte()) & 0xFF; + } - if( ch != this.getChannelsOnSide( d.ordinal() ) ) - { - channelsChanged = true; - this.setChannelsOnSide( d.ordinal(), ch ); - } - } - } + if (ch != this.getChannelsOnSide(d.ordinal())) { + channelsChanged = true; + this.setChannelsOnSide(d.ordinal(), ch); + } + } + } - return !myC.equals( this.getConnections() ) || wasPowered != this.powered || channelsChanged; - } + return !myC.equals(this.getConnections()) || wasPowered != this.powered || channelsChanged; + } - int getChannelsOnSide( final int i ) - { - return this.channelsOnSide[i]; - } + int getChannelsOnSide(final int i) { + return this.channelsOnSide[i]; + } - public int getChannelsOnSide( EnumFacing side ) - { - if( !this.powered ) - { - return 0; - } - return this.channelsOnSide[side.ordinal()]; - } + public int getChannelsOnSide(EnumFacing side) { + if (!this.powered) { + return 0; + } + return this.channelsOnSide[side.ordinal()]; + } - void setChannelsOnSide( final int i, final int channels ) - { - this.channelsOnSide[i] = channels; - } + void setChannelsOnSide(final int i, final int channels) { + this.channelsOnSide[i] = channels; + } - EnumSet getConnections() - { - return this.connections; - } + EnumSet getConnections() { + return this.connections; + } - void setConnections( final EnumSet connections ) - { - this.connections = connections; - } + void setConnections(final EnumSet connections) { + this.connections = connections; + } } diff --git a/src/main/java/appeng/parts/networking/PartCableCovered.java b/src/main/java/appeng/parts/networking/PartCableCovered.java index ef9957f5b..3cf3f7145 100644 --- a/src/main/java/appeng/parts/networking/PartCableCovered.java +++ b/src/main/java/appeng/parts/networking/PartCableCovered.java @@ -19,8 +19,6 @@ package appeng.parts.networking; -import net.minecraft.item.ItemStack; - import appeng.api.networking.IGridNode; import appeng.api.networking.events.MENetworkChannelsChanged; import appeng.api.networking.events.MENetworkEventSubscribe; @@ -30,76 +28,65 @@ import appeng.api.util.AECableType; import appeng.api.util.AEPartLocation; import appeng.helpers.Reflected; import appeng.util.Platform; +import net.minecraft.item.ItemStack; -public class PartCableCovered extends PartCable -{ - @Reflected - public PartCableCovered( final ItemStack is ) - { - super( is ); - } +public class PartCableCovered extends PartCable { + @Reflected + public PartCableCovered(final ItemStack is) { + super(is); + } - @MENetworkEventSubscribe - public void channelUpdated( final MENetworkChannelsChanged c ) - { - this.getHost().markForUpdate(); - } + @MENetworkEventSubscribe + public void channelUpdated(final MENetworkChannelsChanged c) { + this.getHost().markForUpdate(); + } - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } - @Override - public AECableType getCableConnectionType() - { - return AECableType.COVERED; - } + @Override + public AECableType getCableConnectionType() { + return AECableType.COVERED; + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 5.0, 5.0, 5.0, 11.0, 11.0, 11.0 ); + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(5.0, 5.0, 5.0, 11.0, 11.0, 11.0); - if( Platform.isServer() ) - { - final IGridNode n = this.getGridNode(); - if( n != null ) - { - this.setConnections( n.getConnectedSides() ); - } - else - { - this.getConnections().clear(); - } - } + if (Platform.isServer()) { + final IGridNode n = this.getGridNode(); + if (n != null) { + this.setConnections(n.getConnectedSides()); + } else { + this.getConnections().clear(); + } + } - for( final AEPartLocation of : this.getConnections() ) - { - switch( of ) - { - case DOWN: - bch.addBox( 5.0, 0.0, 5.0, 11.0, 5.0, 11.0 ); - break; - case EAST: - bch.addBox( 11.0, 5.0, 5.0, 16.0, 11.0, 11.0 ); - break; - case NORTH: - bch.addBox( 5.0, 5.0, 0.0, 11.0, 11.0, 5.0 ); - break; - case SOUTH: - bch.addBox( 5.0, 5.0, 11.0, 11.0, 11.0, 16.0 ); - break; - case UP: - bch.addBox( 5.0, 11.0, 5.0, 11.0, 16.0, 11.0 ); - break; - case WEST: - bch.addBox( 0.0, 5.0, 5.0, 5.0, 11.0, 11.0 ); - break; - default: - } - } - } + for (final AEPartLocation of : this.getConnections()) { + switch (of) { + case DOWN: + bch.addBox(5.0, 0.0, 5.0, 11.0, 5.0, 11.0); + break; + case EAST: + bch.addBox(11.0, 5.0, 5.0, 16.0, 11.0, 11.0); + break; + case NORTH: + bch.addBox(5.0, 5.0, 0.0, 11.0, 11.0, 5.0); + break; + case SOUTH: + bch.addBox(5.0, 5.0, 11.0, 11.0, 11.0, 16.0); + break; + case UP: + bch.addBox(5.0, 11.0, 5.0, 11.0, 16.0, 11.0); + break; + case WEST: + bch.addBox(0.0, 5.0, 5.0, 5.0, 11.0, 11.0); + break; + default: + } + } + } } diff --git a/src/main/java/appeng/parts/networking/PartCableGlass.java b/src/main/java/appeng/parts/networking/PartCableGlass.java index 4c9525e5f..901d3a77d 100644 --- a/src/main/java/appeng/parts/networking/PartCableGlass.java +++ b/src/main/java/appeng/parts/networking/PartCableGlass.java @@ -19,16 +19,13 @@ package appeng.parts.networking; +import appeng.helpers.Reflected; import net.minecraft.item.ItemStack; -import appeng.helpers.Reflected; - -public class PartCableGlass extends PartCable -{ - @Reflected - public PartCableGlass( final ItemStack is ) - { - super( is ); - } +public class PartCableGlass extends PartCable { + @Reflected + public PartCableGlass(final ItemStack is) { + super(is); + } } diff --git a/src/main/java/appeng/parts/networking/PartCableSmart.java b/src/main/java/appeng/parts/networking/PartCableSmart.java index 5997cc59f..592376bfe 100644 --- a/src/main/java/appeng/parts/networking/PartCableSmart.java +++ b/src/main/java/appeng/parts/networking/PartCableSmart.java @@ -19,8 +19,6 @@ package appeng.parts.networking; -import net.minecraft.item.ItemStack; - import appeng.api.networking.IGridNode; import appeng.api.networking.events.MENetworkChannelsChanged; import appeng.api.networking.events.MENetworkEventSubscribe; @@ -30,76 +28,65 @@ import appeng.api.util.AECableType; import appeng.api.util.AEPartLocation; import appeng.helpers.Reflected; import appeng.util.Platform; +import net.minecraft.item.ItemStack; -public class PartCableSmart extends PartCable -{ - @Reflected - public PartCableSmart( final ItemStack is ) - { - super( is ); - } +public class PartCableSmart extends PartCable { + @Reflected + public PartCableSmart(final ItemStack is) { + super(is); + } - @MENetworkEventSubscribe - public void channelUpdated( final MENetworkChannelsChanged c ) - { - this.getHost().markForUpdate(); - } + @MENetworkEventSubscribe + public void channelUpdated(final MENetworkChannelsChanged c) { + this.getHost().markForUpdate(); + } - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } - @Override - public AECableType getCableConnectionType() - { - return AECableType.SMART; - } + @Override + public AECableType getCableConnectionType() { + return AECableType.SMART; + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 5.0, 5.0, 5.0, 11.0, 11.0, 11.0 ); + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(5.0, 5.0, 5.0, 11.0, 11.0, 11.0); - if( Platform.isServer() ) - { - final IGridNode n = this.getGridNode(); - if( n != null ) - { - this.setConnections( n.getConnectedSides() ); - } - else - { - this.getConnections().clear(); - } - } + if (Platform.isServer()) { + final IGridNode n = this.getGridNode(); + if (n != null) { + this.setConnections(n.getConnectedSides()); + } else { + this.getConnections().clear(); + } + } - for( final AEPartLocation of : this.getConnections() ) - { - switch( of ) - { - case DOWN: - bch.addBox( 5.0, 0.0, 5.0, 11.0, 5.0, 11.0 ); - break; - case EAST: - bch.addBox( 11.0, 5.0, 5.0, 16.0, 11.0, 11.0 ); - break; - case NORTH: - bch.addBox( 5.0, 5.0, 0.0, 11.0, 11.0, 5.0 ); - break; - case SOUTH: - bch.addBox( 5.0, 5.0, 11.0, 11.0, 11.0, 16.0 ); - break; - case UP: - bch.addBox( 5.0, 11.0, 5.0, 11.0, 16.0, 11.0 ); - break; - case WEST: - bch.addBox( 0.0, 5.0, 5.0, 5.0, 11.0, 11.0 ); - break; - default: - } - } - } + for (final AEPartLocation of : this.getConnections()) { + switch (of) { + case DOWN: + bch.addBox(5.0, 0.0, 5.0, 11.0, 5.0, 11.0); + break; + case EAST: + bch.addBox(11.0, 5.0, 5.0, 16.0, 11.0, 11.0); + break; + case NORTH: + bch.addBox(5.0, 5.0, 0.0, 11.0, 11.0, 5.0); + break; + case SOUTH: + bch.addBox(5.0, 5.0, 11.0, 11.0, 11.0, 16.0); + break; + case UP: + bch.addBox(5.0, 11.0, 5.0, 11.0, 16.0, 11.0); + break; + case WEST: + bch.addBox(0.0, 5.0, 5.0, 5.0, 11.0, 11.0); + break; + default: + } + } + } } diff --git a/src/main/java/appeng/parts/networking/PartDenseCable.java b/src/main/java/appeng/parts/networking/PartDenseCable.java index bc7532083..8afbf7ede 100644 --- a/src/main/java/appeng/parts/networking/PartDenseCable.java +++ b/src/main/java/appeng/parts/networking/PartDenseCable.java @@ -19,9 +19,6 @@ package appeng.parts.networking; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - import appeng.api.networking.GridFlags; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -34,123 +31,107 @@ import appeng.api.util.AECableType; import appeng.api.util.AEPartLocation; import appeng.helpers.Reflected; import appeng.util.Platform; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; -public abstract class PartDenseCable extends PartCable -{ - @Reflected - public PartDenseCable( final ItemStack is ) - { - super( is ); +public abstract class PartDenseCable extends PartCable { + @Reflected + public PartDenseCable(final ItemStack is) { + super(is); - this.getProxy().setFlags( GridFlags.DENSE_CAPACITY, GridFlags.PREFERRED ); - } + this.getProxy().setFlags(GridFlags.DENSE_CAPACITY, GridFlags.PREFERRED); + } - @Override - public BusSupport supportsBuses() - { - return BusSupport.DENSE_CABLE; - } + @Override + public BusSupport supportsBuses() { + return BusSupport.DENSE_CABLE; + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - final boolean noLadder = !bch.isBBCollision(); - final double min = noLadder ? 3.0 : 4.9; - final double max = noLadder ? 13.0 : 11.1; + @Override + public void getBoxes(final IPartCollisionHelper bch) { + final boolean noLadder = !bch.isBBCollision(); + final double min = noLadder ? 3.0 : 4.9; + final double max = noLadder ? 13.0 : 11.1; - bch.addBox( min, min, min, max, max, max ); + bch.addBox(min, min, min, max, max, max); - if( Platform.isServer() ) - { - final IGridNode n = this.getGridNode(); - if( n != null ) - { - this.setConnections( n.getConnectedSides() ); - } - else - { - this.getConnections().clear(); - } - } + if (Platform.isServer()) { + final IGridNode n = this.getGridNode(); + if (n != null) { + this.setConnections(n.getConnectedSides()); + } else { + this.getConnections().clear(); + } + } - for( final AEPartLocation of : this.getConnections() ) - { - if( this.isDense( of ) ) - { - switch( of ) - { - case DOWN: - bch.addBox( min, 0.0, min, max, min, max ); - break; - case EAST: - bch.addBox( max, min, min, 16.0, max, max ); - break; - case NORTH: - bch.addBox( min, min, 0.0, max, max, min ); - break; - case SOUTH: - bch.addBox( min, min, max, max, max, 16.0 ); - break; - case UP: - bch.addBox( min, max, min, max, 16.0, max ); - break; - case WEST: - bch.addBox( 0.0, min, min, min, max, max ); - break; - default: - } - } - else - { - switch( of ) - { - case DOWN: - bch.addBox( 5.0, 0.0, 5.0, 11.0, 5.0, 11.0 ); - break; - case EAST: - bch.addBox( 11.0, 5.0, 5.0, 16.0, 11.0, 11.0 ); - break; - case NORTH: - bch.addBox( 5.0, 5.0, 0.0, 11.0, 11.0, 5.0 ); - break; - case SOUTH: - bch.addBox( 5.0, 5.0, 11.0, 11.0, 11.0, 16.0 ); - break; - case UP: - bch.addBox( 5.0, 11.0, 5.0, 11.0, 16.0, 11.0 ); - break; - case WEST: - bch.addBox( 0.0, 5.0, 5.0, 5.0, 11.0, 11.0 ); - break; - default: - } - } - } - } + for (final AEPartLocation of : this.getConnections()) { + if (this.isDense(of)) { + switch (of) { + case DOWN: + bch.addBox(min, 0.0, min, max, min, max); + break; + case EAST: + bch.addBox(max, min, min, 16.0, max, max); + break; + case NORTH: + bch.addBox(min, min, 0.0, max, max, min); + break; + case SOUTH: + bch.addBox(min, min, max, max, max, 16.0); + break; + case UP: + bch.addBox(min, max, min, max, 16.0, max); + break; + case WEST: + bch.addBox(0.0, min, min, min, max, max); + break; + default: + } + } else { + switch (of) { + case DOWN: + bch.addBox(5.0, 0.0, 5.0, 11.0, 5.0, 11.0); + break; + case EAST: + bch.addBox(11.0, 5.0, 5.0, 16.0, 11.0, 11.0); + break; + case NORTH: + bch.addBox(5.0, 5.0, 0.0, 11.0, 11.0, 5.0); + break; + case SOUTH: + bch.addBox(5.0, 5.0, 11.0, 11.0, 11.0, 16.0); + break; + case UP: + bch.addBox(5.0, 11.0, 5.0, 11.0, 16.0, 11.0); + break; + case WEST: + bch.addBox(0.0, 5.0, 5.0, 5.0, 11.0, 11.0); + break; + default: + } + } + } + } - private boolean isDense( final AEPartLocation of ) - { - final TileEntity te = this.getTile().getWorld().getTileEntity( this.getTile().getPos().offset( of.getFacing() ) ); + private boolean isDense(final AEPartLocation of) { + final TileEntity te = this.getTile().getWorld().getTileEntity(this.getTile().getPos().offset(of.getFacing())); - if( te instanceof IGridHost ) - { - final AECableType t = ( (IGridHost) te ).getCableConnectionType( of.getOpposite() ); - return t.isDense(); - } + if (te instanceof IGridHost) { + final AECableType t = ((IGridHost) te).getCableConnectionType(of.getOpposite()); + return t.isDense(); + } - return false; - } + return false; + } - @MENetworkEventSubscribe - public void channelUpdated( final MENetworkChannelsChanged c ) - { - this.getHost().markForUpdate(); - } + @MENetworkEventSubscribe + public void channelUpdated(final MENetworkChannelsChanged c) { + this.getHost().markForUpdate(); + } - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } } diff --git a/src/main/java/appeng/parts/networking/PartDenseCableCovered.java b/src/main/java/appeng/parts/networking/PartDenseCableCovered.java index 1d569e13a..98643a3f0 100644 --- a/src/main/java/appeng/parts/networking/PartDenseCableCovered.java +++ b/src/main/java/appeng/parts/networking/PartDenseCableCovered.java @@ -19,23 +19,19 @@ package appeng.parts.networking; +import appeng.api.util.AECableType; import net.minecraft.item.ItemStack; -import appeng.api.util.AECableType; +public class PartDenseCableCovered extends PartDenseCable { -public class PartDenseCableCovered extends PartDenseCable -{ + public PartDenseCableCovered(ItemStack is) { + super(is); + } - public PartDenseCableCovered( ItemStack is ) - { - super( is ); - } - - @Override - public AECableType getCableConnectionType() - { - return AECableType.DENSE_COVERED; - } + @Override + public AECableType getCableConnectionType() { + return AECableType.DENSE_COVERED; + } } diff --git a/src/main/java/appeng/parts/networking/PartDenseCableSmart.java b/src/main/java/appeng/parts/networking/PartDenseCableSmart.java index fbb0fa944..8a61e748c 100644 --- a/src/main/java/appeng/parts/networking/PartDenseCableSmart.java +++ b/src/main/java/appeng/parts/networking/PartDenseCableSmart.java @@ -19,22 +19,18 @@ package appeng.parts.networking; +import appeng.api.util.AECableType; import net.minecraft.item.ItemStack; -import appeng.api.util.AECableType; +public class PartDenseCableSmart extends PartDenseCable { -public class PartDenseCableSmart extends PartDenseCable -{ + public PartDenseCableSmart(ItemStack is) { + super(is); + } - public PartDenseCableSmart( ItemStack is ) - { - super( is ); - } - - @Override - public AECableType getCableConnectionType() - { - return AECableType.DENSE_SMART; - } + @Override + public AECableType getCableConnectionType() { + return AECableType.DENSE_SMART; + } } diff --git a/src/main/java/appeng/parts/networking/PartQuartzFiber.java b/src/main/java/appeng/parts/networking/PartQuartzFiber.java index f29b80464..05b859e7a 100644 --- a/src/main/java/appeng/parts/networking/PartQuartzFiber.java +++ b/src/main/java/appeng/parts/networking/PartQuartzFiber.java @@ -19,17 +19,6 @@ package appeng.parts.networking; -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumSet; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumHand; -import net.minecraft.util.ResourceLocation; - import appeng.api.config.Actionable; import appeng.api.networking.GridFlags; import appeng.api.networking.IGridNode; @@ -46,154 +35,139 @@ import appeng.me.GridAccessException; import appeng.me.helpers.AENetworkProxy; import appeng.parts.AEBasePart; import appeng.parts.PartModel; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumHand; +import net.minecraft.util.ResourceLocation; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumSet; -public class PartQuartzFiber extends AEBasePart implements IEnergyGridProvider -{ +public class PartQuartzFiber extends AEBasePart implements IEnergyGridProvider { - @PartModels - private static final IPartModel MODELS = new PartModel( new ResourceLocation( AppEng.MOD_ID, "part/quartz_fiber" ) ); + @PartModels + private static final IPartModel MODELS = new PartModel(new ResourceLocation(AppEng.MOD_ID, "part/quartz_fiber")); - private final AENetworkProxy outerProxy = new AENetworkProxy( this, "outer", this.getProxy().getMachineRepresentation(), true ); + private final AENetworkProxy outerProxy = new AENetworkProxy(this, "outer", this.getProxy().getMachineRepresentation(), true); - public PartQuartzFiber( final ItemStack is ) - { - super( is ); - this.getProxy().setIdlePowerUsage( 0 ); - this.getProxy().setFlags( GridFlags.CANNOT_CARRY ); - this.outerProxy.setIdlePowerUsage( 0 ); - this.outerProxy.setFlags( GridFlags.CANNOT_CARRY ); - } + public PartQuartzFiber(final ItemStack is) { + super(is); + this.getProxy().setIdlePowerUsage(0); + this.getProxy().setFlags(GridFlags.CANNOT_CARRY); + this.outerProxy.setIdlePowerUsage(0); + this.outerProxy.setFlags(GridFlags.CANNOT_CARRY); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.GLASS; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.GLASS; + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 6, 6, 10, 10, 10, 16 ); - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(6, 6, 10, 10, 10, 16); + } - @Override - public void readFromNBT( final NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.outerProxy.readFromNBT( extra ); - } + @Override + public void readFromNBT(final NBTTagCompound extra) { + super.readFromNBT(extra); + this.outerProxy.readFromNBT(extra); + } - @Override - public void writeToNBT( final NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.outerProxy.writeToNBT( extra ); - } + @Override + public void writeToNBT(final NBTTagCompound extra) { + super.writeToNBT(extra); + this.outerProxy.writeToNBT(extra); + } - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - this.outerProxy.invalidate(); - } + @Override + public void removeFromWorld() { + super.removeFromWorld(); + this.outerProxy.invalidate(); + } - @Override - public void addToWorld() - { - super.addToWorld(); - this.outerProxy.onReady(); - } + @Override + public void addToWorld() { + super.addToWorld(); + this.outerProxy.onReady(); + } - @Override - public void setPartHostInfo( final AEPartLocation side, final IPartHost host, final TileEntity tile ) - { - super.setPartHostInfo( side, host, tile ); - this.outerProxy.setValidSides( EnumSet.of( side.getFacing() ) ); - } + @Override + public void setPartHostInfo(final AEPartLocation side, final IPartHost host, final TileEntity tile) { + super.setPartHostInfo(side, host, tile); + this.outerProxy.setValidSides(EnumSet.of(side.getFacing())); + } - @Override - public IGridNode getExternalFacingNode() - { - return this.outerProxy.getNode(); - } + @Override + public IGridNode getExternalFacingNode() { + return this.outerProxy.getNode(); + } - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 16; - } + @Override + public float getCableConnectionLength(AECableType cable) { + return 16; + } - @Override - public void onPlacement( final EntityPlayer player, final EnumHand hand, final ItemStack held, final AEPartLocation side ) - { - super.onPlacement( player, hand, held, side ); - this.outerProxy.setOwner( player ); - } + @Override + public void onPlacement(final EntityPlayer player, final EnumHand hand, final ItemStack held, final AEPartLocation side) { + super.onPlacement(player, hand, held, side); + this.outerProxy.setOwner(player); + } - @Override - public Collection providers() - { - Collection providers = new ArrayList<>(); + @Override + public Collection providers() { + Collection providers = new ArrayList<>(); - try - { - final IEnergyGrid eg = this.getProxy().getEnergy(); + try { + final IEnergyGrid eg = this.getProxy().getEnergy(); - providers.add( eg ); - } - catch( final GridAccessException e ) - { - // :P - } + providers.add(eg); + } catch (final GridAccessException e) { + // :P + } - try - { - final IEnergyGrid eg = this.outerProxy.getEnergy(); + try { + final IEnergyGrid eg = this.outerProxy.getEnergy(); - providers.add( eg ); - } - catch( final GridAccessException e ) - { - // :P - } + providers.add(eg); + } catch (final GridAccessException e) { + // :P + } - return providers; - } + return providers; + } - @Override - public double extractProviderPower( final double amt, final Actionable mode ) - { - return 0; - } + @Override + public double extractProviderPower(final double amt, final Actionable mode) { + return 0; + } - @Override - public double injectProviderPower( final double amt, final Actionable mode ) - { - return amt; - } + @Override + public double injectProviderPower(final double amt, final Actionable mode) { + return amt; + } - @Override - public double getProviderEnergyDemand( final double amt ) - { - return 0; - } + @Override + public double getProviderEnergyDemand(final double amt) { + return 0; + } - @Override - public double getProviderStoredEnergy() - { - return 0; - } + @Override + public double getProviderStoredEnergy() { + return 0; + } - @Override - public double getProviderMaxEnergy() - { - return 0; - } + @Override + public double getProviderMaxEnergy() { + return 0; + } - @Override - public IPartModel getStaticModels() - { - return MODELS; - } + @Override + public IPartModel getStaticModels() { + return MODELS; + } } diff --git a/src/main/java/appeng/parts/p2p/P2PModels.java b/src/main/java/appeng/parts/p2p/P2PModels.java index 6bc8060ce..a6b583a0d 100644 --- a/src/main/java/appeng/parts/p2p/P2PModels.java +++ b/src/main/java/appeng/parts/p2p/P2PModels.java @@ -19,63 +19,53 @@ package appeng.parts.p2p; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.util.ResourceLocation; - import appeng.api.parts.IPartModel; import appeng.core.AppEng; import appeng.parts.PartModel; +import net.minecraft.util.ResourceLocation; + +import java.util.ArrayList; +import java.util.List; /** * Helper for maintaining the models used for a variant of the P2P bus. */ -class P2PModels -{ +class P2PModels { - public static final ResourceLocation MODEL_STATUS_OFF = new ResourceLocation( AppEng.MOD_ID, "part/p2p/p2p_tunnel_status_off" ); - public static final ResourceLocation MODEL_STATUS_ON = new ResourceLocation( AppEng.MOD_ID, "part/p2p/p2p_tunnel_status_on" ); - public static final ResourceLocation MODEL_STATUS_HAS_CHANNEL = new ResourceLocation( AppEng.MOD_ID, "part/p2p/p2p_tunnel_status_has_channel" ); - public static final ResourceLocation MODEL_FREQUENCY = new ResourceLocation( AppEng.MOD_ID, "part/builtin/p2p_tunnel_frequency" ); + public static final ResourceLocation MODEL_STATUS_OFF = new ResourceLocation(AppEng.MOD_ID, "part/p2p/p2p_tunnel_status_off"); + public static final ResourceLocation MODEL_STATUS_ON = new ResourceLocation(AppEng.MOD_ID, "part/p2p/p2p_tunnel_status_on"); + public static final ResourceLocation MODEL_STATUS_HAS_CHANNEL = new ResourceLocation(AppEng.MOD_ID, "part/p2p/p2p_tunnel_status_has_channel"); + public static final ResourceLocation MODEL_FREQUENCY = new ResourceLocation(AppEng.MOD_ID, "part/builtin/p2p_tunnel_frequency"); - private final IPartModel modelsOff; - private final IPartModel modelsOn; - private final IPartModel modelsHasChannel; + private final IPartModel modelsOff; + private final IPartModel modelsOn; + private final IPartModel modelsHasChannel; - public P2PModels( String frontModelPath ) - { - ResourceLocation frontModel = new ResourceLocation( AppEng.MOD_ID, frontModelPath ); + public P2PModels(String frontModelPath) { + ResourceLocation frontModel = new ResourceLocation(AppEng.MOD_ID, frontModelPath); - this.modelsOff = new PartModel( MODEL_STATUS_OFF, MODEL_FREQUENCY, frontModel ); - this.modelsOn = new PartModel( MODEL_STATUS_ON, MODEL_FREQUENCY, frontModel ); - this.modelsHasChannel = new PartModel( MODEL_STATUS_HAS_CHANNEL, MODEL_FREQUENCY, frontModel ); - } + this.modelsOff = new PartModel(MODEL_STATUS_OFF, MODEL_FREQUENCY, frontModel); + this.modelsOn = new PartModel(MODEL_STATUS_ON, MODEL_FREQUENCY, frontModel); + this.modelsHasChannel = new PartModel(MODEL_STATUS_HAS_CHANNEL, MODEL_FREQUENCY, frontModel); + } - public IPartModel getModel( boolean hasPower, boolean hasChannel ) - { - if( hasPower && hasChannel ) - { - return this.modelsHasChannel; - } - else if( hasPower ) - { - return this.modelsOn; - } - else - { - return this.modelsOff; - } - } + public IPartModel getModel(boolean hasPower, boolean hasChannel) { + if (hasPower && hasChannel) { + return this.modelsHasChannel; + } else if (hasPower) { + return this.modelsOn; + } else { + return this.modelsOff; + } + } - public List getModels() - { - List result = new ArrayList<>(); - result.add( this.modelsOff ); - result.add( this.modelsOn ); - result.add( this.modelsHasChannel ); - return result; - } + public List getModels() { + List result = new ArrayList<>(); + result.add(this.modelsOff); + result.add(this.modelsOn); + result.add(this.modelsHasChannel); + return result; + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PFEPower.java b/src/main/java/appeng/parts/p2p/PartP2PFEPower.java index 0ac913fcc..64fd8b8a7 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PFEPower.java +++ b/src/main/java/appeng/parts/p2p/PartP2PFEPower.java @@ -19,305 +19,252 @@ package appeng.parts.p2p; -import java.util.*; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import appeng.me.cache.helpers.TunnelCollection; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.energy.IEnergyStorage; - import appeng.api.config.PowerUnits; import appeng.api.parts.IPartModel; import appeng.capabilities.Capabilities; import appeng.items.parts.PartModels; import appeng.me.GridAccessException; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.energy.IEnergyStorage; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayDeque; +import java.util.List; +import java.util.Queue; -public class PartP2PFEPower extends PartP2PTunnel -{ - private static final P2PModels MODELS = new P2PModels( "part/p2p/p2p_tunnel_fe" ); - private static final IEnergyStorage NULL_ENERGY_STORAGE = new NullEnergyStorage(); - private final IEnergyStorage inputHandler = new InputEnergyStorage(); - private final IEnergyStorage outputHandler = new OutputEnergyStorage(); - private final Queue outputs = new ArrayDeque<>(); +public class PartP2PFEPower extends PartP2PTunnel { + private static final P2PModels MODELS = new P2PModels("part/p2p/p2p_tunnel_fe"); + private static final IEnergyStorage NULL_ENERGY_STORAGE = new NullEnergyStorage(); + private final IEnergyStorage inputHandler = new InputEnergyStorage(); + private final IEnergyStorage outputHandler = new OutputEnergyStorage(); + private final Queue outputs = new ArrayDeque<>(); - public PartP2PFEPower( ItemStack is ) - { - super( is ); - } + public PartP2PFEPower(ItemStack is) { + super(is); + } - @PartModels - public static List getModels() - { - return MODELS.getModels(); - } + @PartModels + public static List getModels() { + return MODELS.getModels(); + } - @Override - public IPartModel getStaticModels() - { - return MODELS.getModel( this.isPowered(), this.isActive() ); - } + @Override + public IPartModel getStaticModels() { + return MODELS.getModel(this.isPowered(), this.isActive()); + } - @Override - public void onTunnelNetworkChange() - { - this.getHost().notifyNeighbors(); - } + @Override + public void onTunnelNetworkChange() { + this.getHost().notifyNeighbors(); + } - private IEnergyStorage getAttachedEnergyStorage() - { - if( this.isActive() ) - { - final TileEntity self = this.getTile(); - final TileEntity te = self.getWorld().getTileEntity( self.getPos().offset( this.getSide().getFacing() ) ); + private IEnergyStorage getAttachedEnergyStorage() { + if (this.isActive()) { + final TileEntity self = this.getTile(); + final TileEntity te = self.getWorld().getTileEntity(self.getPos().offset(this.getSide().getFacing())); - if( te != null && te.hasCapability( Capabilities.FORGE_ENERGY, this.getSide().getOpposite().getFacing() ) ) - { - return te.getCapability( Capabilities.FORGE_ENERGY, this.getSide().getOpposite().getFacing() ); - } - } - return NULL_ENERGY_STORAGE; - } + if (te != null && te.hasCapability(Capabilities.FORGE_ENERGY, this.getSide().getOpposite().getFacing())) { + return te.getCapability(Capabilities.FORGE_ENERGY, this.getSide().getOpposite().getFacing()); + } + } + return NULL_ENERGY_STORAGE; + } - @Override - public boolean hasCapability( @Nonnull Capability capability ) - { - if( capability == Capabilities.FORGE_ENERGY ) - { - return true; - } - return super.hasCapability( capability ); - } + @Override + public boolean hasCapability(@Nonnull Capability capability) { + if (capability == Capabilities.FORGE_ENERGY) { + return true; + } + return super.hasCapability(capability); + } - @Nullable - @Override - public T getCapability( @Nonnull Capability capability ) - { - if( capability == Capabilities.FORGE_ENERGY ) - { - if( this.isOutput() ) - { - return (T) this.outputHandler; - } - return (T) this.inputHandler; - } - return super.getCapability( capability ); - } + @Nullable + @Override + public T getCapability(@Nonnull Capability capability) { + if (capability == Capabilities.FORGE_ENERGY) { + if (this.isOutput()) { + return (T) this.outputHandler; + } + return (T) this.inputHandler; + } + return super.getCapability(capability); + } - private class InputEnergyStorage implements IEnergyStorage - { - private boolean iteratingOutputs; + private class InputEnergyStorage implements IEnergyStorage { + private boolean iteratingOutputs; - @Override - public int extractEnergy( int maxExtract, boolean simulate ) - { - return 0; - } + @Override + public int extractEnergy(int maxExtract, boolean simulate) { + return 0; + } - @Override - public int receiveEnergy( int maxReceive, boolean simulate ) - { - int total = 0; + @Override + public int receiveEnergy(int maxReceive, boolean simulate) { + int total = 0; - try - { - final int outputTunnels = PartP2PFEPower.this.getOutputs().size(); + try { + final int outputTunnels = PartP2PFEPower.this.getOutputs().size(); - if( outputTunnels == 0 | maxReceive == 0 ) - { - return 0; - } + if (outputTunnels == 0 | maxReceive == 0) { + return 0; + } - final int amountPerOutput = maxReceive / outputTunnels; - int overflow = 0; + final int amountPerOutput = maxReceive / outputTunnels; + int overflow = 0; - for( PartP2PFEPower o : PartP2PFEPower.this.getOutputs() ) - outputs.add( o ); + for (PartP2PFEPower o : PartP2PFEPower.this.getOutputs()) + outputs.add(o); - while( !outputs.isEmpty() ) - { - PartP2PFEPower target = outputs.poll(); - final IEnergyStorage output = target.getAttachedEnergyStorage(); - final int received = output.receiveEnergy( amountPerOutput, simulate ); + while (!outputs.isEmpty()) { + PartP2PFEPower target = outputs.poll(); + final IEnergyStorage output = target.getAttachedEnergyStorage(); + final int received = output.receiveEnergy(amountPerOutput, simulate); - overflow += amountPerOutput - received; - total += received; - } + overflow += amountPerOutput - received; + total += received; + } - if( overflow > 0 ) - { - for( PartP2PFEPower o : PartP2PFEPower.this.getOutputs() ) - outputs.add( o ); + if (overflow > 0) { + for (PartP2PFEPower o : PartP2PFEPower.this.getOutputs()) + outputs.add(o); - while( !outputs.isEmpty() ) - { - PartP2PFEPower target = outputs.poll(); - final IEnergyStorage output = target.getAttachedEnergyStorage(); - final int received = output.receiveEnergy( overflow, simulate ); + while (!outputs.isEmpty()) { + PartP2PFEPower target = outputs.poll(); + final IEnergyStorage output = target.getAttachedEnergyStorage(); + final int received = output.receiveEnergy(overflow, simulate); - overflow -= received; - total += received; - if( overflow == 0 ) - { - outputs.clear(); - break; - } - } - } + overflow -= received; + total += received; + if (overflow == 0) { + outputs.clear(); + break; + } + } + } - if( !simulate ) - { - PartP2PFEPower.this.queueTunnelDrain( PowerUnits.RF, total ); - } - } - catch( GridAccessException ignored ) - { - } + if (!simulate) { + PartP2PFEPower.this.queueTunnelDrain(PowerUnits.RF, total); + } + } catch (GridAccessException ignored) { + } - return total; - } + return total; + } - @Override - public boolean canExtract() - { - return false; - } + @Override + public boolean canExtract() { + return false; + } - @Override - public boolean canReceive() - { - return true; - } + @Override + public boolean canReceive() { + return true; + } - @Override - public int getMaxEnergyStored() - { - int total = 0; + @Override + public int getMaxEnergyStored() { + int total = 0; - try - { - for( PartP2PFEPower t : PartP2PFEPower.this.getOutputs() ) - { - total += t.getAttachedEnergyStorage().getMaxEnergyStored(); - } - } - catch( GridAccessException e ) - { - return 0; - } + try { + for (PartP2PFEPower t : PartP2PFEPower.this.getOutputs()) { + total += t.getAttachedEnergyStorage().getMaxEnergyStored(); + } + } catch (GridAccessException e) { + return 0; + } - return total; - } + return total; + } - @Override - public int getEnergyStored() - { - int total = 0; + @Override + public int getEnergyStored() { + int total = 0; - try - { - for( PartP2PFEPower t : PartP2PFEPower.this.getOutputs() ) - { - total += t.getAttachedEnergyStorage().getEnergyStored(); - } - } - catch( GridAccessException e ) - { - return 0; - } + try { + for (PartP2PFEPower t : PartP2PFEPower.this.getOutputs()) { + total += t.getAttachedEnergyStorage().getEnergyStored(); + } + } catch (GridAccessException e) { + return 0; + } - return total; - } - } + return total; + } + } - private class OutputEnergyStorage implements IEnergyStorage - { - @Override - public int extractEnergy( int maxExtract, boolean simulate ) - { - final int total = PartP2PFEPower.this.getAttachedEnergyStorage().extractEnergy( maxExtract, simulate ); + private class OutputEnergyStorage implements IEnergyStorage { + @Override + public int extractEnergy(int maxExtract, boolean simulate) { + final int total = PartP2PFEPower.this.getAttachedEnergyStorage().extractEnergy(maxExtract, simulate); - if( !simulate ) - { - PartP2PFEPower.this.queueTunnelDrain( PowerUnits.RF, total ); - } + if (!simulate) { + PartP2PFEPower.this.queueTunnelDrain(PowerUnits.RF, total); + } - return total; - } + return total; + } - @Override - public int receiveEnergy( int maxReceive, boolean simulate ) - { - return 0; - } + @Override + public int receiveEnergy(int maxReceive, boolean simulate) { + return 0; + } - @Override - public boolean canExtract() - { - return PartP2PFEPower.this.getAttachedEnergyStorage().canExtract(); - } + @Override + public boolean canExtract() { + return PartP2PFEPower.this.getAttachedEnergyStorage().canExtract(); + } - @Override - public boolean canReceive() - { - return false; - } + @Override + public boolean canReceive() { + return false; + } - @Override - public int getMaxEnergyStored() - { - return PartP2PFEPower.this.getAttachedEnergyStorage().getMaxEnergyStored(); - } + @Override + public int getMaxEnergyStored() { + return PartP2PFEPower.this.getAttachedEnergyStorage().getMaxEnergyStored(); + } - @Override - public int getEnergyStored() - { - return PartP2PFEPower.this.getAttachedEnergyStorage().getEnergyStored(); - } - } + @Override + public int getEnergyStored() { + return PartP2PFEPower.this.getAttachedEnergyStorage().getEnergyStored(); + } + } - private static class NullEnergyStorage implements IEnergyStorage - { + private static class NullEnergyStorage implements IEnergyStorage { - @Override - public int receiveEnergy( int maxReceive, boolean simulate ) - { - return 0; - } + @Override + public int receiveEnergy(int maxReceive, boolean simulate) { + return 0; + } - @Override - public int extractEnergy( int maxExtract, boolean simulate ) - { - return 0; - } + @Override + public int extractEnergy(int maxExtract, boolean simulate) { + return 0; + } - @Override - public int getEnergyStored() - { - return 0; - } + @Override + public int getEnergyStored() { + return 0; + } - @Override - public int getMaxEnergyStored() - { - return 0; - } + @Override + public int getMaxEnergyStored() { + return 0; + } - @Override - public boolean canExtract() - { - return false; - } + @Override + public boolean canExtract() { + return false; + } - @Override - public boolean canReceive() - { - return false; - } + @Override + public boolean canReceive() { + return false; + } - } + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PFluids.java b/src/main/java/appeng/parts/p2p/PartP2PFluids.java index 3c840559d..e69403c90 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PFluids.java +++ b/src/main/java/appeng/parts/p2p/PartP2PFluids.java @@ -19,12 +19,9 @@ package appeng.parts.p2p; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Deque; -import java.util.Iterator; -import java.util.List; - +import appeng.api.parts.IPartModel; +import appeng.items.parts.PartModels; +import appeng.me.GridAccessException; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; @@ -37,290 +34,230 @@ import net.minecraftforge.fluids.capability.FluidTankProperties; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; -import appeng.api.parts.IPartModel; -import appeng.items.parts.PartModels; -import appeng.me.GridAccessException; +import java.util.*; -public class PartP2PFluids extends PartP2PTunnel implements IFluidHandler -{ +public class PartP2PFluids extends PartP2PTunnel implements IFluidHandler { - private static final P2PModels MODELS = new P2PModels( "part/p2p/p2p_tunnel_fluids" ); + private static final P2PModels MODELS = new P2PModels("part/p2p/p2p_tunnel_fluids"); - private static final ThreadLocal> DEPTH = new ThreadLocal<>(); - private static final FluidTankProperties[] ACTIVE_TANK = { new FluidTankProperties( null, 10000, true, false ) }; - private static final FluidTankProperties[] INACTIVE_TANK = { new FluidTankProperties( null, 0, false, false ) }; + private static final ThreadLocal> DEPTH = new ThreadLocal<>(); + private static final FluidTankProperties[] ACTIVE_TANK = {new FluidTankProperties(null, 10000, true, false)}; + private static final FluidTankProperties[] INACTIVE_TANK = {new FluidTankProperties(null, 0, false, false)}; - private IFluidHandler cachedTank; - private int tmpUsed; + private IFluidHandler cachedTank; + private int tmpUsed; - public PartP2PFluids( final ItemStack is ) - { - super( is ); - } + public PartP2PFluids(final ItemStack is) { + super(is); + } - @PartModels - public static List getModels() - { - return MODELS.getModels(); - } + @PartModels + public static List getModels() { + return MODELS.getModels(); + } - public float getPowerDrainPerTick() - { - return 2.0f; - } + public float getPowerDrainPerTick() { + return 2.0f; + } - @Override - public void onTunnelNetworkChange() - { - this.cachedTank = null; - } + @Override + public void onTunnelNetworkChange() { + this.cachedTank = null; + } - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - this.cachedTank = null; + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + this.cachedTank = null; - if( this.isOutput() ) - { - try - { - for( PartP2PFluids in : this.getInputs() ) - { - if( in != null ) - { - in.onTunnelNetworkChange(); - } - } - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - } - } + if (this.isOutput()) { + try { + for (PartP2PFluids in : this.getInputs()) { + if (in != null) { + in.onTunnelNetworkChange(); + } + } + } catch (GridAccessException e) { + e.printStackTrace(); + } + } + } - @Override - public boolean hasCapability( Capability capabilityClass ) - { - if( capabilityClass == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY ) - { - return true; - } + @Override + public boolean hasCapability(Capability capabilityClass) { + if (capabilityClass == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { + return true; + } - return super.hasCapability( capabilityClass ); - } + return super.hasCapability(capabilityClass); + } - @Override - public T getCapability( Capability capabilityClass ) - { - if( capabilityClass == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY ) - { - return (T) this; - } + @Override + public T getCapability(Capability capabilityClass) { + if (capabilityClass == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { + return (T) this; + } - return super.getCapability( capabilityClass ); - } + return super.getCapability(capabilityClass); + } - @Override - public IPartModel getStaticModels() - { - return MODELS.getModel( this.isPowered(), this.isActive() ); - } + @Override + public IPartModel getStaticModels() { + return MODELS.getModel(this.isPowered(), this.isActive()); + } - @Override - public IFluidTankProperties[] getTankProperties() - { - if( !this.isOutput() ) - { - try - { - for( PartP2PFluids tun : this.getInputs() ) - { - if( tun != null ) - { - return ACTIVE_TANK; - } - } - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - } - return INACTIVE_TANK; - } + @Override + public IFluidTankProperties[] getTankProperties() { + if (!this.isOutput()) { + try { + for (PartP2PFluids tun : this.getInputs()) { + if (tun != null) { + return ACTIVE_TANK; + } + } + } catch (GridAccessException e) { + e.printStackTrace(); + } + } + return INACTIVE_TANK; + } - @Override - public int fill( FluidStack resource, boolean doFill ) - { - final Deque stack = this.getDepth(); + @Override + public int fill(FluidStack resource, boolean doFill) { + final Deque stack = this.getDepth(); - for( final PartP2PFluids t : stack ) - { - if( t == this ) - { - return 0; - } - } + for (final PartP2PFluids t : stack) { + if (t == this) { + return 0; + } + } - stack.push( this ); + stack.push(this); - final List list = this.getOutputs( resource.getFluid() ); - int requestTotal = 0; + final List list = this.getOutputs(resource.getFluid()); + int requestTotal = 0; - Iterator i = list.iterator(); + Iterator i = list.iterator(); - while( i.hasNext() ) - { - final PartP2PFluids l = i.next(); - final IFluidHandler tank = l.getTarget(); - if( tank != null ) - { - l.tmpUsed = tank.fill( resource.copy(), false ); - } - else - { - l.tmpUsed = 0; - } + while (i.hasNext()) { + final PartP2PFluids l = i.next(); + final IFluidHandler tank = l.getTarget(); + if (tank != null) { + l.tmpUsed = tank.fill(resource.copy(), false); + } else { + l.tmpUsed = 0; + } - if( l.tmpUsed <= 0 ) - { - i.remove(); - } - else - { - requestTotal += l.tmpUsed; - } - } + if (l.tmpUsed <= 0) { + i.remove(); + } else { + requestTotal += l.tmpUsed; + } + } - if( requestTotal <= 0 ) - { - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } + if (requestTotal <= 0) { + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } - return 0; - } + return 0; + } - if( !doFill ) - { - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } + if (!doFill) { + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } - return Math.min( resource.amount, requestTotal ); - } + return Math.min(resource.amount, requestTotal); + } - int available = resource.amount; + int available = resource.amount; - i = list.iterator(); - int used = 0; + i = list.iterator(); + int used = 0; - while( i.hasNext() && available > 0 ) - { - final PartP2PFluids l = i.next(); + while (i.hasNext() && available > 0) { + final PartP2PFluids l = i.next(); - final FluidStack insert = resource.copy(); - insert.amount = (int) Math.ceil( insert.amount * ( (double) l.tmpUsed / (double) requestTotal ) ); - if( insert.amount > available ) - { - insert.amount = available; - } + final FluidStack insert = resource.copy(); + insert.amount = (int) Math.ceil(insert.amount * ((double) l.tmpUsed / (double) requestTotal)); + if (insert.amount > available) { + insert.amount = available; + } - final IFluidHandler tank = l.getTarget(); - if( tank != null ) - { - l.tmpUsed = tank.fill( insert.copy(), true ); - } - else - { - l.tmpUsed = 0; - } + final IFluidHandler tank = l.getTarget(); + if (tank != null) { + l.tmpUsed = tank.fill(insert.copy(), true); + } else { + l.tmpUsed = 0; + } - available -= insert.amount; - used += l.tmpUsed; - } + available -= insert.amount; + used += l.tmpUsed; + } - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } - return used; - } + return used; + } - @Override - public FluidStack drain( FluidStack resource, boolean doDrain ) - { - return null; - } + @Override + public FluidStack drain(FluidStack resource, boolean doDrain) { + return null; + } - @Override - public FluidStack drain( int maxDrain, boolean doDrain ) - { - return null; - } + @Override + public FluidStack drain(int maxDrain, boolean doDrain) { + return null; + } - private Deque getDepth() - { - Deque s = DEPTH.get(); + private Deque getDepth() { + Deque s = DEPTH.get(); - if( s == null ) - { - DEPTH.set( s = new ArrayDeque<>() ); - } + if (s == null) { + DEPTH.set(s = new ArrayDeque<>()); + } - return s; - } + return s; + } - private List getOutputs( final Fluid input ) - { - final List outs = new ArrayList<>(); + private List getOutputs(final Fluid input) { + final List outs = new ArrayList<>(); - try - { - for( final PartP2PFluids l : this.getOutputs() ) - { - final IFluidHandler handler = l.getTarget(); + try { + for (final PartP2PFluids l : this.getOutputs()) { + final IFluidHandler handler = l.getTarget(); - if( handler != null ) - { - outs.add( l ); - } - } - } - catch( final GridAccessException e ) - { - // :P - } + if (handler != null) { + outs.add(l); + } + } + } catch (final GridAccessException e) { + // :P + } - return outs; - } + return outs; + } - private IFluidHandler getTarget() - { - if( !this.getProxy().isActive() ) - { - return null; - } + private IFluidHandler getTarget() { + if (!this.getProxy().isActive()) { + return null; + } - if( this.cachedTank != null ) - { - return this.cachedTank; - } + if (this.cachedTank != null) { + return this.cachedTank; + } - final TileEntity te = this.getTile().getWorld().getTileEntity( this.getTile().getPos().offset( this.getSide().getFacing() ) ); + final TileEntity te = this.getTile().getWorld().getTileEntity(this.getTile().getPos().offset(this.getSide().getFacing())); - if( te != null && te.hasCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing().getOpposite() ) ) - { - return this.cachedTank = te.getCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, - this.getSide().getFacing().getOpposite() ); - } + if (te != null && te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing().getOpposite())) { + return this.cachedTank = te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, + this.getSide().getFacing().getOpposite()); + } - return null; - } + return null; + } } \ No newline at end of file diff --git a/src/main/java/appeng/parts/p2p/PartP2PGTCEPower.java b/src/main/java/appeng/parts/p2p/PartP2PGTCEPower.java index c858647e1..100e2767f 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PGTCEPower.java +++ b/src/main/java/appeng/parts/p2p/PartP2PGTCEPower.java @@ -1,8 +1,5 @@ package appeng.parts.p2p; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - import appeng.api.parts.IPartModel; import appeng.items.parts.PartModels; import appeng.me.GridAccessException; @@ -12,245 +9,199 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fml.common.Optional; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayDeque; import java.util.List; import java.util.Queue; +public class PartP2PGTCEPower extends PartP2PTunnel { + private static final P2PModels MODELS = new P2PModels("part/p2p/p2p_tunnel_gteu"); + private static final IEnergyContainer NULL_ENERGY_STORAGE = new NullEnergyStorage(); + private final IEnergyContainer inputHandler = new InputEnergyStorage(); + private final Queue outputs = new ArrayDeque<>(); -public class PartP2PGTCEPower extends PartP2PTunnel -{ - private static final P2PModels MODELS = new P2PModels( "part/p2p/p2p_tunnel_gteu" ); - private static final IEnergyContainer NULL_ENERGY_STORAGE = new NullEnergyStorage(); - private final IEnergyContainer inputHandler = new InputEnergyStorage(); - private final Queue outputs = new ArrayDeque<>(); + public PartP2PGTCEPower(ItemStack is) { + super(is); + } - public PartP2PGTCEPower( ItemStack is ) - { - super( is ); - } + @PartModels + public static List getModels() { + return MODELS.getModels(); + } - @PartModels - public static List getModels() - { - return MODELS.getModels(); - } + @Override + public IPartModel getStaticModels() { + return MODELS.getModel(this.isPowered(), this.isActive()); + } - @Override - public IPartModel getStaticModels() - { - return MODELS.getModel( this.isPowered(), this.isActive() ); - } + @Override + public void onTunnelNetworkChange() { + this.getHost().notifyNeighbors(); + } - @Override - public void onTunnelNetworkChange() - { - this.getHost().notifyNeighbors(); - } + private IEnergyContainer getAttachedEnergyStorage() { + if (this.isActive()) { + final TileEntity self = this.getTile(); + final TileEntity te = self.getWorld().getTileEntity(self.getPos().offset(this.getSide().getFacing())); - private IEnergyContainer getAttachedEnergyStorage() - { - if( this.isActive() ) - { - final TileEntity self = this.getTile(); - final TileEntity te = self.getWorld().getTileEntity( self.getPos().offset( this.getSide().getFacing() ) ); + if (te != null && te.hasCapability(GregtechCapabilities.CAPABILITY_ENERGY_CONTAINER, this.getSide().getOpposite().getFacing())) { + return te.getCapability(GregtechCapabilities.CAPABILITY_ENERGY_CONTAINER, this.getSide().getOpposite().getFacing()); + } + } + return NULL_ENERGY_STORAGE; + } - if( te != null && te.hasCapability( GregtechCapabilities.CAPABILITY_ENERGY_CONTAINER, this.getSide().getOpposite().getFacing() ) ) - { - return te.getCapability( GregtechCapabilities.CAPABILITY_ENERGY_CONTAINER, this.getSide().getOpposite().getFacing() ); - } - } - return NULL_ENERGY_STORAGE; - } + @Override + public boolean hasCapability(@Nonnull Capability capability) { + if (!this.isOutput()) { + if (capability == GregtechCapabilities.CAPABILITY_ENERGY_CONTAINER) { + return true; + } + } + return super.hasCapability(capability); + } - @Override - public boolean hasCapability( @Nonnull Capability capability ) - { - if( !this.isOutput() ) - { - if( capability == GregtechCapabilities.CAPABILITY_ENERGY_CONTAINER ) - { - return true; - } - } - return super.hasCapability( capability ); - } + @Nullable + @Override + public T getCapability(@Nonnull Capability capability) { + if (capability == GregtechCapabilities.CAPABILITY_ENERGY_CONTAINER) { + if (this.isOutput()) { + return null; + } + return (T) this.inputHandler; + } + return super.getCapability(capability); + } - @Nullable - @Override - public T getCapability( @Nonnull Capability capability ) - { - if( capability == GregtechCapabilities.CAPABILITY_ENERGY_CONTAINER ) - { - if( this.isOutput() ) - { - return null; - } - return (T) this.inputHandler; - } - return super.getCapability( capability ); - } + class InputEnergyStorage implements IEnergyContainer { + @Override + public long getEnergyCanBeInserted() { + long canInsert = 0; + if (outputs.isEmpty()) { + try { + for (PartP2PGTCEPower o : PartP2PGTCEPower.this.getOutputs()) + outputs.add(o); + } catch (GridAccessException e) { + e.printStackTrace(); + } + } - class InputEnergyStorage implements IEnergyContainer - { - @Override - public long getEnergyCanBeInserted() - { - long canInsert = 0; - if( outputs.isEmpty() ) - { - try - { - for( PartP2PGTCEPower o : PartP2PGTCEPower.this.getOutputs() ) - outputs.add( o ); - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - } + while (!outputs.isEmpty()) { + PartP2PGTCEPower target = outputs.poll(); + final IEnergyContainer output = target.getAttachedEnergyStorage(); + if (output == this) { + return 0; + } + if (output == null || output.getEnergyCanBeInserted() <= 0) { + continue; + } + canInsert += output.getEnergyCanBeInserted(); + } + return canInsert; + } - while ( !outputs.isEmpty() ) - { - PartP2PGTCEPower target = outputs.poll(); - final IEnergyContainer output = target.getAttachedEnergyStorage(); - if( output == this ) - { - return 0; - } - if( output == null || output.getEnergyCanBeInserted() <= 0 ) - { - continue; - } - canInsert += output.getEnergyCanBeInserted(); - } - return canInsert; - } + @Override + public long acceptEnergyFromNetwork(EnumFacing facing, long voltage, long amperage) { + long amperesUsed = 0L; - @Override - public long acceptEnergyFromNetwork( EnumFacing facing, long voltage, long amperage ) - { - long amperesUsed = 0L; + if (outputs.isEmpty()) { + try { + for (PartP2PGTCEPower o : PartP2PGTCEPower.this.getOutputs()) + outputs.add(o); + } catch (GridAccessException e) { + e.printStackTrace(); + } + } - if( outputs.isEmpty() ) - { - try - { - for( PartP2PGTCEPower o : PartP2PGTCEPower.this.getOutputs() ) - outputs.add( o ); - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - } + voltage = (long) (voltage * 0.95); - voltage = (long) ( voltage * 0.95 ); + if (voltage > 0) { + while (!outputs.isEmpty()) { + PartP2PGTCEPower target = outputs.poll(); + final IEnergyContainer output = target.getAttachedEnergyStorage(); - if( voltage > 0 ) - { - while ( !outputs.isEmpty() ) - { - PartP2PGTCEPower target = outputs.poll(); - final IEnergyContainer output = target.getAttachedEnergyStorage(); + if (output == null || !output.inputsEnergy(target.getSide().getFacing().getOpposite()) || output.getEnergyCanBeInserted() <= 0) { + continue; + } - if( output == null || !output.inputsEnergy( target.getSide().getFacing().getOpposite() ) || output.getEnergyCanBeInserted() <= 0 ) - { - continue; - } + amperesUsed += output.acceptEnergyFromNetwork(target.getSide().getFacing().getOpposite(), voltage, amperage - amperesUsed); - amperesUsed += output.acceptEnergyFromNetwork( target.getSide().getFacing().getOpposite(), voltage, amperage - amperesUsed ); + if (amperesUsed == amperage) { + outputs.clear(); + break; + } + } + } + return amperesUsed; + } - if( amperesUsed == amperage) - { - outputs.clear(); - break; - } - } - } - return amperesUsed; - } + @Override + public boolean inputsEnergy(EnumFacing enumFacing) { + return true; + } - @Override - public boolean inputsEnergy( EnumFacing enumFacing ) - { - return true; - } + @Override + public long changeEnergy(long l) { + return 0; + } - @Override - public long changeEnergy( long l ) - { - return 0; - } + @Override + public long getEnergyStored() { + return 0; + } - @Override - public long getEnergyStored() - { - return 0; - } + @Override + public long getEnergyCapacity() { + return 0; + } - @Override - public long getEnergyCapacity() - { - return 0; - } + @Override + public long getInputAmperage() { + return 0; + } - @Override - public long getInputAmperage() - { - return 0; - } + @Override + public long getInputVoltage() { + return 0; + } + } - @Override - public long getInputVoltage() - { - return 0; - } - } + static class NullEnergyStorage implements IEnergyContainer { + @Override + public long acceptEnergyFromNetwork(EnumFacing enumFacing, long l, long l1) { + return 0; + } - static class NullEnergyStorage implements IEnergyContainer - { - @Override - public long acceptEnergyFromNetwork( EnumFacing enumFacing, long l, long l1 ) - { - return 0; - } + @Override + public boolean inputsEnergy(EnumFacing enumFacing) { + return false; + } - @Override - public boolean inputsEnergy( EnumFacing enumFacing ) - { - return false; - } + @Override + public long changeEnergy(long l) { + return 0; + } - @Override - public long changeEnergy( long l ) - { - return 0; - } + @Override + public long getEnergyStored() { + return 0; + } - @Override - public long getEnergyStored() - { - return 0; - } + @Override + public long getEnergyCapacity() { + return 0; + } - @Override - public long getEnergyCapacity() - { - return 0; - } + @Override + public long getInputAmperage() { + return 0; + } - @Override - public long getInputAmperage() - { - return 0; - } - - @Override - public long getInputVoltage() - { - return 0; - } - } + @Override + public long getInputVoltage() { + return 0; + } + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java b/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java index e9ae8e27c..1041ac307 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java +++ b/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java @@ -19,269 +19,223 @@ package appeng.parts.p2p; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import ic2.api.energy.prefab.BasicSinkSource; -import ic2.api.energy.tile.IEnergyAcceptor; -import ic2.api.energy.tile.IEnergyEmitter; - import appeng.api.config.PowerUnits; import appeng.api.parts.IPartModel; import appeng.items.parts.PartModels; import appeng.me.GridAccessException; import appeng.me.cache.helpers.TunnelCollection; import appeng.util.Platform; +import ic2.api.energy.prefab.BasicSinkSource; +import ic2.api.energy.tile.IEnergyAcceptor; +import ic2.api.energy.tile.IEnergyEmitter; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +import java.util.ArrayList; +import java.util.List; -public class PartP2PIC2Power extends PartP2PTunnel -{ +public class PartP2PIC2Power extends PartP2PTunnel { - private static final String TAG_BUFFERED_ENERGY_1 = "bufferedEnergy1"; - private static final String TAG_BUFFERED_ENERGY_2 = "bufferedEnergy2"; - private static final String TAG_BUFFERED_VOLTAGE_1 = "outputPacket1"; - private static final String TAG_BUFFERED_VOLTAGE_2 = "outputPacket2"; + private static final String TAG_BUFFERED_ENERGY_1 = "bufferedEnergy1"; + private static final String TAG_BUFFERED_ENERGY_2 = "bufferedEnergy2"; + private static final String TAG_BUFFERED_VOLTAGE_1 = "outputPacket1"; + private static final String TAG_BUFFERED_VOLTAGE_2 = "outputPacket2"; - private static final P2PModels MODELS = new P2PModels( "part/p2p/p2p_tunnel_ic2" ); + private static final P2PModels MODELS = new P2PModels("part/p2p/p2p_tunnel_ic2"); - // Buffer the energy + voltage for two IC2 ENET packets - private double bufferedEnergy1; - private double bufferedVoltage1; - private double bufferedEnergy2; - private double bufferedVoltage2; + // Buffer the energy + voltage for two IC2 ENET packets + private double bufferedEnergy1; + private double bufferedVoltage1; + private double bufferedEnergy2; + private double bufferedVoltage2; - private BasicSinkSource sinkSource; + private BasicSinkSource sinkSource; - public PartP2PIC2Power( ItemStack is ) - { - super( is ); - } + public PartP2PIC2Power(ItemStack is) { + super(is); + } - @Override - public void readFromNBT( NBTTagCompound tag ) - { - super.readFromNBT( tag ); - this.bufferedEnergy1 = tag.getDouble( TAG_BUFFERED_ENERGY_1 ); - this.bufferedEnergy2 = tag.getDouble( TAG_BUFFERED_ENERGY_2 ); - this.bufferedVoltage1 = tag.getDouble( TAG_BUFFERED_VOLTAGE_1 ); - this.bufferedVoltage2 = tag.getDouble( TAG_BUFFERED_VOLTAGE_2 ); - } + @Override + public void readFromNBT(NBTTagCompound tag) { + super.readFromNBT(tag); + this.bufferedEnergy1 = tag.getDouble(TAG_BUFFERED_ENERGY_1); + this.bufferedEnergy2 = tag.getDouble(TAG_BUFFERED_ENERGY_2); + this.bufferedVoltage1 = tag.getDouble(TAG_BUFFERED_VOLTAGE_1); + this.bufferedVoltage2 = tag.getDouble(TAG_BUFFERED_VOLTAGE_2); + } - @Override - public void writeToNBT( NBTTagCompound tag ) - { - super.writeToNBT( tag ); - tag.setDouble( TAG_BUFFERED_ENERGY_1, this.bufferedEnergy1 ); - tag.setDouble( TAG_BUFFERED_ENERGY_2, this.bufferedEnergy2 ); - tag.setDouble( TAG_BUFFERED_VOLTAGE_1, this.bufferedVoltage1 ); - tag.setDouble( TAG_BUFFERED_VOLTAGE_2, this.bufferedVoltage2 ); - } + @Override + public void writeToNBT(NBTTagCompound tag) { + super.writeToNBT(tag); + tag.setDouble(TAG_BUFFERED_ENERGY_1, this.bufferedEnergy1); + tag.setDouble(TAG_BUFFERED_ENERGY_2, this.bufferedEnergy2); + tag.setDouble(TAG_BUFFERED_VOLTAGE_1, this.bufferedVoltage1); + tag.setDouble(TAG_BUFFERED_VOLTAGE_2, this.bufferedVoltage2); + } - @Override - public void onTunnelConfigChange() - { - this.updateSinkSource(); - this.getHost().partChanged(); - } + @Override + public void onTunnelConfigChange() { + this.updateSinkSource(); + this.getHost().partChanged(); + } - @Override - public void onTunnelNetworkChange() - { - this.updateSinkSource(); - this.getHost().notifyNeighbors(); - } + @Override + public void onTunnelNetworkChange() { + this.updateSinkSource(); + this.getHost().notifyNeighbors(); + } - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - this.invalidateSinkSource(); - } + @Override + public void removeFromWorld() { + super.removeFromWorld(); + this.invalidateSinkSource(); + } - @Override - public void addToWorld() - { - super.addToWorld(); - this.updateSinkSource(); - } + @Override + public void addToWorld() { + super.addToWorld(); + this.updateSinkSource(); + } - @Override - public IPartModel getStaticModels() - { - return MODELS.getModel( this.isPowered(), this.isActive() ); - } + @Override + public IPartModel getStaticModels() { + return MODELS.getModel(this.isPowered(), this.isActive()); + } - @PartModels - public static List getModels() - { - return MODELS.getModels(); - } + @PartModels + public static List getModels() { + return MODELS.getModels(); + } - private void updateSinkSource() - { - if( this.sinkSource == null ) - { - this.sinkSource = new SinkSource( this.getHost().getTile().getWorld(), this.getHost().getLocation().getPos(), 2048, 4, 4 ); - } + private void updateSinkSource() { + if (this.sinkSource == null) { + this.sinkSource = new SinkSource(this.getHost().getTile().getWorld(), this.getHost().getLocation().getPos(), 2048, 4, 4); + } - this.sinkSource.update(); - } + this.sinkSource.update(); + } - private void invalidateSinkSource() - { - if( this.sinkSource != null ) - { - this.sinkSource.invalidate(); - } - } + private void invalidateSinkSource() { + if (this.sinkSource != null) { + this.sinkSource.invalidate(); + } + } - private class SinkSource extends BasicSinkSource - { + private class SinkSource extends BasicSinkSource { - SinkSource( World world, BlockPos pos, int i, int j, int k ) - { - super( world, pos, i, j, k ); - } + SinkSource(World world, BlockPos pos, int i, int j, int k) { + super(world, pos, i, j, k); + } - @Override - public boolean emitsEnergyTo( IEnergyAcceptor receiver, EnumFacing side ) - { - return PartP2PIC2Power.this.isOutput() && side == PartP2PIC2Power.this.getSide().getFacing(); - } + @Override + public boolean emitsEnergyTo(IEnergyAcceptor receiver, EnumFacing side) { + return PartP2PIC2Power.this.isOutput() && side == PartP2PIC2Power.this.getSide().getFacing(); + } - @Override - public boolean acceptsEnergyFrom( IEnergyEmitter emitter, EnumFacing side ) - { - return !PartP2PIC2Power.this.isOutput() && side == PartP2PIC2Power.this.getSide().getFacing(); - } + @Override + public boolean acceptsEnergyFrom(IEnergyEmitter emitter, EnumFacing side) { + return !PartP2PIC2Power.this.isOutput() && side == PartP2PIC2Power.this.getSide().getFacing(); + } - @Override - public double getDemandedEnergy() - { - if( PartP2PIC2Power.this.isOutput() ) - { - return 0; - } + @Override + public double getDemandedEnergy() { + if (PartP2PIC2Power.this.isOutput()) { + return 0; + } - try - { - for( PartP2PIC2Power t : PartP2PIC2Power.this.getOutputs() ) - { - if( t.bufferedEnergy1 <= 0.0001 || t.bufferedEnergy2 <= 0.0001 ) - { - return 2048; - } - } - } - catch( GridAccessException e ) - { - return 0; - } + try { + for (PartP2PIC2Power t : PartP2PIC2Power.this.getOutputs()) { + if (t.bufferedEnergy1 <= 0.0001 || t.bufferedEnergy2 <= 0.0001) { + return 2048; + } + } + } catch (GridAccessException e) { + return 0; + } - return 0; - } + return 0; + } - @Override - public double injectEnergy( EnumFacing directionFrom, double amount, double voltage ) - { - TunnelCollection outs; - try - { - outs = PartP2PIC2Power.this.getOutputs(); - } - catch( GridAccessException e ) - { - return amount; - } + @Override + public double injectEnergy(EnumFacing directionFrom, double amount, double voltage) { + TunnelCollection outs; + try { + outs = PartP2PIC2Power.this.getOutputs(); + } catch (GridAccessException e) { + return amount; + } - if( outs.isEmpty() ) - { - return amount; - } + if (outs.isEmpty()) { + return amount; + } - List options = new ArrayList<>(); - for( PartP2PIC2Power o : outs ) - { - if( o.bufferedEnergy1 <= 0.01 ) - { - options.add( o ); - } - } + List options = new ArrayList<>(); + for (PartP2PIC2Power o : outs) { + if (o.bufferedEnergy1 <= 0.01) { + options.add(o); + } + } - if( options.isEmpty() ) - { - for( PartP2PIC2Power o : outs ) - { - if( o.bufferedEnergy2 <= 0.01 ) - { - options.add( o ); - } - } - } + if (options.isEmpty()) { + for (PartP2PIC2Power o : outs) { + if (o.bufferedEnergy2 <= 0.01) { + options.add(o); + } + } + } - if( options.isEmpty() ) - { - for( PartP2PIC2Power o : outs ) - { - options.add( o ); - } - } + if (options.isEmpty()) { + for (PartP2PIC2Power o : outs) { + options.add(o); + } + } - if( options.isEmpty() ) - { - return amount; - } + if (options.isEmpty()) { + return amount; + } - PartP2PIC2Power x = Platform.pickRandom( options ); + PartP2PIC2Power x = Platform.pickRandom(options); - if( x != null && x.bufferedEnergy1 <= 0.001 ) - { - PartP2PIC2Power.this.queueTunnelDrain( PowerUnits.EU, amount ); - x.bufferedEnergy1 = amount; - x.bufferedVoltage1 = voltage; - return 0; - } + if (x != null && x.bufferedEnergy1 <= 0.001) { + PartP2PIC2Power.this.queueTunnelDrain(PowerUnits.EU, amount); + x.bufferedEnergy1 = amount; + x.bufferedVoltage1 = voltage; + return 0; + } - if( x != null && x.bufferedEnergy2 <= 0.001 ) - { - PartP2PIC2Power.this.queueTunnelDrain( PowerUnits.EU, amount ); - x.bufferedEnergy2 = amount; - x.bufferedVoltage2 = voltage; - return 0; - } + if (x != null && x.bufferedEnergy2 <= 0.001) { + PartP2PIC2Power.this.queueTunnelDrain(PowerUnits.EU, amount); + x.bufferedEnergy2 = amount; + x.bufferedVoltage2 = voltage; + return 0; + } - return amount; - } + return amount; + } - @Override - public double getOfferedEnergy() - { - if( PartP2PIC2Power.this.isOutput() ) - { - return PartP2PIC2Power.this.bufferedEnergy1; - } - return 0; - } + @Override + public double getOfferedEnergy() { + if (PartP2PIC2Power.this.isOutput()) { + return PartP2PIC2Power.this.bufferedEnergy1; + } + return 0; + } - @Override - public void drawEnergy( double amount ) - { - PartP2PIC2Power.this.bufferedEnergy1 -= amount; - if( PartP2PIC2Power.this.bufferedEnergy1 < 0.001 ) - { - PartP2PIC2Power.this.bufferedEnergy1 = PartP2PIC2Power.this.bufferedEnergy2; - PartP2PIC2Power.this.bufferedEnergy2 = 0; + @Override + public void drawEnergy(double amount) { + PartP2PIC2Power.this.bufferedEnergy1 -= amount; + if (PartP2PIC2Power.this.bufferedEnergy1 < 0.001) { + PartP2PIC2Power.this.bufferedEnergy1 = PartP2PIC2Power.this.bufferedEnergy2; + PartP2PIC2Power.this.bufferedEnergy2 = 0; - PartP2PIC2Power.this.bufferedVoltage1 = PartP2PIC2Power.this.bufferedVoltage2; - PartP2PIC2Power.this.bufferedVoltage2 = 0; - } - } - } + PartP2PIC2Power.this.bufferedVoltage1 = PartP2PIC2Power.this.bufferedVoltage2; + PartP2PIC2Power.this.bufferedVoltage2 = 0; + } + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/parts/p2p/PartP2PItems.java b/src/main/java/appeng/parts/p2p/PartP2PItems.java index 582291b0b..1d518fdea 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PItems.java +++ b/src/main/java/appeng/parts/p2p/PartP2PItems.java @@ -19,19 +19,6 @@ package appeng.parts.p2p; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.items.CapabilityItemHandler; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.wrapper.EmptyHandler; - import appeng.api.networking.IGridNode; import appeng.api.networking.ticking.IGridTickable; import appeng.api.networking.ticking.TickRateModulation; @@ -43,226 +30,190 @@ import appeng.me.GridAccessException; import appeng.me.cache.helpers.TunnelCollection; import appeng.util.Platform; import appeng.util.inv.WrapperChainedItemHandler; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.items.CapabilityItemHandler; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.wrapper.EmptyHandler; + +import java.util.ArrayList; +import java.util.List; -public class PartP2PItems extends PartP2PTunnel implements IItemHandler, IGridTickable -{ - private static final float POWER_DRAIN = 2.0f; - private static final P2PModels MODELS = new P2PModels( "part/p2p/p2p_tunnel_items" ); - private boolean partVisited = false; +public class PartP2PItems extends PartP2PTunnel implements IItemHandler, IGridTickable { + private static final float POWER_DRAIN = 2.0f; + private static final P2PModels MODELS = new P2PModels("part/p2p/p2p_tunnel_items"); + private boolean partVisited = false; - @PartModels - public static List getModels() - { - return MODELS.getModels(); - } + @PartModels + public static List getModels() { + return MODELS.getModels(); + } - private int oldSize = 0; - private boolean requested; - private IItemHandler cachedInv; + private int oldSize = 0; + private boolean requested; + private IItemHandler cachedInv; - public PartP2PItems( final ItemStack is ) - { - super( is ); - } + public PartP2PItems(final ItemStack is) { + super(is); + } - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - this.cachedInv = null; - try - { - if( this.isOutput() ) - { - for( PartP2PItems input : this.getInputs() ) - { - if( input != null ) - { - input.onTunnelNetworkChange(); - } - } - } - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - } + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + this.cachedInv = null; + try { + if (this.isOutput()) { + for (PartP2PItems input : this.getInputs()) { + if (input != null) { + input.onTunnelNetworkChange(); + } + } + } + } catch (GridAccessException e) { + e.printStackTrace(); + } + } - private IItemHandler getDestination() - { - this.requested = true; + private IItemHandler getDestination() { + this.requested = true; - if( this.cachedInv != null ) - { - return this.cachedInv; - } + if (this.cachedInv != null) { + return this.cachedInv; + } - final List outs = new ArrayList(); - final TunnelCollection itemTunnels; + final List outs = new ArrayList(); + final TunnelCollection itemTunnels; - try - { - itemTunnels = this.getOutputs(); - } - catch( final GridAccessException e ) - { - return EmptyHandler.INSTANCE; - } + try { + itemTunnels = this.getOutputs(); + } catch (final GridAccessException e) { + return EmptyHandler.INSTANCE; + } - for( final PartP2PItems t : itemTunnels ) - { - final IItemHandler inv = t.getOutputInv(); - if( inv != null && inv != this ) - { - if( Platform.getRandomInt() % 2 == 0 ) - { - outs.add( inv ); - } - else - { - outs.add( 0, inv ); - } - } - } + for (final PartP2PItems t : itemTunnels) { + final IItemHandler inv = t.getOutputInv(); + if (inv != null && inv != this) { + if (Platform.getRandomInt() % 2 == 0) { + outs.add(inv); + } else { + outs.add(0, inv); + } + } + } - return this.cachedInv = new WrapperChainedItemHandler( outs.toArray( new IItemHandler[outs.size()] ) ); - } + return this.cachedInv = new WrapperChainedItemHandler(outs.toArray(new IItemHandler[outs.size()])); + } - private IItemHandler getOutputInv() - { - IItemHandler ret = null; - if( !this.partVisited ) - { - this.partVisited = true; - if( this.getProxy().isActive() ) - { - final EnumFacing facing = this.getSide().getFacing(); - final TileEntity te = this.getTile().getWorld().getTileEntity( this.getTile().getPos().offset( facing ) ); + private IItemHandler getOutputInv() { + IItemHandler ret = null; + if (!this.partVisited) { + this.partVisited = true; + if (this.getProxy().isActive()) { + final EnumFacing facing = this.getSide().getFacing(); + final TileEntity te = this.getTile().getWorld().getTileEntity(this.getTile().getPos().offset(facing)); - if( te != null && te.hasCapability( CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing.getOpposite() ) ) - { - ret = te.getCapability( CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing.getOpposite() ); - } - } - this.partVisited = false; - } - return ret; - } + if (te != null && te.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing.getOpposite())) { + ret = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing.getOpposite()); + } + } + this.partVisited = false; + } + return ret; + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.ItemTunnel.getMin(), TickRates.ItemTunnel.getMax(), false, false ); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.ItemTunnel.getMin(), TickRates.ItemTunnel.getMax(), false, false); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - final boolean wasReq = this.requested; + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + final boolean wasReq = this.requested; - if( this.requested && this.cachedInv != null ) - { - ( (WrapperChainedItemHandler) this.cachedInv ).cycleOrder(); - } + if (this.requested && this.cachedInv != null) { + ((WrapperChainedItemHandler) this.cachedInv).cycleOrder(); + } - this.requested = false; - return wasReq ? TickRateModulation.FASTER : TickRateModulation.SLOWER; - } + this.requested = false; + return wasReq ? TickRateModulation.FASTER : TickRateModulation.SLOWER; + } - @Override - public void onTunnelNetworkChange() - { - if( !this.isOutput() ) - { - this.cachedInv = null; - final int olderSize = this.oldSize; - this.oldSize = this.getDestination().getSlots(); - if( olderSize != this.oldSize ) - { - this.getHost().notifyNeighbors(); - } - } - else - { - try - { - for( PartP2PItems input : this.getInputs() ) - { - if( input != null ) - { - input.getHost().notifyNeighbors(); - } - } - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - } - } + @Override + public void onTunnelNetworkChange() { + if (!this.isOutput()) { + this.cachedInv = null; + final int olderSize = this.oldSize; + this.oldSize = this.getDestination().getSlots(); + if (olderSize != this.oldSize) { + this.getHost().notifyNeighbors(); + } + } else { + try { + for (PartP2PItems input : this.getInputs()) { + if (input != null) { + input.getHost().notifyNeighbors(); + } + } + } catch (GridAccessException e) { + e.printStackTrace(); + } + } + } - @Override - public boolean hasCapability( Capability capabilityClass ) - { - if( capabilityClass == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY ) - { - return true; - } + @Override + public boolean hasCapability(Capability capabilityClass) { + if (capabilityClass == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { + return true; + } - return super.hasCapability( capabilityClass ); - } + return super.hasCapability(capabilityClass); + } - @SuppressWarnings( "unchecked" ) - @Override - public T getCapability( Capability capabilityClass ) - { - if( capabilityClass == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY ) - { - return (T) this; - } + @SuppressWarnings("unchecked") + @Override + public T getCapability(Capability capabilityClass) { + if (capabilityClass == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { + return (T) this; + } - return super.getCapability( capabilityClass ); - } + return super.getCapability(capabilityClass); + } - @Override - public int getSlots() - { - return this.getDestination().getSlots(); - } + @Override + public int getSlots() { + return this.getDestination().getSlots(); + } - @Override - public ItemStack getStackInSlot( final int i ) - { - return this.getDestination().getStackInSlot( i ); - } + @Override + public ItemStack getStackInSlot(final int i) { + return this.getDestination().getStackInSlot(i); + } - @Override - public ItemStack insertItem( final int slot, final ItemStack stack, boolean simulate ) - { - return this.getDestination().insertItem( slot, stack, simulate ); - } + @Override + public ItemStack insertItem(final int slot, final ItemStack stack, boolean simulate) { + return this.getDestination().insertItem(slot, stack, simulate); + } - @Override - public ItemStack extractItem( final int slot, final int amount, boolean simulate ) - { - return this.getDestination().extractItem( slot, amount, simulate ); - } + @Override + public ItemStack extractItem(final int slot, final int amount, boolean simulate) { + return this.getDestination().extractItem(slot, amount, simulate); + } - @Override - public int getSlotLimit( int slot ) - { - return this.getDestination().getSlotLimit( slot ); - } + @Override + public int getSlotLimit(int slot) { + return this.getDestination().getSlotLimit(slot); + } - public float getPowerDrainPerTick() - { - return POWER_DRAIN; - } + public float getPowerDrainPerTick() { + return POWER_DRAIN; + } - @Override - public IPartModel getStaticModels() - { - return MODELS.getModel( this.isPowered(), this.isActive() ); - } + @Override + public IPartModel getStaticModels() { + return MODELS.getModel(this.isPowered(), this.isActive()); + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PLight.java b/src/main/java/appeng/parts/p2p/PartP2PLight.java index ea7310411..0f039791b 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PLight.java +++ b/src/main/java/appeng/parts/p2p/PartP2PLight.java @@ -19,18 +19,6 @@ package appeng.parts.p2p; -import java.io.IOException; -import java.util.List; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - import appeng.api.networking.IGridNode; import appeng.api.networking.ticking.IGridTickable; import appeng.api.networking.ticking.TickRateModulation; @@ -39,200 +27,171 @@ import appeng.api.parts.IPartModel; import appeng.core.settings.TickRates; import appeng.items.parts.PartModels; import appeng.me.GridAccessException; +import io.netty.buffer.ByteBuf; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; + +import java.io.IOException; +import java.util.List; -public class PartP2PLight extends PartP2PTunnel implements IGridTickable -{ +public class PartP2PLight extends PartP2PTunnel implements IGridTickable { - private static final P2PModels MODELS = new P2PModels( "part/p2p/p2p_tunnel_light" ); + private static final P2PModels MODELS = new P2PModels("part/p2p/p2p_tunnel_light"); - @PartModels - public static List getModels() - { - return MODELS.getModels(); - } + @PartModels + public static List getModels() { + return MODELS.getModels(); + } - private int lastValue = 0; - private int opacity = -1; + private int lastValue = 0; + private int opacity = -1; - public PartP2PLight( final ItemStack is ) - { - super( is ); - } + public PartP2PLight(final ItemStack is) { + super(is); + } - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - data.writeInt( this.isOutput() ? this.lastValue : 0 ); - data.writeInt( this.opacity ); - } + @Override + public void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeInt(this.isOutput() ? this.lastValue : 0); + data.writeInt(this.opacity); + } - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - super.readFromStream( data ); - final int oldValue = this.lastValue; - final int oldOpacity = this.opacity; + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + super.readFromStream(data); + final int oldValue = this.lastValue; + final int oldOpacity = this.opacity; - this.lastValue = data.readInt(); - this.opacity = data.readInt(); + this.lastValue = data.readInt(); + this.opacity = data.readInt(); - this.setOutput( this.lastValue > 0 ); - return this.lastValue != oldValue || oldOpacity != this.opacity; - } + this.setOutput(this.lastValue > 0); + return this.lastValue != oldValue || oldOpacity != this.opacity; + } - private boolean doWork() - { - if( this.isOutput() ) - { - return false; - } + private boolean doWork() { + if (this.isOutput()) { + return false; + } - final TileEntity te = this.getTile(); - final World w = te.getWorld(); + final TileEntity te = this.getTile(); + final World w = te.getWorld(); - final int newLevel = w.getLightFromNeighbors( te.getPos().offset( this.getSide().getFacing() ) ); + final int newLevel = w.getLightFromNeighbors(te.getPos().offset(this.getSide().getFacing())); - if( this.lastValue != newLevel && this.getProxy().isActive() ) - { - this.lastValue = newLevel; - try - { - int light = 0; - for( PartP2PLight src : this.getInputs() ) - { - if( src != null && src.getProxy().isActive() ) - { - light = Math.max( light, src.lastValue ); - } - } - for( final PartP2PLight out : this.getOutputs() ) - { - out.setLightLevel( light ); - } - } - catch( final GridAccessException e ) - { - // :P - } - return true; - } - return false; - } + if (this.lastValue != newLevel && this.getProxy().isActive()) { + this.lastValue = newLevel; + try { + int light = 0; + for (PartP2PLight src : this.getInputs()) { + if (src != null && src.getProxy().isActive()) { + light = Math.max(light, src.lastValue); + } + } + for (final PartP2PLight out : this.getOutputs()) { + out.setLightLevel(light); + } + } catch (final GridAccessException e) { + // :P + } + return true; + } + return false; + } - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - if( this.isOutput() && pos.offset( this.getSide().getFacing() ).equals( neighbor ) ) - { - this.opacity = -1; - this.getHost().markForUpdate(); - } - else - { - this.doWork(); - } - } + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + if (this.isOutput() && pos.offset(this.getSide().getFacing()).equals(neighbor)) { + this.opacity = -1; + this.getHost().markForUpdate(); + } else { + this.doWork(); + } + } - @Override - public int getLightLevel() - { - if( this.isOutput() && this.isPowered() ) - { - return this.blockLight( this.lastValue ); - } + @Override + public int getLightLevel() { + if (this.isOutput() && this.isPowered()) { + return this.blockLight(this.lastValue); + } - return 0; - } + return 0; + } - private void setLightLevel( final int out ) - { - this.lastValue = out; - this.getHost().markForUpdate(); - } + private void setLightLevel(final int out) { + this.lastValue = out; + this.getHost().markForUpdate(); + } - private int blockLight( final int emit ) - { - if( this.opacity < 0 ) - { - final TileEntity te = this.getTile(); - this.opacity = 255 - te.getWorld().getBlockLightOpacity( te.getPos().offset( this.getSide().getFacing() ) ); - } + private int blockLight(final int emit) { + if (this.opacity < 0) { + final TileEntity te = this.getTile(); + this.opacity = 255 - te.getWorld().getBlockLightOpacity(te.getPos().offset(this.getSide().getFacing())); + } - return (int) ( emit * ( this.opacity / 255.0f ) ); - } + return (int) (emit * (this.opacity / 255.0f)); + } - @Override - public void readFromNBT( final NBTTagCompound tag ) - { - super.readFromNBT( tag ); - this.lastValue = tag.getInteger( "lastValue" ); - } + @Override + public void readFromNBT(final NBTTagCompound tag) { + super.readFromNBT(tag); + this.lastValue = tag.getInteger("lastValue"); + } - @Override - public void writeToNBT( final NBTTagCompound tag ) - { - super.writeToNBT( tag ); - tag.setInteger( "lastValue", this.lastValue ); - } + @Override + public void writeToNBT(final NBTTagCompound tag) { + super.writeToNBT(tag); + tag.setInteger("lastValue", this.lastValue); + } - @Override - public void onTunnelConfigChange() - { - this.onTunnelNetworkChange(); - } + @Override + public void onTunnelConfigChange() { + this.onTunnelNetworkChange(); + } - @Override - public void onTunnelNetworkChange() - { - if( this.isOutput() ) - { - try - { - int light = 0; - for( PartP2PLight src : this.getInputs() ) - { - if( src != null && src.getProxy().isActive() ) - { - light = Math.max( light, src.lastValue ); - } - } - this.setLightLevel( light ); - this.getHost().markForUpdate(); - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - } - else - { - this.doWork(); - } - } + @Override + public void onTunnelNetworkChange() { + if (this.isOutput()) { + try { + int light = 0; + for (PartP2PLight src : this.getInputs()) { + if (src != null && src.getProxy().isActive()) { + light = Math.max(light, src.lastValue); + } + } + this.setLightLevel(light); + this.getHost().markForUpdate(); + } catch (GridAccessException e) { + e.printStackTrace(); + } + } else { + this.doWork(); + } + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.LightTunnel.getMin(), TickRates.LightTunnel.getMax(), false, false ); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.LightTunnel.getMin(), TickRates.LightTunnel.getMax(), false, false); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.doWork() ? TickRateModulation.URGENT : TickRateModulation.SLOWER; - } + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.doWork() ? TickRateModulation.URGENT : TickRateModulation.SLOWER; + } - public float getPowerDrainPerTick() - { - return 0.5f; - } + public float getPowerDrainPerTick() { + return 0.5f; + } - @Override - public IPartModel getStaticModels() - { - return MODELS.getModel( this.isPowered(), this.isActive() ); - } + @Override + public IPartModel getStaticModels() { + return MODELS.getModel(this.isPowered(), this.isActive()); + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PRedstone.java b/src/main/java/appeng/parts/p2p/PartP2PRedstone.java index d79d02e99..94abb07f9 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PRedstone.java +++ b/src/main/java/appeng/parts/p2p/PartP2PRedstone.java @@ -19,8 +19,10 @@ package appeng.parts.p2p; -import java.util.List; - +import appeng.api.parts.IPartModel; +import appeng.items.parts.PartModels; +import appeng.me.GridAccessException; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.BlockRedstoneWire; import net.minecraft.block.state.IBlockState; @@ -31,200 +33,154 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import appeng.api.parts.IPartModel; -import appeng.items.parts.PartModels; -import appeng.me.GridAccessException; -import appeng.util.Platform; +import java.util.List; -public class PartP2PRedstone extends PartP2PTunnel -{ +public class PartP2PRedstone extends PartP2PTunnel { - private static final P2PModels MODELS = new P2PModels( "part/p2p/p2p_tunnel_redstone" ); + private static final P2PModels MODELS = new P2PModels("part/p2p/p2p_tunnel_redstone"); - @PartModels - public static List getModels() - { - return MODELS.getModels(); - } + @PartModels + public static List getModels() { + return MODELS.getModels(); + } - private int power; - private boolean recursive = false; + private int power; + private boolean recursive = false; - public PartP2PRedstone( final ItemStack is ) - { - super( is ); - } + public PartP2PRedstone(final ItemStack is) { + super(is); + } - private void setNetworkReady() - { - if( this.isOutput() ) - { - try - { - int power = 0; - for( PartP2PRedstone in : this.getInputs() ) - { - if( in != null ) - { - power = Math.max( power, in.power ); - } - } - this.putInput( power ); - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - } - } + private void setNetworkReady() { + if (this.isOutput()) { + try { + int power = 0; + for (PartP2PRedstone in : this.getInputs()) { + if (in != null) { + power = Math.max(power, in.power); + } + } + this.putInput(power); + } catch (GridAccessException e) { + e.printStackTrace(); + } + } + } - private void putInput( final Object o ) - { - if( this.recursive ) - { - return; - } + private void putInput(final Object o) { + if (this.recursive) { + return; + } - this.recursive = true; - if( this.isOutput() ) - { - if( this.getProxy().isActive() ) - { - final int newPower = (Integer) o; - if( this.power != newPower ) - { - this.power = newPower; - this.notifyNeighbors(); - } - } - else - { - this.power = 0; - this.notifyNeighbors(); - } - } - this.recursive = false; - } + this.recursive = true; + if (this.isOutput()) { + if (this.getProxy().isActive()) { + final int newPower = (Integer) o; + if (this.power != newPower) { + this.power = newPower; + this.notifyNeighbors(); + } + } else { + this.power = 0; + this.notifyNeighbors(); + } + } + this.recursive = false; + } - private void notifyNeighbors() - { - final World world = this.getTile().getWorld(); + private void notifyNeighbors() { + final World world = this.getTile().getWorld(); - Platform.notifyBlocksOfNeighbors( world, this.getTile().getPos() ); + Platform.notifyBlocksOfNeighbors(world, this.getTile().getPos()); - // and this cause sometimes it can go thought walls. - for( final EnumFacing face : EnumFacing.VALUES ) - { - Platform.notifyBlocksOfNeighbors( world, this.getTile().getPos().offset( face ) ); - } - } + // and this cause sometimes it can go thought walls. + for (final EnumFacing face : EnumFacing.VALUES) { + Platform.notifyBlocksOfNeighbors(world, this.getTile().getPos().offset(face)); + } + } - @Override - public void readFromNBT( final NBTTagCompound tag ) - { - super.readFromNBT( tag ); - this.power = tag.getInteger( "power" ); - } + @Override + public void readFromNBT(final NBTTagCompound tag) { + super.readFromNBT(tag); + this.power = tag.getInteger("power"); + } - @Override - public void writeToNBT( final NBTTagCompound tag ) - { - super.writeToNBT( tag ); - tag.setInteger( "power", this.power ); - } + @Override + public void writeToNBT(final NBTTagCompound tag) { + super.writeToNBT(tag); + tag.setInteger("power", this.power); + } - @Override - public void onTunnelNetworkChange() - { - this.setNetworkReady(); - } + @Override + public void onTunnelNetworkChange() { + this.setNetworkReady(); + } - public float getPowerDrainPerTick() - { - return 0.5f; - } + public float getPowerDrainPerTick() { + return 0.5f; + } - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - if( !this.isOutput() ) - { - final BlockPos target = this.getTile().getPos().offset( this.getSide().getFacing() ); + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + if (!this.isOutput()) { + final BlockPos target = this.getTile().getPos().offset(this.getSide().getFacing()); - final IBlockState state = this.getTile().getWorld().getBlockState( target ); - final Block b = state.getBlock(); - if( b != null && !this.isOutput() ) - { - EnumFacing srcSide = this.getSide().getFacing(); - if( b instanceof BlockRedstoneWire ) - { - srcSide = EnumFacing.UP; - } + final IBlockState state = this.getTile().getWorld().getBlockState(target); + final Block b = state.getBlock(); + if (b != null && !this.isOutput()) { + EnumFacing srcSide = this.getSide().getFacing(); + if (b instanceof BlockRedstoneWire) { + srcSide = EnumFacing.UP; + } - this.power = b.getWeakPower( state, this.getTile().getWorld(), target, srcSide ); - this.power = Math.max( this.power, b.getWeakPower( state, this.getTile().getWorld(), target, srcSide ) ); - int powerOut = this.power; - try - { - for( PartP2PRedstone in : this.getInputs() ) - { - if( in != null ) - { - powerOut = Math.max( in.power, powerOut ); - } - } - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - this.sendToOutput( powerOut ); - } - else - { - this.sendToOutput( 0 ); - } - } - } + this.power = b.getWeakPower(state, this.getTile().getWorld(), target, srcSide); + this.power = Math.max(this.power, b.getWeakPower(state, this.getTile().getWorld(), target, srcSide)); + int powerOut = this.power; + try { + for (PartP2PRedstone in : this.getInputs()) { + if (in != null) { + powerOut = Math.max(in.power, powerOut); + } + } + } catch (GridAccessException e) { + e.printStackTrace(); + } + this.sendToOutput(powerOut); + } else { + this.sendToOutput(0); + } + } + } - @Override - public boolean canConnectRedstone() - { - return true; - } + @Override + public boolean canConnectRedstone() { + return true; + } - @Override - public int isProvidingStrongPower() - { - return this.isOutput() ? this.power : 0; - } + @Override + public int isProvidingStrongPower() { + return this.isOutput() ? this.power : 0; + } - @Override - public int isProvidingWeakPower() - { - return this.isOutput() ? this.power : 0; - } + @Override + public int isProvidingWeakPower() { + return this.isOutput() ? this.power : 0; + } - private void sendToOutput( final int power ) - { - try - { - for( final PartP2PRedstone rs : this.getOutputs() ) - { - rs.putInput( power ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } + private void sendToOutput(final int power) { + try { + for (final PartP2PRedstone rs : this.getOutputs()) { + rs.putInput(power); + } + } catch (final GridAccessException e) { + // :P + } + } - @Override - public IPartModel getStaticModels() - { - return MODELS.getModel( this.isPowered(), this.isActive() ); - } + @Override + public IPartModel getStaticModels() { + return MODELS.getModel(this.isPowered(), this.isActive()); + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PTunnel.java b/src/main/java/appeng/parts/p2p/PartP2PTunnel.java index ea155823f..b2415fac9 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PTunnel.java +++ b/src/main/java/appeng/parts/p2p/PartP2PTunnel.java @@ -19,23 +19,6 @@ package appeng.parts.p2p; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Optional; - -import appeng.api.networking.events.MENetworkBootingStatusChange; -import appeng.api.networking.events.MENetworkChannelsChanged; -import appeng.api.networking.events.MENetworkEventSubscribe; -import appeng.api.networking.events.MENetworkPowerStatusChange; -import io.netty.buffer.ByteBuf; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.Vec3d; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -44,6 +27,10 @@ import appeng.api.config.TunnelType; import appeng.api.definitions.IParts; import appeng.api.implementations.items.IMemoryCard; import appeng.api.implementations.items.MemoryCardMessages; +import appeng.api.networking.events.MENetworkBootingStatusChange; +import appeng.api.networking.events.MENetworkChannelsChanged; +import appeng.api.networking.events.MENetworkEventSubscribe; +import appeng.api.networking.events.MENetworkPowerStatusChange; import appeng.api.parts.IPart; import appeng.api.parts.IPartCollisionHelper; import appeng.api.parts.IPartItem; @@ -57,484 +44,415 @@ import appeng.me.cache.P2PCache; import appeng.me.cache.helpers.TunnelCollection; import appeng.parts.PartBasicState; import appeng.util.Platform; -import org.lwjgl.input.Keyboard; - - -public abstract class PartP2PTunnel extends PartBasicState -{ - private final TunnelCollection type = new TunnelCollection( null, this.getClass() ); - private boolean output; - private short freq; - - public PartP2PTunnel( final ItemStack is ) - { - super( is ); - } - - public TunnelCollection getCollection( final Collection collection, final Class c ) - { - if( this.type.matches( c ) ) - { - this.type.setSource( collection ); - return this.type; - } - - return null; - } - - public TunnelCollection getInputs() throws GridAccessException - { - if( this.getProxy().isActive() && this.getFrequency() != 0 ) - { - return (TunnelCollection) this.getProxy().getP2P().getInputs( this.getFrequency(), this.getClass() ); - } - return new TunnelCollection( new ArrayList(), this.getClass() ); - } - - public TunnelCollection getOutputs() throws GridAccessException - { - if( this.getProxy().isActive() ) - { - return (TunnelCollection) this.getProxy().getP2P().getOutputs( this.getFrequency(), this.getClass() ); - } - return new TunnelCollection( new ArrayList(), this.getClass() ); - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 5, 5, 12, 11, 11, 13 ); - bch.addBox( 3, 3, 13, 13, 13, 14 ); - bch.addBox( 2, 2, 14, 14, 14, 16 ); - } - - @Override - public ItemStack getItemStack( final PartItemStack type ) - { - if( type == PartItemStack.WORLD || type == PartItemStack.NETWORK || type == PartItemStack.WRENCH || type == PartItemStack.PICK ) - { - return super.getItemStack( type ); - } - - final Optional maybeMEStack = AEApi.instance().definitions().parts().p2PTunnelME().maybeStack( 1 ); - if( maybeMEStack.isPresent() ) - { - return maybeMEStack.get(); - } - - return super.getItemStack( type ); - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.setOutput( data.getBoolean( "output" ) ); - this.freq = data.getShort( "freq" ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setBoolean( "output", this.isOutput() ); - data.setShort( "freq", this.getFrequency() ); - } - - @Override - public boolean readFromStream( ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - final short oldf = this.freq; - this.freq = data.readShort(); - return c || oldf != this.freq; - } - - @Override - public void writeToStream( ByteBuf data ) throws IOException - { - super.writeToStream( data ); - data.writeShort( this.getFrequency() ); - } - - @Override - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - this.onTunnelNetworkChange(); - super.chanRender( c ); - } - - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.onTunnelNetworkChange(); - super.powerRender( c ); - } - - @Override - @MENetworkEventSubscribe - public void bootingRender( final MENetworkBootingStatusChange bs ) - { - this.onTunnelNetworkChange(); - super.bootingRender( bs ); - } - - @Override - public float getCableConnectionLength( AECableType cable ) - { - return 1; - } - - @Override - public boolean useStandardMemoryCard() - { - return false; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isClient() ) - { - return true; - } - - if( hand == EnumHand.OFF_HAND ) - { - return false; - } - - boolean pasteAsOutput = true; - ItemStack is = player.getHeldItem( hand ); - if( is.isEmpty() ) - { - pasteAsOutput = false; - is = player.getHeldItemOffhand(); - } - - // UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor( is.getItem() ); - // AELog.info( "ID:" + id.toString() + " : " + is.getItemDamage() ); - - final TunnelType tt = AEApi.instance().registries().p2pTunnel().getTunnelTypeByItem( is ); - if( !is.isEmpty() && is.getItem() instanceof IMemoryCard ) - { - final IMemoryCard mc = (IMemoryCard) is.getItem(); - final NBTTagCompound data = mc.getData( is ); - - final ItemStack newType = new ItemStack( data ); - final short freq = data.getShort( "freq" ); - - if( !newType.isEmpty() ) - { - if( newType.getItem() instanceof IPartItem ) - { - final IPart testPart = ( (IPartItem) newType.getItem() ).createPartFromItemStack( newType ); - if( testPart instanceof PartP2PTunnel ) - { - - try - { - this.getProxy().getP2P().removeTunnel( this, this.getFrequency() ); - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - - this.getHost().removePart( this.getSide(), true ); - - final AEPartLocation dir = this.getHost().addPart( newType, this.getSide(), player, hand ); - final IPart newBus = this.getHost().getPart( dir ); - - if( newBus instanceof PartP2PTunnel ) - { - final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; - - if( pasteAsOutput ) - { - newTunnel.setOutput( true ); - } - - try - { - final P2PCache p2p = newTunnel.getProxy().getP2P(); - p2p.updateFreq( newTunnel, freq ); - } - catch( final GridAccessException e ) - { - // :P - } - - newTunnel.onTunnelNetworkChange(); - } - - mc.notifyUser( player, MemoryCardMessages.SETTINGS_LOADED ); - return true; - } - } - } - mc.notifyUser( player, MemoryCardMessages.INVALID_MACHINE ); - } - else if( tt != null ) // attunement - { - final ItemStack newType; - - final IParts parts = AEApi.instance().definitions().parts(); - - switch ( tt ) - { - case LIGHT: - newType = parts.p2PTunnelLight().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - break; - - case FE_POWER: - newType = parts.p2PTunnelFE().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - break; - - case GTEU_POWER: - newType = parts.p2PTunnelGTEU().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - break; - - case FLUID: - newType = parts.p2PTunnelFluids().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - break; - - case IC2_POWER: - newType = parts.p2PTunnelEU().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - break; - - case ITEM: - newType = parts.p2PTunnelItems().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - break; - - case ME: - newType = parts.p2PTunnelME().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - break; - - case REDSTONE: - newType = parts.p2PTunnelRedstone().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - break; - - /* - * case COMPUTER_MESSAGE: - * for( ItemStack stack : parts.p2PTunnelOpenComputers().maybeStack( 1 ).asSet() ) - * { - * newType = stack; - * } - * break; - */ - - default: - newType = ItemStack.EMPTY; - break; - } - - if( !newType.isEmpty() && !ItemStack.areItemsEqual( newType, this.getItemStack() ) ) - { - final boolean oldOutput = this.isOutput(); - final short myFreq = this.getFrequency(); - - try - { - this.getProxy().getP2P().removeTunnel( this, this.getFrequency() ); - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - - this.getHost().removePart( this.getSide(), false ); - - final AEPartLocation dir = this.getHost().addPart( newType, this.getSide(), player, hand ); - final IPart newBus = this.getHost().getPart( dir ); - - if( newBus instanceof PartP2PTunnel ) - { - final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; - newTunnel.setOutput( oldOutput ); - - try - { - final P2PCache p2p = newTunnel.getProxy().getP2P(); - p2p.updateFreq( newTunnel, myFreq ); - } - catch( final GridAccessException e ) - { - // :P - } - newTunnel.onTunnelNetworkChange(); - - } - - return true; - } - } - - return false; - } - - @Override - public boolean onPartShiftActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - final ItemStack is = player.inventory.getCurrentItem(); - if( !is.isEmpty() && is.getItem() instanceof IMemoryCard ) - { - if( Platform.isClient() ) - { - return true; - } - - final IMemoryCard mc = (IMemoryCard) is.getItem(); - final NBTTagCompound data = mc.getData( is ); - final short storedFrequency = data.getShort( "freq" ); - - short newFreq = this.getFrequency(); - final boolean wasOutput = this.isOutput(); - this.setOutput( false ); - - final boolean needsNewFrequency = wasOutput || this.getFrequency() == 0 || storedFrequency == newFreq; - - try - { - if( needsNewFrequency ) - { - newFreq = this.getProxy().getP2P().newFrequency(); - - final ItemStack newType = this.getHost().getPart( this.getSide() ).getItemStack( PartItemStack.WRENCH ); - - try - { - this.getProxy().getP2P().removeTunnel( this, this.getFrequency() ); - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - - this.getHost().removePart( this.getSide(), false ); - - final AEPartLocation dir = this.getHost().addPart( newType, this.getSide(), player, hand ); - final IPart newBus = this.getHost().getPart( dir ); - - if( newBus instanceof PartP2PTunnel ) - { - final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; - newTunnel.setOutput( false ); - newTunnel.getProxy().getP2P().updateFreq( newTunnel, newFreq ); - - newTunnel.onTunnelNetworkChange(); - } - } - else - { - this.getProxy().getP2P().updateFreq( this, newFreq ); - this.onTunnelNetworkChange(); - } - Platform.notifyBlocksOfNeighbors( this.getTile().getWorld(), this.getTile().getPos() ); - } - catch( final GridAccessException e ) - { - // :P - } - - this.onTunnelConfigChange(); - - final ItemStack p2pItem = this.getItemStack( PartItemStack.WRENCH ); - final String type = p2pItem.getUnlocalizedName(); - - p2pItem.writeToNBT( data ); - if( needsNewFrequency ) - { - data.setShort( "freq", newFreq ); - } - else - { - data.setShort( "freq", this.getFrequency() ); - } - - final AEColor[] colors = Platform.p2p().toColors( this.getFrequency() ); - final int[] colorCode = new int[]{ - colors[0].ordinal(), colors[0].ordinal(), - colors[1].ordinal(), colors[1].ordinal(), - colors[2].ordinal(), colors[2].ordinal(), - colors[3].ordinal(), colors[3].ordinal(), - }; - - data.setIntArray( "colorCode", colorCode ); - - mc.setMemoryCardContents( is, type + ".name", data ); - if( needsNewFrequency ) - { - mc.notifyUser( player, MemoryCardMessages.SETTINGS_RESET ); - } - else - { - mc.notifyUser( player, MemoryCardMessages.SETTINGS_SAVED ); - } - return true; - } - return false; - } - - public void onTunnelConfigChange() - { - } - - public void onTunnelNetworkChange() - { - } - - protected void queueTunnelDrain( final PowerUnits unit, final double f ) - { - final double ae_to_tax = unit.convertTo( PowerUnits.AE, f * AEConfig.TUNNEL_POWER_LOSS ); - - try - { - this.getProxy().getEnergy().extractAEPower( ae_to_tax, Actionable.MODULATE, PowerMultiplier.ONE ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - public short getFrequency() - { - return this.freq; - } - - public void setFrequency( final short freq ) - { - final short oldf = this.freq; - this.freq = freq; - if( oldf != this.freq ) - { - this.getHost().markForUpdate(); - } - } - - public boolean isOutput() - { - return this.output; - } - - void setOutput( final boolean output ) - { - this.output = output; - } - - @Override - public Long getRenderFlag() - { - long ret = Short.toUnsignedLong( this.getFrequency() ); - - if( this.isActive() && this.isPowered() ) - { - ret |= 0x10000L; - } - - return ret; - } +import io.netty.buffer.ByteBuf; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.Vec3d; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Optional; + + +public abstract class PartP2PTunnel extends PartBasicState { + private final TunnelCollection type = new TunnelCollection(null, this.getClass()); + private boolean output; + private short freq; + + public PartP2PTunnel(final ItemStack is) { + super(is); + } + + public TunnelCollection getCollection(final Collection collection, final Class c) { + if (this.type.matches(c)) { + this.type.setSource(collection); + return this.type; + } + + return null; + } + + public TunnelCollection getInputs() throws GridAccessException { + if (this.getProxy().isActive() && this.getFrequency() != 0) { + return (TunnelCollection) this.getProxy().getP2P().getInputs(this.getFrequency(), this.getClass()); + } + return new TunnelCollection(new ArrayList(), this.getClass()); + } + + public TunnelCollection getOutputs() throws GridAccessException { + if (this.getProxy().isActive()) { + return (TunnelCollection) this.getProxy().getP2P().getOutputs(this.getFrequency(), this.getClass()); + } + return new TunnelCollection(new ArrayList(), this.getClass()); + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(5, 5, 12, 11, 11, 13); + bch.addBox(3, 3, 13, 13, 13, 14); + bch.addBox(2, 2, 14, 14, 14, 16); + } + + @Override + public ItemStack getItemStack(final PartItemStack type) { + if (type == PartItemStack.WORLD || type == PartItemStack.NETWORK || type == PartItemStack.WRENCH || type == PartItemStack.PICK) { + return super.getItemStack(type); + } + + final Optional maybeMEStack = AEApi.instance().definitions().parts().p2PTunnelME().maybeStack(1); + if (maybeMEStack.isPresent()) { + return maybeMEStack.get(); + } + + return super.getItemStack(type); + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.setOutput(data.getBoolean("output")); + this.freq = data.getShort("freq"); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setBoolean("output", this.isOutput()); + data.setShort("freq", this.getFrequency()); + } + + @Override + public boolean readFromStream(ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + final short oldf = this.freq; + this.freq = data.readShort(); + return c || oldf != this.freq; + } + + @Override + public void writeToStream(ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeShort(this.getFrequency()); + } + + @Override + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + this.onTunnelNetworkChange(); + super.chanRender(c); + } + + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.onTunnelNetworkChange(); + super.powerRender(c); + } + + @Override + @MENetworkEventSubscribe + public void bootingRender(final MENetworkBootingStatusChange bs) { + this.onTunnelNetworkChange(); + super.bootingRender(bs); + } + + @Override + public float getCableConnectionLength(AECableType cable) { + return 1; + } + + @Override + public boolean useStandardMemoryCard() { + return false; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (Platform.isClient()) { + return true; + } + + if (hand == EnumHand.OFF_HAND) { + return false; + } + + boolean pasteAsOutput = true; + ItemStack is = player.getHeldItem(hand); + if (is.isEmpty()) { + pasteAsOutput = false; + is = player.getHeldItemOffhand(); + } + + // UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor( is.getItem() ); + // AELog.info( "ID:" + id.toString() + " : " + is.getItemDamage() ); + + final TunnelType tt = AEApi.instance().registries().p2pTunnel().getTunnelTypeByItem(is); + if (!is.isEmpty() && is.getItem() instanceof IMemoryCard) { + final IMemoryCard mc = (IMemoryCard) is.getItem(); + final NBTTagCompound data = mc.getData(is); + + final ItemStack newType = new ItemStack(data); + final short freq = data.getShort("freq"); + + if (!newType.isEmpty()) { + if (newType.getItem() instanceof IPartItem) { + final IPart testPart = ((IPartItem) newType.getItem()).createPartFromItemStack(newType); + if (testPart instanceof PartP2PTunnel) { + + try { + this.getProxy().getP2P().removeTunnel(this, this.getFrequency()); + } catch (GridAccessException e) { + e.printStackTrace(); + } + + this.getHost().removePart(this.getSide(), true); + + final AEPartLocation dir = this.getHost().addPart(newType, this.getSide(), player, hand); + final IPart newBus = this.getHost().getPart(dir); + + if (newBus instanceof PartP2PTunnel) { + final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; + + if (pasteAsOutput) { + newTunnel.setOutput(true); + } + + try { + final P2PCache p2p = newTunnel.getProxy().getP2P(); + p2p.updateFreq(newTunnel, freq); + } catch (final GridAccessException e) { + // :P + } + + newTunnel.onTunnelNetworkChange(); + } + + mc.notifyUser(player, MemoryCardMessages.SETTINGS_LOADED); + return true; + } + } + } + mc.notifyUser(player, MemoryCardMessages.INVALID_MACHINE); + } else if (tt != null) // attunement + { + final ItemStack newType; + + final IParts parts = AEApi.instance().definitions().parts(); + + switch (tt) { + case LIGHT: + newType = parts.p2PTunnelLight().maybeStack(1).orElse(ItemStack.EMPTY); + break; + + case FE_POWER: + newType = parts.p2PTunnelFE().maybeStack(1).orElse(ItemStack.EMPTY); + break; + + case GTEU_POWER: + newType = parts.p2PTunnelGTEU().maybeStack(1).orElse(ItemStack.EMPTY); + break; + + case FLUID: + newType = parts.p2PTunnelFluids().maybeStack(1).orElse(ItemStack.EMPTY); + break; + + case IC2_POWER: + newType = parts.p2PTunnelEU().maybeStack(1).orElse(ItemStack.EMPTY); + break; + + case ITEM: + newType = parts.p2PTunnelItems().maybeStack(1).orElse(ItemStack.EMPTY); + break; + + case ME: + newType = parts.p2PTunnelME().maybeStack(1).orElse(ItemStack.EMPTY); + break; + + case REDSTONE: + newType = parts.p2PTunnelRedstone().maybeStack(1).orElse(ItemStack.EMPTY); + break; + + /* + * case COMPUTER_MESSAGE: + * for( ItemStack stack : parts.p2PTunnelOpenComputers().maybeStack( 1 ).asSet() ) + * { + * newType = stack; + * } + * break; + */ + + default: + newType = ItemStack.EMPTY; + break; + } + + if (!newType.isEmpty() && !ItemStack.areItemsEqual(newType, this.getItemStack())) { + final boolean oldOutput = this.isOutput(); + final short myFreq = this.getFrequency(); + + try { + this.getProxy().getP2P().removeTunnel(this, this.getFrequency()); + } catch (GridAccessException e) { + e.printStackTrace(); + } + + this.getHost().removePart(this.getSide(), false); + + final AEPartLocation dir = this.getHost().addPart(newType, this.getSide(), player, hand); + final IPart newBus = this.getHost().getPart(dir); + + if (newBus instanceof PartP2PTunnel) { + final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; + newTunnel.setOutput(oldOutput); + + try { + final P2PCache p2p = newTunnel.getProxy().getP2P(); + p2p.updateFreq(newTunnel, myFreq); + } catch (final GridAccessException e) { + // :P + } + newTunnel.onTunnelNetworkChange(); + + } + + return true; + } + } + + return false; + } + + @Override + public boolean onPartShiftActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + final ItemStack is = player.inventory.getCurrentItem(); + if (!is.isEmpty() && is.getItem() instanceof IMemoryCard) { + if (Platform.isClient()) { + return true; + } + + final IMemoryCard mc = (IMemoryCard) is.getItem(); + final NBTTagCompound data = mc.getData(is); + final short storedFrequency = data.getShort("freq"); + + short newFreq = this.getFrequency(); + final boolean wasOutput = this.isOutput(); + this.setOutput(false); + + final boolean needsNewFrequency = wasOutput || this.getFrequency() == 0 || storedFrequency == newFreq; + + try { + if (needsNewFrequency) { + newFreq = this.getProxy().getP2P().newFrequency(); + + final ItemStack newType = this.getHost().getPart(this.getSide()).getItemStack(PartItemStack.WRENCH); + + try { + this.getProxy().getP2P().removeTunnel(this, this.getFrequency()); + } catch (GridAccessException e) { + e.printStackTrace(); + } + + this.getHost().removePart(this.getSide(), false); + + final AEPartLocation dir = this.getHost().addPart(newType, this.getSide(), player, hand); + final IPart newBus = this.getHost().getPart(dir); + + if (newBus instanceof PartP2PTunnel) { + final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; + newTunnel.setOutput(false); + newTunnel.getProxy().getP2P().updateFreq(newTunnel, newFreq); + + newTunnel.onTunnelNetworkChange(); + } + } else { + this.getProxy().getP2P().updateFreq(this, newFreq); + this.onTunnelNetworkChange(); + } + Platform.notifyBlocksOfNeighbors(this.getTile().getWorld(), this.getTile().getPos()); + } catch (final GridAccessException e) { + // :P + } + + this.onTunnelConfigChange(); + + final ItemStack p2pItem = this.getItemStack(PartItemStack.WRENCH); + final String type = p2pItem.getUnlocalizedName(); + + p2pItem.writeToNBT(data); + if (needsNewFrequency) { + data.setShort("freq", newFreq); + } else { + data.setShort("freq", this.getFrequency()); + } + + final AEColor[] colors = Platform.p2p().toColors(this.getFrequency()); + final int[] colorCode = new int[]{ + colors[0].ordinal(), colors[0].ordinal(), + colors[1].ordinal(), colors[1].ordinal(), + colors[2].ordinal(), colors[2].ordinal(), + colors[3].ordinal(), colors[3].ordinal(), + }; + + data.setIntArray("colorCode", colorCode); + + mc.setMemoryCardContents(is, type + ".name", data); + if (needsNewFrequency) { + mc.notifyUser(player, MemoryCardMessages.SETTINGS_RESET); + } else { + mc.notifyUser(player, MemoryCardMessages.SETTINGS_SAVED); + } + return true; + } + return false; + } + + public void onTunnelConfigChange() { + } + + public void onTunnelNetworkChange() { + } + + protected void queueTunnelDrain(final PowerUnits unit, final double f) { + final double ae_to_tax = unit.convertTo(PowerUnits.AE, f * AEConfig.TUNNEL_POWER_LOSS); + + try { + this.getProxy().getEnergy().extractAEPower(ae_to_tax, Actionable.MODULATE, PowerMultiplier.ONE); + } catch (final GridAccessException e) { + // :P + } + } + + public short getFrequency() { + return this.freq; + } + + public void setFrequency(final short freq) { + final short oldf = this.freq; + this.freq = freq; + if (oldf != this.freq) { + this.getHost().markForUpdate(); + } + } + + public boolean isOutput() { + return this.output; + } + + void setOutput(final boolean output) { + this.output = output; + } + + @Override + public Long getRenderFlag() { + long ret = Short.toUnsignedLong(this.getFrequency()); + + if (this.isActive() && this.isPowered()) { + ret |= 0x10000L; + } + + return ret; + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java b/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java index f7a335900..a661dc695 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java +++ b/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java @@ -19,17 +19,6 @@ package appeng.parts.p2p; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumHand; - import appeng.api.AEApi; import appeng.api.exceptions.FailedConnectionException; import appeng.api.networking.GridFlags; @@ -49,228 +38,188 @@ import appeng.me.GridAccessException; import appeng.me.cache.helpers.Connections; import appeng.me.cache.helpers.TunnelConnection; import appeng.me.helpers.AENetworkProxy; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumHand; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.List; -public class PartP2PTunnelME extends PartP2PTunnel implements IGridTickable -{ +public class PartP2PTunnelME extends PartP2PTunnel implements IGridTickable { - private static final P2PModels MODELS = new P2PModels( "part/p2p/p2p_tunnel_me" ); + private static final P2PModels MODELS = new P2PModels("part/p2p/p2p_tunnel_me"); - @PartModels - public static List getModels() - { - return MODELS.getModels(); - } + @PartModels + public static List getModels() { + return MODELS.getModels(); + } - private final Connections connection = new Connections( this ); - private final AENetworkProxy outerProxy = new AENetworkProxy( this, "outer", ItemStack.EMPTY, true ); + private final Connections connection = new Connections(this); + private final AENetworkProxy outerProxy = new AENetworkProxy(this, "outer", ItemStack.EMPTY, true); - public PartP2PTunnelME( final ItemStack is ) - { - super( is ); - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL, GridFlags.COMPRESSED_CHANNEL ); - this.outerProxy.setFlags( GridFlags.DENSE_CAPACITY, GridFlags.CANNOT_CARRY_COMPRESSED ); - } + public PartP2PTunnelME(final ItemStack is) { + super(is); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL, GridFlags.COMPRESSED_CHANNEL); + this.outerProxy.setFlags(GridFlags.DENSE_CAPACITY, GridFlags.CANNOT_CARRY_COMPRESSED); + } - @Override - public void readFromNBT( final NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.outerProxy.readFromNBT( extra ); - } + @Override + public void readFromNBT(final NBTTagCompound extra) { + super.readFromNBT(extra); + this.outerProxy.readFromNBT(extra); + } - @Override - public void writeToNBT( final NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.outerProxy.writeToNBT( extra ); - } + @Override + public void writeToNBT(final NBTTagCompound extra) { + super.writeToNBT(extra); + this.outerProxy.writeToNBT(extra); + } - @Override - public void onTunnelNetworkChange() - { - super.onTunnelNetworkChange(); - if( !this.isOutput() ) - { - try - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - } + @Override + public void onTunnelNetworkChange() { + super.onTunnelNetworkChange(); + if (!this.isOutput()) { + try { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // :P + } + } + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.DENSE_SMART; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.DENSE_SMART; + } - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - this.outerProxy.invalidate(); - } + @Override + public void removeFromWorld() { + super.removeFromWorld(); + this.outerProxy.invalidate(); + } - @Override - public void addToWorld() - { - super.addToWorld(); - this.outerProxy.onReady(); - } + @Override + public void addToWorld() { + super.addToWorld(); + this.outerProxy.onReady(); + } - @Override - public void setPartHostInfo( final AEPartLocation side, final IPartHost host, final TileEntity tile ) - { - super.setPartHostInfo( side, host, tile ); - this.outerProxy.setValidSides( EnumSet.of( side.getFacing() ) ); - } + @Override + public void setPartHostInfo(final AEPartLocation side, final IPartHost host, final TileEntity tile) { + super.setPartHostInfo(side, host, tile); + this.outerProxy.setValidSides(EnumSet.of(side.getFacing())); + } - @Override - public IGridNode getExternalFacingNode() - { - return this.outerProxy.getNode(); - } + @Override + public IGridNode getExternalFacingNode() { + return this.outerProxy.getNode(); + } - @Override - public void onPlacement( final EntityPlayer player, final EnumHand hand, final ItemStack held, final AEPartLocation side ) - { - super.onPlacement( player, hand, held, side ); - this.outerProxy.setOwner( player ); - } + @Override + public void onPlacement(final EntityPlayer player, final EnumHand hand, final ItemStack held, final AEPartLocation side) { + super.onPlacement(player, hand, held, side); + this.outerProxy.setOwner(player); + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.METunnel.getMin(), TickRates.METunnel.getMax(), true, false ); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.METunnel.getMin(), TickRates.METunnel.getMax(), true, false); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - // just move on... - try - { - if( !this.getProxy().getPath().isNetworkBooting() ) - { - if( !this.getProxy().getEnergy().isNetworkPowered() ) - { - this.connection.markDestroy(); - TickHandler.INSTANCE.addCallable( this.getTile().getWorld(), this.connection ); - } - else - { - if( this.getProxy().isActive() ) - { - this.connection.markCreate(); - TickHandler.INSTANCE.addCallable( this.getTile().getWorld(), this.connection ); - } - else - { - this.connection.markDestroy(); - TickHandler.INSTANCE.addCallable( this.getTile().getWorld(), this.connection ); - } - } + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + // just move on... + try { + if (!this.getProxy().getPath().isNetworkBooting()) { + if (!this.getProxy().getEnergy().isNetworkPowered()) { + this.connection.markDestroy(); + TickHandler.INSTANCE.addCallable(this.getTile().getWorld(), this.connection); + } else { + if (this.getProxy().isActive()) { + this.connection.markCreate(); + TickHandler.INSTANCE.addCallable(this.getTile().getWorld(), this.connection); + } else { + this.connection.markDestroy(); + TickHandler.INSTANCE.addCallable(this.getTile().getWorld(), this.connection); + } + } - return TickRateModulation.SLEEP; - } - } - catch( final GridAccessException e ) - { - // meh? - } + return TickRateModulation.SLEEP; + } + } catch (final GridAccessException e) { + // meh? + } - return TickRateModulation.IDLE; - } + return TickRateModulation.IDLE; + } - public void updateConnections( final Connections connections ) - { - if( connections.isDestroy() ) - { - for( final TunnelConnection cw : this.connection.getConnections().values() ) - { - cw.getConnection().destroy(); - } + public void updateConnections(final Connections connections) { + if (connections.isDestroy()) { + for (final TunnelConnection cw : this.connection.getConnections().values()) { + cw.getConnection().destroy(); + } - this.connection.getConnections().clear(); - } - else if( connections.isCreate() ) - { + this.connection.getConnections().clear(); + } else if (connections.isCreate()) { - final Iterator i = this.connection.getConnections().values().iterator(); - while( i.hasNext() ) - { - final TunnelConnection cw = i.next(); - try - { - if( cw.getTunnel().getProxy().getGrid() != this.getProxy().getGrid() ) - { - cw.getConnection().destroy(); - i.remove(); - } - else if( !cw.getTunnel().getProxy().isActive() ) - { - cw.getConnection().destroy(); - i.remove(); - } - } - catch( final GridAccessException e ) - { - // :P - } - } + final Iterator i = this.connection.getConnections().values().iterator(); + while (i.hasNext()) { + final TunnelConnection cw = i.next(); + try { + if (cw.getTunnel().getProxy().getGrid() != this.getProxy().getGrid()) { + cw.getConnection().destroy(); + i.remove(); + } else if (!cw.getTunnel().getProxy().isActive()) { + cw.getConnection().destroy(); + i.remove(); + } + } catch (final GridAccessException e) { + // :P + } + } - final List newSides = new ArrayList<>(); - try - { - for( final PartP2PTunnelME me : this.getOutputs() ) - { - if( me.getProxy().isActive() && connections.getConnections().get( me.getGridNode() ) == null ) - { - newSides.add( me ); - } - } + final List newSides = new ArrayList<>(); + try { + for (final PartP2PTunnelME me : this.getOutputs()) { + if (me.getProxy().isActive() && connections.getConnections().get(me.getGridNode()) == null) { + newSides.add(me); + } + } - for( final PartP2PTunnelME me : newSides ) - { - try - { - connections.getConnections() - .put( me.getGridNode(), - new TunnelConnection( me, AEApi.instance() - .grid() - .createGridConnection( this.outerProxy.getNode(), - me.outerProxy.getNode() ) ) ); - } - catch( final FailedConnectionException e ) - { - final TileEntity start = this.getTile(); - final TileEntity end = me.getTile(); + for (final PartP2PTunnelME me : newSides) { + try { + connections.getConnections() + .put(me.getGridNode(), + new TunnelConnection(me, AEApi.instance() + .grid() + .createGridConnection(this.outerProxy.getNode(), + me.outerProxy.getNode()))); + } catch (final FailedConnectionException e) { + final TileEntity start = this.getTile(); + final TileEntity end = me.getTile(); - AELog.debug( e ); + AELog.debug(e); - AELog.warn( "Failed to establish a ME P2P Tunnel between the tunnels at [x=%d, y=%d, z=%d] and [x=%d, y=%d, z=%d]", - start.getPos().getX(), start.getPos().getY(), start.getPos().getZ(), end.getPos().getX(), end.getPos().getY(), - end.getPos().getZ() ); - // :( - } - } - } - catch( final GridAccessException e ) - { - AELog.debug( e ); - } - } - } + AELog.warn("Failed to establish a ME P2P Tunnel between the tunnels at [x=%d, y=%d, z=%d] and [x=%d, y=%d, z=%d]", + start.getPos().getX(), start.getPos().getY(), start.getPos().getZ(), end.getPos().getX(), end.getPos().getY(), + end.getPos().getZ()); + // :( + } + } + } catch (final GridAccessException e) { + AELog.debug(e); + } + } + } - @Override - public IPartModel getStaticModels() - { - return MODELS.getModel( this.isPowered(), this.isActive() ); - } + @Override + public IPartModel getStaticModels() { + return MODELS.getModel(this.isPowered(), this.isActive()); + } } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartDisplay.java b/src/main/java/appeng/parts/reporting/AbstractPartDisplay.java index 3fe11adeb..d20ef3c4b 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartDisplay.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartDisplay.java @@ -19,16 +19,15 @@ package appeng.parts.reporting; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - import appeng.core.AppEng; import appeng.items.parts.PartModels; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; /** * A more sophisticated part overlapping all 3 textures. - * + *

* Subclass this if you need want a new part and need all 3 textures. * For more concrete implementations, the direct abstract subclasses might be a better alternative. * @@ -37,30 +36,27 @@ import appeng.items.parts.PartModels; * @version rv3 * @since rv3 */ -public abstract class AbstractPartDisplay extends AbstractPartReporting -{ +public abstract class AbstractPartDisplay extends AbstractPartReporting { - // The base chassis of all display parts - @PartModels - protected static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "part/display_base" ); + // The base chassis of all display parts + @PartModels + protected static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "part/display_base"); - // Models that contain the status indicator light - @PartModels - protected static final ResourceLocation MODEL_STATUS_OFF = new ResourceLocation( AppEng.MOD_ID, "part/display_status_off" ); - @PartModels - protected static final ResourceLocation MODEL_STATUS_ON = new ResourceLocation( AppEng.MOD_ID, "part/display_status_on" ); - @PartModels - protected static final ResourceLocation MODEL_STATUS_HAS_CHANNEL = new ResourceLocation( AppEng.MOD_ID, "part/display_status_has_channel" ); + // Models that contain the status indicator light + @PartModels + protected static final ResourceLocation MODEL_STATUS_OFF = new ResourceLocation(AppEng.MOD_ID, "part/display_status_off"); + @PartModels + protected static final ResourceLocation MODEL_STATUS_ON = new ResourceLocation(AppEng.MOD_ID, "part/display_status_on"); + @PartModels + protected static final ResourceLocation MODEL_STATUS_HAS_CHANNEL = new ResourceLocation(AppEng.MOD_ID, "part/display_status_has_channel"); - public AbstractPartDisplay( final ItemStack is ) - { - super( is, true ); - } + public AbstractPartDisplay(final ItemStack is) { + super(is, true); + } - @Override - public boolean isLightSource() - { - return false; - } + @Override + public boolean isLightSource() { + return false; + } } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartMonitor.java b/src/main/java/appeng/parts/reporting/AbstractPartMonitor.java index 00810e109..089fbae2b 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartMonitor.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartMonitor.java @@ -19,18 +19,33 @@ package appeng.parts.reporting; -import java.io.IOException; - +import appeng.api.AEApi; +import appeng.api.implementations.parts.IPartStorageMonitor; import appeng.api.networking.events.MENetworkChannelsChanged; import appeng.api.networking.events.MENetworkEventSubscribe; import appeng.api.networking.events.MENetworkPowerStatusChange; import appeng.api.networking.security.IActionSource; +import appeng.api.networking.storage.IStackWatcher; +import appeng.api.networking.storage.IStackWatcherHost; +import appeng.api.parts.IPartModel; +import appeng.api.storage.IMEMonitor; +import appeng.api.storage.IStorageChannel; import appeng.api.storage.channels.IFluidStorageChannel; +import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEFluidStack; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; +import appeng.client.render.TesrRenderHelper; +import appeng.core.localization.PlayerMessages; import appeng.fluids.util.AEFluidStack; +import appeng.helpers.Reflected; +import appeng.me.GridAccessException; +import appeng.util.IWideReadableNumberConverter; +import appeng.util.Platform; +import appeng.util.ReadableNumberConverter; +import appeng.util.item.AEItemStack; import io.netty.buffer.ByteBuf; - import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -45,29 +60,12 @@ import net.minecraftforge.fluids.capability.IFluidHandlerItem; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.AEApi; -import appeng.api.implementations.parts.IPartStorageMonitor; -import appeng.api.networking.storage.IStackWatcher; -import appeng.api.networking.storage.IStackWatcherHost; -import appeng.api.parts.IPartModel; -import appeng.api.storage.IMEMonitor; -import appeng.api.storage.IStorageChannel; -import appeng.api.storage.channels.IItemStorageChannel; -import appeng.api.storage.data.IAEItemStack; -import appeng.api.storage.data.IAEStack; -import appeng.client.render.TesrRenderHelper; -import appeng.core.localization.PlayerMessages; -import appeng.helpers.Reflected; -import appeng.me.GridAccessException; -import appeng.util.IWideReadableNumberConverter; -import appeng.util.Platform; -import appeng.util.ReadableNumberConverter; -import appeng.util.item.AEItemStack; +import java.io.IOException; /** * A basic subclass for any item monitor like display with an item icon and an amount. - * + *

* It can also be used to extract items from somewhere and spawned into the world. * * @author AlgorithmX2 @@ -76,401 +74,315 @@ import appeng.util.item.AEItemStack; * @version rv3 * @since rv3 */ -public abstract class AbstractPartMonitor extends AbstractPartDisplay implements IPartStorageMonitor, IStackWatcherHost -{ - private static final IWideReadableNumberConverter NUMBER_CONVERTER = ReadableNumberConverter.INSTANCE; +public abstract class AbstractPartMonitor extends AbstractPartDisplay implements IPartStorageMonitor, IStackWatcherHost { + private static final IWideReadableNumberConverter NUMBER_CONVERTER = ReadableNumberConverter.INSTANCE; - private IAEItemStack configuredItem; - private IAEFluidStack configuredFluid; - private long configuredAmount; - private String lastHumanReadableText; - private boolean isLocked; - private IStackWatcher myWatcher; + private IAEItemStack configuredItem; + private IAEFluidStack configuredFluid; + private long configuredAmount; + private String lastHumanReadableText; + private boolean isLocked; + private IStackWatcher myWatcher; - @Reflected - public AbstractPartMonitor( final ItemStack is ) - { - super( is ); - } + @Reflected + public AbstractPartMonitor(final ItemStack is) { + super(is); + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); - this.isLocked = data.getBoolean( "isLocked" ); + this.isLocked = data.getBoolean("isLocked"); - final NBTTagCompound myItem = data.getCompoundTag( "configuredItem" ); - this.configuredItem = AEItemStack.fromNBT( myItem ); + final NBTTagCompound myItem = data.getCompoundTag("configuredItem"); + this.configuredItem = AEItemStack.fromNBT(myItem); - final NBTTagCompound myFluid = data.getCompoundTag( "configuredFluid" ); - this.configuredFluid = AEFluidStack.fromNBT( myFluid ); - } + final NBTTagCompound myFluid = data.getCompoundTag("configuredFluid"); + this.configuredFluid = AEFluidStack.fromNBT(myFluid); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); - data.setBoolean( "isLocked", this.isLocked ); + data.setBoolean("isLocked", this.isLocked); - final NBTTagCompound myItem = new NBTTagCompound(); - if( this.configuredItem != null ) - { - this.configuredItem.writeToNBT( myItem ); - } - final NBTTagCompound myFluid = new NBTTagCompound(); - if( this.configuredFluid != null ) - { - this.configuredFluid.writeToNBT( myFluid ); - } + final NBTTagCompound myItem = new NBTTagCompound(); + if (this.configuredItem != null) { + this.configuredItem.writeToNBT(myItem); + } + final NBTTagCompound myFluid = new NBTTagCompound(); + if (this.configuredFluid != null) { + this.configuredFluid.writeToNBT(myFluid); + } - data.setTag( "configuredItem", myItem ); - data.setTag( "configuredFluid", myFluid ); + data.setTag("configuredItem", myItem); + data.setTag("configuredFluid", myFluid); - } + } - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); + @Override + public void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); - data.writeBoolean( this.isLocked ); - //is configured - data.writeBoolean( this.configuredItem != null); - data.writeBoolean( this.configuredFluid != null); - if( this.configuredItem != null ) - { - this.configuredItem.writeToPacket( data ); - } - else if( this.configuredFluid != null ) - { - this.configuredFluid.writeToPacket( data ); - } - } + data.writeBoolean(this.isLocked); + //is configured + data.writeBoolean(this.configuredItem != null); + data.writeBoolean(this.configuredFluid != null); + if (this.configuredItem != null) { + this.configuredItem.writeToPacket(data); + } else if (this.configuredFluid != null) { + this.configuredFluid.writeToPacket(data); + } + } - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - boolean needRedraw = super.readFromStream( data ); + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + boolean needRedraw = super.readFromStream(data); - final boolean isLocked = data.readBoolean(); - needRedraw = this.isLocked != isLocked; + final boolean isLocked = data.readBoolean(); + needRedraw = this.isLocked != isLocked; - this.isLocked = isLocked; + this.isLocked = isLocked; - final boolean isItem = data.readBoolean(); - final boolean isFluid = data.readBoolean(); - if( isItem ) - { - this.configuredItem = AEItemStack.fromPacket( data ); - this.configuredFluid = null; - } - else if( isFluid ) - { - this.configuredFluid = AEFluidStack.fromPacket( data ); - this.configuredItem = null; - } - else - { - this.configuredItem = null; - this.configuredFluid = null; - } + final boolean isItem = data.readBoolean(); + final boolean isFluid = data.readBoolean(); + if (isItem) { + this.configuredItem = AEItemStack.fromPacket(data); + this.configuredFluid = null; + } else if (isFluid) { + this.configuredFluid = AEFluidStack.fromPacket(data); + this.configuredItem = null; + } else { + this.configuredItem = null; + this.configuredFluid = null; + } - return needRedraw; - } + return needRedraw; + } - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( Platform.isClient() ) - { - return true; - } + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (Platform.isClient()) { + return true; + } - if( !this.getProxy().isActive() ) - { - return false; - } + if (!this.getProxy().isActive()) { + return false; + } - if( !Platform.hasPermissions( this.getLocation(), player ) ) - { - return false; - } + if (!Platform.hasPermissions(this.getLocation(), player)) { + return false; + } - if( !this.isLocked ) - { - final ItemStack eq = player.getHeldItem( hand ); - FluidStack fluidInTank = null; + if (!this.isLocked) { + final ItemStack eq = player.getHeldItem(hand); + FluidStack fluidInTank = null; - if( eq.hasCapability( CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null ) ) - { - IFluidHandlerItem fluidHandlerItem = ( eq.getCapability( CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null ) ); - fluidInTank = fluidHandlerItem.drain( Integer.MAX_VALUE, false ); - } + if (eq.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { + IFluidHandlerItem fluidHandlerItem = (eq.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)); + fluidInTank = fluidHandlerItem.drain(Integer.MAX_VALUE, false); + } - if( fluidInTank == null ) - { - this.configuredFluid = null; - if( !eq.isEmpty() ) - { - this.configuredItem = AEItemStack.fromItemStack( eq ).setStackSize( 0 ); - } - else - { - this.configuredItem = null; - } - } - else if( fluidInTank.amount > 0 ) - { - this.configuredFluid = AEFluidStack.fromFluidStack( fluidInTank ).setStackSize( 0 ); - this.configuredItem = null; - } + if (fluidInTank == null) { + this.configuredFluid = null; + if (!eq.isEmpty()) { + this.configuredItem = AEItemStack.fromItemStack(eq).setStackSize(0); + } else { + this.configuredItem = null; + } + } else if (fluidInTank.amount > 0) { + this.configuredFluid = AEFluidStack.fromFluidStack(fluidInTank).setStackSize(0); + this.configuredItem = null; + } - this.configureWatchers(); - this.getHost().markForSave(); - this.getHost().markForUpdate(); - } - else - { - return super.onPartActivate( player, hand, pos ); - } + this.configureWatchers(); + this.getHost().markForSave(); + this.getHost().markForUpdate(); + } else { + return super.onPartActivate(player, hand, pos); + } - return true; - } + return true; + } - @Override - public boolean onPartShiftActivate( EntityPlayer player, EnumHand hand, Vec3d pos ) - { - if( Platform.isClient() ) - { - return true; - } + @Override + public boolean onPartShiftActivate(EntityPlayer player, EnumHand hand, Vec3d pos) { + if (Platform.isClient()) { + return true; + } - if( !this.getProxy().isActive() ) - { - return false; - } + if (!this.getProxy().isActive()) { + return false; + } - if( !Platform.hasPermissions( this.getLocation(), player ) ) - { - return false; - } + if (!Platform.hasPermissions(this.getLocation(), player)) { + return false; + } - if( player.getHeldItem( hand ).isEmpty() ) - { - this.isLocked = !this.isLocked; - player.sendMessage( ( this.isLocked ? PlayerMessages.isNowLocked : PlayerMessages.isNowUnlocked ).get() ); - this.getHost().markForSave(); - this.getHost().markForUpdate(); - } + if (player.getHeldItem(hand).isEmpty()) { + this.isLocked = !this.isLocked; + player.sendMessage((this.isLocked ? PlayerMessages.isNowLocked : PlayerMessages.isNowUnlocked).get()); + this.getHost().markForSave(); + this.getHost().markForUpdate(); + } - return true; - } + return true; + } - // update the system... - private void configureWatchers() - { - if( this.myWatcher != null ) - { - this.myWatcher.reset(); - } + // update the system... + private void configureWatchers() { + if (this.myWatcher != null) { + this.myWatcher.reset(); + } - try - { - if( this.configuredItem != null ) - { - if( this.myWatcher != null ) - { - this.myWatcher.add( this.configuredItem ); - } + try { + if (this.configuredItem != null) { + if (this.myWatcher != null) { + this.myWatcher.add(this.configuredItem); + } - this.updateReportingValue( - this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) ); - } - else if ( this.configuredFluid != null ) - { - if( this.myWatcher != null ) - { - this.myWatcher.add( this.configuredFluid ); - } + this.updateReportingValue( + this.getProxy().getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class))); + } else if (this.configuredFluid != null) { + if (this.myWatcher != null) { + this.myWatcher.add(this.configuredFluid); + } - this.updateReportingValue( - this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) ); - } - } - catch( final GridAccessException e ) - { - // >.> - } - } + this.updateReportingValue( + this.getProxy().getStorage().getInventory(AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class))); + } + } catch (final GridAccessException e) { + // >.> + } + } - private > void updateReportingValue ( final IMEMonitor monitor ) - { - if( this.configuredItem != null) - { - final IAEItemStack result = (IAEItemStack) monitor.getStorageList().findPrecise( (T) this.configuredItem ); - if( result == null ) - { - this.configuredAmount = 0; - } - else - { - this.configuredAmount = result.getStackSize(); - } - this.configuredItem.setStackSize( this.configuredAmount ); - } - else if( this.configuredFluid != null) - { - final IAEFluidStack result = (IAEFluidStack) monitor.getStorageList().findPrecise( (T) this.configuredFluid ); - if( result == null ) - { - this.configuredAmount = 0; - } - else - { - this.configuredAmount = result.getStackSize(); - } - this.configuredFluid.setStackSize( this.configuredAmount ); - } - } + private > void updateReportingValue(final IMEMonitor monitor) { + if (this.configuredItem != null) { + final IAEItemStack result = (IAEItemStack) monitor.getStorageList().findPrecise((T) this.configuredItem); + if (result == null) { + this.configuredAmount = 0; + } else { + this.configuredAmount = result.getStackSize(); + } + this.configuredItem.setStackSize(this.configuredAmount); + } else if (this.configuredFluid != null) { + final IAEFluidStack result = (IAEFluidStack) monitor.getStorageList().findPrecise((T) this.configuredFluid); + if (result == null) { + this.configuredAmount = 0; + } else { + this.configuredAmount = result.getStackSize(); + } + this.configuredFluid.setStackSize(this.configuredAmount); + } + } - @Override - @SideOnly( Side.CLIENT ) - public void renderDynamic( double x, double y, double z, float partialTicks, int destroyStage ) - { + @Override + @SideOnly(Side.CLIENT) + public void renderDynamic(double x, double y, double z, float partialTicks, int destroyStage) { - if( ( this.getClientFlags() & ( PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG ) ) != ( PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG ) ) - { - return; - } + if ((this.getClientFlags() & (PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG)) != (PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG)) { + return; + } - IAEStack ais = this.getDisplayed(); + IAEStack ais = this.getDisplayed(); - if( ais == null ) - { - return; - } + if (ais == null) { + return; + } - GlStateManager.pushMatrix(); - GlStateManager.translate( x + 0.5, y + 0.5, z + 0.5 ); + GlStateManager.pushMatrix(); + GlStateManager.translate(x + 0.5, y + 0.5, z + 0.5); - EnumFacing facing = this.getSide().getFacing(); + EnumFacing facing = this.getSide().getFacing(); - TesrRenderHelper.moveToFace( facing ); - TesrRenderHelper.rotateToFace( facing, this.getSpin() ); - if (ais instanceof IAEItemStack) - TesrRenderHelper.renderItem2dWithAmount( (IAEItemStack) ais, 0.8f, 0.17f ); - if (ais instanceof IAEFluidStack) - TesrRenderHelper.renderFluid2dWithAmount( (IAEFluidStack) ais, 0.8f, 0.17f ); - GlStateManager.popMatrix(); + TesrRenderHelper.moveToFace(facing); + TesrRenderHelper.rotateToFace(facing, this.getSpin()); + if (ais instanceof IAEItemStack) + TesrRenderHelper.renderItem2dWithAmount((IAEItemStack) ais, 0.8f, 0.17f); + if (ais instanceof IAEFluidStack) + TesrRenderHelper.renderFluid2dWithAmount((IAEFluidStack) ais, 0.8f, 0.17f); + GlStateManager.popMatrix(); - } + } - @Override - public boolean requireDynamicRender() - { - return true; - } + @Override + public boolean requireDynamicRender() { + return true; + } - @Override - public IAEStack getDisplayed() - { - if (this.configuredItem != null) - return this.configuredItem; - else if (this.configuredFluid != null) - return this.configuredFluid; - return null; - } + @Override + public IAEStack getDisplayed() { + if (this.configuredItem != null) + return this.configuredItem; + else if (this.configuredFluid != null) + return this.configuredFluid; + return null; + } - @Override - public boolean isLocked() - { - return this.isLocked; - } + @Override + public boolean isLocked() { + return this.isLocked; + } - @Override - public void updateWatcher( final IStackWatcher newWatcher ) - { - this.myWatcher = newWatcher; - this.configureWatchers(); - } + @Override + public void updateWatcher(final IStackWatcher newWatcher) { + this.myWatcher = newWatcher; + this.configureWatchers(); + } - @MENetworkEventSubscribe - public void powerStatusChange( final MENetworkPowerStatusChange ev ) - { - if( this.getProxy().isPowered() ) - { - this.configureWatchers(); - } - } + @MENetworkEventSubscribe + public void powerStatusChange(final MENetworkPowerStatusChange ev) { + if (this.getProxy().isPowered()) { + this.configureWatchers(); + } + } - @MENetworkEventSubscribe - public void channelChanged( final MENetworkChannelsChanged c ) - { - if( this.getProxy().isPowered() ) - { - this.configureWatchers(); - } - } + @MENetworkEventSubscribe + public void channelChanged(final MENetworkChannelsChanged c) { + if (this.getProxy().isPowered()) { + this.configureWatchers(); + } + } - @Override - public void onStackChange( IItemList o, IAEStack fullStack, IAEStack diffStack, IActionSource src, IStorageChannel chan ) - { - this.configuredAmount = fullStack.getStackSize(); + @Override + public void onStackChange(IItemList o, IAEStack fullStack, IAEStack diffStack, IActionSource src, IStorageChannel chan) { + this.configuredAmount = fullStack.getStackSize(); - if( this.configuredItem != null ) - { - this.configuredItem.setStackSize( this.configuredAmount ); - } - else if( this.configuredFluid != null ) - { - this.configuredFluid.setStackSize( this.configuredAmount ); - } - this.getHost().markForUpdate(); - } + if (this.configuredItem != null) { + this.configuredItem.setStackSize(this.configuredAmount); + } else if (this.configuredFluid != null) { + this.configuredFluid.setStackSize(this.configuredAmount); + } + this.getHost().markForUpdate(); + } - @Override - public boolean showNetworkInfo( final RayTraceResult where ) - { - return false; - } + @Override + public boolean showNetworkInfo(final RayTraceResult where) { + return false; + } - protected IPartModel selectModel( IPartModel off, IPartModel on, IPartModel hasChannel, IPartModel lockedOff, IPartModel lockedOn, IPartModel lockedHasChannel ) - { - if( this.isActive() ) - { - if( this.isLocked() ) - { - return lockedHasChannel; - } - else - { - return hasChannel; - } - } - else if( this.isPowered() ) - { - if( this.isLocked() ) - { - return lockedOn; - } - else - { - return on; - } - } - else - { - if( this.isLocked() ) - { - return lockedOff; - } - else - { - return off; - } - } - } + protected IPartModel selectModel(IPartModel off, IPartModel on, IPartModel hasChannel, IPartModel lockedOff, IPartModel lockedOn, IPartModel lockedHasChannel) { + if (this.isActive()) { + if (this.isLocked()) { + return lockedHasChannel; + } else { + return hasChannel; + } + } else if (this.isPowered()) { + if (this.isLocked()) { + return lockedOn; + } else { + return on; + } + } else { + if (this.isLocked()) { + return lockedOff; + } else { + return off; + } + } + } } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartPanel.java b/src/main/java/appeng/parts/reporting/AbstractPartPanel.java index 01e75859d..310486454 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartPanel.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartPanel.java @@ -19,17 +19,16 @@ package appeng.parts.reporting; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - import appeng.api.util.AEColor; import appeng.core.AppEng; import appeng.items.parts.PartModels; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; /** * A very simple part for emitting light. - * + *

* Opposed to the other subclass of {@link AbstractPartReporting}, it will only use the bright front texture. * * @author AlgorithmX2 @@ -37,29 +36,26 @@ import appeng.items.parts.PartModels; * @version rv3 * @since rv3 */ -public abstract class AbstractPartPanel extends AbstractPartReporting -{ +public abstract class AbstractPartPanel extends AbstractPartReporting { - @PartModels - public static final ResourceLocation MODEL_BASE = new ResourceLocation( AppEng.MOD_ID, "part/monitor_base" ); + @PartModels + public static final ResourceLocation MODEL_BASE = new ResourceLocation(AppEng.MOD_ID, "part/monitor_base"); - public AbstractPartPanel( final ItemStack is ) - { - super( is, false ); - } + public AbstractPartPanel(final ItemStack is) { + super(is, false); + } - @Override - public boolean isLightSource() - { - return true; - } + @Override + public boolean isLightSource() { + return true; + } - /** - * How bright the color the panel should appear. Usually it depends on a {@link AEColor} variant. - * This does not affect the actual light level of the part. - * - * @return the brightness to be used. - */ - protected abstract int getBrightnessColor(); + /** + * How bright the color the panel should appear. Usually it depends on a {@link AEColor} variant. + * This does not affect the actual light level of the part. + * + * @return the brightness to be used. + */ + protected abstract int getBrightnessColor(); } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartReporting.java b/src/main/java/appeng/parts/reporting/AbstractPartReporting.java index dfb4bbbcb..acc35ed68 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartReporting.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartReporting.java @@ -19,20 +19,6 @@ package appeng.parts.reporting; -import java.io.IOException; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.IBlockAccess; - import appeng.api.implementations.IPowerChannelState; import appeng.api.implementations.parts.IPartMonitor; import appeng.api.networking.GridFlags; @@ -45,14 +31,26 @@ import appeng.api.util.AEPartLocation; import appeng.me.GridAccessException; import appeng.parts.AEBasePart; import appeng.util.Platform; +import io.netty.buffer.ByteBuf; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.MathHelper; +import net.minecraft.util.math.Vec3d; +import net.minecraft.world.IBlockAccess; + +import java.io.IOException; /** * The most basic class for any part reporting information, like terminals or monitors. This can also include basic * panels which just provide light. - * + *

* It deals with the most basic functionalities like network data, grid registration or the rotation of the actual part. - * + *

* The direct abstract subclasses are usually a better entry point for adding new concrete ones. * But this might be an ideal starting point to completely new type, which does not resemble any existing one. * @@ -61,270 +59,211 @@ import appeng.util.Platform; * @version rv3 * @since rv3 */ -public abstract class AbstractPartReporting extends AEBasePart implements IPartMonitor, IPowerChannelState -{ +public abstract class AbstractPartReporting extends AEBasePart implements IPartMonitor, IPowerChannelState { - protected static final int POWERED_FLAG = 4; - protected static final int CHANNEL_FLAG = 16; - private static final int BOOTING_FLAG = 8; + protected static final int POWERED_FLAG = 4; + protected static final int CHANNEL_FLAG = 16; + private static final int BOOTING_FLAG = 8; - private byte spin = 0; // 0-3 - private int clientFlags = 0; // sent as byte. - private int opacity = -1; + private byte spin = 0; // 0-3 + private int clientFlags = 0; // sent as byte. + private int opacity = -1; - public AbstractPartReporting( final ItemStack is ) - { - this( is, false ); - } + public AbstractPartReporting(final ItemStack is) { + this(is, false); + } - protected AbstractPartReporting( final ItemStack is, final boolean requireChannel ) - { - super( is ); + protected AbstractPartReporting(final ItemStack is, final boolean requireChannel) { + super(is); - if( requireChannel ) - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.getProxy().setIdlePowerUsage( 1.0 / 2.0 ); - } - else - { - this.getProxy().setIdlePowerUsage( 1.0 / 16.0 ); // lights drain a little bit. - } - } + if (requireChannel) { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.getProxy().setIdlePowerUsage(1.0 / 2.0); + } else { + this.getProxy().setIdlePowerUsage(1.0 / 16.0); // lights drain a little bit. + } + } - @MENetworkEventSubscribe - public final void bootingRender( final MENetworkBootingStatusChange c ) - { - if( !this.isLightSource() ) - { - this.getHost().markForUpdate(); - } - } + @MENetworkEventSubscribe + public final void bootingRender(final MENetworkBootingStatusChange c) { + if (!this.isLightSource()) { + this.getHost().markForUpdate(); + } + } - @MENetworkEventSubscribe - public final void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } + @MENetworkEventSubscribe + public final void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } - @Override - public final void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 2, 2, 14, 14, 14, 16 ); - bch.addBox( 4, 4, 13, 12, 12, 14 ); - } + @Override + public final void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + bch.addBox(4, 4, 13, 12, 12, 14); + } - @Override - public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - if( pos.offset( this.getSide().getFacing() ).equals( neighbor ) ) - { - this.opacity = -1; - this.getHost().markForUpdate(); - } - } + @Override + public void onNeighborChanged(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + if (pos.offset(this.getSide().getFacing()).equals(neighbor)) { + this.opacity = -1; + this.getHost().markForUpdate(); + } + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.spin = data.getByte( "spin" ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.spin = data.getByte("spin"); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setByte( "spin", this.getSpin() ); - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setByte("spin", this.getSpin()); + } - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - this.clientFlags = this.getSpin() & 3; + @Override + public void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + this.clientFlags = this.getSpin() & 3; - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - this.clientFlags = this.getClientFlags() | AbstractPartReporting.POWERED_FLAG; - } + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + this.clientFlags = this.getClientFlags() | AbstractPartReporting.POWERED_FLAG; + } - if( this.getProxy().getPath().isNetworkBooting() ) - { - this.clientFlags = this.getClientFlags() | AbstractPartReporting.BOOTING_FLAG; - } + if (this.getProxy().getPath().isNetworkBooting()) { + this.clientFlags = this.getClientFlags() | AbstractPartReporting.BOOTING_FLAG; + } - if( this.getProxy().getNode().meetsChannelRequirements() ) - { - this.clientFlags = this.getClientFlags() | AbstractPartReporting.CHANNEL_FLAG; - } - } - catch( final GridAccessException e ) - { - // um.. nothing. - } + if (this.getProxy().getNode().meetsChannelRequirements()) { + this.clientFlags = this.getClientFlags() | AbstractPartReporting.CHANNEL_FLAG; + } + } catch (final GridAccessException e) { + // um.. nothing. + } - data.writeByte( (byte) this.getClientFlags() ); - data.writeInt( this.opacity ); - } + data.writeByte((byte) this.getClientFlags()); + data.writeInt(this.opacity); + } - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - super.readFromStream( data ); - final int oldFlags = this.getClientFlags(); - final int oldOpacity = this.opacity; + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + super.readFromStream(data); + final int oldFlags = this.getClientFlags(); + final int oldOpacity = this.opacity; - this.clientFlags = data.readByte(); - this.opacity = data.readInt(); + this.clientFlags = data.readByte(); + this.opacity = data.readInt(); - this.spin = (byte) ( this.getClientFlags() & 3 ); - if( this.getClientFlags() == oldFlags && this.opacity == oldOpacity ) - { - return false; - } - return true; - } + this.spin = (byte) (this.getClientFlags() & 3); + return this.getClientFlags() != oldFlags || this.opacity != oldOpacity; + } - @Override - public final int getLightLevel() - { - return this.blockLight( this.isPowered() ? ( this.isLightSource() ? 15 : 9 ) : 0 ); - } + @Override + public final int getLightLevel() { + return this.blockLight(this.isPowered() ? (this.isLightSource() ? 15 : 9) : 0); + } - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - final TileEntity te = this.getTile(); + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + final TileEntity te = this.getTile(); - if( Platform.isWrench( player, player.inventory.getCurrentItem(), te.getPos() ) ) - { - if( Platform.isServer() ) - { - if( this.getSpin() > 3 ) - { - this.spin = 0; - } + if (Platform.isWrench(player, player.inventory.getCurrentItem(), te.getPos())) { + if (Platform.isServer()) { + if (this.getSpin() > 3) { + this.spin = 0; + } - switch( this.getSpin() ) - { - case 0: - this.spin = 1; - break; - case 1: - this.spin = 3; - break; - case 2: - this.spin = 0; - break; - case 3: - this.spin = 2; - break; - } + switch (this.getSpin()) { + case 0: + this.spin = 1; + break; + case 1: + this.spin = 3; + break; + case 2: + this.spin = 0; + break; + case 3: + this.spin = 2; + break; + } - this.getHost().markForUpdate(); - this.saveChanges(); - } - return true; - } - else - { - return super.onPartActivate( player, hand, pos ); - } - } + this.getHost().markForUpdate(); + this.saveChanges(); + } + return true; + } else { + return super.onPartActivate(player, hand, pos); + } + } - @Override - public final void onPlacement( final EntityPlayer player, final EnumHand hand, final ItemStack held, final AEPartLocation side ) - { - super.onPlacement( player, hand, held, side ); + @Override + public final void onPlacement(final EntityPlayer player, final EnumHand hand, final ItemStack held, final AEPartLocation side) { + super.onPlacement(player, hand, held, side); - final byte rotation = (byte) ( MathHelper.floor( ( player.rotationYaw * 4F ) / 360F + 2.5D ) & 3 ); - if( side == AEPartLocation.UP ) - { - this.spin = rotation; - } - else if( side == AEPartLocation.DOWN ) - { - this.spin = rotation; - } - } + final byte rotation = (byte) (MathHelper.floor((player.rotationYaw * 4F) / 360F + 2.5D) & 3); + if (side == AEPartLocation.UP) { + this.spin = rotation; + } else if (side == AEPartLocation.DOWN) { + this.spin = rotation; + } + } - private final int blockLight( final int emit ) - { - if( this.opacity < 0 ) - { - final TileEntity te = this.getTile(); - this.opacity = 255 - te.getWorld().getBlockLightOpacity( te.getPos().offset( this.getSide().getFacing() ) ); - } + private final int blockLight(final int emit) { + if (this.opacity < 0) { + final TileEntity te = this.getTile(); + this.opacity = 255 - te.getWorld().getBlockLightOpacity(te.getPos().offset(this.getSide().getFacing())); + } - return (int) ( emit * ( this.opacity / 255.0f ) ); - } + return (int) (emit * (this.opacity / 255.0f)); + } - @Override - public final boolean isPowered() - { - try - { - if( Platform.isServer() ) - { - return this.getProxy().getEnergy().isNetworkPowered(); - } - else - { - return( ( this.getClientFlags() & PartPanel.POWERED_FLAG ) == PartPanel.POWERED_FLAG ); - } - } - catch( final GridAccessException e ) - { - return false; - } - } + @Override + public final boolean isPowered() { + try { + if (Platform.isServer()) { + return this.getProxy().getEnergy().isNetworkPowered(); + } else { + return ((this.getClientFlags() & PartPanel.POWERED_FLAG) == PartPanel.POWERED_FLAG); + } + } catch (final GridAccessException e) { + return false; + } + } - @Override - public final boolean isActive() - { - if( !this.isLightSource() ) - { - return( ( this.getClientFlags() & ( PartPanel.CHANNEL_FLAG | PartPanel.POWERED_FLAG ) ) == ( PartPanel.CHANNEL_FLAG | PartPanel.POWERED_FLAG ) ); - } - else - { - return this.isPowered(); - } - } + @Override + public final boolean isActive() { + if (!this.isLightSource()) { + return ((this.getClientFlags() & (PartPanel.CHANNEL_FLAG | PartPanel.POWERED_FLAG)) == (PartPanel.CHANNEL_FLAG | PartPanel.POWERED_FLAG)); + } else { + return this.isPowered(); + } + } - protected IPartModel selectModel( IPartModel offModels, IPartModel onModels, IPartModel hasChannelModels ) - { - if( this.isActive() ) - { - return hasChannelModels; - } - else if( this.isPowered() ) - { - return onModels; - } - else - { - return offModels; - } - } + protected IPartModel selectModel(IPartModel offModels, IPartModel onModels, IPartModel hasChannelModels) { + if (this.isActive()) { + return hasChannelModels; + } else if (this.isPowered()) { + return onModels; + } else { + return offModels; + } + } - public final int getClientFlags() - { - return this.clientFlags; - } + public final int getClientFlags() { + return this.clientFlags; + } - public final byte getSpin() - { - return this.spin; - } + public final byte getSpin() { + return this.spin; + } - /** - * Should the part emit light. This actually only affects the light level, light source use a level of 15 and non - * light source 9. - */ - public abstract boolean isLightSource(); + /** + * Should the part emit light. This actually only affects the light level, light source use a level of 15 and non + * light source 9. + */ + public abstract boolean isLightSource(); } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartTerminal.java b/src/main/java/appeng/parts/reporting/AbstractPartTerminal.java index be4a62408..f808d17e4 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartTerminal.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartTerminal.java @@ -19,15 +19,6 @@ package appeng.parts.reporting; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.Vec3d; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.Settings; import appeng.api.config.SortDir; import appeng.api.config.SortOrder; @@ -46,11 +37,19 @@ import appeng.util.IConfigManagerHost; import appeng.util.Platform; import appeng.util.inv.IAEAppEngInventory; import appeng.util.inv.InvOperation; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.Vec3d; +import net.minecraftforge.items.IItemHandler; + +import java.util.List; /** * Anything resembling an network terminal with view cells can reuse this. - * + *

* Note this applies only to terminals like the ME Terminal. It does not apply for more specialized terminals like the * Interface Terminal. * @@ -59,104 +58,85 @@ import appeng.util.inv.InvOperation; * @version rv3 * @since rv3 */ -public abstract class AbstractPartTerminal extends AbstractPartDisplay implements ITerminalHost, IConfigManagerHost, IViewCellStorage, IAEAppEngInventory -{ +public abstract class AbstractPartTerminal extends AbstractPartDisplay implements ITerminalHost, IConfigManagerHost, IViewCellStorage, IAEAppEngInventory { - private final IConfigManager cm = new ConfigManager( this ); - private final AppEngInternalInventory viewCell = new AppEngInternalInventory( this, 5 ); + private final IConfigManager cm = new ConfigManager(this); + private final AppEngInternalInventory viewCell = new AppEngInternalInventory(this, 5); - public AbstractPartTerminal( final ItemStack is ) - { - super( is ); + public AbstractPartTerminal(final ItemStack is) { + super(is); - this.cm.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - this.cm.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - this.cm.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - } + this.cm.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.cm.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + this.cm.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + } - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - super.getDrops( drops, wrenched ); + @Override + public void getDrops(final List drops, final boolean wrenched) { + super.getDrops(drops, wrenched); - for( final ItemStack is : this.viewCell ) - { - if( !is.isEmpty() ) - { - drops.add( is ); - } - } - } + for (final ItemStack is : this.viewCell) { + if (!is.isEmpty()) { + drops.add(is); + } + } + } - @Override - public IConfigManager getConfigManager() - { - return this.cm; - } + @Override + public IConfigManager getConfigManager() { + return this.cm; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.cm.readFromNBT( data ); - this.viewCell.readFromNBT( data, "viewCell" ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.cm.readFromNBT(data); + this.viewCell.readFromNBT(data, "viewCell"); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.cm.writeToNBT( data ); - this.viewCell.writeToNBT( data, "viewCell" ); - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.cm.writeToNBT(data); + this.viewCell.writeToNBT(data, "viewCell"); + } - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( !super.onPartActivate( player, hand, pos ) ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), this.getGui( player ) ); - } - } - return true; - } + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (!super.onPartActivate(player, hand, pos)) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), this.getGui(player)); + } + } + return true; + } - public GuiBridge getGui( final EntityPlayer player ) - { - return GuiBridge.GUI_ME; - } + public GuiBridge getGui(final EntityPlayer player) { + return GuiBridge.GUI_ME; + } - @Override - public > IMEMonitor getInventory( IStorageChannel channel ) - { - try - { - return this.getProxy().getStorage().getInventory( channel ); - } - catch( final GridAccessException e ) - { - // err nope? - } - return null; - } + @Override + public > IMEMonitor getInventory(IStorageChannel channel) { + try { + return this.getProxy().getStorage().getInventory(channel); + } catch (final GridAccessException e) { + // err nope? + } + return null; + } - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { - } + } - @Override - public IItemHandler getViewCellStorage() - { - return this.viewCell; - } + @Override + public IItemHandler getViewCellStorage() { + return this.viewCell; + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - this.getHost().markForSave(); - } + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { + this.getHost().markForSave(); + } } diff --git a/src/main/java/appeng/parts/reporting/PartConversionMonitor.java b/src/main/java/appeng/parts/reporting/PartConversionMonitor.java index e6ea896da..dd3c0580c 100644 --- a/src/main/java/appeng/parts/reporting/PartConversionMonitor.java +++ b/src/main/java/appeng/parts/reporting/PartConversionMonitor.java @@ -19,22 +19,27 @@ package appeng.parts.reporting; -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - +import appeng.api.AEApi; import appeng.api.config.Actionable; +import appeng.api.networking.energy.IEnergySource; +import appeng.api.parts.IPartModel; +import appeng.api.storage.IMEMonitor; import appeng.api.storage.channels.IFluidStorageChannel; +import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEFluidStack; -import appeng.api.storage.data.IAEStack; +import appeng.api.storage.data.IAEItemStack; import appeng.core.AELog; -import appeng.core.sync.network.NetworkHandler; -import appeng.core.sync.packets.PacketInventoryAction; +import appeng.core.AppEng; import appeng.fluids.util.AEFluidStack; -import appeng.helpers.InventoryAction; +import appeng.helpers.Reflected; +import appeng.items.parts.PartModels; +import appeng.me.GridAccessException; +import appeng.me.helpers.PlayerSource; +import appeng.parts.PartModel; +import appeng.util.InventoryAdaptor; +import appeng.util.Platform; +import appeng.util.item.AEItemStack; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumHand; @@ -47,413 +52,323 @@ import net.minecraftforge.fluids.capability.IFluidHandlerItem; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.wrapper.PlayerMainInvWrapper; -import appeng.api.AEApi; -import appeng.api.networking.energy.IEnergySource; -import appeng.api.parts.IPartModel; -import appeng.api.storage.IMEMonitor; -import appeng.api.storage.channels.IItemStorageChannel; -import appeng.api.storage.data.IAEItemStack; -import appeng.core.AppEng; -import appeng.helpers.Reflected; -import appeng.items.parts.PartModels; -import appeng.me.GridAccessException; -import appeng.me.helpers.PlayerSource; -import appeng.parts.PartModel; -import appeng.util.InventoryAdaptor; -import appeng.util.Platform; -import appeng.util.item.AEItemStack; +import java.util.Collections; +import java.util.List; -public class PartConversionMonitor extends AbstractPartMonitor -{ +public class PartConversionMonitor extends AbstractPartMonitor { - @PartModels - public static final ResourceLocation MODEL_OFF = new ResourceLocation( AppEng.MOD_ID, "part/conversion_monitor_off" ); - @PartModels - public static final ResourceLocation MODEL_ON = new ResourceLocation( AppEng.MOD_ID, "part/conversion_monitor_on" ); - @PartModels - public static final ResourceLocation MODEL_LOCKED_OFF = new ResourceLocation( AppEng.MOD_ID, "part/conversion_monitor_locked_off" ); - @PartModels - public static final ResourceLocation MODEL_LOCKED_ON = new ResourceLocation( AppEng.MOD_ID, "part/conversion_monitor_locked_on" ); + @PartModels + public static final ResourceLocation MODEL_OFF = new ResourceLocation(AppEng.MOD_ID, "part/conversion_monitor_off"); + @PartModels + public static final ResourceLocation MODEL_ON = new ResourceLocation(AppEng.MOD_ID, "part/conversion_monitor_on"); + @PartModels + public static final ResourceLocation MODEL_LOCKED_OFF = new ResourceLocation(AppEng.MOD_ID, "part/conversion_monitor_locked_off"); + @PartModels + public static final ResourceLocation MODEL_LOCKED_ON = new ResourceLocation(AppEng.MOD_ID, "part/conversion_monitor_locked_on"); - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF ); - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_ON ); - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL ); - public static final IPartModel MODELS_LOCKED_OFF = new PartModel( MODEL_BASE, MODEL_LOCKED_OFF, MODEL_STATUS_OFF ); - public static final IPartModel MODELS_LOCKED_ON = new PartModel( MODEL_BASE, MODEL_LOCKED_ON, MODEL_STATUS_ON ); - public static final IPartModel MODELS_LOCKED_HAS_CHANNEL = new PartModel( MODEL_BASE, MODEL_LOCKED_ON, MODEL_STATUS_HAS_CHANNEL ); + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_ON); + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL); + public static final IPartModel MODELS_LOCKED_OFF = new PartModel(MODEL_BASE, MODEL_LOCKED_OFF, MODEL_STATUS_OFF); + public static final IPartModel MODELS_LOCKED_ON = new PartModel(MODEL_BASE, MODEL_LOCKED_ON, MODEL_STATUS_ON); + public static final IPartModel MODELS_LOCKED_HAS_CHANNEL = new PartModel(MODEL_BASE, MODEL_LOCKED_ON, MODEL_STATUS_HAS_CHANNEL); - @Reflected - public PartConversionMonitor( final ItemStack is ) - { - super( is ); - } + @Reflected + public PartConversionMonitor(final ItemStack is) { + super(is); + } - @Override - public boolean onPartActivate( EntityPlayer player, EnumHand hand, Vec3d pos ) - { - if( Platform.isClient() ) - { - return true; - } + @Override + public boolean onPartActivate(EntityPlayer player, EnumHand hand, Vec3d pos) { + if (Platform.isClient()) { + return true; + } - if( !this.getProxy().isActive() ) - { - return false; - } + if (!this.getProxy().isActive()) { + return false; + } - if( !Platform.hasPermissions( this.getLocation(), player ) ) - { - return false; - } + if (!Platform.hasPermissions(this.getLocation(), player)) { + return false; + } - final ItemStack eq = player.getHeldItem( hand ); - FluidStack fluidInTank = null; - if( eq.hasCapability( CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null ) ) - { - IFluidHandlerItem fluidHandlerItem = ( eq.getCapability( CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null ) ); - fluidInTank = fluidHandlerItem.drain( Integer.MAX_VALUE, false ); - } + final ItemStack eq = player.getHeldItem(hand); + FluidStack fluidInTank = null; + if (eq.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { + IFluidHandlerItem fluidHandlerItem = (eq.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)); + fluidInTank = fluidHandlerItem.drain(Integer.MAX_VALUE, false); + } - if( this.isLocked() ) - { - if( eq.isEmpty() ) - { - this.insertItem( player, hand, true ); - } - else if( Platform.isWrench( player, eq, this.getLocation().getPos() ) && ( this.getDisplayed() == null || !this.getDisplayed().equals( eq ) ) ) - { - // wrench it - return super.onPartActivate( player, hand, pos ); - } - else if( fluidInTank != null && fluidInTank.amount > 0 ) - { - if( this.getDisplayed() != null && getDisplayed().equals( AEFluidStack.fromFluidStack( fluidInTank ) ) ) - { - this.drainFluidContainer( player, hand ); - } - } - else - { - this.insertItem( player, hand, false ); - } - } + if (this.isLocked()) { + if (eq.isEmpty()) { + this.insertItem(player, hand, true); + } else if (Platform.isWrench(player, eq, this.getLocation().getPos()) && (this.getDisplayed() == null || !this.getDisplayed().equals(eq))) { + // wrench it + return super.onPartActivate(player, hand, pos); + } else if (fluidInTank != null && fluidInTank.amount > 0) { + if (this.getDisplayed() != null && getDisplayed().equals(AEFluidStack.fromFluidStack(fluidInTank))) { + this.drainFluidContainer(player, hand); + } + } else { + this.insertItem(player, hand, false); + } + } - //If its a fluid container, grab its fluidstack. if its empty pass its itemstack; + //If its a fluid container, grab its fluidstack. if its empty pass its itemstack; - if( fluidInTank != null && fluidInTank.amount > 0 ) - { - if( getDisplayed() instanceof IAEItemStack || getDisplayed() == null ) - { - return super.onPartActivate( player, hand, pos ); - } - if( ( (IAEFluidStack) this.getDisplayed() ).equals( AEFluidStack.fromFluidStack( fluidInTank ) ) ) - { - this.drainFluidContainer( player, hand ); - } - else - { - return super.onPartActivate( player, hand, pos ); - } - } - else if( this.getDisplayed() != null && this.getDisplayed().equals( player.getHeldItem( hand ) ) ) - { - this.insertItem( player, hand, false ); - } - return super.onPartActivate( player, hand, pos ); - } + if (fluidInTank != null && fluidInTank.amount > 0) { + if (getDisplayed() instanceof IAEItemStack || getDisplayed() == null) { + return super.onPartActivate(player, hand, pos); + } + if (((IAEFluidStack) this.getDisplayed()).equals(AEFluidStack.fromFluidStack(fluidInTank))) { + this.drainFluidContainer(player, hand); + } else { + return super.onPartActivate(player, hand, pos); + } + } else if (this.getDisplayed() != null && this.getDisplayed().equals(player.getHeldItem(hand))) { + this.insertItem(player, hand, false); + } + return super.onPartActivate(player, hand, pos); + } - @Override - public boolean onClicked( EntityPlayer player, EnumHand hand, Vec3d pos ) - { - if( Platform.isClient() ) - { - return true; - } + @Override + public boolean onClicked(EntityPlayer player, EnumHand hand, Vec3d pos) { + if (Platform.isClient()) { + return true; + } - if( !this.getProxy().isActive() ) - { - return false; - } + if (!this.getProxy().isActive()) { + return false; + } - if( !Platform.hasPermissions( this.getLocation(), player ) ) - { - return false; - } + if (!Platform.hasPermissions(this.getLocation(), player)) { + return false; + } - if( this.getDisplayed() != null && this.getDisplayed() instanceof IAEItemStack ) - { - this.extractItem( player, ( (IAEItemStack) this.getDisplayed() ).getDefinition().getMaxStackSize() ); - } - else if( this.getDisplayed() != null && this.getDisplayed() instanceof IAEFluidStack ) - { - this.fillFluidContainer( player,hand ); - } + if (this.getDisplayed() != null && this.getDisplayed() instanceof IAEItemStack) { + this.extractItem(player, ((IAEItemStack) this.getDisplayed()).getDefinition().getMaxStackSize()); + } else if (this.getDisplayed() != null && this.getDisplayed() instanceof IAEFluidStack) { + this.fillFluidContainer(player, hand); + } - return true; - } + return true; + } - @Override - public boolean onShiftClicked( EntityPlayer player, EnumHand hand, Vec3d pos ) - { - if( Platform.isClient() ) - { - return true; - } + @Override + public boolean onShiftClicked(EntityPlayer player, EnumHand hand, Vec3d pos) { + if (Platform.isClient()) { + return true; + } - if( !this.getProxy().isActive() ) - { - return false; - } + if (!this.getProxy().isActive()) { + return false; + } - if( !Platform.hasPermissions( this.getLocation(), player ) ) - { - return false; - } + if (!Platform.hasPermissions(this.getLocation(), player)) { + return false; + } - if( this.getDisplayed() != null ) - { - this.extractItem( player, 1 ); - } + if (this.getDisplayed() != null) { + this.extractItem(player, 1); + } - return true; - } + return true; + } - private void insertItem( final EntityPlayer player, final EnumHand hand, final boolean allItems ) - { - try - { - final IEnergySource energy = this.getProxy().getEnergy(); - final IMEMonitor cell = this.getProxy() - .getStorage() - .getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); + private void insertItem(final EntityPlayer player, final EnumHand hand, final boolean allItems) { + try { + final IEnergySource energy = this.getProxy().getEnergy(); + final IMEMonitor cell = this.getProxy() + .getStorage() + .getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); - if( allItems ) - { - if( this.getDisplayed() != null && this.getDisplayed() instanceof IAEItemStack) - { - final IAEItemStack input = (IAEItemStack) this.getDisplayed().copy(); - IItemHandler inv = new PlayerMainInvWrapper( player.inventory ); + if (allItems) { + if (this.getDisplayed() != null && this.getDisplayed() instanceof IAEItemStack) { + final IAEItemStack input = (IAEItemStack) this.getDisplayed().copy(); + IItemHandler inv = new PlayerMainInvWrapper(player.inventory); - for( int x = 0; x < inv.getSlots(); x++ ) - { - final ItemStack targetStack = inv.getStackInSlot( x ); - if( input.equals( targetStack ) ) - { - final ItemStack canExtract = inv.extractItem( x, targetStack.getCount(), true ); - if( !canExtract.isEmpty() ) - { - input.setStackSize( canExtract.getCount() ); - final IAEItemStack failedToInsert = Platform.poweredInsert( energy, cell, input, new PlayerSource( player, this ) ); - inv.extractItem( x, - failedToInsert == null ? canExtract.getCount() : canExtract.getCount() - (int) failedToInsert.getStackSize(), - false ); - } - } - } - } - } - else - { - final IAEItemStack input = AEItemStack.fromItemStack( player.getHeldItem( hand ) ); - final IAEItemStack failedToInsert = Platform.poweredInsert( energy, cell, input, new PlayerSource( player, this ) ); - player.setHeldItem( hand, failedToInsert == null ? ItemStack.EMPTY : failedToInsert.createItemStack() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } + for (int x = 0; x < inv.getSlots(); x++) { + final ItemStack targetStack = inv.getStackInSlot(x); + if (input.equals(targetStack)) { + final ItemStack canExtract = inv.extractItem(x, targetStack.getCount(), true); + if (!canExtract.isEmpty()) { + input.setStackSize(canExtract.getCount()); + final IAEItemStack failedToInsert = Platform.poweredInsert(energy, cell, input, new PlayerSource(player, this)); + inv.extractItem(x, + failedToInsert == null ? canExtract.getCount() : canExtract.getCount() - (int) failedToInsert.getStackSize(), + false); + } + } + } + } + } else { + final IAEItemStack input = AEItemStack.fromItemStack(player.getHeldItem(hand)); + final IAEItemStack failedToInsert = Platform.poweredInsert(energy, cell, input, new PlayerSource(player, this)); + player.setHeldItem(hand, failedToInsert == null ? ItemStack.EMPTY : failedToInsert.createItemStack()); + } + } catch (final GridAccessException e) { + // :P + } + } - private void extractItem( final EntityPlayer player, int count ) - { - if (!(this.getDisplayed() instanceof IAEItemStack)) - return; - final IAEItemStack input = (IAEItemStack) this.getDisplayed().copy(); - if( input != null ) - { - try - { - if( !this.getProxy().isActive() ) - { - return; - } + private void extractItem(final EntityPlayer player, int count) { + if (!(this.getDisplayed() instanceof IAEItemStack)) + return; + final IAEItemStack input = (IAEItemStack) this.getDisplayed().copy(); + if (input != null) { + try { + if (!this.getProxy().isActive()) { + return; + } - final IEnergySource energy = this.getProxy().getEnergy(); - final IMEMonitor cell = this.getProxy() - .getStorage() - .getInventory( - AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); + final IEnergySource energy = this.getProxy().getEnergy(); + final IMEMonitor cell = this.getProxy() + .getStorage() + .getInventory( + AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); - input.setStackSize( count ); + input.setStackSize(count); - final IAEItemStack retrieved = Platform.poweredExtraction( energy, cell, input, new PlayerSource( player, this ) ); - if( retrieved != null ) - { - ItemStack newItems = retrieved.createItemStack(); - final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor( player ); - newItems = adaptor.addItems( newItems ); - if( !newItems.isEmpty() ) - { - final TileEntity te = this.getTile(); - final List list = Collections.singletonList( newItems ); - Platform.spawnDrops( player.world, te.getPos().offset( this.getSide().getFacing() ), list ); - } + final IAEItemStack retrieved = Platform.poweredExtraction(energy, cell, input, new PlayerSource(player, this)); + if (retrieved != null) { + ItemStack newItems = retrieved.createItemStack(); + final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor(player); + newItems = adaptor.addItems(newItems); + if (!newItems.isEmpty()) { + final TileEntity te = this.getTile(); + final List list = Collections.singletonList(newItems); + Platform.spawnDrops(player.world, te.getPos().offset(this.getSide().getFacing()), list); + } - if( player.openContainer != null ) - { - player.openContainer.detectAndSendChanges(); - } - } - } - catch( final GridAccessException e ) - { - // :P - } - } - } + if (player.openContainer != null) { + player.openContainer.detectAndSendChanges(); + } + } + } catch (final GridAccessException e) { + // :P + } + } + } - private void drainFluidContainer( final EntityPlayer player, final EnumHand hand ) { - try - { - final ItemStack held = player.getHeldItem( hand ); - if( held.getCount() != 1 ) - { - // only support stacksize 1 for now - return; - } + private void drainFluidContainer(final EntityPlayer player, final EnumHand hand) { + try { + final ItemStack held = player.getHeldItem(hand); + if (held.getCount() != 1) { + // only support stacksize 1 for now + return; + } - final IFluidHandlerItem fh = FluidUtil.getFluidHandler( held ); - if( fh == null ) - { - // only fluid handlers items - return; - } + final IFluidHandlerItem fh = FluidUtil.getFluidHandler(held); + if (fh == null) { + // only fluid handlers items + return; + } - // See how much we can drain from the item - final FluidStack extract = fh.drain( Integer.MAX_VALUE, false ); - if( extract == null || extract.amount < 1 ) - { - return; - } + // See how much we can drain from the item + final FluidStack extract = fh.drain(Integer.MAX_VALUE, false); + if (extract == null || extract.amount < 1) { + return; + } - // Check if we can push into the system - final IEnergySource energy = this.getProxy().getEnergy(); - final IMEMonitor cell = this.getProxy() - .getStorage() - .getInventory( - AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ); - final IAEFluidStack notStorable = Platform.poweredInsert( energy, cell, AEFluidStack.fromFluidStack( extract ), new PlayerSource( player, this ), Actionable.SIMULATE ); + // Check if we can push into the system + final IEnergySource energy = this.getProxy().getEnergy(); + final IMEMonitor cell = this.getProxy() + .getStorage() + .getInventory( + AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)); + final IAEFluidStack notStorable = Platform.poweredInsert(energy, cell, AEFluidStack.fromFluidStack(extract), new PlayerSource(player, this), Actionable.SIMULATE); - if( notStorable != null && notStorable.getStackSize() > 0 ) - { - final int toStore = (int) ( extract.amount - notStorable.getStackSize() ); - final FluidStack storable = fh.drain( toStore, false ); + if (notStorable != null && notStorable.getStackSize() > 0) { + final int toStore = (int) (extract.amount - notStorable.getStackSize()); + final FluidStack storable = fh.drain(toStore, false); - if( storable == null || storable.amount == 0 ) - { - return; - } - else - { - extract.amount = storable.amount; - } - } + if (storable == null || storable.amount == 0) { + return; + } else { + extract.amount = storable.amount; + } + } - // Actually drain - final FluidStack drained = fh.drain( extract, true ); - extract.amount = drained.amount; + // Actually drain + final FluidStack drained = fh.drain(extract, true); + extract.amount = drained.amount; - final IAEFluidStack notInserted = Platform.poweredInsert( energy, cell, AEFluidStack.fromFluidStack( extract ), new PlayerSource( player, this ) ); + final IAEFluidStack notInserted = Platform.poweredInsert(energy, cell, AEFluidStack.fromFluidStack(extract), new PlayerSource(player, this)); - if( notInserted != null && notInserted.getStackSize() > 0 ) - { - AELog.error( "Fluid item [%s] reported a different possible amount to drain than it actually provided.", held.getDisplayName() ); - } + if (notInserted != null && notInserted.getStackSize() > 0) { + AELog.error("Fluid item [%s] reported a different possible amount to drain than it actually provided.", held.getDisplayName()); + } - player.setHeldItem( hand, fh.getContainer() ); - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - } + player.setHeldItem(hand, fh.getContainer()); + } catch (GridAccessException e) { + e.printStackTrace(); + } + } - private void fillFluidContainer( final EntityPlayer player, final EnumHand hand ) - { - try - { - final ItemStack held = player.getHeldItem( hand ); - if( held.getCount() != 1 ) - { - // only support stacksize 1 for now - return; - } + private void fillFluidContainer(final EntityPlayer player, final EnumHand hand) { + try { + final ItemStack held = player.getHeldItem(hand); + if (held.getCount() != 1) { + // only support stacksize 1 for now + return; + } - final IFluidHandlerItem fh = FluidUtil.getFluidHandler( held ); - if( fh == null ) - { - // only fluid handlers items - return; - } + final IFluidHandlerItem fh = FluidUtil.getFluidHandler(held); + if (fh == null) { + // only fluid handlers items + return; + } - final IAEFluidStack stack = (IAEFluidStack) this.getDisplayed().copy(); + final IAEFluidStack stack = (IAEFluidStack) this.getDisplayed().copy(); - // Check how much we can store in the item - stack.setStackSize( Integer.MAX_VALUE ); - int amountAllowed = fh.fill( stack.getFluidStack(), false ); - stack.setStackSize( amountAllowed ); + // Check how much we can store in the item + stack.setStackSize(Integer.MAX_VALUE); + int amountAllowed = fh.fill(stack.getFluidStack(), false); + stack.setStackSize(amountAllowed); - // Check if we can pull out of the system - final IEnergySource energy = this.getProxy().getEnergy(); - final IMEMonitor cell = this.getProxy() - .getStorage() - .getInventory( - AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ); - final IAEFluidStack canPull = Platform.poweredExtraction( energy, cell, stack, new PlayerSource( player, this ), Actionable.SIMULATE ); - if( canPull == null || canPull.getStackSize() < 1 ) - { - return; - } + // Check if we can pull out of the system + final IEnergySource energy = this.getProxy().getEnergy(); + final IMEMonitor cell = this.getProxy() + .getStorage() + .getInventory( + AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)); + final IAEFluidStack canPull = Platform.poweredExtraction(energy, cell, stack, new PlayerSource(player, this), Actionable.SIMULATE); + if (canPull == null || canPull.getStackSize() < 1) { + return; + } - // How much could fit into the container - final int canFill = fh.fill( canPull.getFluidStack(), false ); - if( canFill == 0 ) - { - return; - } + // How much could fit into the container + final int canFill = fh.fill(canPull.getFluidStack(), false); + if (canFill == 0) { + return; + } - // Now actually pull out of the system - stack.setStackSize( canFill ); - final IAEFluidStack pulled = Platform.poweredExtraction( energy, cell, stack, new PlayerSource( player, this ) ); - if( pulled == null || pulled.getStackSize() < 1 ) - { - // Something went wrong - AELog.error( "Unable to pull fluid out of the ME system even though the simulation said yes " ); - return; - } + // Now actually pull out of the system + stack.setStackSize(canFill); + final IAEFluidStack pulled = Platform.poweredExtraction(energy, cell, stack, new PlayerSource(player, this)); + if (pulled == null || pulled.getStackSize() < 1) { + // Something went wrong + AELog.error("Unable to pull fluid out of the ME system even though the simulation said yes "); + return; + } - // Actually fill - final int used = fh.fill( pulled.getFluidStack(), true ); + // Actually fill + final int used = fh.fill(pulled.getFluidStack(), true); - if( used != canFill ) - { - AELog.error( "Fluid item [%s] reported a different possible amount than it actually accepted.", held.getDisplayName() ); - } - player.setHeldItem( hand, fh.getContainer() ); - } - catch( GridAccessException e ) - { - e.printStackTrace(); - } - } + if (used != canFill) { + AELog.error("Fluid item [%s] reported a different possible amount than it actually accepted.", held.getDisplayName()); + } + player.setHeldItem(hand, fh.getContainer()); + } catch (GridAccessException e) { + e.printStackTrace(); + } + } - @Override - public IPartModel getStaticModels() - { - return this.selectModel( MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL, - MODELS_LOCKED_OFF, MODELS_LOCKED_ON, MODELS_LOCKED_HAS_CHANNEL ); - } + @Override + public IPartModel getStaticModels() { + return this.selectModel(MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL, + MODELS_LOCKED_OFF, MODELS_LOCKED_ON, MODELS_LOCKED_HAS_CHANNEL); + } } diff --git a/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java b/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java index d4fd1413a..ccc0906a4 100644 --- a/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java @@ -19,14 +19,6 @@ package appeng.parts.reporting; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.items.IItemHandler; - import appeng.api.parts.IPartModel; import appeng.core.AppEng; import appeng.core.sync.GuiBridge; @@ -34,90 +26,84 @@ import appeng.helpers.Reflected; import appeng.items.parts.PartModels; import appeng.parts.PartModel; import appeng.tile.inventory.AppEngInternalInventory; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.items.IItemHandler; + +import java.util.List; -public class PartCraftingTerminal extends AbstractPartTerminal -{ +public class PartCraftingTerminal extends AbstractPartTerminal { - @PartModels - public static final ResourceLocation MODEL_OFF = new ResourceLocation( AppEng.MOD_ID, "part/crafting_terminal_off" ); - @PartModels - public static final ResourceLocation MODEL_ON = new ResourceLocation( AppEng.MOD_ID, "part/crafting_terminal_on" ); + @PartModels + public static final ResourceLocation MODEL_OFF = new ResourceLocation(AppEng.MOD_ID, "part/crafting_terminal_off"); + @PartModels + public static final ResourceLocation MODEL_ON = new ResourceLocation(AppEng.MOD_ID, "part/crafting_terminal_on"); - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF ); - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_ON ); - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL ); + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_ON); + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL); - private final AppEngInternalInventory craftingGrid = new AppEngInternalInventory( this, 9 ); + private final AppEngInternalInventory craftingGrid = new AppEngInternalInventory(this, 9); - @Reflected - public PartCraftingTerminal( final ItemStack is ) - { - super( is ); - } + @Reflected + public PartCraftingTerminal(final ItemStack is) { + super(is); + } - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - super.getDrops( drops, wrenched ); + @Override + public void getDrops(final List drops, final boolean wrenched) { + super.getDrops(drops, wrenched); - for( final ItemStack is : this.craftingGrid ) - { - if( !is.isEmpty() ) - { - drops.add( is ); - } - } - } + for (final ItemStack is : this.craftingGrid) { + if (!is.isEmpty()) { + drops.add(is); + } + } + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.craftingGrid.readFromNBT( data, "craftingGrid" ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.craftingGrid.readFromNBT(data, "craftingGrid"); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.craftingGrid.writeToNBT( data, "craftingGrid" ); - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.craftingGrid.writeToNBT(data, "craftingGrid"); + } - @Override - public GuiBridge getGui( final EntityPlayer p ) - { - int x = (int) p.posX; - int y = (int) p.posY; - int z = (int) p.posZ; - if( this.getHost().getTile() != null ) - { - x = this.getTile().getPos().getX(); - y = this.getTile().getPos().getY(); - z = this.getTile().getPos().getZ(); - } + @Override + public GuiBridge getGui(final EntityPlayer p) { + int x = (int) p.posX; + int y = (int) p.posY; + int z = (int) p.posZ; + if (this.getHost().getTile() != null) { + x = this.getTile().getPos().getX(); + y = this.getTile().getPos().getY(); + z = this.getTile().getPos().getZ(); + } - if( GuiBridge.GUI_CRAFTING_TERMINAL.hasPermissions( this.getHost().getTile(), x, y, z, this.getSide(), p ) ) - { - return GuiBridge.GUI_CRAFTING_TERMINAL; - } - return GuiBridge.GUI_ME; - } + if (GuiBridge.GUI_CRAFTING_TERMINAL.hasPermissions(this.getHost().getTile(), x, y, z, this.getSide(), p)) { + return GuiBridge.GUI_CRAFTING_TERMINAL; + } + return GuiBridge.GUI_ME; + } - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "crafting" ) ) - { - return this.craftingGrid; - } - return super.getInventoryByName( name ); - } + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("crafting")) { + return this.craftingGrid; + } + return super.getInventoryByName(name); + } - @Override - public IPartModel getStaticModels() - { - return this.selectModel( MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL ); - } + @Override + public IPartModel getStaticModels() { + return this.selectModel(MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL); + } } diff --git a/src/main/java/appeng/parts/reporting/PartDarkPanel.java b/src/main/java/appeng/parts/reporting/PartDarkPanel.java index 268a0684a..e633873c9 100644 --- a/src/main/java/appeng/parts/reporting/PartDarkPanel.java +++ b/src/main/java/appeng/parts/reporting/PartDarkPanel.java @@ -19,43 +19,38 @@ package appeng.parts.reporting; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - import appeng.api.parts.IPartModel; import appeng.core.AppEng; import appeng.helpers.Reflected; import appeng.items.parts.PartModels; import appeng.parts.PartModel; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; -public class PartDarkPanel extends AbstractPartPanel -{ +public class PartDarkPanel extends AbstractPartPanel { - @PartModels - public static final ResourceLocation MODEL_OFF = new ResourceLocation( AppEng.MOD_ID, "part/monitor_dark_off" ); - @PartModels - public static final ResourceLocation MODEL_ON = new ResourceLocation( AppEng.MOD_ID, "part/monitor_dark_on" ); + @PartModels + public static final ResourceLocation MODEL_OFF = new ResourceLocation(AppEng.MOD_ID, "part/monitor_dark_off"); + @PartModels + public static final ResourceLocation MODEL_ON = new ResourceLocation(AppEng.MOD_ID, "part/monitor_dark_on"); - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_OFF ); - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_ON ); + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_OFF); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_ON); - @Reflected - public PartDarkPanel( final ItemStack is ) - { - super( is ); - } + @Reflected + public PartDarkPanel(final ItemStack is) { + super(is); + } - @Override - protected int getBrightnessColor() - { - return this.getColor().mediumVariant; - } + @Override + protected int getBrightnessColor() { + return this.getColor().mediumVariant; + } - @Override - public IPartModel getStaticModels() - { - return this.isPowered() ? MODELS_ON : MODELS_OFF; - } + @Override + public IPartModel getStaticModels() { + return this.isPowered() ? MODELS_ON : MODELS_OFF; + } } diff --git a/src/main/java/appeng/parts/reporting/PartExpandedProcessingPatternTerminal.java b/src/main/java/appeng/parts/reporting/PartExpandedProcessingPatternTerminal.java index bf20f7807..f0a31b531 100644 --- a/src/main/java/appeng/parts/reporting/PartExpandedProcessingPatternTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartExpandedProcessingPatternTerminal.java @@ -23,100 +23,84 @@ import static appeng.helpers.PatternHelper.PROCESSING_INPUT_LIMIT; import static appeng.helpers.PatternHelper.PROCESSING_OUTPUT_LIMIT; -public class PartExpandedProcessingPatternTerminal extends AbstractPartTerminal -{ +public class PartExpandedProcessingPatternTerminal extends AbstractPartTerminal { @PartModels - public static final ResourceLocation MODEL_OFF = new ResourceLocation( AppEng.MOD_ID, "part/expanded_processing_pattern_terminal_off" ); + public static final ResourceLocation MODEL_OFF = new ResourceLocation(AppEng.MOD_ID, "part/expanded_processing_pattern_terminal_off"); @PartModels - public static final ResourceLocation MODEL_ON = new ResourceLocation( AppEng.MOD_ID, "part/expanded_processing_pattern_terminal_on" ); + public static final ResourceLocation MODEL_ON = new ResourceLocation(AppEng.MOD_ID, "part/expanded_processing_pattern_terminal_on"); - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF ); - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_ON ); - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL ); + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_ON); + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL); - private final AppEngInternalInventory crafting = new AppEngInternalInventory( this, PROCESSING_INPUT_LIMIT ); + private final AppEngInternalInventory crafting = new AppEngInternalInventory(this, PROCESSING_INPUT_LIMIT); - private final AppEngInternalInventory output = new AppEngInternalInventory( this, PROCESSING_OUTPUT_LIMIT ); - private final AppEngInternalInventory pattern = new AppEngInternalInventory( this, 2 ); + private final AppEngInternalInventory output = new AppEngInternalInventory(this, PROCESSING_OUTPUT_LIMIT); + private final AppEngInternalInventory pattern = new AppEngInternalInventory(this, 2); @Reflected - public PartExpandedProcessingPatternTerminal( final ItemStack is ) - { - super( is ); + public PartExpandedProcessingPatternTerminal(final ItemStack is) { + super(is); } @Override - public void getDrops( final List drops, final boolean wrenched ) - { - for( final ItemStack is : this.pattern ) - { - if( !is.isEmpty() ) - { - drops.add( is ); + public void getDrops(final List drops, final boolean wrenched) { + for (final ItemStack is : this.pattern) { + if (!is.isEmpty()) { + drops.add(is); } } } @Override - public void readFromNBT( NBTTagCompound data ) - { - super.readFromNBT( data ); - this.crafting.readFromNBT( data, "processingGrid" ); - this.pattern.readFromNBT( data, "pattern" ); - this.output.readFromNBT( data, "outputList" ); + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + this.crafting.readFromNBT(data, "processingGrid"); + this.pattern.readFromNBT(data, "pattern"); + this.output.readFromNBT(data, "outputList"); } @Override - public void writeToNBT( NBTTagCompound data ) - { - super.writeToNBT( data ); - this.crafting.writeToNBT( data, "processingGrid" ); - this.pattern.writeToNBT( data, "pattern" ); - this.output.writeToNBT( data, "outputList" ); + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + this.crafting.writeToNBT(data, "processingGrid"); + this.pattern.writeToNBT(data, "pattern"); + this.output.writeToNBT(data, "outputList"); } @Override - public GuiBridge getGui( final EntityPlayer p ) - { + public GuiBridge getGui(final EntityPlayer p) { int x = (int) p.posX; int y = (int) p.posY; int z = (int) p.posZ; - if( this.getHost().getTile() != null ) - { + if (this.getHost().getTile() != null) { x = this.getTile().getPos().getX(); y = this.getTile().getPos().getY(); z = this.getTile().getPos().getZ(); } - if( GuiBridge.GUI_EXPANDED_PROCESSING_PATTERN_TERMINAL.hasPermissions( this.getHost().getTile(), x, y, z, this.getSide(), p ) ) - { + if (GuiBridge.GUI_EXPANDED_PROCESSING_PATTERN_TERMINAL.hasPermissions(this.getHost().getTile(), x, y, z, this.getSide(), p)) { return GuiBridge.GUI_EXPANDED_PROCESSING_PATTERN_TERMINAL; } return GuiBridge.GUI_ME; } @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( inv == this.pattern && slot == 1 ) - { - final ItemStack is = this.pattern.getStackInSlot( 1 ); - if( !is.isEmpty() && is.getItem() instanceof ICraftingPatternItem ) - { + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { + if (inv == this.pattern && slot == 1) { + final ItemStack is = this.pattern.getStackInSlot(1); + if (!is.isEmpty() && is.getItem() instanceof ICraftingPatternItem) { final ICraftingPatternItem pattern = (ICraftingPatternItem) is.getItem(); - final ICraftingPatternDetails details = pattern.getPatternForItem( is, this.getHost().getTile().getWorld() ); - if( details != null ) - { - for( int x = 0; x < this.crafting.getSlots() && x < details.getInputs().length; x++ ) - { + final ICraftingPatternDetails details = pattern.getPatternForItem(is, this.getHost().getTile().getWorld()); + if (details != null) { + for (int x = 0; x < this.crafting.getSlots() && x < details.getInputs().length; x++) { final IAEItemStack item = details.getInputs()[x]; - this.crafting.setStackInSlot( x, item == null ? ItemStack.EMPTY : item.createItemStack() ); + this.crafting.setStackInSlot(x, item == null ? ItemStack.EMPTY : item.createItemStack()); } - for( int x = 0; x < this.output.getSlots() && x < details.getOutputs().length; x++ ) - { + for (int x = 0; x < this.output.getSlots() && x < details.getOutputs().length; x++) { final IAEItemStack item = details.getOutputs()[x]; - this.output.setStackInSlot( x, item == null ? ItemStack.EMPTY : item.createItemStack() ); + this.output.setStackInSlot(x, item == null ? ItemStack.EMPTY : item.createItemStack()); } } } @@ -126,27 +110,22 @@ public class PartExpandedProcessingPatternTerminal extends AbstractPartTerminal } @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "crafting" ) ) - { + public IItemHandler getInventoryByName(final String name) { + if (name.equals("crafting")) { return this.crafting; } - if( name.equals( "output" ) ) - { + if (name.equals("output")) { return this.output; } - if( name.equals( "pattern" ) ) - { + if (name.equals("pattern")) { return this.pattern; } - return super.getInventoryByName( name ); + return super.getInventoryByName(name); } @Override - public IPartModel getStaticModels() - { - return this.selectModel( MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL ); + public IPartModel getStaticModels() { + return this.selectModel(MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL); } } diff --git a/src/main/java/appeng/parts/reporting/PartInterfaceConfigurationTerminal.java b/src/main/java/appeng/parts/reporting/PartInterfaceConfigurationTerminal.java index 44c73f0f3..7ba9339a0 100644 --- a/src/main/java/appeng/parts/reporting/PartInterfaceConfigurationTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartInterfaceConfigurationTerminal.java @@ -19,59 +19,51 @@ package appeng.parts.reporting; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumHand; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.Vec3d; - import appeng.api.parts.IPartModel; import appeng.core.AppEng; import appeng.core.sync.GuiBridge; import appeng.items.parts.PartModels; import appeng.parts.PartModel; import appeng.util.Platform; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumHand; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.Vec3d; -public class PartInterfaceConfigurationTerminal extends AbstractPartDisplay -{ +public class PartInterfaceConfigurationTerminal extends AbstractPartDisplay { - @PartModels - public static final ResourceLocation MODEL_OFF = new ResourceLocation( AppEng.MOD_ID, "part/interface_configuration_terminal_off" ); - @PartModels - public static final ResourceLocation MODEL_ON = new ResourceLocation( AppEng.MOD_ID, "part/interface_configuration_terminal_on" ); + @PartModels + public static final ResourceLocation MODEL_OFF = new ResourceLocation(AppEng.MOD_ID, "part/interface_configuration_terminal_off"); + @PartModels + public static final ResourceLocation MODEL_ON = new ResourceLocation(AppEng.MOD_ID, "part/interface_configuration_terminal_on"); - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF ); - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_ON ); - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL ); - public String in = ""; + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_ON); + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL); + public String in = ""; - public PartInterfaceConfigurationTerminal( final ItemStack is ) - { - super( is ); - } + public PartInterfaceConfigurationTerminal(final ItemStack is) { + super(is); + } - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( !super.onPartActivate( player, hand, pos ) ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_INTERFACE_CONFIGURATION_TERMINAL ); - } - } - return true; - } + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (!super.onPartActivate(player, hand, pos)) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_INTERFACE_CONFIGURATION_TERMINAL); + } + } + return true; + } - @Override - public IPartModel getStaticModels() - { - return this.selectModel( MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL ); - } + @Override + public IPartModel getStaticModels() { + return this.selectModel(MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL); + } - public void saveSearchStrings( String in ) - { - this.in = in; - } + public void saveSearchStrings(String in) { + this.in = in; + } } diff --git a/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java b/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java index 075d03050..dd72e071e 100644 --- a/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java @@ -19,61 +19,54 @@ package appeng.parts.reporting; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumHand; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.Vec3d; - import appeng.api.parts.IPartModel; import appeng.core.AppEng; import appeng.core.sync.GuiBridge; import appeng.items.parts.PartModels; import appeng.parts.PartModel; import appeng.util.Platform; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumHand; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.Vec3d; -public class PartInterfaceTerminal extends AbstractPartDisplay -{ +public class PartInterfaceTerminal extends AbstractPartDisplay { - @PartModels - public static final ResourceLocation MODEL_OFF = new ResourceLocation( AppEng.MOD_ID, "part/interface_terminal_off" ); - @PartModels - public static final ResourceLocation MODEL_ON = new ResourceLocation( AppEng.MOD_ID, "part/interface_terminal_on" ); + @PartModels + public static final ResourceLocation MODEL_OFF = new ResourceLocation(AppEng.MOD_ID, "part/interface_terminal_off"); + @PartModels + public static final ResourceLocation MODEL_ON = new ResourceLocation(AppEng.MOD_ID, "part/interface_terminal_on"); - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF ); - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_ON ); - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL ); - public String in = ""; - public String out = ""; - public boolean onlyInterfacesWithFreeSlots = false; + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_ON); + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL); + public String in = ""; + public String out = ""; + public boolean onlyInterfacesWithFreeSlots = false; - public PartInterfaceTerminal( final ItemStack is ) - { - super( is ); - } + public PartInterfaceTerminal(final ItemStack is) { + super(is); + } - @Override - public boolean onPartActivate( final EntityPlayer player, final EnumHand hand, final Vec3d pos ) - { - if( !super.onPartActivate( player, hand, pos ) ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_INTERFACE_TERMINAL ); - } - } - return true; - } + @Override + public boolean onPartActivate(final EntityPlayer player, final EnumHand hand, final Vec3d pos) { + if (!super.onPartActivate(player, hand, pos)) { + if (Platform.isServer()) { + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_INTERFACE_TERMINAL); + } + } + return true; + } - @Override - public IPartModel getStaticModels() - { - return this.selectModel( MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL ); - } + @Override + public IPartModel getStaticModels() { + return this.selectModel(MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL); + } - public void saveSearchStrings(String in, String out){ - this.in = in; - this.out = out; - } + public void saveSearchStrings(String in, String out) { + this.in = in; + this.out = out; + } } diff --git a/src/main/java/appeng/parts/reporting/PartPanel.java b/src/main/java/appeng/parts/reporting/PartPanel.java index 78410476f..a66a3c831 100644 --- a/src/main/java/appeng/parts/reporting/PartPanel.java +++ b/src/main/java/appeng/parts/reporting/PartPanel.java @@ -19,43 +19,38 @@ package appeng.parts.reporting; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - import appeng.api.parts.IPartModel; import appeng.core.AppEng; import appeng.helpers.Reflected; import appeng.items.parts.PartModels; import appeng.parts.PartModel; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; -public class PartPanel extends AbstractPartPanel -{ +public class PartPanel extends AbstractPartPanel { - @PartModels - public static final ResourceLocation MODEL_OFF = new ResourceLocation( AppEng.MOD_ID, "part/monitor_bright_off" ); - @PartModels - public static final ResourceLocation MODEL_ON = new ResourceLocation( AppEng.MOD_ID, "part/monitor_bright_on" ); + @PartModels + public static final ResourceLocation MODEL_OFF = new ResourceLocation(AppEng.MOD_ID, "part/monitor_bright_off"); + @PartModels + public static final ResourceLocation MODEL_ON = new ResourceLocation(AppEng.MOD_ID, "part/monitor_bright_on"); - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_OFF ); - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_ON ); + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_OFF); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_ON); - @Reflected - public PartPanel( final ItemStack is ) - { - super( is ); - } + @Reflected + public PartPanel(final ItemStack is) { + super(is); + } - @Override - protected int getBrightnessColor() - { - return this.getColor().whiteVariant; - } + @Override + protected int getBrightnessColor() { + return this.getColor().whiteVariant; + } - @Override - public IPartModel getStaticModels() - { - return this.isPowered() ? MODELS_ON : MODELS_OFF; - } + @Override + public IPartModel getStaticModels() { + return this.isPowered() ? MODELS_ON : MODELS_OFF; + } } diff --git a/src/main/java/appeng/parts/reporting/PartPatternTerminal.java b/src/main/java/appeng/parts/reporting/PartPatternTerminal.java index d917907a3..a7f27dc0f 100644 --- a/src/main/java/appeng/parts/reporting/PartPatternTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartPatternTerminal.java @@ -19,14 +19,6 @@ package appeng.parts.reporting; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.items.IItemHandler; - import appeng.api.implementations.ICraftingPatternItem; import appeng.api.networking.crafting.ICraftingPatternDetails; import appeng.api.parts.IPartModel; @@ -38,184 +30,160 @@ import appeng.items.parts.PartModels; import appeng.parts.PartModel; import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.inv.InvOperation; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.items.IItemHandler; + +import java.util.List; -public class PartPatternTerminal extends AbstractPartTerminal -{ +public class PartPatternTerminal extends AbstractPartTerminal { - @PartModels - public static final ResourceLocation MODEL_OFF = new ResourceLocation( AppEng.MOD_ID, "part/pattern_terminal_off" ); - @PartModels - public static final ResourceLocation MODEL_ON = new ResourceLocation( AppEng.MOD_ID, "part/pattern_terminal_on" ); + @PartModels + public static final ResourceLocation MODEL_OFF = new ResourceLocation(AppEng.MOD_ID, "part/pattern_terminal_off"); + @PartModels + public static final ResourceLocation MODEL_ON = new ResourceLocation(AppEng.MOD_ID, "part/pattern_terminal_on"); - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF ); - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_ON ); - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL ); + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_ON); + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL); - private final AppEngInternalInventory crafting = new AppEngInternalInventory( this, 9 ); - private final AppEngInternalInventory output = new AppEngInternalInventory( this, 3 ); - private final AppEngInternalInventory pattern = new AppEngInternalInventory( this, 2 ); + private final AppEngInternalInventory crafting = new AppEngInternalInventory(this, 9); + private final AppEngInternalInventory output = new AppEngInternalInventory(this, 3); + private final AppEngInternalInventory pattern = new AppEngInternalInventory(this, 2); - private boolean craftingMode = true; - private boolean substitute = false; + private boolean craftingMode = true; + private boolean substitute = false; - @Reflected - public PartPatternTerminal( final ItemStack is ) - { - super( is ); - } + @Reflected + public PartPatternTerminal(final ItemStack is) { + super(is); + } - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - for( final ItemStack is : this.pattern ) - { - if( !is.isEmpty() ) - { - drops.add( is ); - } - } - } + @Override + public void getDrops(final List drops, final boolean wrenched) { + for (final ItemStack is : this.pattern) { + if (!is.isEmpty()) { + drops.add(is); + } + } + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.setCraftingRecipe( data.getBoolean( "craftingMode" ) ); - this.setSubstitution( data.getBoolean( "substitute" ) ); - this.pattern.readFromNBT( data, "pattern" ); - this.output.readFromNBT( data, "outputList" ); - this.crafting.readFromNBT( data, "craftingGrid" ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.setCraftingRecipe(data.getBoolean("craftingMode")); + this.setSubstitution(data.getBoolean("substitute")); + this.pattern.readFromNBT(data, "pattern"); + this.output.readFromNBT(data, "outputList"); + this.crafting.readFromNBT(data, "craftingGrid"); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setBoolean( "craftingMode", this.craftingMode ); - data.setBoolean( "substitute", this.substitute ); - this.pattern.writeToNBT( data, "pattern" ); - this.output.writeToNBT( data, "outputList" ); - this.crafting.writeToNBT( data, "craftingGrid" ); - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setBoolean("craftingMode", this.craftingMode); + data.setBoolean("substitute", this.substitute); + this.pattern.writeToNBT(data, "pattern"); + this.output.writeToNBT(data, "outputList"); + this.crafting.writeToNBT(data, "craftingGrid"); + } - @Override - public GuiBridge getGui( final EntityPlayer p ) - { - int x = (int) p.posX; - int y = (int) p.posY; - int z = (int) p.posZ; - if( this.getHost().getTile() != null ) - { - x = this.getTile().getPos().getX(); - y = this.getTile().getPos().getY(); - z = this.getTile().getPos().getZ(); - } + @Override + public GuiBridge getGui(final EntityPlayer p) { + int x = (int) p.posX; + int y = (int) p.posY; + int z = (int) p.posZ; + if (this.getHost().getTile() != null) { + x = this.getTile().getPos().getX(); + y = this.getTile().getPos().getY(); + z = this.getTile().getPos().getZ(); + } - if( GuiBridge.GUI_PATTERN_TERMINAL.hasPermissions( this.getHost().getTile(), x, y, z, this.getSide(), p ) ) - { - return GuiBridge.GUI_PATTERN_TERMINAL; - } - return GuiBridge.GUI_ME; - } + if (GuiBridge.GUI_PATTERN_TERMINAL.hasPermissions(this.getHost().getTile(), x, y, z, this.getSide(), p)) { + return GuiBridge.GUI_PATTERN_TERMINAL; + } + return GuiBridge.GUI_ME; + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( inv == this.pattern && slot == 1 ) - { - final ItemStack is = this.pattern.getStackInSlot( 1 ); - if( !is.isEmpty() && is.getItem() instanceof ICraftingPatternItem ) - { - final ICraftingPatternItem pattern = (ICraftingPatternItem) is.getItem(); - final ICraftingPatternDetails details = pattern.getPatternForItem( is, this.getHost().getTile().getWorld() ); - if( details != null ) - { - this.setCraftingRecipe( details.isCraftable() ); - this.setSubstitution( details.canSubstitute() ); + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { + if (inv == this.pattern && slot == 1) { + final ItemStack is = this.pattern.getStackInSlot(1); + if (!is.isEmpty() && is.getItem() instanceof ICraftingPatternItem) { + final ICraftingPatternItem pattern = (ICraftingPatternItem) is.getItem(); + final ICraftingPatternDetails details = pattern.getPatternForItem(is, this.getHost().getTile().getWorld()); + if (details != null) { + this.setCraftingRecipe(details.isCraftable()); + this.setSubstitution(details.canSubstitute()); - for( int x = 0; x < this.crafting.getSlots() && x < details.getInputs().length; x++ ) - { - final IAEItemStack item = details.getInputs()[x]; - this.crafting.setStackInSlot( x, item == null ? ItemStack.EMPTY : item.createItemStack() ); - } + for (int x = 0; x < this.crafting.getSlots() && x < details.getInputs().length; x++) { + final IAEItemStack item = details.getInputs()[x]; + this.crafting.setStackInSlot(x, item == null ? ItemStack.EMPTY : item.createItemStack()); + } - for( int x = 0; x < this.output.getSlots() && x < details.getOutputs().length; x++ ) - { - final IAEItemStack item = details.getOutputs()[x]; - this.output.setStackInSlot( x, item == null ? ItemStack.EMPTY : item.createItemStack() ); - } - } - } - } - else if( inv == this.crafting ) - { - this.fixCraftingRecipes(); - } + for (int x = 0; x < this.output.getSlots() && x < details.getOutputs().length; x++) { + final IAEItemStack item = details.getOutputs()[x]; + this.output.setStackInSlot(x, item == null ? ItemStack.EMPTY : item.createItemStack()); + } + } + } + } else if (inv == this.crafting) { + this.fixCraftingRecipes(); + } - this.getHost().markForSave(); - } + this.getHost().markForSave(); + } - private void fixCraftingRecipes() - { - if( this.craftingMode ) - { - for( int x = 0; x < this.crafting.getSlots(); x++ ) - { - final ItemStack is = this.crafting.getStackInSlot( x ); - if( !is.isEmpty() ) - { - is.setCount( 1 ); - } - } - } - } + private void fixCraftingRecipes() { + if (this.craftingMode) { + for (int x = 0; x < this.crafting.getSlots(); x++) { + final ItemStack is = this.crafting.getStackInSlot(x); + if (!is.isEmpty()) { + is.setCount(1); + } + } + } + } - public boolean isCraftingRecipe() - { - return this.craftingMode; - } + public boolean isCraftingRecipe() { + return this.craftingMode; + } - public void setCraftingRecipe( final boolean craftingMode ) - { - this.craftingMode = craftingMode; - this.fixCraftingRecipes(); - } + public void setCraftingRecipe(final boolean craftingMode) { + this.craftingMode = craftingMode; + this.fixCraftingRecipes(); + } - public boolean isSubstitution() - { - return this.substitute; - } + public boolean isSubstitution() { + return this.substitute; + } - public void setSubstitution( final boolean canSubstitute ) - { - this.substitute = canSubstitute; - } + public void setSubstitution(final boolean canSubstitute) { + this.substitute = canSubstitute; + } - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "crafting" ) ) - { - return this.crafting; - } + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("crafting")) { + return this.crafting; + } - if( name.equals( "output" ) ) - { - return this.output; - } + if (name.equals("output")) { + return this.output; + } - if( name.equals( "pattern" ) ) - { - return this.pattern; - } + if (name.equals("pattern")) { + return this.pattern; + } - return super.getInventoryByName( name ); - } + return super.getInventoryByName(name); + } - @Override - public IPartModel getStaticModels() - { - return this.selectModel( MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL ); - } + @Override + public IPartModel getStaticModels() { + return this.selectModel(MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL); + } } diff --git a/src/main/java/appeng/parts/reporting/PartSemiDarkPanel.java b/src/main/java/appeng/parts/reporting/PartSemiDarkPanel.java index 0a6f3d0ef..ba1a1ea2a 100644 --- a/src/main/java/appeng/parts/reporting/PartSemiDarkPanel.java +++ b/src/main/java/appeng/parts/reporting/PartSemiDarkPanel.java @@ -19,44 +19,39 @@ package appeng.parts.reporting; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - import appeng.api.parts.IPartModel; import appeng.core.AppEng; import appeng.helpers.Reflected; import appeng.items.parts.PartModels; import appeng.parts.PartModel; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; -public class PartSemiDarkPanel extends AbstractPartPanel -{ - @PartModels - public static final ResourceLocation MODEL_OFF = new ResourceLocation( AppEng.MOD_ID, "part/monitor_medium_off" ); - @PartModels - public static final ResourceLocation MODEL_ON = new ResourceLocation( AppEng.MOD_ID, "part/monitor_medium_on" ); +public class PartSemiDarkPanel extends AbstractPartPanel { + @PartModels + public static final ResourceLocation MODEL_OFF = new ResourceLocation(AppEng.MOD_ID, "part/monitor_medium_off"); + @PartModels + public static final ResourceLocation MODEL_ON = new ResourceLocation(AppEng.MOD_ID, "part/monitor_medium_on"); - public static final PartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_OFF ); - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_ON ); + public static final PartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_OFF); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_ON); - @Reflected - public PartSemiDarkPanel( final ItemStack is ) - { - super( is ); - } + @Reflected + public PartSemiDarkPanel(final ItemStack is) { + super(is); + } - @Override - protected int getBrightnessColor() - { - final int light = this.getColor().whiteVariant; - final int dark = this.getColor().mediumVariant; - return ( ( ( ( ( light >> 16 ) & 0xff ) + ( ( dark >> 16 ) & 0xff ) ) / 2 ) << 16 ) | ( ( ( ( ( light >> 8 ) & 0xff ) + ( ( dark >> 8 ) & 0xff ) ) / 2 ) << 8 ) | ( ( ( ( light ) & 0xff ) + ( ( dark ) & 0xff ) ) / 2 ); - } + @Override + protected int getBrightnessColor() { + final int light = this.getColor().whiteVariant; + final int dark = this.getColor().mediumVariant; + return (((((light >> 16) & 0xff) + ((dark >> 16) & 0xff)) / 2) << 16) | (((((light >> 8) & 0xff) + ((dark >> 8) & 0xff)) / 2) << 8) | ((((light) & 0xff) + ((dark) & 0xff)) / 2); + } - @Override - public IPartModel getStaticModels() - { - return this.isPowered() ? MODELS_ON : MODELS_OFF; - } + @Override + public IPartModel getStaticModels() { + return this.isPowered() ? MODELS_ON : MODELS_OFF; + } } diff --git a/src/main/java/appeng/parts/reporting/PartStorageMonitor.java b/src/main/java/appeng/parts/reporting/PartStorageMonitor.java index 06d1fd604..c8c2d6391 100644 --- a/src/main/java/appeng/parts/reporting/PartStorageMonitor.java +++ b/src/main/java/appeng/parts/reporting/PartStorageMonitor.java @@ -19,14 +19,13 @@ package appeng.parts.reporting; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - import appeng.api.parts.IPartModel; import appeng.core.AppEng; import appeng.helpers.Reflected; import appeng.items.parts.PartModels; import appeng.parts.PartModel; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; /** @@ -35,36 +34,33 @@ import appeng.parts.PartModel; * @version rv2 * @since rv0 */ -public class PartStorageMonitor extends AbstractPartMonitor -{ +public class PartStorageMonitor extends AbstractPartMonitor { - @PartModels - public static final ResourceLocation MODEL_OFF = new ResourceLocation( AppEng.MOD_ID, "part/storage_monitor_off" ); - @PartModels - public static final ResourceLocation MODEL_ON = new ResourceLocation( AppEng.MOD_ID, "part/storage_monitor_on" ); - @PartModels - public static final ResourceLocation MODEL_LOCKED_OFF = new ResourceLocation( AppEng.MOD_ID, "part/storage_monitor_locked_off" ); - @PartModels - public static final ResourceLocation MODEL_LOCKED_ON = new ResourceLocation( AppEng.MOD_ID, "part/storage_monitor_locked_on" ); + @PartModels + public static final ResourceLocation MODEL_OFF = new ResourceLocation(AppEng.MOD_ID, "part/storage_monitor_off"); + @PartModels + public static final ResourceLocation MODEL_ON = new ResourceLocation(AppEng.MOD_ID, "part/storage_monitor_on"); + @PartModels + public static final ResourceLocation MODEL_LOCKED_OFF = new ResourceLocation(AppEng.MOD_ID, "part/storage_monitor_locked_off"); + @PartModels + public static final ResourceLocation MODEL_LOCKED_ON = new ResourceLocation(AppEng.MOD_ID, "part/storage_monitor_locked_on"); - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF ); - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_ON ); - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL ); + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_ON); + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL); - public static final IPartModel MODELS_LOCKED_OFF = new PartModel( MODEL_BASE, MODEL_LOCKED_OFF, MODEL_STATUS_OFF ); - public static final IPartModel MODELS_LOCKED_ON = new PartModel( MODEL_BASE, MODEL_LOCKED_ON, MODEL_STATUS_ON ); - public static final IPartModel MODELS_LOCKED_HAS_CHANNEL = new PartModel( MODEL_BASE, MODEL_LOCKED_ON, MODEL_STATUS_HAS_CHANNEL ); + public static final IPartModel MODELS_LOCKED_OFF = new PartModel(MODEL_BASE, MODEL_LOCKED_OFF, MODEL_STATUS_OFF); + public static final IPartModel MODELS_LOCKED_ON = new PartModel(MODEL_BASE, MODEL_LOCKED_ON, MODEL_STATUS_ON); + public static final IPartModel MODELS_LOCKED_HAS_CHANNEL = new PartModel(MODEL_BASE, MODEL_LOCKED_ON, MODEL_STATUS_HAS_CHANNEL); - @Reflected - public PartStorageMonitor( final ItemStack is ) - { - super( is ); - } + @Reflected + public PartStorageMonitor(final ItemStack is) { + super(is); + } - @Override - public IPartModel getStaticModels() - { - return this.selectModel( MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL, - MODELS_LOCKED_OFF, MODELS_LOCKED_ON, MODELS_LOCKED_HAS_CHANNEL ); - } + @Override + public IPartModel getStaticModels() { + return this.selectModel(MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL, + MODELS_LOCKED_OFF, MODELS_LOCKED_ON, MODELS_LOCKED_HAS_CHANNEL); + } } diff --git a/src/main/java/appeng/parts/reporting/PartTerminal.java b/src/main/java/appeng/parts/reporting/PartTerminal.java index cc582b1a5..540fc6a9c 100644 --- a/src/main/java/appeng/parts/reporting/PartTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartTerminal.java @@ -19,35 +19,31 @@ package appeng.parts.reporting; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - import appeng.api.parts.IPartModel; import appeng.core.AppEng; import appeng.items.parts.PartModels; import appeng.parts.PartModel; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; -public class PartTerminal extends AbstractPartTerminal -{ +public class PartTerminal extends AbstractPartTerminal { - @PartModels - public static final ResourceLocation MODEL_OFF = new ResourceLocation( AppEng.MOD_ID, "part/terminal_off" ); - @PartModels - public static final ResourceLocation MODEL_ON = new ResourceLocation( AppEng.MOD_ID, "part/terminal_on" ); + @PartModels + public static final ResourceLocation MODEL_OFF = new ResourceLocation(AppEng.MOD_ID, "part/terminal_off"); + @PartModels + public static final ResourceLocation MODEL_ON = new ResourceLocation(AppEng.MOD_ID, "part/terminal_on"); - public static final IPartModel MODELS_OFF = new PartModel( MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF ); - public static final IPartModel MODELS_ON = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_ON ); - public static final IPartModel MODELS_HAS_CHANNEL = new PartModel( MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL ); + public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE, MODEL_OFF, MODEL_STATUS_OFF); + public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_ON); + public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE, MODEL_ON, MODEL_STATUS_HAS_CHANNEL); - public PartTerminal( final ItemStack is ) - { - super( is ); - } + public PartTerminal(final ItemStack is) { + super(is); + } - @Override - public IPartModel getStaticModels() - { - return this.selectModel( MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL ); - } + @Override + public IPartModel getStaticModels() { + return this.selectModel(MODELS_OFF, MODELS_ON, MODELS_HAS_CHANNEL); + } } diff --git a/src/main/java/appeng/recipes/AEItemResolver.java b/src/main/java/appeng/recipes/AEItemResolver.java index 42c76f411..4d34678e2 100644 --- a/src/main/java/appeng/recipes/AEItemResolver.java +++ b/src/main/java/appeng/recipes/AEItemResolver.java @@ -19,8 +19,6 @@ package appeng.recipes; -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.definitions.IItems; @@ -36,162 +34,131 @@ import appeng.items.materials.MaterialType; import appeng.items.misc.ItemCrystalSeed; import appeng.items.parts.ItemPart; import appeng.items.parts.PartType; +import net.minecraft.item.ItemStack; -public class AEItemResolver implements ISubItemResolver -{ +public class AEItemResolver implements ISubItemResolver { - @Override - public Object resolveItemByName( final String nameSpace, final String itemName ) - { + @Override + public Object resolveItemByName(final String nameSpace, final String itemName) { - if( nameSpace.equals( AppEng.MOD_ID ) ) - { - final IDefinitions definitions = AEApi.instance().definitions(); - final IItems items = definitions.items(); - final IParts parts = definitions.parts(); + if (nameSpace.equals(AppEng.MOD_ID)) { + final IDefinitions definitions = AEApi.instance().definitions(); + final IItems items = definitions.items(); + final IParts parts = definitions.parts(); - if( itemName.startsWith( "paint_ball." ) ) - { - return this.paintBall( items.coloredPaintBall(), itemName.substring( itemName.indexOf( '.' ) + 1 ), false ); - } + if (itemName.startsWith("paint_ball.")) { + return this.paintBall(items.coloredPaintBall(), itemName.substring(itemName.indexOf('.') + 1), false); + } - if( itemName.startsWith( "lumen_paint_ball." ) ) - { - return this.paintBall( items.coloredPaintBall(), itemName.substring( itemName.indexOf( '.' ) + 1 ), true ); - } + if (itemName.startsWith("lumen_paint_ball.")) { + return this.paintBall(items.coloredPaintBall(), itemName.substring(itemName.indexOf('.') + 1), true); + } - if( itemName.equals( "cable_glass" ) ) - { - return new ResolverResultSet( "cable_glass", parts.cableGlass().allStacks( 1 ) ); - } + if (itemName.equals("cable_glass")) { + return new ResolverResultSet("cable_glass", parts.cableGlass().allStacks(1)); + } - if( itemName.startsWith( "cable_glass." ) ) - { - return this.cableItem( parts.cableGlass(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } + if (itemName.startsWith("cable_glass.")) { + return this.cableItem(parts.cableGlass(), itemName.substring(itemName.indexOf('.') + 1)); + } - if( itemName.equals( "cable_covered" ) ) - { - return new ResolverResultSet( "cable_covered", parts.cableCovered().allStacks( 1 ) ); - } + if (itemName.equals("cable_covered")) { + return new ResolverResultSet("cable_covered", parts.cableCovered().allStacks(1)); + } - if( itemName.startsWith( "cable_covered." ) ) - { - return this.cableItem( parts.cableCovered(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } + if (itemName.startsWith("cable_covered.")) { + return this.cableItem(parts.cableCovered(), itemName.substring(itemName.indexOf('.') + 1)); + } - if( itemName.equals( "cable_smart" ) ) - { - return new ResolverResultSet( "cable_smart", parts.cableSmart().allStacks( 1 ) ); - } + if (itemName.equals("cable_smart")) { + return new ResolverResultSet("cable_smart", parts.cableSmart().allStacks(1)); + } - if( itemName.startsWith( "cable_smart." ) ) - { - return this.cableItem( parts.cableSmart(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } + if (itemName.startsWith("cable_smart.")) { + return this.cableItem(parts.cableSmart(), itemName.substring(itemName.indexOf('.') + 1)); + } - if( itemName.equals( "cable_dense_covered" ) ) - { - return new ResolverResultSet( "cable_dense_covered", parts.cableDenseCovered().allStacks( 1 ) ); - } + if (itemName.equals("cable_dense_covered")) { + return new ResolverResultSet("cable_dense_covered", parts.cableDenseCovered().allStacks(1)); + } - if( itemName.startsWith( "cable_dense_covered." ) ) - { - return this.cableItem( parts.cableDenseCovered(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } + if (itemName.startsWith("cable_dense_covered.")) { + return this.cableItem(parts.cableDenseCovered(), itemName.substring(itemName.indexOf('.') + 1)); + } - if( itemName.equals( "cable_dense_smart" ) ) - { - return new ResolverResultSet( "cable_dense_smart", parts.cableDenseSmart().allStacks( 1 ) ); - } + if (itemName.equals("cable_dense_smart")) { + return new ResolverResultSet("cable_dense_smart", parts.cableDenseSmart().allStacks(1)); + } - if( itemName.startsWith( "cable_dense_smart." ) ) - { - return this.cableItem( parts.cableDenseSmart(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } + if (itemName.startsWith("cable_dense_smart.")) { + return this.cableItem(parts.cableDenseSmart(), itemName.substring(itemName.indexOf('.') + 1)); + } - if( itemName.startsWith( "crystal_seed." ) ) - { - if( itemName.equalsIgnoreCase( "crystal_seed.certus" ) ) - { - return ItemCrystalSeed.getResolver( ItemCrystalSeed.CERTUS ); - } - if( itemName.equalsIgnoreCase( "crystal_seed.nether" ) ) - { - return ItemCrystalSeed.getResolver( ItemCrystalSeed.NETHER ); - } - if( itemName.equalsIgnoreCase( "crystal_seed.fluix" ) ) - { - return ItemCrystalSeed.getResolver( ItemCrystalSeed.FLUIX ); - } + if (itemName.startsWith("crystal_seed.")) { + if (itemName.equalsIgnoreCase("crystal_seed.certus")) { + return ItemCrystalSeed.getResolver(ItemCrystalSeed.CERTUS); + } + if (itemName.equalsIgnoreCase("crystal_seed.nether")) { + return ItemCrystalSeed.getResolver(ItemCrystalSeed.NETHER); + } + if (itemName.equalsIgnoreCase("crystal_seed.fluix")) { + return ItemCrystalSeed.getResolver(ItemCrystalSeed.FLUIX); + } - return null; - } + return null; + } - if( itemName.startsWith( "material." ) ) - { - final String materialName = itemName.substring( itemName.indexOf( '.' ) + 1 ); - final MaterialType mt = MaterialType.valueOf( materialName.toUpperCase() ); - // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); - if( mt.getItemInstance() == ItemMaterial.instance && mt.getDamageValue() >= 0 && mt.isRegistered() ) - { - return new ResolverResult( "material", mt.getDamageValue() ); - } - } + if (itemName.startsWith("material.")) { + final String materialName = itemName.substring(itemName.indexOf('.') + 1); + final MaterialType mt = MaterialType.valueOf(materialName.toUpperCase()); + // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); + if (mt.getItemInstance() == ItemMaterial.instance && mt.getDamageValue() >= 0 && mt.isRegistered()) { + return new ResolverResult("material", mt.getDamageValue()); + } + } - if( itemName.startsWith( "part." ) ) - { - final String partName = itemName.substring( itemName.indexOf( '.' ) + 1 ); - final PartType pt = PartType.valueOf( partName.toUpperCase() ); - // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); - final int dVal = ItemPart.instance.getDamageByType( pt ); - if( dVal >= 0 ) - { - return new ResolverResult( "part", dVal ); - } - } - } + if (itemName.startsWith("part.")) { + final String partName = itemName.substring(itemName.indexOf('.') + 1); + final PartType pt = PartType.valueOf(partName.toUpperCase()); + // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); + final int dVal = ItemPart.instance.getDamageByType(pt); + if (dVal >= 0) { + return new ResolverResult("part", dVal); + } + } + } - return null; - } + return null; + } - private Object paintBall( final AEColoredItemDefinition partType, final String substring, final boolean lumen ) - { - AEColor col; + private Object paintBall(final AEColoredItemDefinition partType, final String substring, final boolean lumen) { + AEColor col; - try - { - col = AEColor.valueOf( substring.toUpperCase() ); - } - catch( final Throwable t ) - { - col = AEColor.TRANSPARENT; - } + try { + col = AEColor.valueOf(substring.toUpperCase()); + } catch (final Throwable t) { + col = AEColor.TRANSPARENT; + } - if( col == AEColor.TRANSPARENT ) - { - return null; - } + if (col == AEColor.TRANSPARENT) { + return null; + } - final ItemStack is = partType.stack( col, 1 ); - return new ResolverResult( "paint_ball", ( lumen ? 20 : 0 ) + is.getItemDamage() ); - } + final ItemStack is = partType.stack(col, 1); + return new ResolverResult("paint_ball", (lumen ? 20 : 0) + is.getItemDamage()); + } - private Object cableItem( final AEColoredItemDefinition partType, final String substring ) - { - AEColor col; + private Object cableItem(final AEColoredItemDefinition partType, final String substring) { + AEColor col; - try - { - col = AEColor.valueOf( substring.toUpperCase() ); - } - catch( final Throwable t ) - { - col = AEColor.TRANSPARENT; - } + try { + col = AEColor.valueOf(substring.toUpperCase()); + } catch (final Throwable t) { + col = AEColor.TRANSPARENT; + } - final ItemStack is = partType.stack( col, 1 ); - return new ResolverResult( "part", is.getItemDamage() ); - } + final ItemStack is = partType.stack(col, 1); + return new ResolverResult("part", is.getItemDamage()); + } } diff --git a/src/main/java/appeng/recipes/AERecipeLoader.java b/src/main/java/appeng/recipes/AERecipeLoader.java index 1b5763d03..ebda35628 100644 --- a/src/main/java/appeng/recipes/AERecipeLoader.java +++ b/src/main/java/appeng/recipes/AERecipeLoader.java @@ -1,7 +1,21 @@ - package appeng.recipes; +import appeng.core.AppEng; +import appeng.recipes.handlers.GrinderHandler; +import appeng.recipes.handlers.InscriberHandler; +import appeng.recipes.handlers.SmeltingHandler; +import com.google.gson.*; +import net.minecraft.util.JsonUtils; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.common.crafting.CraftingHelper; +import net.minecraftforge.common.crafting.JsonContext; +import net.minecraftforge.fml.common.FMLLog; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.common.ModContainer; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.IOUtils; + import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; @@ -9,123 +23,82 @@ import java.nio.file.Path; import java.util.HashMap; import java.util.Map; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSyntaxException; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; +public class AERecipeLoader { + private static final String AERECIPE_BASE = "/aerecipes"; + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); + private final Map factories = new HashMap<>(); -import net.minecraft.util.JsonUtils; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.common.crafting.CraftingHelper; -import net.minecraftforge.common.crafting.JsonContext; -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.ModContainer; + private final ModContainer mod; + private final JsonContext ctx; -import appeng.core.AppEng; -import appeng.recipes.handlers.GrinderHandler; -import appeng.recipes.handlers.InscriberHandler; -import appeng.recipes.handlers.SmeltingHandler; + public AERecipeLoader() { + this.mod = Loader.instance().getIndexedModList().get(AppEng.MOD_ID); + this.ctx = new JsonContext(AppEng.MOD_ID); + this.initFactories(); + } -public class AERecipeLoader -{ - private static final String AERECIPE_BASE = "/aerecipes"; - private static Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); - private final Map factories = new HashMap<>(); + public boolean loadProcessingRecipes() { + return CraftingHelper.findFiles(this.mod, "assets/" + AppEng.MOD_ID + AERECIPE_BASE, this::preprocess, this::process, true, true); + } - private final ModContainer mod; - private final JsonContext ctx; + private boolean preprocess(final Path root) { + return true; + } - public AERecipeLoader() - { - this.mod = Loader.instance().getIndexedModList().get( AppEng.MOD_ID ); - this.ctx = new JsonContext( AppEng.MOD_ID ); + private boolean process(final Path root, final Path file) { + String relative = root.relativize(file).toString(); + if (!"json".equals(FilenameUtils.getExtension(file.toString())) || relative.startsWith("_")) { + return true; + } - this.initFactories(); - } + String name = FilenameUtils.removeExtension(relative).replaceAll("\\\\", "/"); + ResourceLocation key = new ResourceLocation(this.ctx.getModId(), name); - public boolean loadProcessingRecipes() - { - return CraftingHelper.findFiles( this.mod, "assets/" + AppEng.MOD_ID + AERECIPE_BASE, this::preprocess, this::process, true, true ); - } + BufferedReader reader = null; + try { + reader = Files.newBufferedReader(file); + JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class); + if (json.has("conditions") && !CraftingHelper.processConditions(JsonUtils.getJsonArray(json, "conditions"), this.ctx)) { + return true; + } - private boolean preprocess( final Path root ) - { - return true; - } + this.register(json); + } catch (JsonParseException e) { + FMLLog.log.error("Parsing error loading recipe {}", key, e); + return false; + } catch (IOException e) { + FMLLog.log.error("Couldn't read recipe {} from {}", key, file, e); + return false; + } finally { + IOUtils.closeQuietly(reader); + } - private boolean process( final Path root, final Path file ) - { - String relative = root.relativize( file ).toString(); - if( !"json".equals( FilenameUtils.getExtension( file.toString() ) ) || relative.startsWith( "_" ) ) - { - return true; - } + return true; + } - String name = FilenameUtils.removeExtension( relative ).replaceAll( "\\\\", "/" ); - ResourceLocation key = new ResourceLocation( this.ctx.getModId(), name ); + private void register(JsonObject json) { + if (json == null || json.isJsonNull()) { + throw new JsonSyntaxException("Json cannot be null"); + } - BufferedReader reader = null; - try - { - reader = Files.newBufferedReader( file ); - JsonObject json = JsonUtils.fromJson( GSON, reader, JsonObject.class ); - if( json.has( "conditions" ) && !CraftingHelper.processConditions( JsonUtils.getJsonArray( json, "conditions" ), this.ctx ) ) - { - return true; - } + String type = this.ctx.appendModId(JsonUtils.getString(json, "type")); + if (type.isEmpty()) { + throw new JsonSyntaxException("Recipe type can not be an empty string"); + } - this.register( json ); - } - catch( JsonParseException e ) - { - FMLLog.log.error( "Parsing error loading recipe {}", key, e ); - return false; - } - catch( IOException e ) - { - FMLLog.log.error( "Couldn't read recipe {} from {}", key, file, e ); - return false; - } - finally - { - IOUtils.closeQuietly( reader ); - } + IAERecipeFactory factory = this.factories.get(new ResourceLocation(type)); + if (factory == null) { + throw new JsonSyntaxException("Unknown recipe type: " + type); + } - return true; - } + factory.register(json, this.ctx); + } - private void register( JsonObject json ) - { - if( json == null || json.isJsonNull() ) - { - throw new JsonSyntaxException( "Json cannot be null" ); - } - - String type = this.ctx.appendModId( JsonUtils.getString( json, "type" ) ); - if( type.isEmpty() ) - { - throw new JsonSyntaxException( "Recipe type can not be an empty string" ); - } - - IAERecipeFactory factory = this.factories.get( new ResourceLocation( type ) ); - if( factory == null ) - { - throw new JsonSyntaxException( "Unknown recipe type: " + type ); - } - - factory.register( json, this.ctx ); - } - - private void initFactories() - { - this.factories.put( new ResourceLocation( AppEng.MOD_ID, "inscriber" ), new InscriberHandler() ); - this.factories.put( new ResourceLocation( AppEng.MOD_ID, "smelt" ), new SmeltingHandler() ); - this.factories.put( new ResourceLocation( AppEng.MOD_ID, "grinder" ), new GrinderHandler() ); - } + private void initFactories() { + this.factories.put(new ResourceLocation(AppEng.MOD_ID, "inscriber"), new InscriberHandler()); + this.factories.put(new ResourceLocation(AppEng.MOD_ID, "smelt"), new SmeltingHandler()); + this.factories.put(new ResourceLocation(AppEng.MOD_ID, "grinder"), new GrinderHandler()); + } } diff --git a/src/main/java/appeng/recipes/IAERecipeFactory.java b/src/main/java/appeng/recipes/IAERecipeFactory.java index 091ddff9f..ed4f3113a 100644 --- a/src/main/java/appeng/recipes/IAERecipeFactory.java +++ b/src/main/java/appeng/recipes/IAERecipeFactory.java @@ -1,13 +1,10 @@ - package appeng.recipes; import com.google.gson.JsonObject; - import net.minecraftforge.common.crafting.JsonContext; -public interface IAERecipeFactory -{ - void register( JsonObject json, JsonContext ctx ); +public interface IAERecipeFactory { + void register(JsonObject json, JsonContext ctx); } diff --git a/src/main/java/appeng/recipes/RecipeHandler.java b/src/main/java/appeng/recipes/RecipeHandler.java index f578e9965..b42c18a5c 100644 --- a/src/main/java/appeng/recipes/RecipeHandler.java +++ b/src/main/java/appeng/recipes/RecipeHandler.java @@ -29,17 +29,14 @@ import appeng.api.recipes.IRecipeLoader; * @version rv3 - 10.08.2015 * @since rv0 */ -public class RecipeHandler implements IRecipeHandler -{ - @Override - public void parseRecipes( final IRecipeLoader loader, final String path ) - { - // dummy - } +public class RecipeHandler implements IRecipeHandler { + @Override + public void parseRecipes(final IRecipeLoader loader, final String path) { + // dummy + } - @Override - public void injectRecipes() - { - // dummy - } + @Override + public void injectRecipes() { + // dummy + } } diff --git a/src/main/java/appeng/recipes/factories/conditions/Features.java b/src/main/java/appeng/recipes/factories/conditions/Features.java index b37b08e3c..47ed5cf32 100644 --- a/src/main/java/appeng/recipes/factories/conditions/Features.java +++ b/src/main/java/appeng/recipes/factories/conditions/Features.java @@ -19,49 +19,40 @@ package appeng.recipes.factories.conditions; -import java.util.Locale; -import java.util.function.BooleanSupplier; -import java.util.stream.Stream; - +import appeng.core.AEConfig; +import appeng.core.features.AEFeature; import com.google.gson.JsonArray; import com.google.gson.JsonObject; - import net.minecraft.util.JsonUtils; import net.minecraftforge.common.crafting.IConditionFactory; import net.minecraftforge.common.crafting.JsonContext; -import appeng.core.AEConfig; -import appeng.core.features.AEFeature; +import java.util.Locale; +import java.util.function.BooleanSupplier; +import java.util.stream.Stream; -public class Features implements IConditionFactory -{ - private static final String JSON_FEATURES_KEY = "features"; +public class Features implements IConditionFactory { + private static final String JSON_FEATURES_KEY = "features"; - @Override - public BooleanSupplier parse( JsonContext jsonContext, JsonObject jsonObject ) - { - final boolean result; + @Override + public BooleanSupplier parse(JsonContext jsonContext, JsonObject jsonObject) { + final boolean result; - if( JsonUtils.isJsonArray( jsonObject, JSON_FEATURES_KEY ) ) - { - final JsonArray features = JsonUtils.getJsonArray( jsonObject, JSON_FEATURES_KEY ); + if (JsonUtils.isJsonArray(jsonObject, JSON_FEATURES_KEY)) { + final JsonArray features = JsonUtils.getJsonArray(jsonObject, JSON_FEATURES_KEY); - result = Stream.of( features ) - .allMatch( p -> AEConfig.instance().isFeatureEnabled( AEFeature.valueOf( p.getAsString().toUpperCase( Locale.ENGLISH ) ) ) ); - } - else if( JsonUtils.isString( jsonObject, JSON_FEATURES_KEY ) ) - { - final String featureName = JsonUtils.getString( jsonObject, JSON_FEATURES_KEY ).toUpperCase( Locale.ENGLISH ); - final AEFeature feature = AEFeature.valueOf( featureName ); + result = Stream.of(features) + .allMatch(p -> AEConfig.instance().isFeatureEnabled(AEFeature.valueOf(p.getAsString().toUpperCase(Locale.ENGLISH)))); + } else if (JsonUtils.isString(jsonObject, JSON_FEATURES_KEY)) { + final String featureName = JsonUtils.getString(jsonObject, JSON_FEATURES_KEY).toUpperCase(Locale.ENGLISH); + final AEFeature feature = AEFeature.valueOf(featureName); - result = AEConfig.instance().isFeatureEnabled( feature ); - } - else - { - result = false; - } + result = AEConfig.instance().isFeatureEnabled(feature); + } else { + result = false; + } - return () -> result; - } + return () -> result; + } } \ No newline at end of file diff --git a/src/main/java/appeng/recipes/factories/conditions/MaterialExists.java b/src/main/java/appeng/recipes/factories/conditions/MaterialExists.java index 25617d59f..487f2202e 100644 --- a/src/main/java/appeng/recipes/factories/conditions/MaterialExists.java +++ b/src/main/java/appeng/recipes/factories/conditions/MaterialExists.java @@ -19,40 +19,33 @@ package appeng.recipes.factories.conditions; -import java.util.function.BooleanSupplier; - +import appeng.core.Api; +import appeng.core.AppEng; import com.google.gson.JsonObject; - import net.minecraft.util.JsonUtils; import net.minecraftforge.common.crafting.IConditionFactory; import net.minecraftforge.common.crafting.JsonContext; -import appeng.core.Api; -import appeng.core.AppEng; +import java.util.function.BooleanSupplier; -public class MaterialExists implements IConditionFactory -{ - private static final String JSON_MATERIAL_KEY = "material"; +public class MaterialExists implements IConditionFactory { + private static final String JSON_MATERIAL_KEY = "material"; - @Override - public BooleanSupplier parse( JsonContext jsonContext, JsonObject jsonObject ) - { - final boolean result; + @Override + public BooleanSupplier parse(JsonContext jsonContext, JsonObject jsonObject) { + final boolean result; - if( JsonUtils.isString( jsonObject, JSON_MATERIAL_KEY ) ) - { - final String material = JsonUtils.getString( jsonObject, JSON_MATERIAL_KEY ); - final Object item = Api.INSTANCE.registries().recipes().resolveItem( AppEng.MOD_ID, material ); + if (JsonUtils.isString(jsonObject, JSON_MATERIAL_KEY)) { + final String material = JsonUtils.getString(jsonObject, JSON_MATERIAL_KEY); + final Object item = Api.INSTANCE.registries().recipes().resolveItem(AppEng.MOD_ID, material); - result = item != null; - } - else - { - result = false; - } + result = item != null; + } else { + result = false; + } - return () -> result; + return () -> result; - } + } } \ No newline at end of file diff --git a/src/main/java/appeng/recipes/factories/conditions/PartExists.java b/src/main/java/appeng/recipes/factories/conditions/PartExists.java index 4edc52f11..9ab9681db 100644 --- a/src/main/java/appeng/recipes/factories/conditions/PartExists.java +++ b/src/main/java/appeng/recipes/factories/conditions/PartExists.java @@ -14,19 +14,15 @@ public class PartExists implements IConditionFactory { private static final String JSON_MATERIAL_KEY = "part"; @Override - public BooleanSupplier parse(JsonContext jsonContext, JsonObject jsonObject ) - { + public BooleanSupplier parse(JsonContext jsonContext, JsonObject jsonObject) { final boolean result; - if( JsonUtils.isString( jsonObject, JSON_MATERIAL_KEY ) ) - { - final String part = JsonUtils.getString( jsonObject, JSON_MATERIAL_KEY ); - final Object item = Api.INSTANCE.registries().recipes().resolveItem( AppEng.MOD_ID, part ); + if (JsonUtils.isString(jsonObject, JSON_MATERIAL_KEY)) { + final String part = JsonUtils.getString(jsonObject, JSON_MATERIAL_KEY); + final Object item = Api.INSTANCE.registries().recipes().resolveItem(AppEng.MOD_ID, part); result = item != null; - } - else - { + } else { result = false; } diff --git a/src/main/java/appeng/recipes/factories/ingredients/PartIngredientFactory.java b/src/main/java/appeng/recipes/factories/ingredients/PartIngredientFactory.java index c3d3ab43d..84d6b9507 100644 --- a/src/main/java/appeng/recipes/factories/ingredients/PartIngredientFactory.java +++ b/src/main/java/appeng/recipes/factories/ingredients/PartIngredientFactory.java @@ -19,50 +19,43 @@ package appeng.recipes.factories.ingredients; -import javax.annotation.Nonnull; - -import com.google.gson.JsonObject; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraftforge.common.crafting.IIngredientFactory; -import net.minecraftforge.common.crafting.JsonContext; - import appeng.api.recipes.ResolverResult; import appeng.api.recipes.ResolverResultSet; import appeng.core.AELog; import appeng.core.Api; import appeng.core.AppEng; +import com.google.gson.JsonObject; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.crafting.IIngredientFactory; +import net.minecraftforge.common.crafting.JsonContext; + +import javax.annotation.Nonnull; -public class PartIngredientFactory implements IIngredientFactory -{ +public class PartIngredientFactory implements IIngredientFactory { - @Nonnull - @Override - public net.minecraft.item.crafting.Ingredient parse( JsonContext context, JsonObject json ) - { - final String partName = json.get( "part" ).getAsString(); - final Object result = Api.INSTANCE.registries().recipes().resolveItem( AppEng.MOD_ID, partName ); + @Nonnull + @Override + public net.minecraft.item.crafting.Ingredient parse(JsonContext context, JsonObject json) { + final String partName = json.get("part").getAsString(); + final Object result = Api.INSTANCE.registries().recipes().resolveItem(AppEng.MOD_ID, partName); - if( result instanceof ResolverResultSet ) - { - final ResolverResultSet resolverResultSet = (ResolverResultSet) result; + if (result instanceof ResolverResultSet) { + final ResolverResultSet resolverResultSet = (ResolverResultSet) result; - return net.minecraft.item.crafting.Ingredient - .fromStacks( resolverResultSet.results.toArray( new ItemStack[resolverResultSet.results.size()] ) ); - } - else if( result instanceof ResolverResult ) - { - final ResolverResult resolverResult = (ResolverResult) result; + return net.minecraft.item.crafting.Ingredient + .fromStacks(resolverResultSet.results.toArray(new ItemStack[resolverResultSet.results.size()])); + } else if (result instanceof ResolverResult) { + final ResolverResult resolverResult = (ResolverResult) result; - final Item item = Item.getByNameOrId( AppEng.MOD_ID + ":" + resolverResult.itemName ); - final ItemStack itemStack = new ItemStack( item, 1, resolverResult.damageValue, resolverResult.compound ); + final Item item = Item.getByNameOrId(AppEng.MOD_ID + ":" + resolverResult.itemName); + final ItemStack itemStack = new ItemStack(item, 1, resolverResult.damageValue, resolverResult.compound); - return net.minecraft.item.crafting.Ingredient.fromStacks( itemStack ); - } + return net.minecraft.item.crafting.Ingredient.fromStacks(itemStack); + } - AELog.warn( "Looking for ingredient with name '" + partName + "' ended up with a null item!" ); - return net.minecraft.item.crafting.Ingredient.EMPTY; - } + AELog.warn("Looking for ingredient with name '" + partName + "' ended up with a null item!"); + return net.minecraft.item.crafting.Ingredient.EMPTY; + } } \ No newline at end of file diff --git a/src/main/java/appeng/recipes/factories/recipes/PartRecipeFactory.java b/src/main/java/appeng/recipes/factories/recipes/PartRecipeFactory.java index f4b536cbd..de21749f7 100644 --- a/src/main/java/appeng/recipes/factories/recipes/PartRecipeFactory.java +++ b/src/main/java/appeng/recipes/factories/recipes/PartRecipeFactory.java @@ -19,17 +19,13 @@ package appeng.recipes.factories.recipes; -import java.util.Map; -import java.util.Set; - +import appeng.api.AEApi; +import appeng.api.recipes.ResolverResult; +import appeng.core.AELog; +import appeng.core.AppEng; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSyntaxException; - +import com.google.gson.*; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; @@ -43,170 +39,135 @@ import net.minecraftforge.common.crafting.JsonContext; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; -import appeng.api.AEApi; -import appeng.api.recipes.ResolverResult; -import appeng.core.AELog; -import appeng.core.AppEng; +import java.util.Map; +import java.util.Set; /** * @author GuntherDW */ -public class PartRecipeFactory implements IRecipeFactory -{ - @Override - public IRecipe parse( JsonContext context, JsonObject json ) - { - String type = JsonUtils.getString( json, "type" ); - if( type.contains( "shaped" ) ) - { - return shapedFactory( context, json ); - } - else if( type.contains( "shapeless" ) ) - { - return shapelessFactory( context, json ); - } - else - { - throw new JsonSyntaxException( "Applied Energistics 2 was given a custom recipe that it does not know how to handle!\n" + "Type should either be '" + AppEng.MOD_ID + ":shapeless' or '" + AppEng.MOD_ID + ":shaped', got '" + type + "'!" ); - } - } +public class PartRecipeFactory implements IRecipeFactory { + @Override + public IRecipe parse(JsonContext context, JsonObject json) { + String type = JsonUtils.getString(json, "type"); + if (type.contains("shaped")) { + return shapedFactory(context, json); + } else if (type.contains("shapeless")) { + return shapelessFactory(context, json); + } else { + throw new JsonSyntaxException("Applied Energistics 2 was given a custom recipe that it does not know how to handle!\n" + "Type should either be '" + AppEng.MOD_ID + ":shapeless' or '" + AppEng.MOD_ID + ":shaped', got '" + type + "'!"); + } + } - public static ItemStack getResult( JsonObject json, JsonContext context ) - { - return getResult( json, context, "result" ); - } + public static ItemStack getResult(JsonObject json, JsonContext context) { + return getResult(json, context, "result"); + } - public static ItemStack getResult( JsonObject json, JsonContext context, String name ) - { - JsonObject resultObject = JsonUtils.getJsonObject( json, name ); + public static ItemStack getResult(JsonObject json, JsonContext context, String name) { + JsonObject resultObject = JsonUtils.getJsonObject(json, name); - if( resultObject.has( "part" ) ) - { - return getPart( resultObject ); - } - else if( resultObject.has( "item" ) ) - { - return CraftingHelper.getItemStack( resultObject, context ); - } - else - { - throw new JsonSyntaxException( "Result has no 'part' or 'item' property." ); - } - } + if (resultObject.has("part")) { + return getPart(resultObject); + } else if (resultObject.has("item")) { + return CraftingHelper.getItemStack(resultObject, context); + } else { + throw new JsonSyntaxException("Result has no 'part' or 'item' property."); + } + } - private static ItemStack getPart( JsonObject resultObject ) - { - String ingredient = JsonUtils.getString( resultObject, "part" ); - Object result = AEApi.instance().registries().recipes().resolveItem( AppEng.MOD_ID, ingredient ); - if( result instanceof ResolverResult ) - { - ResolverResult resolverResult = (ResolverResult) result; + private static ItemStack getPart(JsonObject resultObject) { + String ingredient = JsonUtils.getString(resultObject, "part"); + Object result = AEApi.instance().registries().recipes().resolveItem(AppEng.MOD_ID, ingredient); + if (result instanceof ResolverResult) { + ResolverResult resolverResult = (ResolverResult) result; - Item item = Item.getByNameOrId( AppEng.MOD_ID + ":" + resolverResult.itemName ); + Item item = Item.getByNameOrId(AppEng.MOD_ID + ":" + resolverResult.itemName); - if( item == null ) - { - AELog.warn( "item was null for " + resolverResult.itemName + " ( " + ingredient + " )!" ); - throw new JsonSyntaxException( "Got a null item for " + resolverResult.itemName + " ( " + ingredient + " ). This should never happen!" ); - } + if (item == null) { + AELog.warn("item was null for " + resolverResult.itemName + " ( " + ingredient + " )!"); + throw new JsonSyntaxException("Got a null item for " + resolverResult.itemName + " ( " + ingredient + " ). This should never happen!"); + } - return new ItemStack( item, JsonUtils.getInt( resultObject, "count", 1 ), resolverResult.damageValue, resolverResult.compound ); - } - else - { - throw new JsonSyntaxException( "Couldn't find the resulting item in AE. This means AE was provided a recipe that it shouldn't be handling.\n" + "Was looking for : '" + ingredient + "'." ); - } - } + return new ItemStack(item, JsonUtils.getInt(resultObject, "count", 1), resolverResult.damageValue, resolverResult.compound); + } else { + throw new JsonSyntaxException("Couldn't find the resulting item in AE. This means AE was provided a recipe that it shouldn't be handling.\n" + "Was looking for : '" + ingredient + "'."); + } + } - // Copied from ShapedOreRecipe.java, modified a bit. - private static ShapedOreRecipe shapedFactory( JsonContext context, JsonObject json ) - { - String group = JsonUtils.getString( json, "group", "" ); + // Copied from ShapedOreRecipe.java, modified a bit. + private static ShapedOreRecipe shapedFactory(JsonContext context, JsonObject json) { + String group = JsonUtils.getString(json, "group", ""); - Map ingMap = Maps.newHashMap(); - for( Map.Entry entry : JsonUtils.getJsonObject( json, "key" ).entrySet() ) - { - if( entry.getKey().length() != 1 ) - { - throw new JsonSyntaxException( "Invalid key entry: '" + entry.getKey() + "' is an invalid symbol (must be 1 character only)." ); - } - if( " ".equals( entry.getKey() ) ) - { - throw new JsonSyntaxException( "Invalid key entry: ' ' is a reserved symbol." ); - } + Map ingMap = Maps.newHashMap(); + for (Map.Entry entry : JsonUtils.getJsonObject(json, "key").entrySet()) { + if (entry.getKey().length() != 1) { + throw new JsonSyntaxException("Invalid key entry: '" + entry.getKey() + "' is an invalid symbol (must be 1 character only)."); + } + if (" ".equals(entry.getKey())) { + throw new JsonSyntaxException("Invalid key entry: ' ' is a reserved symbol."); + } - ingMap.put( entry.getKey().toCharArray()[0], CraftingHelper.getIngredient( entry.getValue(), context ) ); - } + ingMap.put(entry.getKey().toCharArray()[0], CraftingHelper.getIngredient(entry.getValue(), context)); + } - ingMap.put( ' ', net.minecraft.item.crafting.Ingredient.EMPTY ); + ingMap.put(' ', net.minecraft.item.crafting.Ingredient.EMPTY); - JsonArray patternJ = JsonUtils.getJsonArray( json, "pattern" ); + JsonArray patternJ = JsonUtils.getJsonArray(json, "pattern"); - if( patternJ.size() == 0 ) - { - throw new JsonSyntaxException( "Invalid pattern: empty pattern not allowed" ); - } + if (patternJ.size() == 0) { + throw new JsonSyntaxException("Invalid pattern: empty pattern not allowed"); + } - String[] pattern = new String[patternJ.size()]; - for( int x = 0; x < pattern.length; ++x ) - { - String line = JsonUtils.getString( patternJ.get( x ), "pattern[" + x + "]" ); - if( x > 0 && pattern[0].length() != line.length() ) - { - throw new JsonSyntaxException( "Invalid pattern: each row must be the same width" ); - } - pattern[x] = line; - } + String[] pattern = new String[patternJ.size()]; + for (int x = 0; x < pattern.length; ++x) { + String line = JsonUtils.getString(patternJ.get(x), "pattern[" + x + "]"); + if (x > 0 && pattern[0].length() != line.length()) { + throw new JsonSyntaxException("Invalid pattern: each row must be the same width"); + } + pattern[x] = line; + } - CraftingHelper.ShapedPrimer primer = new CraftingHelper.ShapedPrimer(); - primer.width = pattern[0].length(); - primer.height = pattern.length; - primer.mirrored = JsonUtils.getBoolean( json, "mirrored", true ); - primer.input = NonNullList.withSize( primer.width * primer.height, net.minecraft.item.crafting.Ingredient.EMPTY ); + CraftingHelper.ShapedPrimer primer = new CraftingHelper.ShapedPrimer(); + primer.width = pattern[0].length(); + primer.height = pattern.length; + primer.mirrored = JsonUtils.getBoolean(json, "mirrored", true); + primer.input = NonNullList.withSize(primer.width * primer.height, net.minecraft.item.crafting.Ingredient.EMPTY); - Set keys = Sets.newHashSet( ingMap.keySet() ); - keys.remove( ' ' ); + Set keys = Sets.newHashSet(ingMap.keySet()); + keys.remove(' '); - int x = 0; - for( String line : pattern ) - { - for( char chr : line.toCharArray() ) - { - net.minecraft.item.crafting.Ingredient ing = ingMap.get( chr ); - if( ing == null ) - { - throw new JsonSyntaxException( "Pattern references symbol '" + chr + "' but it's not defined in the key" ); - } - primer.input.set( x++, ing ); - keys.remove( chr ); - } - } + int x = 0; + for (String line : pattern) { + for (char chr : line.toCharArray()) { + net.minecraft.item.crafting.Ingredient ing = ingMap.get(chr); + if (ing == null) { + throw new JsonSyntaxException("Pattern references symbol '" + chr + "' but it's not defined in the key"); + } + primer.input.set(x++, ing); + keys.remove(chr); + } + } - if( !keys.isEmpty() ) - { - throw new JsonSyntaxException( "Key defines symbols that aren't used in pattern: " + keys ); - } + if (!keys.isEmpty()) { + throw new JsonSyntaxException("Key defines symbols that aren't used in pattern: " + keys); + } - return new ShapedOreRecipe( group.isEmpty() ? null : new ResourceLocation( group ), getResult( json, context ), primer ); - } + return new ShapedOreRecipe(group.isEmpty() ? null : new ResourceLocation(group), getResult(json, context), primer); + } - // Copied from ShapelessOreRecipe.java, modified a bit. - private static ShapelessOreRecipe shapelessFactory( JsonContext context, JsonObject json ) - { - String group = JsonUtils.getString( json, "group", "" ); + // Copied from ShapelessOreRecipe.java, modified a bit. + private static ShapelessOreRecipe shapelessFactory(JsonContext context, JsonObject json) { + String group = JsonUtils.getString(json, "group", ""); - NonNullList ings = NonNullList.create(); - for( JsonElement ele : JsonUtils.getJsonArray( json, "ingredients" ) ) - { - ings.add( CraftingHelper.getIngredient( ele, context ) ); - } + NonNullList ings = NonNullList.create(); + for (JsonElement ele : JsonUtils.getJsonArray(json, "ingredients")) { + ings.add(CraftingHelper.getIngredient(ele, context)); + } - if( ings.isEmpty() ) - { - throw new JsonParseException( "No ingredients for shapeless recipe" ); - } + if (ings.isEmpty()) { + throw new JsonParseException("No ingredients for shapeless recipe"); + } - return new ShapelessOreRecipe( group.isEmpty() ? null : new ResourceLocation( group ), ings, getResult( json, context ) ); - } + return new ShapelessOreRecipe(group.isEmpty() ? null : new ResourceLocation(group), ings, getResult(json, context)); + } } diff --git a/src/main/java/appeng/recipes/game/DisassembleRecipe.java b/src/main/java/appeng/recipes/game/DisassembleRecipe.java index eb179001c..749928517 100644 --- a/src/main/java/appeng/recipes/game/DisassembleRecipe.java +++ b/src/main/java/appeng/recipes/game/DisassembleRecipe.java @@ -19,13 +19,12 @@ package appeng.recipes.game; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - +import appeng.api.AEApi; +import appeng.api.definitions.*; +import appeng.api.storage.IMEInventory; +import appeng.api.storage.channels.IItemStorageChannel; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; @@ -34,154 +33,130 @@ import net.minecraft.util.NonNullList; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; -import appeng.api.AEApi; -import appeng.api.definitions.IBlocks; -import appeng.api.definitions.IDefinitions; -import appeng.api.definitions.IItemDefinition; -import appeng.api.definitions.IItems; -import appeng.api.definitions.IMaterials; -import appeng.api.storage.IMEInventory; -import appeng.api.storage.channels.IItemStorageChannel; -import appeng.api.storage.data.IAEItemStack; -import appeng.api.storage.data.IItemList; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; -public final class DisassembleRecipe extends net.minecraftforge.registries.IForgeRegistryEntry.Impl implements IRecipe -{ - private static final ItemStack MISMATCHED_STACK = ItemStack.EMPTY; +public final class DisassembleRecipe extends net.minecraftforge.registries.IForgeRegistryEntry.Impl implements IRecipe { + private static final ItemStack MISMATCHED_STACK = ItemStack.EMPTY; - private final Map cellMappings; - private final Map nonCellMappings; + private final Map cellMappings; + private final Map nonCellMappings; - public DisassembleRecipe() - { - final IDefinitions definitions = AEApi.instance().definitions(); - final IBlocks blocks = definitions.blocks(); - final IItems items = definitions.items(); - final IMaterials mats = definitions.materials(); + public DisassembleRecipe() { + final IDefinitions definitions = AEApi.instance().definitions(); + final IBlocks blocks = definitions.blocks(); + final IItems items = definitions.items(); + final IMaterials mats = definitions.materials(); - this.cellMappings = new HashMap<>( 4 ); - this.nonCellMappings = new HashMap<>( 5 ); + this.cellMappings = new HashMap<>(4); + this.nonCellMappings = new HashMap<>(5); - this.cellMappings.put( items.cell1k(), mats.cell1kPart() ); - this.cellMappings.put( items.cell4k(), mats.cell4kPart() ); - this.cellMappings.put( items.cell16k(), mats.cell16kPart() ); - this.cellMappings.put( items.cell64k(), mats.cell64kPart() ); + this.cellMappings.put(items.cell1k(), mats.cell1kPart()); + this.cellMappings.put(items.cell4k(), mats.cell4kPart()); + this.cellMappings.put(items.cell16k(), mats.cell16kPart()); + this.cellMappings.put(items.cell64k(), mats.cell64kPart()); - this.nonCellMappings.put( items.encodedPattern(), mats.blankPattern() ); - this.nonCellMappings.put( blocks.craftingStorage1k(), mats.cell1kPart() ); - this.nonCellMappings.put( blocks.craftingStorage4k(), mats.cell4kPart() ); - this.nonCellMappings.put( blocks.craftingStorage16k(), mats.cell16kPart() ); - this.nonCellMappings.put( blocks.craftingStorage64k(), mats.cell64kPart() ); - } + this.nonCellMappings.put(items.encodedPattern(), mats.blankPattern()); + this.nonCellMappings.put(blocks.craftingStorage1k(), mats.cell1kPart()); + this.nonCellMappings.put(blocks.craftingStorage4k(), mats.cell4kPart()); + this.nonCellMappings.put(blocks.craftingStorage16k(), mats.cell16kPart()); + this.nonCellMappings.put(blocks.craftingStorage64k(), mats.cell64kPart()); + } - @Override - public boolean matches( final InventoryCrafting inv, final World w ) - { - return !this.getOutput( inv ).isEmpty(); - } + @Override + public boolean matches(final InventoryCrafting inv, final World w) { + return !this.getOutput(inv).isEmpty(); + } - @Nullable - private ItemStack getOutput( final IInventory inventory ) - { - int itemCount = 0; - ItemStack output = MISMATCHED_STACK; + @Nullable + private ItemStack getOutput(final IInventory inventory) { + int itemCount = 0; + ItemStack output = MISMATCHED_STACK; - for( int slotIndex = 0; slotIndex < inventory.getSizeInventory(); slotIndex++ ) - { - final ItemStack stackInSlot = inventory.getStackInSlot( slotIndex ); - if( !stackInSlot.isEmpty() ) - { - // needs a single input in the recipe - itemCount++; - if( itemCount > 1 ) - { - return MISMATCHED_STACK; - } + for (int slotIndex = 0; slotIndex < inventory.getSizeInventory(); slotIndex++) { + final ItemStack stackInSlot = inventory.getStackInSlot(slotIndex); + if (!stackInSlot.isEmpty()) { + // needs a single input in the recipe + itemCount++; + if (itemCount > 1) { + return MISMATCHED_STACK; + } - // handle storage cells - Optional maybeCellOutput = this.getCellOutput( stackInSlot ); - if( maybeCellOutput.isPresent() ) - { - ItemStack storageCellStack = maybeCellOutput.get(); - // make sure the storage cell stackInSlot empty... - final IMEInventory cellInv = AEApi.instance() - .registries() - .cell() - .getCellInventory( stackInSlot, null, - AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - if( cellInv != null ) - { - final IItemList list = cellInv - .getAvailableItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList() ); - if( !list.isEmpty() ) - { - return ItemStack.EMPTY; - } - } + // handle storage cells + Optional maybeCellOutput = this.getCellOutput(stackInSlot); + if (maybeCellOutput.isPresent()) { + ItemStack storageCellStack = maybeCellOutput.get(); + // make sure the storage cell stackInSlot empty... + final IMEInventory cellInv = AEApi.instance() + .registries() + .cell() + .getCellInventory(stackInSlot, null, + AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + if (cellInv != null) { + final IItemList list = cellInv + .getAvailableItems(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList()); + if (!list.isEmpty()) { + return ItemStack.EMPTY; + } + } - output = storageCellStack; - } + output = storageCellStack; + } - // handle crafting storage blocks - output = this.getNonCellOutput( stackInSlot ).orElse( output ); - } - } + // handle crafting storage blocks + output = this.getNonCellOutput(stackInSlot).orElse(output); + } + } - return output; - } + return output; + } - @Nonnull - private Optional getCellOutput( final ItemStack compared ) - { - for( final Map.Entry entry : this.cellMappings.entrySet() ) - { - if( entry.getKey().isSameAs( compared ) ) - { - return entry.getValue().maybeStack( 1 ); - } - } + @Nonnull + private Optional getCellOutput(final ItemStack compared) { + for (final Map.Entry entry : this.cellMappings.entrySet()) { + if (entry.getKey().isSameAs(compared)) { + return entry.getValue().maybeStack(1); + } + } - return Optional.empty(); - } + return Optional.empty(); + } - @Nonnull - private Optional getNonCellOutput( final ItemStack compared ) - { - for( final Map.Entry entry : this.nonCellMappings.entrySet() ) - { - if( entry.getKey().isSameAs( compared ) ) - { - return entry.getValue().maybeStack( 1 ); - } - } + @Nonnull + private Optional getNonCellOutput(final ItemStack compared) { + for (final Map.Entry entry : this.nonCellMappings.entrySet()) { + if (entry.getKey().isSameAs(compared)) { + return entry.getValue().maybeStack(1); + } + } - return Optional.empty(); - } + return Optional.empty(); + } - @Nullable - @Override - public ItemStack getCraftingResult( final InventoryCrafting inv ) - { - return this.getOutput( inv ); - } + @Nullable + @Override + public ItemStack getCraftingResult(final InventoryCrafting inv) { + return this.getOutput(inv); + } - @Override - public boolean canFit( int i, int i1 ) - { - return false; - } + @Override + public boolean canFit(int i, int i1) { + return false; + } - @Nullable - @Override - public ItemStack getRecipeOutput() // no default output.. - { - return ItemStack.EMPTY; - } + @Nullable + @Override + public ItemStack getRecipeOutput() // no default output.. + { + return ItemStack.EMPTY; + } - @Override - public NonNullList getRemainingItems( final InventoryCrafting inv ) - { - return ForgeHooks.defaultRecipeGetRemainingItems( inv ); - } + @Override + public NonNullList getRemainingItems(final InventoryCrafting inv) { + return ForgeHooks.defaultRecipeGetRemainingItems(inv); + } } \ No newline at end of file diff --git a/src/main/java/appeng/recipes/game/FacadeRecipe.java b/src/main/java/appeng/recipes/game/FacadeRecipe.java index 47d2d0119..b2f9bf28d 100644 --- a/src/main/java/appeng/recipes/game/FacadeRecipe.java +++ b/src/main/java/appeng/recipes/game/FacadeRecipe.java @@ -19,8 +19,10 @@ package appeng.recipes.game; -import javax.annotation.Nullable; - +import appeng.api.AEApi; +import appeng.api.definitions.IComparableDefinition; +import appeng.api.definitions.IDefinitions; +import appeng.items.parts.ItemFacade; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; @@ -29,72 +31,59 @@ import net.minecraft.util.NonNullList; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; -import appeng.api.AEApi; -import appeng.api.definitions.IComparableDefinition; -import appeng.api.definitions.IDefinitions; -import appeng.items.parts.ItemFacade; +import javax.annotation.Nullable; -public final class FacadeRecipe extends net.minecraftforge.registries.IForgeRegistryEntry.Impl implements IRecipe -{ - private final IComparableDefinition anchor; - private final ItemFacade facade; +public final class FacadeRecipe extends net.minecraftforge.registries.IForgeRegistryEntry.Impl implements IRecipe { + private final IComparableDefinition anchor; + private final ItemFacade facade; - public FacadeRecipe( ItemFacade facade ) - { - this.facade = facade; - final IDefinitions definitions = AEApi.instance().definitions(); + public FacadeRecipe(ItemFacade facade) { + this.facade = facade; + final IDefinitions definitions = AEApi.instance().definitions(); - this.anchor = definitions.parts().cableAnchor(); - } + this.anchor = definitions.parts().cableAnchor(); + } - @Override - public boolean matches( final InventoryCrafting inv, final World w ) - { - return !this.getOutput( inv, false ).isEmpty(); - } + @Override + public boolean matches(final InventoryCrafting inv, final World w) { + return !this.getOutput(inv, false).isEmpty(); + } - @Nullable - private ItemStack getOutput( final IInventory inv, final boolean createFacade ) - { - if( inv.getStackInSlot( 0 ).isEmpty() && inv.getStackInSlot( 2 ).isEmpty() && inv.getStackInSlot( 6 ).isEmpty() && inv.getStackInSlot( 8 ).isEmpty() ) - { - if( this.anchor.isSameAs( inv.getStackInSlot( 1 ) ) && this.anchor.isSameAs( inv.getStackInSlot( 3 ) ) && this.anchor - .isSameAs( inv.getStackInSlot( 5 ) ) && this.anchor.isSameAs( inv.getStackInSlot( 7 ) ) ) - { - final ItemStack facades = this.facade.createFacadeForItem( inv.getStackInSlot( 4 ), !createFacade ); - if( !facades.isEmpty() && createFacade ) - { - facades.setCount( 4 ); - } - return facades; - } - } + @Nullable + private ItemStack getOutput(final IInventory inv, final boolean createFacade) { + if (inv.getStackInSlot(0).isEmpty() && inv.getStackInSlot(2).isEmpty() && inv.getStackInSlot(6).isEmpty() && inv.getStackInSlot(8).isEmpty()) { + if (this.anchor.isSameAs(inv.getStackInSlot(1)) && this.anchor.isSameAs(inv.getStackInSlot(3)) && this.anchor + .isSameAs(inv.getStackInSlot(5)) && this.anchor.isSameAs(inv.getStackInSlot(7))) { + final ItemStack facades = this.facade.createFacadeForItem(inv.getStackInSlot(4), !createFacade); + if (!facades.isEmpty() && createFacade) { + facades.setCount(4); + } + return facades; + } + } - return ItemStack.EMPTY; - } + return ItemStack.EMPTY; + } - @Override - public ItemStack getCraftingResult( final InventoryCrafting inv ) - { - return this.getOutput( inv, true ); - } + @Override + public ItemStack getCraftingResult(final InventoryCrafting inv) { + return this.getOutput(inv, true); + } - @Override - public boolean canFit( int i, int i1 ) - { - return false; - } + @Override + public boolean canFit(int i, int i1) { + return false; + } - @Override - public ItemStack getRecipeOutput() // no default output.. - { - return ItemStack.EMPTY; - } + @Override + public ItemStack getRecipeOutput() // no default output.. + { + return ItemStack.EMPTY; + } - @Override - public NonNullList getRemainingItems( final InventoryCrafting inv ) - { - return ForgeHooks.defaultRecipeGetRemainingItems( inv ); - } + @Override + public NonNullList getRemainingItems(final InventoryCrafting inv) { + return ForgeHooks.defaultRecipeGetRemainingItems(inv); + } } \ No newline at end of file diff --git a/src/main/java/appeng/recipes/handlers/GrinderHandler.java b/src/main/java/appeng/recipes/handlers/GrinderHandler.java index d734c8ce6..bafdb067e 100644 --- a/src/main/java/appeng/recipes/handlers/GrinderHandler.java +++ b/src/main/java/appeng/recipes/handlers/GrinderHandler.java @@ -1,49 +1,42 @@ - package appeng.recipes.handlers; -import com.google.gson.JsonObject; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.JsonUtils; -import net.minecraftforge.common.crafting.CraftingHelper; -import net.minecraftforge.common.crafting.JsonContext; - import appeng.api.AEApi; import appeng.api.features.IGrinderRecipeBuilder; import appeng.api.features.IGrinderRegistry; import appeng.recipes.IAERecipeFactory; import appeng.recipes.factories.recipes.PartRecipeFactory; +import com.google.gson.JsonObject; +import net.minecraft.item.ItemStack; +import net.minecraft.util.JsonUtils; +import net.minecraftforge.common.crafting.CraftingHelper; +import net.minecraftforge.common.crafting.JsonContext; -public class GrinderHandler implements IAERecipeFactory -{ +public class GrinderHandler implements IAERecipeFactory { - @Override - public void register( JsonObject json, JsonContext ctx ) - { - // TODO only primary for now + @Override + public void register(JsonObject json, JsonContext ctx) { + // TODO only primary for now - JsonObject result = JsonUtils.getJsonObject( json, "result" ); - ItemStack primary = PartRecipeFactory.getResult( result, ctx, "primary" ); - ItemStack[] input = CraftingHelper.getIngredient( json.get( "input" ), ctx ).getMatchingStacks(); + JsonObject result = JsonUtils.getJsonObject(json, "result"); + ItemStack primary = PartRecipeFactory.getResult(result, ctx, "primary"); + ItemStack[] input = CraftingHelper.getIngredient(json.get("input"), ctx).getMatchingStacks(); - int turns = 5; - if( json.has( "turns" ) ) - { - turns = JsonUtils.getInt( json, "turns" ); - } + int turns = 5; + if (json.has("turns")) { + turns = JsonUtils.getInt(json, "turns"); + } - final IGrinderRegistry reg = AEApi.instance().registries().grinder(); - for( int i = 0; i < input.length; ++i ) - { - final IGrinderRecipeBuilder builder = reg.builder(); + final IGrinderRegistry reg = AEApi.instance().registries().grinder(); + for (int i = 0; i < input.length; ++i) { + final IGrinderRecipeBuilder builder = reg.builder(); - builder.withOutput( primary ); - builder.withInput( input[i] ); - builder.withTurns( turns ); + builder.withOutput(primary); + builder.withInput(input[i]); + builder.withTurns(turns); - reg.addRecipe( builder.build() ); - } - } + reg.addRecipe(builder.build()); + } + } } diff --git a/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java b/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java index 037b76e82..b6f208e9a 100644 --- a/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java +++ b/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java @@ -19,17 +19,15 @@ package appeng.recipes.handlers; -import net.minecraft.item.ItemStack; - import appeng.api.exceptions.MissingIngredientException; import appeng.api.exceptions.RegistrationException; import appeng.recipes.RecipeHandler; +import net.minecraft.item.ItemStack; -public interface IWebsiteSerializer -{ +public interface IWebsiteSerializer { - String getPattern( RecipeHandler han ); + String getPattern(RecipeHandler han); - boolean canCraft( ItemStack output ) throws RegistrationException, MissingIngredientException; + boolean canCraft(ItemStack output) throws RegistrationException, MissingIngredientException; } diff --git a/src/main/java/appeng/recipes/handlers/InscriberHandler.java b/src/main/java/appeng/recipes/handlers/InscriberHandler.java index dd6962f2d..63ec9dee0 100644 --- a/src/main/java/appeng/recipes/handlers/InscriberHandler.java +++ b/src/main/java/appeng/recipes/handlers/InscriberHandler.java @@ -1,71 +1,60 @@ - package appeng.recipes.handlers; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.JsonObject; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.JsonUtils; -import net.minecraftforge.common.crafting.CraftingHelper; -import net.minecraftforge.common.crafting.JsonContext; - import appeng.api.AEApi; import appeng.api.features.IInscriberRecipeBuilder; import appeng.api.features.IInscriberRegistry; import appeng.api.features.InscriberProcessType; import appeng.recipes.IAERecipeFactory; import appeng.recipes.factories.recipes.PartRecipeFactory; +import com.google.gson.JsonObject; +import net.minecraft.item.ItemStack; +import net.minecraft.util.JsonUtils; +import net.minecraftforge.common.crafting.CraftingHelper; +import net.minecraftforge.common.crafting.JsonContext; + +import java.util.Arrays; +import java.util.List; -public class InscriberHandler implements IAERecipeFactory -{ +public class InscriberHandler implements IAERecipeFactory { - @Override - public void register( JsonObject json, JsonContext ctx ) - { - ItemStack result = PartRecipeFactory.getResult( json, ctx ); - String mode = JsonUtils.getString( json, "mode" ); + @Override + public void register(JsonObject json, JsonContext ctx) { + ItemStack result = PartRecipeFactory.getResult(json, ctx); + String mode = JsonUtils.getString(json, "mode"); - JsonObject ingredients = JsonUtils.getJsonObject( json, "ingredients" ); + JsonObject ingredients = JsonUtils.getJsonObject(json, "ingredients"); - List middle = Arrays.asList( CraftingHelper.getIngredient( ingredients.get( "middle" ), ctx ).getMatchingStacks() ); - ItemStack[] top = new ItemStack[] { null }; - if( ingredients.has( "top" ) ) - { - top = CraftingHelper.getIngredient( JsonUtils.getJsonObject( ingredients, "top" ), ctx ).getMatchingStacks(); - } + List middle = Arrays.asList(CraftingHelper.getIngredient(ingredients.get("middle"), ctx).getMatchingStacks()); + ItemStack[] top = new ItemStack[]{null}; + if (ingredients.has("top")) { + top = CraftingHelper.getIngredient(JsonUtils.getJsonObject(ingredients, "top"), ctx).getMatchingStacks(); + } - ItemStack[] bottom = new ItemStack[] { null }; - if( ingredients.has( "bottom" ) ) - { - bottom = CraftingHelper.getIngredient( JsonUtils.getJsonObject( ingredients, "bottom" ), ctx ).getMatchingStacks(); - } + ItemStack[] bottom = new ItemStack[]{null}; + if (ingredients.has("bottom")) { + bottom = CraftingHelper.getIngredient(JsonUtils.getJsonObject(ingredients, "bottom"), ctx).getMatchingStacks(); + } - final IInscriberRegistry reg = AEApi.instance().registries().inscriber(); - for( int i = 0; i < top.length; ++i ) - { - for( int j = 0; j < bottom.length; ++j ) - { - final IInscriberRecipeBuilder builder = reg.builder(); - builder.withOutput( result ); - builder.withProcessType( "press".equals( mode ) ? InscriberProcessType.PRESS : InscriberProcessType.INSCRIBE ); - builder.withInputs( middle ); + final IInscriberRegistry reg = AEApi.instance().registries().inscriber(); + for (int i = 0; i < top.length; ++i) { + for (int j = 0; j < bottom.length; ++j) { + final IInscriberRecipeBuilder builder = reg.builder(); + builder.withOutput(result); + builder.withProcessType("press".equals(mode) ? InscriberProcessType.PRESS : InscriberProcessType.INSCRIBE); + builder.withInputs(middle); - if( top[i] != null ) - { - builder.withTopOptional( top[i] ); - } - if( bottom[j] != null ) - { - builder.withBottomOptional( bottom[j] ); - } + if (top[i] != null) { + builder.withTopOptional(top[i]); + } + if (bottom[j] != null) { + builder.withBottomOptional(bottom[j]); + } - reg.addRecipe( builder.build() ); - } - } - } + reg.addRecipe(builder.build()); + } + } + } } diff --git a/src/main/java/appeng/recipes/handlers/SmeltingHandler.java b/src/main/java/appeng/recipes/handlers/SmeltingHandler.java index 0dc466bc8..4dd01105d 100644 --- a/src/main/java/appeng/recipes/handlers/SmeltingHandler.java +++ b/src/main/java/appeng/recipes/handlers/SmeltingHandler.java @@ -1,36 +1,29 @@ - package appeng.recipes.handlers; +import appeng.recipes.IAERecipeFactory; +import appeng.recipes.factories.recipes.PartRecipeFactory; import com.google.gson.JsonObject; - import net.minecraft.item.ItemStack; import net.minecraft.util.JsonUtils; import net.minecraftforge.common.crafting.CraftingHelper; import net.minecraftforge.common.crafting.JsonContext; import net.minecraftforge.fml.common.registry.GameRegistry; -import appeng.recipes.IAERecipeFactory; -import appeng.recipes.factories.recipes.PartRecipeFactory; +public class SmeltingHandler implements IAERecipeFactory { + @Override + public void register(JsonObject json, JsonContext ctx) { + ItemStack result = PartRecipeFactory.getResult(json, ctx); + ItemStack[] input = CraftingHelper.getIngredient(json.get("input"), ctx).getMatchingStacks(); + float xp = 0.0f; + if (json.has("xp")) { + xp = JsonUtils.getFloat(json, "xp"); + } -public class SmeltingHandler implements IAERecipeFactory -{ - @Override - public void register( JsonObject json, JsonContext ctx ) - { - ItemStack result = PartRecipeFactory.getResult( json, ctx ); - ItemStack[] input = CraftingHelper.getIngredient( json.get( "input" ), ctx ).getMatchingStacks(); - float xp = 0.0f; - if( json.has( "xp" ) ) - { - xp = JsonUtils.getFloat( json, "xp" ); - } - - for( int i = 0; i < input.length; ++i ) - { - GameRegistry.addSmelting( input[i], result, xp ); - } - } + for (int i = 0; i < input.length; ++i) { + GameRegistry.addSmelting(input[i], result, xp); + } + } } diff --git a/src/main/java/appeng/recipes/ores/IOreListener.java b/src/main/java/appeng/recipes/ores/IOreListener.java index 404883719..b1ab478e9 100644 --- a/src/main/java/appeng/recipes/ores/IOreListener.java +++ b/src/main/java/appeng/recipes/ores/IOreListener.java @@ -22,15 +22,14 @@ package appeng.recipes.ores; import net.minecraft.item.ItemStack; -public interface IOreListener -{ +public interface IOreListener { - /** - * Called with various items registered in the dictionary. - * AppEng.oreDictionary.observe(...) to register them. - * - * @param name name of ore - * @param item item with name - */ - void oreRegistered( String name, ItemStack item ); + /** + * Called with various items registered in the dictionary. + * AppEng.oreDictionary.observe(...) to register them. + * + * @param name name of ore + * @param item item with name + */ + void oreRegistered(String name, ItemStack item); } diff --git a/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java b/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java index a294df76d..2b73c5cf2 100644 --- a/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java +++ b/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java @@ -19,73 +19,61 @@ package appeng.recipes.ores; -import java.util.ArrayList; -import java.util.List; - import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.oredict.OreDictionary; +import java.util.ArrayList; +import java.util.List; -public class OreDictionaryHandler -{ - public static final OreDictionaryHandler INSTANCE = new OreDictionaryHandler(); +public class OreDictionaryHandler { - private final List oreListeners = new ArrayList<>(); + public static final OreDictionaryHandler INSTANCE = new OreDictionaryHandler(); - @SubscribeEvent - public void onOreDictionaryRegister( final OreDictionary.OreRegisterEvent event ) - { - if( event.getName() == null || event.getOre().isEmpty() ) - { - return; - } + private final List oreListeners = new ArrayList<>(); - if( this.shouldCare( event.getName() ) ) - { - for( final IOreListener v : this.oreListeners ) - { - v.oreRegistered( event.getName(), event.getOre() ); - } - } - } + @SubscribeEvent + public void onOreDictionaryRegister(final OreDictionary.OreRegisterEvent event) { + if (event.getName() == null || event.getOre().isEmpty()) { + return; + } - /** - * Just limit what items are sent to the final listeners, I got sick of strange items showing up... - * - * @param name name about cared item - * - * @return true if it should care - */ - private boolean shouldCare( final String name ) - { - return true; - } + if (this.shouldCare(event.getName())) { + for (final IOreListener v : this.oreListeners) { + v.oreRegistered(event.getName(), event.getOre()); + } + } + } - /** - * Adds a new IOreListener and immediately notifies it of any previous ores, any ores added latter will be added at - * that point. - * - * @param n to be added ore listener - */ - public void observe( final IOreListener n ) - { - this.oreListeners.add( n ); + /** + * Just limit what items are sent to the final listeners, I got sick of strange items showing up... + * + * @param name name about cared item + * @return true if it should care + */ + private boolean shouldCare(final String name) { + return true; + } - // notify the listener of any ore already in existence. - for( final String name : OreDictionary.getOreNames() ) - { - if( name != null && this.shouldCare( name ) ) - { - for( final ItemStack item : OreDictionary.getOres( name ) ) - { - if( !item.isEmpty() ) - { - n.oreRegistered( name, item ); - } - } - } - } - } + /** + * Adds a new IOreListener and immediately notifies it of any previous ores, any ores added latter will be added at + * that point. + * + * @param n to be added ore listener + */ + public void observe(final IOreListener n) { + this.oreListeners.add(n); + + // notify the listener of any ore already in existence. + for (final String name : OreDictionary.getOreNames()) { + if (name != null && this.shouldCare(name)) { + for (final ItemStack item : OreDictionary.getOres(name)) { + if (!item.isEmpty()) { + n.oreRegistered(name, item); + } + } + } + } + } } diff --git a/src/main/java/appeng/server/AECommand.java b/src/main/java/appeng/server/AECommand.java index 4d274a1db..c2ceefa20 100644 --- a/src/main/java/appeng/server/AECommand.java +++ b/src/main/java/appeng/server/AECommand.java @@ -20,7 +20,6 @@ package appeng.server; import com.google.common.base.Joiner; - import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; @@ -28,85 +27,58 @@ import net.minecraft.command.WrongUsageException; import net.minecraft.server.MinecraftServer; -public final class AECommand extends CommandBase -{ - private final MinecraftServer srv; +public final class AECommand extends CommandBase { + private final MinecraftServer srv; - public AECommand( final MinecraftServer server ) - { - this.srv = server; - } + public AECommand(final MinecraftServer server) { + this.srv = server; + } - @Override - public int getRequiredPermissionLevel() - { - return 0; - } + @Override + public int getRequiredPermissionLevel() { + return 0; + } - @Override - public String getName() - { - return "ae2"; - } + @Override + public String getName() { + return "ae2"; + } - @Override - public String getUsage( final ICommandSender icommandsender ) - { - return "commands.ae2.usage"; - } + @Override + public String getUsage(final ICommandSender icommandsender) { + return "commands.ae2.usage"; + } - @Override - public void execute( final MinecraftServer server, final ICommandSender sender, final String[] args ) throws CommandException - { - if( args.length == 0 ) - { - throw new WrongUsageException( "commands.ae2.usage" ); - } - else if( "help".equals( args[0] ) ) - { - try - { - if( args.length > 1 ) - { - final Commands c = Commands.valueOf( args[1] ); - throw new WrongUsageException( c.command.getHelp( this.srv ) ); - } - } - catch( final WrongUsageException wrong ) - { - throw wrong; - } - catch( final Throwable er ) - { - throw new WrongUsageException( "commands.ae2.usage" ); - } - } - else if( "list".equals( args[0] ) ) - { - throw new WrongUsageException( Joiner.on( ", " ).join( Commands.values() ) ); - } - else - { - try - { - final Commands c = Commands.valueOf( args[0] ); - if( sender.canUseCommand( c.level, this.getName() ) ) - { - c.command.call( this.srv, args, sender ); - } - else - { - throw new WrongUsageException( "commands.ae2.permissions" ); - } - } - catch( final WrongUsageException wrong ) - { - throw wrong; - } - catch( final Throwable er ) - { - throw new WrongUsageException( "commands.ae2.usage" ); - } - } - } + @Override + public void execute(final MinecraftServer server, final ICommandSender sender, final String[] args) throws CommandException { + if (args.length == 0) { + throw new WrongUsageException("commands.ae2.usage"); + } else if ("help".equals(args[0])) { + try { + if (args.length > 1) { + final Commands c = Commands.valueOf(args[1]); + throw new WrongUsageException(c.command.getHelp(this.srv)); + } + } catch (final WrongUsageException wrong) { + throw wrong; + } catch (final Throwable er) { + throw new WrongUsageException("commands.ae2.usage"); + } + } else if ("list".equals(args[0])) { + throw new WrongUsageException(Joiner.on(", ").join(Commands.values())); + } else { + try { + final Commands c = Commands.valueOf(args[0]); + if (sender.canUseCommand(c.level, this.getName())) { + c.command.call(this.srv, args, sender); + } else { + throw new WrongUsageException("commands.ae2.permissions"); + } + } catch (final WrongUsageException wrong) { + throw wrong; + } catch (final Throwable er) { + throw new WrongUsageException("commands.ae2.usage"); + } + } + } } diff --git a/src/main/java/appeng/server/AccessType.java b/src/main/java/appeng/server/AccessType.java index 0d45762ae..4a36685fd 100644 --- a/src/main/java/appeng/server/AccessType.java +++ b/src/main/java/appeng/server/AccessType.java @@ -19,35 +19,34 @@ package appeng.server; -public enum AccessType -{ - /** - * allows basic access to manipulate the block via gui, or other. - */ - BLOCK_ACCESS, +public enum AccessType { + /** + * allows basic access to manipulate the block via gui, or other. + */ + BLOCK_ACCESS, - /** - * Can player deposit items into the network. - */ - NETWORK_DEPOSIT, + /** + * Can player deposit items into the network. + */ + NETWORK_DEPOSIT, - /** - * can player withdraw items from the network. - */ - NETWORK_WITHDRAW, + /** + * can player withdraw items from the network. + */ + NETWORK_WITHDRAW, - /** - * can player issue crafting requests? - */ - NETWORK_CRAFT, + /** + * can player issue crafting requests? + */ + NETWORK_CRAFT, - /** - * can player add new blocks to the network. - */ - NETWORK_BUILD, + /** + * can player add new blocks to the network. + */ + NETWORK_BUILD, - /** - * can player manipulate security settings. - */ - NETWORK_SECURITY + /** + * can player manipulate security settings. + */ + NETWORK_SECURITY } diff --git a/src/main/java/appeng/server/Commands.java b/src/main/java/appeng/server/Commands.java index c80e88813..21c4bd792 100644 --- a/src/main/java/appeng/server/Commands.java +++ b/src/main/java/appeng/server/Commands.java @@ -23,23 +23,20 @@ import appeng.server.subcommands.ChunkLogger; import appeng.server.subcommands.Supporters; -public enum Commands -{ - Chunklogger( 4, new ChunkLogger() ), Supporters( 0, new Supporters() ); +public enum Commands { + Chunklogger(4, new ChunkLogger()), Supporters(0, new Supporters()); - public final int level; - public final ISubCommand command; + public final int level; + public final ISubCommand command; - Commands( final int level, final ISubCommand w ) - { - this.level = level; - this.command = w; - } + Commands(final int level, final ISubCommand w) { + this.level = level; + this.command = w; + } - @Override - public String toString() - { - return this.name(); - } + @Override + public String toString() { + return this.name(); + } } diff --git a/src/main/java/appeng/server/ISubCommand.java b/src/main/java/appeng/server/ISubCommand.java index 4abd9ddec..74de95614 100644 --- a/src/main/java/appeng/server/ISubCommand.java +++ b/src/main/java/appeng/server/ISubCommand.java @@ -23,10 +23,9 @@ import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; -public interface ISubCommand -{ +public interface ISubCommand { - String getHelp( MinecraftServer srv ); + String getHelp(MinecraftServer srv); - void call( MinecraftServer srv, String[] args, ICommandSender sender ); + void call(MinecraftServer srv, String[] args, ICommandSender sender); } diff --git a/src/main/java/appeng/server/ServerHelper.java b/src/main/java/appeng/server/ServerHelper.java index 3c9339374..e93c9814a 100644 --- a/src/main/java/appeng/server/ServerHelper.java +++ b/src/main/java/appeng/server/ServerHelper.java @@ -19,10 +19,15 @@ package appeng.server; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - +import appeng.api.parts.CableRenderMode; +import appeng.block.AEBaseBlock; +import appeng.client.ActionKey; +import appeng.client.EffectType; +import appeng.core.CommonHelper; +import appeng.core.sync.AppEngPacket; +import appeng.core.sync.network.NetworkHandler; +import appeng.items.tools.ToolNetworkTool; +import appeng.util.Platform; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; @@ -34,166 +39,132 @@ import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; import net.minecraftforge.fml.common.FMLCommonHandler; -import appeng.api.parts.CableRenderMode; -import appeng.block.AEBaseBlock; -import appeng.client.ActionKey; -import appeng.client.EffectType; -import appeng.core.CommonHelper; -import appeng.core.sync.AppEngPacket; -import appeng.core.sync.network.NetworkHandler; -import appeng.items.tools.ToolNetworkTool; -import appeng.util.Platform; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; -public class ServerHelper extends CommonHelper -{ +public class ServerHelper extends CommonHelper { - private EntityPlayer renderModeBased; + private EntityPlayer renderModeBased; - @Override - public void preinit() - { + @Override + public void preinit() { - } + } - @Override - public void init() - { + @Override + public void init() { - } + } - @Override - public World getWorld() - { - throw new UnsupportedOperationException( "This is a server..." ); - } + @Override + public World getWorld() { + throw new UnsupportedOperationException("This is a server..."); + } - @Override - public void bindTileEntitySpecialRenderer( final Class tile, final AEBaseBlock blk ) - { - throw new UnsupportedOperationException( "This is a server..." ); - } + @Override + public void bindTileEntitySpecialRenderer(final Class tile, final AEBaseBlock blk) { + throw new UnsupportedOperationException("This is a server..."); + } - @Override - public List getPlayers() - { - if( !Platform.isClient() ) - { - final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + @Override + public List getPlayers() { + if (!Platform.isClient()) { + final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - if( server != null ) - { - return (List) server.getPlayerList().getPlayers(); - } - } + if (server != null) { + return (List) server.getPlayerList().getPlayers(); + } + } - return new ArrayList<>(); - } + return new ArrayList<>(); + } - @Override - public void sendToAllNearExcept( final EntityPlayer p, final double x, final double y, final double z, final double dist, final World w, final AppEngPacket packet ) - { - if( Platform.isClient() ) - { - return; - } + @Override + public void sendToAllNearExcept(final EntityPlayer p, final double x, final double y, final double z, final double dist, final World w, final AppEngPacket packet) { + if (Platform.isClient()) { + return; + } - for( final EntityPlayer o : this.getPlayers() ) - { - final EntityPlayerMP entityplayermp = (EntityPlayerMP) o; + for (final EntityPlayer o : this.getPlayers()) { + final EntityPlayerMP entityplayermp = (EntityPlayerMP) o; - if( entityplayermp != p && entityplayermp.world == w ) - { - final double dX = x - entityplayermp.posX; - final double dY = y - entityplayermp.posY; - final double dZ = z - entityplayermp.posZ; + if (entityplayermp != p && entityplayermp.world == w) { + final double dX = x - entityplayermp.posX; + final double dY = y - entityplayermp.posY; + final double dZ = z - entityplayermp.posZ; - if( dX * dX + dY * dY + dZ * dZ < dist * dist ) - { - NetworkHandler.instance().sendTo( packet, entityplayermp ); - } - } - } - } + if (dX * dX + dY * dY + dZ * dZ < dist * dist) { + NetworkHandler.instance().sendTo(packet, entityplayermp); + } + } + } + } - @Override - public void spawnEffect( final EffectType type, final World world, final double posX, final double posY, final double posZ, final Object o ) - { - // :P - } + @Override + public void spawnEffect(final EffectType type, final World world, final double posX, final double posY, final double posZ, final Object o) { + // :P + } - @Override - public boolean shouldAddParticles( final Random r ) - { - return false; - } + @Override + public boolean shouldAddParticles(final Random r) { + return false; + } - @Override - public RayTraceResult getRTR() - { - return null; - } + @Override + public RayTraceResult getRTR() { + return null; + } - @Override - public void postInit() - { + @Override + public void postInit() { - } + } - @Override - public CableRenderMode getRenderMode() - { - if( this.renderModeBased == null ) - { - return CableRenderMode.STANDARD; - } + @Override + public CableRenderMode getRenderMode() { + if (this.renderModeBased == null) { + return CableRenderMode.STANDARD; + } - return this.renderModeForPlayer( this.renderModeBased ); - } + return this.renderModeForPlayer(this.renderModeBased); + } - @Override - public void triggerUpdates() - { + @Override + public void triggerUpdates() { - } + } - @Override - public void updateRenderMode( final EntityPlayer player ) - { - this.renderModeBased = player; - } + @Override + public void updateRenderMode(final EntityPlayer player) { + this.renderModeBased = player; + } - protected CableRenderMode renderModeForPlayer( final EntityPlayer player ) - { - if( player != null ) - { - for( int x = 0; x < InventoryPlayer.getHotbarSize(); x++ ) - { - final ItemStack is = player.inventory.getStackInSlot( x ); + protected CableRenderMode renderModeForPlayer(final EntityPlayer player) { + if (player != null) { + for (int x = 0; x < InventoryPlayer.getHotbarSize(); x++) { + final ItemStack is = player.inventory.getStackInSlot(x); - if( !is.isEmpty() && is.getItem() instanceof ToolNetworkTool ) - { - final NBTTagCompound c = is.getTagCompound(); - if( c != null && c.getBoolean( "hideFacades" ) ) - { - return CableRenderMode.CABLE_VIEW; - } - } - } - } + if (!is.isEmpty() && is.getItem() instanceof ToolNetworkTool) { + final NBTTagCompound c = is.getTagCompound(); + if (c != null && c.getBoolean("hideFacades")) { + return CableRenderMode.CABLE_VIEW; + } + } + } + } - return CableRenderMode.STANDARD; - } + return CableRenderMode.STANDARD; + } - @Override - public boolean isKeyPressed( ActionKey key ) - { - return false; - } + @Override + public boolean isKeyPressed(ActionKey key) { + return false; + } - @Override - public boolean isActionKey( ActionKey key, int pressedKeyCode ) - { - return false; - } + @Override + public boolean isActionKey(ActionKey key, int pressedKeyCode) { + return false; + } } diff --git a/src/main/java/appeng/server/subcommands/ChunkLogger.java b/src/main/java/appeng/server/subcommands/ChunkLogger.java index 17f1270ce..b2e8d15d7 100644 --- a/src/main/java/appeng/server/subcommands/ChunkLogger.java +++ b/src/main/java/appeng/server/subcommands/ChunkLogger.java @@ -19,6 +19,10 @@ package appeng.server.subcommands; +import appeng.core.AEConfig; +import appeng.core.AELog; +import appeng.core.features.AEFeature; +import appeng.server.ISubCommand; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.text.TextComponentTranslation; @@ -26,76 +30,55 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.world.ChunkEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import appeng.core.AEConfig; -import appeng.core.AELog; -import appeng.core.features.AEFeature; -import appeng.server.ISubCommand; +public class ChunkLogger implements ISubCommand { -public class ChunkLogger implements ISubCommand -{ + private boolean enabled = false; - private boolean enabled = false; + @SubscribeEvent + public void onChunkLoadEvent(final ChunkEvent.Load event) { + if (!event.getWorld().isRemote) { + AELog.info("Chunk Loaded: " + event.getChunk().x + ", " + event.getChunk().z); + this.displayStack(); + } + } - @SubscribeEvent - public void onChunkLoadEvent( final ChunkEvent.Load event ) - { - if( !event.getWorld().isRemote ) - { - AELog.info( "Chunk Loaded: " + event.getChunk().x + ", " + event.getChunk().z ); - this.displayStack(); - } - } + private void displayStack() { + if (AEConfig.instance().isFeatureEnabled(AEFeature.CHUNK_LOGGER_TRACE)) { + boolean output = false; + for (final StackTraceElement e : Thread.currentThread().getStackTrace()) { + if (output) { + AELog.info(" " + e.getClassName() + '.' + e.getMethodName() + " (" + e.getLineNumber() + ')'); + } else { + output = e.getClassName().contains("EventBus") && e.getMethodName().contains("post"); + } + } + } + } - private void displayStack() - { - if( AEConfig.instance().isFeatureEnabled( AEFeature.CHUNK_LOGGER_TRACE ) ) - { - boolean output = false; - for( final StackTraceElement e : Thread.currentThread().getStackTrace() ) - { - if( output ) - { - AELog.info( " " + e.getClassName() + '.' + e.getMethodName() + " (" + e.getLineNumber() + ')' ); - } - else - { - output = e.getClassName().contains( "EventBus" ) && e.getMethodName().contains( "post" ); - } - } - } - } + @SubscribeEvent + public void onChunkUnloadEvent(final ChunkEvent.Unload unload) { + if (!unload.getWorld().isRemote) { + AELog.info("Chunk Unloaded: " + unload.getChunk().x + ", " + unload.getChunk().z); + this.displayStack(); + } + } - @SubscribeEvent - public void onChunkUnloadEvent( final ChunkEvent.Unload unload ) - { - if( !unload.getWorld().isRemote ) - { - AELog.info( "Chunk Unloaded: " + unload.getChunk().x + ", " + unload.getChunk().z ); - this.displayStack(); - } - } + @Override + public String getHelp(final MinecraftServer srv) { + return "commands.ae2.ChunkLogger"; + } - @Override - public String getHelp( final MinecraftServer srv ) - { - return "commands.ae2.ChunkLogger"; - } + @Override + public void call(final MinecraftServer srv, final String[] data, final ICommandSender sender) { + this.enabled = !this.enabled; - @Override - public void call( final MinecraftServer srv, final String[] data, final ICommandSender sender ) - { - this.enabled = !this.enabled; - - if( this.enabled ) - { - MinecraftForge.EVENT_BUS.register( this ); - sender.sendMessage( new TextComponentTranslation( "commands.ae2.ChunkLoggerOn" ) ); - } - else - { - MinecraftForge.EVENT_BUS.unregister( this ); - sender.sendMessage( new TextComponentTranslation( "commands.ae2.ChunkLoggerOff" ) ); - } - } + if (this.enabled) { + MinecraftForge.EVENT_BUS.register(this); + sender.sendMessage(new TextComponentTranslation("commands.ae2.ChunkLoggerOn")); + } else { + MinecraftForge.EVENT_BUS.unregister(this); + sender.sendMessage(new TextComponentTranslation("commands.ae2.ChunkLoggerOff")); + } + } } diff --git a/src/main/java/appeng/server/subcommands/Supporters.java b/src/main/java/appeng/server/subcommands/Supporters.java index aef35eba7..321919e81 100644 --- a/src/main/java/appeng/server/subcommands/Supporters.java +++ b/src/main/java/appeng/server/subcommands/Supporters.java @@ -19,28 +19,23 @@ package appeng.server.subcommands; +import appeng.server.ISubCommand; import com.google.common.base.Joiner; - import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.text.TextComponentString; -import appeng.server.ISubCommand; +public class Supporters implements ISubCommand { -public class Supporters implements ISubCommand -{ + @Override + public String getHelp(final MinecraftServer srv) { + return "commands.ae2.Supporters"; + } - @Override - public String getHelp( final MinecraftServer srv ) - { - return "commands.ae2.Supporters"; - } - - @Override - public void call( final MinecraftServer srv, final String[] data, final ICommandSender sender ) - { - final String[] who = { "Stig Halvorsen", "Josh Ricker", "Jenny \"Othlon\" Sutherland", "Hristo Bogdanov", "BevoLJ" }; - sender.sendMessage( new TextComponentString( "Special thanks to " + Joiner.on( ", " ).join( who ) ) ); - } + @Override + public void call(final MinecraftServer srv, final String[] data, final ICommandSender sender) { + final String[] who = {"Stig Halvorsen", "Josh Ricker", "Jenny \"Othlon\" Sutherland", "Hristo Bogdanov", "BevoLJ"}; + sender.sendMessage(new TextComponentString("Special thanks to " + Joiner.on(", ").join(who))); + } } diff --git a/src/main/java/appeng/services/CompassService.java b/src/main/java/appeng/services/CompassService.java index 193f31f92..103a25873 100644 --- a/src/main/java/appeng/services/CompassService.java +++ b/src/main/java/appeng/services/CompassService.java @@ -19,349 +19,295 @@ package appeng.services; -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nonnull; - +import appeng.api.AEApi; +import appeng.api.util.DimensionalCoord; +import appeng.services.compass.CompassReader; +import appeng.services.compass.ICompassCallback; +import appeng.util.Platform; import com.google.common.base.Preconditions; - import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import appeng.api.AEApi; -import appeng.api.util.DimensionalCoord; -import appeng.services.compass.CompassReader; -import appeng.services.compass.ICompassCallback; -import appeng.util.Platform; +import javax.annotation.Nonnull; +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.*; -public final class CompassService -{ - private static final int CHUNK_SIZE = 16; +public final class CompassService { + private static final int CHUNK_SIZE = 16; - private final Map worldSet = new HashMap<>( 10 ); - private final ExecutorService executor; + private final Map worldSet = new HashMap<>(10); + private final ExecutorService executor; - /** - * AE2 Folder for each world - */ - private final File worldCompassFolder; + /** + * AE2 Folder for each world + */ + private final File worldCompassFolder; - private int jobSize; + private int jobSize; - public CompassService( @Nonnull final File worldCompassFolder, @Nonnull final ThreadFactory factory ) - { - Preconditions.checkNotNull( worldCompassFolder ); + public CompassService(@Nonnull final File worldCompassFolder, @Nonnull final ThreadFactory factory) { + Preconditions.checkNotNull(worldCompassFolder); - this.worldCompassFolder = worldCompassFolder; - this.executor = Executors.newSingleThreadExecutor( factory ); - this.jobSize = 0; - } + this.worldCompassFolder = worldCompassFolder; + this.executor = Executors.newSingleThreadExecutor(factory); + this.jobSize = 0; + } - public Future getCompassDirection( final DimensionalCoord coord, final int maxRange, final ICompassCallback cc ) - { - this.jobSize++; - return this.executor.submit( new CMDirectionRequest( coord, maxRange, cc ) ); - } + public Future getCompassDirection(final DimensionalCoord coord, final int maxRange, final ICompassCallback cc) { + this.jobSize++; + return this.executor.submit(new CMDirectionRequest(coord, maxRange, cc)); + } - /** - * Ensure the a compass service is removed once a world gets unloaded by forge. - * - * @param event the event containing the unloaded world. - */ - @SubscribeEvent - public void unloadWorld( final WorldEvent.Unload event ) - { - if( Platform.isServer() && this.worldSet.containsKey( event.getWorld() ) ) - { - final CompassReader compassReader = this.worldSet.remove( event.getWorld() ); + /** + * Ensure the a compass service is removed once a world gets unloaded by forge. + * + * @param event the event containing the unloaded world. + */ + @SubscribeEvent + public void unloadWorld(final WorldEvent.Unload event) { + if (Platform.isServer() && this.worldSet.containsKey(event.getWorld())) { + final CompassReader compassReader = this.worldSet.remove(event.getWorld()); - compassReader.close(); - } - } + compassReader.close(); + } + } - private int jobSize() - { - return this.jobSize; - } + private int jobSize() { + return this.jobSize; + } - private void cleanUp() - { - for( final CompassReader cr : this.worldSet.values() ) - { - cr.close(); - } - } + private void cleanUp() { + for (final CompassReader cr : this.worldSet.values()) { + cr.close(); + } + } - public void updateArea( final World w, final int chunkX, final int chunkZ ) - { - final int x = chunkX << 4; - final int z = chunkZ << 4; + public void updateArea(final World w, final int chunkX, final int chunkZ) { + final int x = chunkX << 4; + final int z = chunkZ << 4; - this.updateArea( w, x, CHUNK_SIZE, z ); - this.updateArea( w, x, CHUNK_SIZE + 32, z ); - this.updateArea( w, x, CHUNK_SIZE + 64, z ); - this.updateArea( w, x, CHUNK_SIZE + 96, z ); + this.updateArea(w, x, CHUNK_SIZE, z); + this.updateArea(w, x, CHUNK_SIZE + 32, z); + this.updateArea(w, x, CHUNK_SIZE + 64, z); + this.updateArea(w, x, CHUNK_SIZE + 96, z); - this.updateArea( w, x, CHUNK_SIZE + 128, z ); - this.updateArea( w, x, CHUNK_SIZE + 160, z ); - this.updateArea( w, x, CHUNK_SIZE + 192, z ); - this.updateArea( w, x, CHUNK_SIZE + 224, z ); - } + this.updateArea(w, x, CHUNK_SIZE + 128, z); + this.updateArea(w, x, CHUNK_SIZE + 160, z); + this.updateArea(w, x, CHUNK_SIZE + 192, z); + this.updateArea(w, x, CHUNK_SIZE + 224, z); + } - public Future updateArea( final World w, final int x, final int y, final int z ) - { - this.jobSize++; + public Future updateArea(final World w, final int x, final int y, final int z) { + this.jobSize++; - final int cx = x >> 4; - final int cdy = y >> 5; - final int cz = z >> 4; + final int cx = x >> 4; + final int cdy = y >> 5; + final int cz = z >> 4; - final int low_y = cdy << 5; - final int hi_y = low_y + 32; + final int low_y = cdy << 5; + final int hi_y = low_y + 32; - // lower level... - final Chunk c = w.getChunkFromChunkCoords( cx, cz ); + // lower level... + final Chunk c = w.getChunkFromChunkCoords(cx, cz); - Optional maybeBlock = AEApi.instance().definitions().blocks().skyStoneBlock().maybeBlock(); - if( maybeBlock.isPresent() ) - { - Block skyStoneBlock = maybeBlock.get(); - for( int i = 0; i < CHUNK_SIZE; i++ ) - { - for( int j = 0; j < CHUNK_SIZE; j++ ) - { - for( int k = low_y; k < hi_y; k++ ) - { - final Block blk = c.getBlockState( i, k, j ).getBlock(); - if( blk == skyStoneBlock ) - { - return this.executor.submit( new CMUpdatePost( w, cx, cz, cdy, true ) ); - } - } - } - } - } + Optional maybeBlock = AEApi.instance().definitions().blocks().skyStoneBlock().maybeBlock(); + if (maybeBlock.isPresent()) { + Block skyStoneBlock = maybeBlock.get(); + for (int i = 0; i < CHUNK_SIZE; i++) { + for (int j = 0; j < CHUNK_SIZE; j++) { + for (int k = low_y; k < hi_y; k++) { + final Block blk = c.getBlockState(i, k, j).getBlock(); + if (blk == skyStoneBlock) { + return this.executor.submit(new CMUpdatePost(w, cx, cz, cdy, true)); + } + } + } + } + } - return this.executor.submit( new CMUpdatePost( w, cx, cz, cdy, false ) ); - } + return this.executor.submit(new CMUpdatePost(w, cx, cz, cdy, false)); + } - public void kill() - { - this.executor.shutdown(); + public void kill() { + this.executor.shutdown(); - try - { - this.executor.awaitTermination( 6, TimeUnit.MINUTES ); - this.jobSize = 0; + try { + this.executor.awaitTermination(6, TimeUnit.MINUTES); + this.jobSize = 0; - for( final CompassReader cr : this.worldSet.values() ) - { - cr.close(); - } + for (final CompassReader cr : this.worldSet.values()) { + cr.close(); + } - this.worldSet.clear(); - } - catch( final InterruptedException e ) - { - // wrap this up.. - } - } + this.worldSet.clear(); + } catch (final InterruptedException e) { + // wrap this up.. + } + } - private CompassReader getReader( final World w ) - { - CompassReader cr = this.worldSet.get( w ); + private CompassReader getReader(final World w) { + CompassReader cr = this.worldSet.get(w); - if( cr == null ) - { - cr = new CompassReader( w.provider.getDimension(), this.worldCompassFolder ); - this.worldSet.put( w, cr ); - } + if (cr == null) { + cr = new CompassReader(w.provider.getDimension(), this.worldCompassFolder); + this.worldSet.put(w, cr); + } - return cr; - } + return cr; + } - private int dist( final int ax, final int az, final int bx, final int bz ) - { - final int up = ( bz - az ) * CHUNK_SIZE; - final int side = ( bx - ax ) * CHUNK_SIZE; + private int dist(final int ax, final int az, final int bx, final int bz) { + final int up = (bz - az) * CHUNK_SIZE; + final int side = (bx - ax) * CHUNK_SIZE; - return up * up + side * side; - } + return up * up + side * side; + } - private double rad( final int ax, final int az, final int bx, final int bz ) - { - final int up = bz - az; - final int side = bx - ax; + private double rad(final int ax, final int az, final int bx, final int bz) { + final int up = bz - az; + final int side = bx - ax; - return Math.atan2( -up, side ) - Math.PI / 2.0; - } + return Math.atan2(-up, side) - Math.PI / 2.0; + } - private class CMUpdatePost implements Runnable - { + private class CMUpdatePost implements Runnable { - public final World world; + public final World world; - public final int chunkX; - public final int chunkZ; - public final int doubleChunkY; // 32 blocks instead of 16. - public final boolean value; + public final int chunkX; + public final int chunkZ; + public final int doubleChunkY; // 32 blocks instead of 16. + public final boolean value; - public CMUpdatePost( final World w, final int cx, final int cz, final int dcy, final boolean val ) - { - this.world = w; - this.chunkX = cx; - this.doubleChunkY = dcy; - this.chunkZ = cz; - this.value = val; - } + public CMUpdatePost(final World w, final int cx, final int cz, final int dcy, final boolean val) { + this.world = w; + this.chunkX = cx; + this.doubleChunkY = dcy; + this.chunkZ = cz; + this.value = val; + } - @Override - public void run() - { - CompassService.this.jobSize--; + @Override + public void run() { + CompassService.this.jobSize--; - final CompassReader cr = CompassService.this.getReader( this.world ); - cr.setHasBeacon( this.chunkX, this.chunkZ, this.doubleChunkY, this.value ); + final CompassReader cr = CompassService.this.getReader(this.world); + cr.setHasBeacon(this.chunkX, this.chunkZ, this.doubleChunkY, this.value); - if( CompassService.this.jobSize() < 2 ) - { - CompassService.this.cleanUp(); - } - } - } + if (CompassService.this.jobSize() < 2) { + CompassService.this.cleanUp(); + } + } + } - private class CMDirectionRequest implements Runnable - { + private class CMDirectionRequest implements Runnable { - public final int maxRange; - public final DimensionalCoord coord; - public final ICompassCallback callback; + public final int maxRange; + public final DimensionalCoord coord; + public final ICompassCallback callback; - public CMDirectionRequest( final DimensionalCoord coord, final int getMaxRange, final ICompassCallback cc ) - { - this.coord = coord; - this.maxRange = getMaxRange; - this.callback = cc; - } + public CMDirectionRequest(final DimensionalCoord coord, final int getMaxRange, final ICompassCallback cc) { + this.coord = coord; + this.maxRange = getMaxRange; + this.callback = cc; + } - @Override - public void run() - { - CompassService.this.jobSize--; + @Override + public void run() { + CompassService.this.jobSize--; - final int cx = this.coord.x >> 4; - final int cz = this.coord.z >> 4; + final int cx = this.coord.x >> 4; + final int cz = this.coord.z >> 4; - final CompassReader cr = CompassService.this.getReader( this.coord.getWorld() ); + final CompassReader cr = CompassService.this.getReader(this.coord.getWorld()); - // Am I standing on it? - if( cr.hasBeacon( cx, cz ) ) - { - this.callback.calculatedDirection( true, true, -999, 0 ); + // Am I standing on it? + if (cr.hasBeacon(cx, cz)) { + this.callback.calculatedDirection(true, true, -999, 0); - if( CompassService.this.jobSize() < 2 ) - { - CompassService.this.cleanUp(); - } + if (CompassService.this.jobSize() < 2) { + CompassService.this.cleanUp(); + } - return; - } + return; + } - // spiral outward... - for( int offset = 1; offset < this.maxRange; offset++ ) - { - final int minX = cx - offset; - final int minZ = cz - offset; - final int maxX = cx + offset; - final int maxZ = cz + offset; + // spiral outward... + for (int offset = 1; offset < this.maxRange; offset++) { + final int minX = cx - offset; + final int minZ = cz - offset; + final int maxX = cx + offset; + final int maxZ = cz + offset; - int closest = Integer.MAX_VALUE; - int chosen_x = cx; - int chosen_z = cz; + int closest = Integer.MAX_VALUE; + int chosen_x = cx; + int chosen_z = cz; - for( int z = minZ; z <= maxZ; z++ ) - { - if( cr.hasBeacon( minX, z ) ) - { - final int closeness = CompassService.this.dist( cx, cz, minX, z ); - if( closeness < closest ) - { - closest = closeness; - chosen_x = minX; - chosen_z = z; - } - } + for (int z = minZ; z <= maxZ; z++) { + if (cr.hasBeacon(minX, z)) { + final int closeness = CompassService.this.dist(cx, cz, minX, z); + if (closeness < closest) { + closest = closeness; + chosen_x = minX; + chosen_z = z; + } + } - if( cr.hasBeacon( maxX, z ) ) - { - final int closeness = CompassService.this.dist( cx, cz, maxX, z ); - if( closeness < closest ) - { - closest = closeness; - chosen_x = maxX; - chosen_z = z; - } - } - } + if (cr.hasBeacon(maxX, z)) { + final int closeness = CompassService.this.dist(cx, cz, maxX, z); + if (closeness < closest) { + closest = closeness; + chosen_x = maxX; + chosen_z = z; + } + } + } - for( int x = minX + 1; x < maxX; x++ ) - { - if( cr.hasBeacon( x, minZ ) ) - { - final int closeness = CompassService.this.dist( cx, cz, x, minZ ); - if( closeness < closest ) - { - closest = closeness; - chosen_x = x; - chosen_z = minZ; - } - } + for (int x = minX + 1; x < maxX; x++) { + if (cr.hasBeacon(x, minZ)) { + final int closeness = CompassService.this.dist(cx, cz, x, minZ); + if (closeness < closest) { + closest = closeness; + chosen_x = x; + chosen_z = minZ; + } + } - if( cr.hasBeacon( x, maxZ ) ) - { - final int closeness = CompassService.this.dist( cx, cz, x, maxZ ); - if( closeness < closest ) - { - closest = closeness; - chosen_x = x; - chosen_z = maxZ; - } - } - } + if (cr.hasBeacon(x, maxZ)) { + final int closeness = CompassService.this.dist(cx, cz, x, maxZ); + if (closeness < closest) { + closest = closeness; + chosen_x = x; + chosen_z = maxZ; + } + } + } - if( closest < Integer.MAX_VALUE ) - { - this.callback.calculatedDirection( true, false, CompassService.this.rad( cx, cz, chosen_x, chosen_z ), - CompassService.this.dist( cx, cz, chosen_x, chosen_z ) ); + if (closest < Integer.MAX_VALUE) { + this.callback.calculatedDirection(true, false, CompassService.this.rad(cx, cz, chosen_x, chosen_z), + CompassService.this.dist(cx, cz, chosen_x, chosen_z)); - if( CompassService.this.jobSize() < 2 ) - { - CompassService.this.cleanUp(); - } + if (CompassService.this.jobSize() < 2) { + CompassService.this.cleanUp(); + } - return; - } - } + return; + } + } - // didn't find shit... - this.callback.calculatedDirection( false, true, -999, 999 ); + // didn't find shit... + this.callback.calculatedDirection(false, true, -999, 999); - if( CompassService.this.jobSize() < 2 ) - { - CompassService.this.cleanUp(); - } - } - } + if (CompassService.this.jobSize() < 2) { + CompassService.this.cleanUp(); + } + } + } } diff --git a/src/main/java/appeng/services/VersionChecker.java b/src/main/java/appeng/services/VersionChecker.java index 87bec13df..ab79e139d 100644 --- a/src/main/java/appeng/services/VersionChecker.java +++ b/src/main/java/appeng/services/VersionChecker.java @@ -19,186 +19,158 @@ package appeng.services; -import java.util.Date; - -import javax.annotation.Nonnull; - +import appeng.core.AEConfig; +import appeng.core.AELog; +import appeng.core.AppEng; +import appeng.services.version.*; +import appeng.services.version.github.FormattedRelease; +import appeng.services.version.github.ReleaseFetcher; import com.google.common.base.Preconditions; - import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.event.FMLInterModComms; -import appeng.core.AEConfig; -import appeng.core.AELog; -import appeng.core.AppEng; -import appeng.services.version.ModVersionFetcher; -import appeng.services.version.Version; -import appeng.services.version.VersionCheckerConfig; -import appeng.services.version.VersionFetcher; -import appeng.services.version.VersionParser; -import appeng.services.version.github.FormattedRelease; -import appeng.services.version.github.ReleaseFetcher; +import javax.annotation.Nonnull; +import java.util.Date; /** * Tries to connect to GitHub to retrieve the most current build. * After comparison with the local version, several path can be chosen. - * + *

* If the local version is invalid, somebody might have build that version themselves * or it is run in a developer environment, then nothing needs to be done. - * + *

* If GitHub can not be reached, then either is GitHub down * or the connection to GitHub disturbed, then nothing needs to be done, * since no comparison can be reached - * + *

* If the version was just recently checked, then no need to poll again. * Nobody wants to bother to update several times a day. - * + *

* Config enables to fine-tune when a version is considered newer - * + *

* If the local version is newer or equal to the GitHub version, * then no update needs to be posted - * + *

* Only after all that cases, if the external version is higher than the local, * use Version Checker Mod and post several information needed for it to update the mod. */ -public final class VersionChecker implements Runnable -{ - private static final int SEC_TO_HOUR = 3600; - private static final int MS_TO_SEC = 1000; - private final VersionCheckerConfig config; +public final class VersionChecker implements Runnable { + private static final int SEC_TO_HOUR = 3600; + private static final int MS_TO_SEC = 1000; + private final VersionCheckerConfig config; - public VersionChecker( @Nonnull final VersionCheckerConfig config ) - { - Preconditions.checkNotNull( config ); + public VersionChecker(@Nonnull final VersionCheckerConfig config) { + Preconditions.checkNotNull(config); - this.config = config; - } + this.config = config; + } - @Override - public void run() - { - try - { - Thread.yield(); + @Override + public void run() { + try { + Thread.yield(); - // persist the config - this.config.save(); + // persist the config + this.config.save(); - // retrieve data - final String rawLastCheck = this.config.lastCheck(); + // retrieve data + final String rawLastCheck = this.config.lastCheck(); - // process data - final long lastCheck = Long.parseLong( rawLastCheck ); - final Date now = new Date(); - final long nowInMs = now.getTime(); - final long intervalInMs = this.config.interval() * SEC_TO_HOUR * MS_TO_SEC; - final long lastAfterInterval = lastCheck + intervalInMs; + // process data + final long lastCheck = Long.parseLong(rawLastCheck); + final Date now = new Date(); + final long nowInMs = now.getTime(); + final long intervalInMs = this.config.interval() * SEC_TO_HOUR * MS_TO_SEC; + final long lastAfterInterval = lastCheck + intervalInMs; - this.processInterval( nowInMs, lastAfterInterval ); - } - catch( final Exception exception ) - { - // Log any unhandled exception to prevent the JVM from reporting them as unhandled. - AELog.debug( exception ); - } + this.processInterval(nowInMs, lastAfterInterval); + } catch (final Exception exception) { + // Log any unhandled exception to prevent the JVM from reporting them as unhandled. + AELog.debug(exception); + } - AELog.info( "Stopping AE2 VersionChecker" ); - } + AELog.info("Stopping AE2 VersionChecker"); + } - /** - * checks if enough time since last check has expired - * - * @param nowInMs now in milli seconds - * @param lastAfterInterval last version check including the interval defined in the config - */ - private void processInterval( final long nowInMs, final long lastAfterInterval ) - { - if( nowInMs > lastAfterInterval ) - { - final String rawModVersion = AEConfig.VERSION; - final VersionParser parser = new VersionParser(); - final VersionFetcher modFetcher = new ModVersionFetcher( rawModVersion, parser ); - final ReleaseFetcher githubFetcher = new ReleaseFetcher( this.config, parser ); + /** + * checks if enough time since last check has expired + * + * @param nowInMs now in milli seconds + * @param lastAfterInterval last version check including the interval defined in the config + */ + private void processInterval(final long nowInMs, final long lastAfterInterval) { + if (nowInMs > lastAfterInterval) { + final String rawModVersion = AEConfig.VERSION; + final VersionParser parser = new VersionParser(); + final VersionFetcher modFetcher = new ModVersionFetcher(rawModVersion, parser); + final ReleaseFetcher githubFetcher = new ReleaseFetcher(this.config, parser); - final Version modVersion = modFetcher.get(); - final FormattedRelease githubRelease = githubFetcher.get(); + final Version modVersion = modFetcher.get(); + final FormattedRelease githubRelease = githubFetcher.get(); - this.processVersions( modVersion, githubRelease ); - } - else - { - AELog.info( "Last check was just recently." ); - } - } + this.processVersions(modVersion, githubRelease); + } else { + AELog.info("Last check was just recently."); + } + } - /** - * Checks if the retrieved version is newer as the current mod version. - * Will notify player if config is enabled. - * - * @param modVersion version of mod - * @param githubRelease release retrieved through github - */ - private void processVersions( @Nonnull final Version modVersion, @Nonnull final FormattedRelease githubRelease ) - { - final Version githubVersion = githubRelease.version(); - final String modFormatted = modVersion.formatted(); - final String ghFormatted = githubVersion.formatted(); + /** + * Checks if the retrieved version is newer as the current mod version. + * Will notify player if config is enabled. + * + * @param modVersion version of mod + * @param githubRelease release retrieved through github + */ + private void processVersions(@Nonnull final Version modVersion, @Nonnull final FormattedRelease githubRelease) { + final Version githubVersion = githubRelease.version(); + final String modFormatted = modVersion.formatted(); + final String ghFormatted = githubVersion.formatted(); - if( githubVersion.isNewerAs( modVersion ) ) - { - final String changelog = githubRelease.changelog(); + if (githubVersion.isNewerAs(modVersion)) { + final String changelog = githubRelease.changelog(); - if( this.config.shouldNotifyPlayer() ) - { - AELog.info( "Newer version is available: " + ghFormatted + " (found) > " + modFormatted + " (current)" ); + if (this.config.shouldNotifyPlayer()) { + AELog.info("Newer version is available: " + ghFormatted + " (found) > " + modFormatted + " (current)"); - if( this.config.shouldPostChangelog() ) - { - AELog.info( "Changelog: " + changelog ); - } - } + if (this.config.shouldPostChangelog()) { + AELog.info("Changelog: " + changelog); + } + } - this.interactWithVersionCheckerMod( modFormatted, ghFormatted, changelog ); - } - else - { - AELog.info( "No newer version is available: " + ghFormatted + "(found) < " + modFormatted + " (current)" ); - } - } + this.interactWithVersionCheckerMod(modFormatted, ghFormatted, changelog); + } else { + AELog.info("No newer version is available: " + ghFormatted + "(found) < " + modFormatted + " (current)"); + } + } - /** - * Checks if the version checker mod is installed and handles it depending on that information - * - * @param modFormatted mod version formatted as rv2-beta-8 - * @param ghFormatted retrieved github version formatted as rv2-beta-8 - * @param changelog retrieved github changelog - */ - private void interactWithVersionCheckerMod( @Nonnull final String modFormatted, @Nonnull final String ghFormatted, @Nonnull final String changelog ) - { - if( Loader.isModLoaded( "VersionChecker" ) ) - { - final NBTTagCompound versionInf = new NBTTagCompound(); - versionInf.setString( "modDisplayName", AppEng.MOD_NAME ); - versionInf.setString( "oldVersion", modFormatted ); - versionInf.setString( "newVersion", ghFormatted ); - versionInf.setString( "updateUrl", "http://ae-mod.info/builds/appliedenergistics2-" + ghFormatted + ".jar" ); - versionInf.setBoolean( "isDirectLink", true ); + /** + * Checks if the version checker mod is installed and handles it depending on that information + * + * @param modFormatted mod version formatted as rv2-beta-8 + * @param ghFormatted retrieved github version formatted as rv2-beta-8 + * @param changelog retrieved github changelog + */ + private void interactWithVersionCheckerMod(@Nonnull final String modFormatted, @Nonnull final String ghFormatted, @Nonnull final String changelog) { + if (Loader.isModLoaded("VersionChecker")) { + final NBTTagCompound versionInf = new NBTTagCompound(); + versionInf.setString("modDisplayName", AppEng.MOD_NAME); + versionInf.setString("oldVersion", modFormatted); + versionInf.setString("newVersion", ghFormatted); + versionInf.setString("updateUrl", "http://ae-mod.info/builds/appliedenergistics2-" + ghFormatted + ".jar"); + versionInf.setBoolean("isDirectLink", true); - if( !changelog.isEmpty() ) - { - versionInf.setString( "changeLog", changelog ); - } + if (!changelog.isEmpty()) { + versionInf.setString("changeLog", changelog); + } - versionInf.setString( "newFileName", "appliedenergistics2-" + ghFormatted + ".jar" ); - FMLInterModComms.sendRuntimeMessage( AppEng.instance(), "VersionChecker", "addUpdate", versionInf ); + versionInf.setString("newFileName", "appliedenergistics2-" + ghFormatted + ".jar"); + FMLInterModComms.sendRuntimeMessage(AppEng.instance(), "VersionChecker", "addUpdate", versionInf); - AELog.info( "Reported new version to VersionChecker mod." ); - } - else - { - AELog.info( "VersionChecker mod is not installed; Proceeding." ); - } - } + AELog.info("Reported new version to VersionChecker mod."); + } else { + AELog.info("VersionChecker mod is not installed; Proceeding."); + } + } } diff --git a/src/main/java/appeng/services/compass/CompassException.java b/src/main/java/appeng/services/compass/CompassException.java index e61c09c2d..f71f0de13 100644 --- a/src/main/java/appeng/services/compass/CompassException.java +++ b/src/main/java/appeng/services/compass/CompassException.java @@ -19,15 +19,13 @@ package appeng.services.compass; -public class CompassException extends RuntimeException -{ +public class CompassException extends RuntimeException { - private static final long serialVersionUID = 8825268683203860877L; + private static final long serialVersionUID = 8825268683203860877L; - private final Throwable inner; + private final Throwable inner; - public CompassException( final Throwable t ) - { - this.inner = t; - } + public CompassException(final Throwable t) { + this.inner = t; + } } diff --git a/src/main/java/appeng/services/compass/CompassReader.java b/src/main/java/appeng/services/compass/CompassReader.java index f0d34c786..3f81068ad 100644 --- a/src/main/java/appeng/services/compass/CompassReader.java +++ b/src/main/java/appeng/services/compass/CompassReader.java @@ -19,68 +19,59 @@ package appeng.services.compass; +import com.google.common.base.Preconditions; + +import javax.annotation.Nonnull; import java.io.File; import java.util.HashMap; import java.util.Map; -import javax.annotation.Nonnull; -import com.google.common.base.Preconditions; +public final class CompassReader { + private final Map regions = new HashMap<>(100); + private final int dimensionId; + private final File worldCompassFolder; + public CompassReader(final int dimensionId, @Nonnull final File worldCompassFolder) { + Preconditions.checkNotNull(worldCompassFolder); + Preconditions.checkArgument(worldCompassFolder.isDirectory()); -public final class CompassReader -{ - private final Map regions = new HashMap<>( 100 ); - private final int dimensionId; - private final File worldCompassFolder; + this.dimensionId = dimensionId; + this.worldCompassFolder = worldCompassFolder; + } - public CompassReader( final int dimensionId, @Nonnull final File worldCompassFolder ) - { - Preconditions.checkNotNull( worldCompassFolder ); - Preconditions.checkArgument( worldCompassFolder.isDirectory() ); + public void close() { + for (final CompassRegion r : this.regions.values()) { + r.close(); + } - this.dimensionId = dimensionId; - this.worldCompassFolder = worldCompassFolder; - } + this.regions.clear(); + } - public void close() - { - for( final CompassRegion r : this.regions.values() ) - { - r.close(); - } + public void setHasBeacon(final int cx, final int cz, final int cdy, final boolean hasBeacon) { + final CompassRegion r = this.getRegion(cx, cz); - this.regions.clear(); - } + r.setHasBeacon(cx, cz, cdy, hasBeacon); + } - public void setHasBeacon( final int cx, final int cz, final int cdy, final boolean hasBeacon ) - { - final CompassRegion r = this.getRegion( cx, cz ); + public boolean hasBeacon(final int cx, final int cz) { + final CompassRegion r = this.getRegion(cx, cz); - r.setHasBeacon( cx, cz, cdy, hasBeacon ); - } + return r.hasBeacon(cx, cz); + } - public boolean hasBeacon( final int cx, final int cz ) - { - final CompassRegion r = this.getRegion( cx, cz ); + private CompassRegion getRegion(final int cx, final int cz) { + long pos = cx >> 10; + pos <<= 32; + pos |= (cz >> 10); - return r.hasBeacon( cx, cz ); - } + CompassRegion cr = this.regions.get(pos); - private CompassRegion getRegion( final int cx, final int cz ) - { - long pos = cx >> 10; - pos <<= 32; - pos |= ( cz >> 10 ); + if (cr == null) { + cr = new CompassRegion(cx, cz, this.dimensionId, this.worldCompassFolder); + this.regions.put(pos, cr); + } - CompassRegion cr = this.regions.get( pos ); - - if( cr == null ) - { - cr = new CompassRegion( cx, cz, this.dimensionId, this.worldCompassFolder ); - this.regions.put( pos, cr ); - } - - return cr; - } + return cr; + } } diff --git a/src/main/java/appeng/services/compass/CompassRegion.java b/src/main/java/appeng/services/compass/CompassRegion.java index c22780655..c1fa71bcc 100644 --- a/src/main/java/appeng/services/compass/CompassRegion.java +++ b/src/main/java/appeng/services/compass/CompassRegion.java @@ -19,193 +19,150 @@ package appeng.services.compass; +import appeng.core.worlddata.MeteorDataNameEncoder; +import com.google.common.base.Preconditions; + +import javax.annotation.Nonnull; import java.io.File; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; -import javax.annotation.Nonnull; -import com.google.common.base.Preconditions; +public final class CompassRegion { + private final int lowX; + private final int lowZ; + private final int world; + private final File worldCompassFolder; + private final MeteorDataNameEncoder encoder; -import appeng.core.worlddata.MeteorDataNameEncoder; + private boolean hasFile = false; + private RandomAccessFile raf = null; + private ByteBuffer buffer; + public CompassRegion(final int cx, final int cz, final int worldID, @Nonnull final File worldCompassFolder) { + Preconditions.checkNotNull(worldCompassFolder); + Preconditions.checkArgument(worldCompassFolder.isDirectory()); -public final class CompassRegion -{ - private final int lowX; - private final int lowZ; - private final int world; - private final File worldCompassFolder; - private final MeteorDataNameEncoder encoder; + this.world = worldID; + this.worldCompassFolder = worldCompassFolder; + this.encoder = new MeteorDataNameEncoder(0); - private boolean hasFile = false; - private RandomAccessFile raf = null; - private ByteBuffer buffer; + final int region_x = cx >> 10; + final int region_z = cz >> 10; - public CompassRegion( final int cx, final int cz, final int worldID, @Nonnull final File worldCompassFolder ) - { - Preconditions.checkNotNull( worldCompassFolder ); - Preconditions.checkArgument( worldCompassFolder.isDirectory() ); + this.lowX = region_x << 10; + this.lowZ = region_z << 10; - this.world = worldID; - this.worldCompassFolder = worldCompassFolder; - this.encoder = new MeteorDataNameEncoder( 0 ); + this.openFile(false); + } - final int region_x = cx >> 10; - final int region_z = cz >> 10; + void close() { + try { + if (this.hasFile) { + this.buffer = null; + this.raf.close(); + this.raf = null; + this.hasFile = false; + } + } catch (final Throwable t) { + throw new CompassException(t); + } + } - this.lowX = region_x << 10; - this.lowZ = region_z << 10; + boolean hasBeacon(int cx, int cz) { + if (this.hasFile) { + cx &= 0x3FF; + cz &= 0x3FF; - this.openFile( false ); - } + final int val = this.read(cx, cz); + return val != 0; + } - void close() - { - try - { - if( this.hasFile ) - { - this.buffer = null; - this.raf.close(); - this.raf = null; - this.hasFile = false; - } - } - catch( final Throwable t ) - { - throw new CompassException( t ); - } - } + return false; + } - boolean hasBeacon( int cx, int cz ) - { - if( this.hasFile ) - { - cx &= 0x3FF; - cz &= 0x3FF; + void setHasBeacon(int cx, int cz, final int cdy, final boolean hasBeacon) { + cx &= 0x3FF; + cz &= 0x3FF; - final int val = this.read( cx, cz ); - if( val != 0 ) - { - return true; - } - } + this.openFile(hasBeacon); - return false; - } + if (this.hasFile) { + int val = this.read(cx, cz); + final int originalVal = val; - void setHasBeacon( int cx, int cz, final int cdy, final boolean hasBeacon ) - { - cx &= 0x3FF; - cz &= 0x3FF; + if (hasBeacon) { + val |= 1 << cdy; + } else { + val &= ~(1 << cdy); + } - this.openFile( hasBeacon ); + if (originalVal != val) { + this.write(cx, cz, val); + } + } + } - if( this.hasFile ) - { - int val = this.read( cx, cz ); - final int originalVal = val; + @Override + protected void finalize() throws Throwable { + try { + if (this.raf != null) { + this.raf.close(); + } + } finally { + super.finalize(); + } - if( hasBeacon ) - { - val |= 1 << cdy; - } - else - { - val &= ~( 1 << cdy ); - } + } - if( originalVal != val ) - { - this.write( cx, cz, val ); - } - } - } + private void openFile(final boolean create) { + if (this.hasFile) { + return; + } - @Override - protected void finalize() throws Throwable - { - try - { - if( this.raf != null ) - { - this.raf.close(); - } - } - finally - { - super.finalize(); - } + final File file = this.getFile(); + if (create || this.isFileExistent(file)) { + try { + this.raf = new RandomAccessFile(file, "rw"); + final FileChannel fc = this.raf.getChannel(); + this.buffer = fc.map(FileChannel.MapMode.READ_WRITE, 0, 0x400 * 0x400);// fc.size() ); + this.hasFile = true; + } catch (final Throwable t) { + throw new CompassException(t); + } + } + } - } + private File getFile() { + final String fileName = this.encoder.encode(this.world, this.lowX, this.lowZ); - private void openFile( final boolean create ) - { - if( this.hasFile ) - { - return; - } + return new File(this.worldCompassFolder, fileName); + } - final File file = this.getFile(); - if( create || this.isFileExistent( file ) ) - { - try - { - this.raf = new RandomAccessFile( file, "rw" ); - final FileChannel fc = this.raf.getChannel(); - this.buffer = fc.map( FileChannel.MapMode.READ_WRITE, 0, 0x400 * 0x400 );// fc.size() ); - this.hasFile = true; - } - catch( final Throwable t ) - { - throw new CompassException( t ); - } - } - } + private boolean isFileExistent(final File file) { + return file.exists() && file.isFile(); + } - private File getFile() - { - final String fileName = this.encoder.encode( this.world, this.lowX, this.lowZ ); + private int read(final int cx, final int cz) { + try { + return this.buffer.get(cx + cz * 0x400); + // raf.seek( cx + cz * 0x400 ); + // return raf.readByte(); + } catch (final IndexOutOfBoundsException outOfBounds) { + return 0; + } catch (final Throwable t) { + throw new CompassException(t); + } + } - return new File( this.worldCompassFolder, fileName ); - } - - private boolean isFileExistent( final File file ) - { - return file.exists() && file.isFile(); - } - - private int read( final int cx, final int cz ) - { - try - { - return this.buffer.get( cx + cz * 0x400 ); - // raf.seek( cx + cz * 0x400 ); - // return raf.readByte(); - } - catch( final IndexOutOfBoundsException outOfBounds ) - { - return 0; - } - catch( final Throwable t ) - { - throw new CompassException( t ); - } - } - - private void write( final int cx, final int cz, final int val ) - { - try - { - this.buffer.put( cx + cz * 0x400, (byte) val ); - // raf.seek( cx + cz * 0x400 ); - // raf.writeByte( val ); - } - catch( final Throwable t ) - { - throw new CompassException( t ); - } - } + private void write(final int cx, final int cz, final int val) { + try { + this.buffer.put(cx + cz * 0x400, (byte) val); + // raf.seek( cx + cz * 0x400 ); + // raf.writeByte( val ); + } catch (final Throwable t) { + throw new CompassException(t); + } + } } diff --git a/src/main/java/appeng/services/compass/CompassThreadFactory.java b/src/main/java/appeng/services/compass/CompassThreadFactory.java index 0c9ac26e4..fbc23e9b2 100644 --- a/src/main/java/appeng/services/compass/CompassThreadFactory.java +++ b/src/main/java/appeng/services/compass/CompassThreadFactory.java @@ -19,11 +19,10 @@ package appeng.services.compass; -import java.util.concurrent.ThreadFactory; +import com.google.common.base.Preconditions; import javax.annotation.Nonnull; - -import com.google.common.base.Preconditions; +import java.util.concurrent.ThreadFactory; /** @@ -31,13 +30,11 @@ import com.google.common.base.Preconditions; * @version rv3 - 31.05.2015 * @since rv3 31.05.2015 */ -public final class CompassThreadFactory implements ThreadFactory -{ - @Override - public Thread newThread( @Nonnull final Runnable job ) - { - Preconditions.checkNotNull( job ); +public final class CompassThreadFactory implements ThreadFactory { + @Override + public Thread newThread(@Nonnull final Runnable job) { + Preconditions.checkNotNull(job); - return new Thread( job, "AE Compass Service" ); - } + return new Thread(job, "AE Compass Service"); + } } diff --git a/src/main/java/appeng/services/compass/ICompassCallback.java b/src/main/java/appeng/services/compass/ICompassCallback.java index 06cf52d38..8a8d89842 100644 --- a/src/main/java/appeng/services/compass/ICompassCallback.java +++ b/src/main/java/appeng/services/compass/ICompassCallback.java @@ -19,16 +19,15 @@ package appeng.services.compass; -public interface ICompassCallback -{ +public interface ICompassCallback { - /** - * Called from another thread. - * - * @param hasResult true if found a target - * @param spin true if should spin - * @param radians radians - * @param dist distance - */ - void calculatedDirection( boolean hasResult, boolean spin, double radians, double dist ); + /** + * Called from another thread. + * + * @param hasResult true if found a target + * @param spin true if should spin + * @param radians radians + * @param dist distance + */ + void calculatedDirection(boolean hasResult, boolean spin, double radians, double dist); } diff --git a/src/main/java/appeng/services/export/CheckType.java b/src/main/java/appeng/services/export/CheckType.java index 7b37e04bf..d75cd0f61 100644 --- a/src/main/java/appeng/services/export/CheckType.java +++ b/src/main/java/appeng/services/export/CheckType.java @@ -27,15 +27,14 @@ package appeng.services.export; * @see Checker * @since rv3 - 25.09.2015 */ -enum CheckType -{ - /** - * If checking resulted in both objects being equal - */ - EQUAL, +enum CheckType { + /** + * If checking resulted in both objects being equal + */ + EQUAL, - /** - * If checking resulted in both objects being unequal - */ - UNEQUAL + /** + * If checking resulted in both objects being unequal + */ + UNEQUAL } diff --git a/src/main/java/appeng/services/export/Checker.java b/src/main/java/appeng/services/export/Checker.java index 1b896acf6..d3c073420 100644 --- a/src/main/java/appeng/services/export/Checker.java +++ b/src/main/java/appeng/services/export/Checker.java @@ -24,22 +24,19 @@ import javax.annotation.Nonnull; /** * Checks against a specific type with its own check type for clear outcome. - * + *

* The constructor will generally have a value which the checker will check against * * @author thatsIch * @version rv3 - 01.09.2015 * @since rv3 - 01.09.2015 */ -interface Checker -{ - /** - * @param checkedAgainst the object it is checked against - * - * @return non null being either equal or unequal - * - * @since rv3 - 01.09.2015 - */ - @Nonnull - CheckType isEqual( @Nonnull final T checkedAgainst ); +interface Checker { + /** + * @param checkedAgainst the object it is checked against + * @return non null being either equal or unequal + * @since rv3 - 01.09.2015 + */ + @Nonnull + CheckType isEqual(@Nonnull final T checkedAgainst); } diff --git a/src/main/java/appeng/services/export/ExportConfig.java b/src/main/java/appeng/services/export/ExportConfig.java index 8d57e6cc0..32d67fd03 100644 --- a/src/main/java/appeng/services/export/ExportConfig.java +++ b/src/main/java/appeng/services/export/ExportConfig.java @@ -27,56 +27,55 @@ import javax.annotation.Nonnull; * @version rv3 - 14.08.2015 * @since rv3 14.08.2015 */ -public interface ExportConfig -{ - /** - * config switch to disable the exporting. - * if the recipes system is not used - * there is no reason to export them. - * Still can be useful for debugging purpose, - * thus not tying it to the recipe system directly. - * - * @return true if exporting is enabled - */ - boolean isExportingItemNamesEnabled(); +public interface ExportConfig { + /** + * config switch to disable the exporting. + * if the recipes system is not used + * there is no reason to export them. + * Still can be useful for debugging purpose, + * thus not tying it to the recipe system directly. + * + * @return true if exporting is enabled + */ + boolean isExportingItemNamesEnabled(); - /** - * config switch for using the digest cache. - * - * @return true if cache is enabled - */ - boolean isCacheEnabled(); + /** + * config switch for using the digest cache. + * + * @return true if cache is enabled + */ + boolean isCacheEnabled(); - /** - * config switch to always refresh the CSV. Might be useful to activate on debugging. - * - * @return true if force refresh is enabled - */ - boolean isForceRefreshEnabled(); + /** + * config switch to always refresh the CSV. Might be useful to activate on debugging. + * + * @return true if force refresh is enabled + */ + boolean isForceRefreshEnabled(); - /** - * config switch to export more information mostly used for debugging - * - * @return true if additional information are enabled - */ - boolean isAdditionalInformationEnabled(); + /** + * config switch to export more information mostly used for debugging + * + * @return true if additional information are enabled + */ + boolean isAdditionalInformationEnabled(); - /** - * Will get the cache from last session. Can be used to reduce I/O operations though containing itself calculation. - * - * @return a digest from the last calculation - */ - String getCache(); + /** + * Will get the cache from last session. Can be used to reduce I/O operations though containing itself calculation. + * + * @return a digest from the last calculation + */ + String getCache(); - /** - * sets the cache for the next session to reduce calculation overhead - * - * @param digest new digest for the cache - */ - void setCache( @Nonnull String digest ); + /** + * sets the cache for the next session to reduce calculation overhead + * + * @param digest new digest for the cache + */ + void setCache(@Nonnull String digest); - /** - * Will delegate the saving - */ - void save(); + /** + * Will delegate the saving + */ + void save(); } diff --git a/src/main/java/appeng/services/export/ExportMode.java b/src/main/java/appeng/services/export/ExportMode.java index 20f7ecfa8..b38da7259 100644 --- a/src/main/java/appeng/services/export/ExportMode.java +++ b/src/main/java/appeng/services/export/ExportMode.java @@ -21,22 +21,21 @@ package appeng.services.export; /** * Defines the different modes which need to be distinguished upon exporting. - * + *

* using a different mode will result in a different export outcome. * * @author thatsIch * @version rv3 - 23.09.2015 * @since rv3 - 23.09.2015 */ -enum ExportMode -{ - /** - * Will provide general users with information required for recipe making - */ - MINIMAL, +enum ExportMode { + /** + * Will provide general users with information required for recipe making + */ + MINIMAL, - /** - * Will provide advanced users with information with debugging functionality - */ - VERBOSE + /** + * Will provide advanced users with information with debugging functionality + */ + VERBOSE } diff --git a/src/main/java/appeng/services/export/ExportProcess.java b/src/main/java/appeng/services/export/ExportProcess.java index e3534a307..2db5e9f67 100644 --- a/src/main/java/appeng/services/export/ExportProcess.java +++ b/src/main/java/appeng/services/export/ExportProcess.java @@ -19,112 +19,97 @@ package appeng.services.export; -import java.io.File; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nonnull; - +import appeng.core.AELog; import com.google.common.base.Preconditions; import com.google.common.base.Stopwatch; - import net.minecraft.item.Item; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.registry.ForgeRegistries; import net.minecraftforge.registries.IForgeRegistry; -import appeng.core.AELog; +import javax.annotation.Nonnull; +import java.io.File; +import java.util.List; +import java.util.concurrent.TimeUnit; /** * Main entry point for exporting the CSV file - * + *

* makes everything threadable * * @author thatsIch * @version rv3 - 14.08.2015 * @since rv3 14.08.2015 */ -public class ExportProcess implements Runnable -{ - private static final String FORCE_REFRESH_MESSAGE = "Force Refresh enabled. Will ignore cache and export CSV content."; - private static final String CACHE_ENABLED_MESSAGE = "Cache is enabled. Checking for new mod configurations."; - private static final String EQUAL_CONTENT_MESSAGE = "Same mod configuration was found. Not updating CSV content."; - private static final String UNEQUAL_CONTENT_MESSAGE = "New mod configuration was found. Commencing exporting."; - private static final String CACHE_DISABLED_MESSAGE = "Cache is disabled. Commencing exporting."; - private static final String EXPORT_START_MESSAGE = "Item Exporting ( started )"; - private static final String EXPORT_END_MESSAGE = "Item Exporting ( ended after %s ms)"; +public class ExportProcess implements Runnable { + private static final String FORCE_REFRESH_MESSAGE = "Force Refresh enabled. Will ignore cache and export CSV content."; + private static final String CACHE_ENABLED_MESSAGE = "Cache is enabled. Checking for new mod configurations."; + private static final String EQUAL_CONTENT_MESSAGE = "Same mod configuration was found. Not updating CSV content."; + private static final String UNEQUAL_CONTENT_MESSAGE = "New mod configuration was found. Commencing exporting."; + private static final String CACHE_DISABLED_MESSAGE = "Cache is disabled. Commencing exporting."; + private static final String EXPORT_START_MESSAGE = "Item Exporting ( started )"; + private static final String EXPORT_END_MESSAGE = "Item Exporting ( ended after %s ms)"; - @Nonnull - private final File exportDirectory; - @Nonnull - private final Checker> modChecker; - @Nonnull - private final ExportConfig config; + @Nonnull + private final File exportDirectory; + @Nonnull + private final Checker> modChecker; + @Nonnull + private final ExportConfig config; - /** - * @param exportDirectory directory where the final CSV file will be exported to - * @param config configuration to manipulate the export process - */ - public ExportProcess( @Nonnull final File exportDirectory, @Nonnull final ExportConfig config ) - { - this.exportDirectory = Preconditions.checkNotNull( exportDirectory ); - this.config = Preconditions.checkNotNull( config ); + /** + * @param exportDirectory directory where the final CSV file will be exported to + * @param config configuration to manipulate the export process + */ + public ExportProcess(@Nonnull final File exportDirectory, @Nonnull final ExportConfig config) { + this.exportDirectory = Preconditions.checkNotNull(exportDirectory); + this.config = Preconditions.checkNotNull(config); - this.modChecker = new ModListChecker( config ); - } + this.modChecker = new ModListChecker(config); + } - /** - * Will check and export if various config settings will lead to exporting the CSV file. - */ - @Override - public void run() - { - // no priority to this thread - Thread.yield(); + /** + * Will check and export if various config settings will lead to exporting the CSV file. + */ + @Override + public void run() { + // no priority to this thread + Thread.yield(); - // logic when to cancel the export process - if( this.config.isForceRefreshEnabled() ) - { - AELog.info( FORCE_REFRESH_MESSAGE ); - } - else - { - if( this.config.isCacheEnabled() ) - { - AELog.info( CACHE_ENABLED_MESSAGE ); + // logic when to cancel the export process + if (this.config.isForceRefreshEnabled()) { + AELog.info(FORCE_REFRESH_MESSAGE); + } else { + if (this.config.isCacheEnabled()) { + AELog.info(CACHE_ENABLED_MESSAGE); - final Loader loader = Loader.instance(); - final List mods = loader.getActiveModList(); + final Loader loader = Loader.instance(); + final List mods = loader.getActiveModList(); - if( this.modChecker.isEqual( mods ) == CheckType.EQUAL ) - { - AELog.info( EQUAL_CONTENT_MESSAGE ); + if (this.modChecker.isEqual(mods) == CheckType.EQUAL) { + AELog.info(EQUAL_CONTENT_MESSAGE); - return; - } - else - { - AELog.info( UNEQUAL_CONTENT_MESSAGE ); - } - } - else - { - AELog.info( CACHE_DISABLED_MESSAGE ); - } - } + return; + } else { + AELog.info(UNEQUAL_CONTENT_MESSAGE); + } + } else { + AELog.info(CACHE_DISABLED_MESSAGE); + } + } - AELog.info( EXPORT_START_MESSAGE ); - final Stopwatch watch = Stopwatch.createStarted(); + AELog.info(EXPORT_START_MESSAGE); + final Stopwatch watch = Stopwatch.createStarted(); - final IForgeRegistry itemRegistry = ForgeRegistries.ITEMS; + final IForgeRegistry itemRegistry = ForgeRegistries.ITEMS; - final ExportMode mode = this.config.isAdditionalInformationEnabled() ? ExportMode.VERBOSE : ExportMode.MINIMAL; - final Exporter exporter = new MinecraftItemCSVExporter( this.exportDirectory, itemRegistry, mode ); + final ExportMode mode = this.config.isAdditionalInformationEnabled() ? ExportMode.VERBOSE : ExportMode.MINIMAL; + final Exporter exporter = new MinecraftItemCSVExporter(this.exportDirectory, itemRegistry, mode); - exporter.export(); + exporter.export(); - AELog.info( EXPORT_END_MESSAGE, watch.elapsed( TimeUnit.MILLISECONDS ) ); - } + AELog.info(EXPORT_END_MESSAGE, watch.elapsed(TimeUnit.MILLISECONDS)); + } } diff --git a/src/main/java/appeng/services/export/Exporter.java b/src/main/java/appeng/services/export/Exporter.java index 4bd5aa648..951c57c60 100644 --- a/src/main/java/appeng/services/export/Exporter.java +++ b/src/main/java/appeng/services/export/Exporter.java @@ -26,10 +26,9 @@ package appeng.services.export; * @version rv3 - 19.08.2015 * @since rv3 19.08.2015 */ -interface Exporter -{ - /** - * Will export something defined by the Exporter with side effects - */ - void export(); +interface Exporter { + /** + * Will export something defined by the Exporter with side effects + */ + void export(); } diff --git a/src/main/java/appeng/services/export/ForgeExportConfig.java b/src/main/java/appeng/services/export/ForgeExportConfig.java index 261f90aff..093b4dc1a 100644 --- a/src/main/java/appeng/services/export/ForgeExportConfig.java +++ b/src/main/java/appeng/services/export/ForgeExportConfig.java @@ -19,13 +19,12 @@ package appeng.services.export; -import javax.annotation.Nonnull; - import com.google.common.base.Preconditions; - import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; +import javax.annotation.Nonnull; + /** * Offers configuration switches for the user to change the export process @@ -34,100 +33,91 @@ import net.minecraftforge.common.config.Property; * @version rv3 - 14.08.2015 * @since rv3 14.08.2015 */ -public final class ForgeExportConfig implements ExportConfig -{ - private static final String GENERAL_CATEGORY = "general"; - private static final String CACHE_CATEGORY = "cache"; +public final class ForgeExportConfig implements ExportConfig { + private static final String GENERAL_CATEGORY = "general"; + private static final String CACHE_CATEGORY = "cache"; - private static final String EXPORT_ITEM_NAMES_KEY = "exportItemNames"; - private static final boolean EXPORT_ITEM_NAMES_DEFAULT = true; - private static final String EXPORT_ITEM_NAMES_DESCRIPTION = "If true, all registered items will be exported containing the internal minecraft name and the localized name to actually find the item you are using. This also contains the item representation of the blocks, but are missing items, which are too much to display e.g. FMP."; + private static final String EXPORT_ITEM_NAMES_KEY = "exportItemNames"; + private static final boolean EXPORT_ITEM_NAMES_DEFAULT = true; + private static final String EXPORT_ITEM_NAMES_DESCRIPTION = "If true, all registered items will be exported containing the internal minecraft name and the localized name to actually find the item you are using. This also contains the item representation of the blocks, but are missing items, which are too much to display e.g. FMP."; - private static final String ENABLE_FORCE_REFRESH_KEY = "enableForceRefresh"; - private static final boolean ENABLE_FORCE_REFRESH_DEFAULT = false; - private static final String ENABLE_FORCE_REFRESH_DESCRIPTION = "If true, the CSV exporting will always happen. This will not use the cache to reduce the computation."; + private static final String ENABLE_FORCE_REFRESH_KEY = "enableForceRefresh"; + private static final boolean ENABLE_FORCE_REFRESH_DEFAULT = false; + private static final String ENABLE_FORCE_REFRESH_DESCRIPTION = "If true, the CSV exporting will always happen. This will not use the cache to reduce the computation."; - private static final String ENABLE_CACHE_KEY = "enableCache"; - private static final boolean ENABLE_CACHE_DEFAULT = true; - private static final String ENABLE_CACHE_DESCRIPTION = "Caching can save processing time, if there are a lot of items."; + private static final String ENABLE_CACHE_KEY = "enableCache"; + private static final boolean ENABLE_CACHE_DEFAULT = true; + private static final String ENABLE_CACHE_DESCRIPTION = "Caching can save processing time, if there are a lot of items."; - private static final String ENABLE_ADDITIONAL_INFO_KEY = "enableAdditionalInfo"; - private static final boolean ENABLE_ADDITIONAL_INFO_DEFAULT = false; - private static final String ENABLE_ADDITIONAL_INFO_DESCRIPTION = "Will output more detailed information into the CSV like corresponding items"; + private static final String ENABLE_ADDITIONAL_INFO_KEY = "enableAdditionalInfo"; + private static final boolean ENABLE_ADDITIONAL_INFO_DEFAULT = false; + private static final String ENABLE_ADDITIONAL_INFO_DESCRIPTION = "Will output more detailed information into the CSV like corresponding items"; - private static final String DIGEST_KEY = "digest"; - private static final String DIGEST_DEFAULT = ""; - private static final String DIGEST_DESCRIPTION = "Digest of all the mods and versions to check if a re-export of the item names is required."; + private static final String DIGEST_KEY = "digest"; + private static final String DIGEST_DEFAULT = ""; + private static final String DIGEST_DESCRIPTION = "Digest of all the mods and versions to check if a re-export of the item names is required."; - private final boolean exportItemNamesEnabled; - private final boolean cacheEnabled; - private final boolean forceRefreshEnabled; - private final boolean additionalInformationEnabled; - private final String cache; - private final Configuration config; + private final boolean exportItemNamesEnabled; + private final boolean cacheEnabled; + private final boolean forceRefreshEnabled; + private final boolean additionalInformationEnabled; + private final String cache; + private final Configuration config; - /** - * Constructor using the configuration. Apparently there are some race conditions if constructing configurations on - * multiple file accesses - * - * @param config to be wrapped configuration. - */ - public ForgeExportConfig( @Nonnull final Configuration config ) - { - this.config = Preconditions.checkNotNull( config ); + /** + * Constructor using the configuration. Apparently there are some race conditions if constructing configurations on + * multiple file accesses + * + * @param config to be wrapped configuration. + */ + public ForgeExportConfig(@Nonnull final Configuration config) { + this.config = Preconditions.checkNotNull(config); - this.exportItemNamesEnabled = this.config.getBoolean( EXPORT_ITEM_NAMES_KEY, GENERAL_CATEGORY, EXPORT_ITEM_NAMES_DEFAULT, - EXPORT_ITEM_NAMES_DESCRIPTION ); - this.cacheEnabled = this.config.getBoolean( ENABLE_CACHE_KEY, CACHE_CATEGORY, ENABLE_CACHE_DEFAULT, ENABLE_CACHE_DESCRIPTION ); - this.additionalInformationEnabled = this.config.getBoolean( ENABLE_ADDITIONAL_INFO_KEY, GENERAL_CATEGORY, ENABLE_ADDITIONAL_INFO_DEFAULT, - ENABLE_ADDITIONAL_INFO_DESCRIPTION ); - this.cache = this.config.getString( DIGEST_KEY, CACHE_CATEGORY, DIGEST_DEFAULT, DIGEST_DESCRIPTION ); - this.forceRefreshEnabled = this.config.getBoolean( ENABLE_FORCE_REFRESH_KEY, GENERAL_CATEGORY, ENABLE_FORCE_REFRESH_DEFAULT, - ENABLE_FORCE_REFRESH_DESCRIPTION ); - } + this.exportItemNamesEnabled = this.config.getBoolean(EXPORT_ITEM_NAMES_KEY, GENERAL_CATEGORY, EXPORT_ITEM_NAMES_DEFAULT, + EXPORT_ITEM_NAMES_DESCRIPTION); + this.cacheEnabled = this.config.getBoolean(ENABLE_CACHE_KEY, CACHE_CATEGORY, ENABLE_CACHE_DEFAULT, ENABLE_CACHE_DESCRIPTION); + this.additionalInformationEnabled = this.config.getBoolean(ENABLE_ADDITIONAL_INFO_KEY, GENERAL_CATEGORY, ENABLE_ADDITIONAL_INFO_DEFAULT, + ENABLE_ADDITIONAL_INFO_DESCRIPTION); + this.cache = this.config.getString(DIGEST_KEY, CACHE_CATEGORY, DIGEST_DEFAULT, DIGEST_DESCRIPTION); + this.forceRefreshEnabled = this.config.getBoolean(ENABLE_FORCE_REFRESH_KEY, GENERAL_CATEGORY, ENABLE_FORCE_REFRESH_DEFAULT, + ENABLE_FORCE_REFRESH_DESCRIPTION); + } - @Override - public boolean isExportingItemNamesEnabled() - { - return this.exportItemNamesEnabled; - } + @Override + public boolean isExportingItemNamesEnabled() { + return this.exportItemNamesEnabled; + } - @Override - public boolean isCacheEnabled() - { - return this.cacheEnabled; - } + @Override + public boolean isCacheEnabled() { + return this.cacheEnabled; + } - @Override - public boolean isForceRefreshEnabled() - { - return this.forceRefreshEnabled; - } + @Override + public boolean isForceRefreshEnabled() { + return this.forceRefreshEnabled; + } - @Override - public boolean isAdditionalInformationEnabled() - { - return this.additionalInformationEnabled; - } + @Override + public boolean isAdditionalInformationEnabled() { + return this.additionalInformationEnabled; + } - @Override - public String getCache() - { - return this.cache; - } + @Override + public String getCache() { + return this.cache; + } - @Override - public void setCache( @Nonnull final String digest ) - { - final Property digestProperty = this.config.get( CACHE_CATEGORY, DIGEST_KEY, DIGEST_DEFAULT ); - digestProperty.set( digest ); + @Override + public void setCache(@Nonnull final String digest) { + final Property digestProperty = this.config.get(CACHE_CATEGORY, DIGEST_KEY, DIGEST_DEFAULT); + digestProperty.set(digest); - this.config.save(); - } + this.config.save(); + } - @Override - public void save() - { - this.config.save(); - } + @Override + public void save() { + this.config.save(); + } } diff --git a/src/main/java/appeng/services/export/MinecraftItemCSVExporter.java b/src/main/java/appeng/services/export/MinecraftItemCSVExporter.java index e18f487ae..4c3d28a38 100644 --- a/src/main/java/appeng/services/export/MinecraftItemCSVExporter.java +++ b/src/main/java/appeng/services/export/MinecraftItemCSVExporter.java @@ -19,25 +19,11 @@ package appeng.services.export; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.nio.charset.Charset; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - +import appeng.core.AELog; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; - -import org.apache.commons.io.FileUtils; - import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; @@ -47,8 +33,14 @@ import net.minecraft.util.NonNullList; import net.minecraft.util.text.translation.I18n; import net.minecraftforge.fml.common.registry.ForgeRegistries; import net.minecraftforge.registries.IForgeRegistry; +import org.apache.commons.io.FileUtils; -import appeng.core.AELog; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.*; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.List; /** @@ -58,234 +50,209 @@ import appeng.core.AELog; * @version rv3 - 14.08.2015 * @since rv3 14.08.2015 */ -final class MinecraftItemCSVExporter implements Exporter -{ - private static final String ITEM_CSV_FILE_NAME = "items.csv"; - private static final String MINIMAL_HEADER = "Mod:Item:MetaData, Localized Name"; - private static final String VERBOSE_HEADER = MINIMAL_HEADER + ", Unlocalized Name, Is Block?, Class Name"; - private static final String EXPORT_SUCCESSFUL_MESSAGE = "Exported successfully %d items into %s"; - private static final String EXPORT_UNSUCCESSFUL_MESSAGE = "Exporting was unsuccessful."; +final class MinecraftItemCSVExporter implements Exporter { + private static final String ITEM_CSV_FILE_NAME = "items.csv"; + private static final String MINIMAL_HEADER = "Mod:Item:MetaData, Localized Name"; + private static final String VERBOSE_HEADER = MINIMAL_HEADER + ", Unlocalized Name, Is Block?, Class Name"; + private static final String EXPORT_SUCCESSFUL_MESSAGE = "Exported successfully %d items into %s"; + private static final String EXPORT_UNSUCCESSFUL_MESSAGE = "Exporting was unsuccessful."; - @Nonnull - private final File exportDirectory; - @Nonnull - private final IForgeRegistry itemRegistry; - @Nonnull - private final ExportMode mode; + @Nonnull + private final File exportDirectory; + @Nonnull + private final IForgeRegistry itemRegistry; + @Nonnull + private final ExportMode mode; - /** - * @param exportDirectory directory of the resulting export file. Non-null required. - * @param itemRegistry the registry with minecraft items. Needs to be populated at that time, thus the exporting can - * only happen in init (pre-init is the - * phase when all items are determined) - * @param mode mode in which the export should be operated. Resulting CSV will change depending on this. - */ - MinecraftItemCSVExporter( @Nonnull final File exportDirectory, @Nonnull final IForgeRegistry itemRegistry, @Nonnull final ExportMode mode ) - { - this.exportDirectory = Preconditions.checkNotNull( exportDirectory ); - Preconditions.checkArgument( !exportDirectory.isFile() ); - this.itemRegistry = Preconditions.checkNotNull( itemRegistry ); - this.mode = Preconditions.checkNotNull( mode ); - } + /** + * @param exportDirectory directory of the resulting export file. Non-null required. + * @param itemRegistry the registry with minecraft items. Needs to be populated at that time, thus the exporting can + * only happen in init (pre-init is the + * phase when all items are determined) + * @param mode mode in which the export should be operated. Resulting CSV will change depending on this. + */ + MinecraftItemCSVExporter(@Nonnull final File exportDirectory, @Nonnull final IForgeRegistry itemRegistry, @Nonnull final ExportMode mode) { + this.exportDirectory = Preconditions.checkNotNull(exportDirectory); + Preconditions.checkArgument(!exportDirectory.isFile()); + this.itemRegistry = Preconditions.checkNotNull(itemRegistry); + this.mode = Preconditions.checkNotNull(mode); + } - @Override - public void export() - { - final Iterable items = this.itemRegistry; - final List itemList = Lists.newArrayList( items ); + @Override + public void export() { + final Iterable items = this.itemRegistry; + final List itemList = Lists.newArrayList(items); - final List lines = Lists.transform( itemList, new ItemRowExtractFunction( this.itemRegistry, this.mode ) ); + final List lines = Lists.transform(itemList, new ItemRowExtractFunction(this.itemRegistry, this.mode)); - final Joiner newLineJoiner = Joiner.on( '\n' ); - final Joiner newLineJoinerIgnoringNull = newLineJoiner.skipNulls(); - final String joined = newLineJoinerIgnoringNull.join( lines ); + final Joiner newLineJoiner = Joiner.on('\n'); + final Joiner newLineJoinerIgnoringNull = newLineJoiner.skipNulls(); + final String joined = newLineJoinerIgnoringNull.join(lines); - final File file = new File( this.exportDirectory, ITEM_CSV_FILE_NAME ); + final File file = new File(this.exportDirectory, ITEM_CSV_FILE_NAME); - try( final Writer writer = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( file ), Charset.forName( "UTF-8" ) ) ) ) - { - FileUtils.forceMkdir( this.exportDirectory ); + try (final Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) { + FileUtils.forceMkdir(this.exportDirectory); - final String header = this.mode == ExportMode.MINIMAL ? MINIMAL_HEADER : VERBOSE_HEADER; - writer.write( header ); - writer.write( "\n" ); - writer.write( joined ); - writer.flush(); + final String header = this.mode == ExportMode.MINIMAL ? MINIMAL_HEADER : VERBOSE_HEADER; + writer.write(header); + writer.write("\n"); + writer.write(joined); + writer.flush(); - AELog.info( EXPORT_SUCCESSFUL_MESSAGE, lines.size(), ITEM_CSV_FILE_NAME ); - } - catch( final IOException e ) - { - AELog.warn( EXPORT_UNSUCCESSFUL_MESSAGE ); - AELog.debug( e ); - } - } + AELog.info(EXPORT_SUCCESSFUL_MESSAGE, lines.size(), ITEM_CSV_FILE_NAME); + } catch (final IOException e) { + AELog.warn(EXPORT_UNSUCCESSFUL_MESSAGE); + AELog.debug(e); + } + } - /** - * Extracts item name with meta and the display name - */ - private static final class TypeExtractFunction implements Function - { - private static final String EXTRACTING_NULL_MESSAGE = "extracting type null"; - private static final String EXTRACTING_ITEM_MESSAGE = "extracting type %s:%d"; + /** + * Extracts item name with meta and the display name + */ + private static final class TypeExtractFunction implements Function { + private static final String EXTRACTING_NULL_MESSAGE = "extracting type null"; + private static final String EXTRACTING_ITEM_MESSAGE = "extracting type %s:%d"; - @Nonnull - private final String itemName; - @Nonnull - private final ExportMode mode; + @Nonnull + private final String itemName; + @Nonnull + private final ExportMode mode; - private TypeExtractFunction( @Nonnull final String itemName, @Nonnull final ExportMode mode ) - { - this.itemName = Preconditions.checkNotNull( itemName ); - Preconditions.checkArgument( !itemName.isEmpty() ); + private TypeExtractFunction(@Nonnull final String itemName, @Nonnull final ExportMode mode) { + this.itemName = Preconditions.checkNotNull(itemName); + Preconditions.checkArgument(!itemName.isEmpty()); - this.mode = Preconditions.checkNotNull( mode ); - } + this.mode = Preconditions.checkNotNull(mode); + } - @Nullable - @Override - public String apply( @Nullable final ItemStack input ) - { - if( input == null ) - { - AELog.debug( EXTRACTING_NULL_MESSAGE ); + @Nullable + @Override + public String apply(@Nullable final ItemStack input) { + if (input == null) { + AELog.debug(EXTRACTING_NULL_MESSAGE); - return null; - } - else - { - AELog.debug( EXTRACTING_ITEM_MESSAGE, input.getDisplayName(), input.getItemDamage() ); - } + return null; + } else { + AELog.debug(EXTRACTING_ITEM_MESSAGE, input.getDisplayName(), input.getItemDamage()); + } - final List joinedBlockAttributes = Lists.newArrayListWithCapacity( 5 ); - final int meta = input.getItemDamage(); - final String metaName = this.itemName + ':' + meta; - final String localization = input.getDisplayName(); + final List joinedBlockAttributes = Lists.newArrayListWithCapacity(5); + final int meta = input.getItemDamage(); + final String metaName = this.itemName + ':' + meta; + final String localization = input.getDisplayName(); - joinedBlockAttributes.add( metaName ); - joinedBlockAttributes.add( localization ); + joinedBlockAttributes.add(metaName); + joinedBlockAttributes.add(localization); - if( this.mode == ExportMode.VERBOSE ) - { - final Item item = input.getItem(); - final String unlocalizedItem = input.getUnlocalizedName(); - final Block block = Block.getBlockFromItem( item ); - final boolean isBlock = block != Blocks.AIR && !block.equals( Blocks.AIR ); - final Class stackClass = input.getClass(); - final String stackClassName = stackClass.getName(); + if (this.mode == ExportMode.VERBOSE) { + final Item item = input.getItem(); + final String unlocalizedItem = input.getUnlocalizedName(); + final Block block = Block.getBlockFromItem(item); + final boolean isBlock = block != Blocks.AIR && !block.equals(Blocks.AIR); + final Class stackClass = input.getClass(); + final String stackClassName = stackClass.getName(); - joinedBlockAttributes.add( unlocalizedItem ); - joinedBlockAttributes.add( Boolean.toString( isBlock ) ); - joinedBlockAttributes.add( stackClassName ); - } + joinedBlockAttributes.add(unlocalizedItem); + joinedBlockAttributes.add(Boolean.toString(isBlock)); + joinedBlockAttributes.add(stackClassName); + } - final Joiner csvJoiner = Joiner.on( ", " ); - final Joiner csvJoinerIgnoringNulls = csvJoiner.skipNulls(); + final Joiner csvJoiner = Joiner.on(", "); + final Joiner csvJoinerIgnoringNulls = csvJoiner.skipNulls(); - return csvJoinerIgnoringNulls.join( joinedBlockAttributes ); - } - } + return csvJoinerIgnoringNulls.join(joinedBlockAttributes); + } + } - /** - * transforms an item into a row representation of the CSV file - */ - private static final class ItemRowExtractFunction implements Function - { - /** - * this extension is required to apply the {@link I18n} - */ - private static final String LOCALIZATION_NAME_EXTENSION = ".name"; - private static final String EXPORTING_NOTHING_MESSAGE = "Exporting nothing"; - private static final String EXPORTING_SUBTYPES_MESSAGE = "Exporting input %s with subtypes: %b"; - private static final String EXPORTING_SUBTYPES_FAILED_MESSAGE = "Could not export subtypes of: %s"; + /** + * transforms an item into a row representation of the CSV file + */ + private static final class ItemRowExtractFunction implements Function { + /** + * this extension is required to apply the {@link I18n} + */ + private static final String LOCALIZATION_NAME_EXTENSION = ".name"; + private static final String EXPORTING_NOTHING_MESSAGE = "Exporting nothing"; + private static final String EXPORTING_SUBTYPES_MESSAGE = "Exporting input %s with subtypes: %b"; + private static final String EXPORTING_SUBTYPES_FAILED_MESSAGE = "Could not export subtypes of: %s"; - @Nonnull - private final IForgeRegistry itemRegistry; - @Nonnull - private final ExportMode mode; + @Nonnull + private final IForgeRegistry itemRegistry; + @Nonnull + private final ExportMode mode; - /** - * @param itemRegistry used to retrieve the name of the item - * @param mode extracts more or less information from item depending on mode - */ - ItemRowExtractFunction( @Nonnull final IForgeRegistry itemRegistry, @Nonnull final ExportMode mode ) - { - this.itemRegistry = Preconditions.checkNotNull( itemRegistry ); - this.mode = Preconditions.checkNotNull( mode ); - } + /** + * @param itemRegistry used to retrieve the name of the item + * @param mode extracts more or less information from item depending on mode + */ + ItemRowExtractFunction(@Nonnull final IForgeRegistry itemRegistry, @Nonnull final ExportMode mode) { + this.itemRegistry = Preconditions.checkNotNull(itemRegistry); + this.mode = Preconditions.checkNotNull(mode); + } - @Nullable - @Override - public String apply( @Nullable final Item input ) - { - if( input == null ) - { - AELog.debug( EXPORTING_NOTHING_MESSAGE ); + @Nullable + @Override + public String apply(@Nullable final Item input) { + if (input == null) { + AELog.debug(EXPORTING_NOTHING_MESSAGE); - return null; - } - else - { - AELog.debug( EXPORTING_SUBTYPES_MESSAGE, input.getUnlocalizedName(), input.getHasSubtypes() ); - } + return null; + } else { + AELog.debug(EXPORTING_SUBTYPES_MESSAGE, input.getUnlocalizedName(), input.getHasSubtypes()); + } - final String itemName = ForgeRegistries.ITEMS.getKey( input ).toString(); - final boolean hasSubtypes = input.getHasSubtypes(); - if( hasSubtypes ) - { - final CreativeTabs creativeTab = input.getCreativeTab(); - final NonNullList stacks = NonNullList.create(); + final String itemName = ForgeRegistries.ITEMS.getKey(input).toString(); + final boolean hasSubtypes = input.getHasSubtypes(); + if (hasSubtypes) { + final CreativeTabs creativeTab = input.getCreativeTab(); + final NonNullList stacks = NonNullList.create(); - // modifies the stacks list and adds the different sub types to it - try - { - input.getSubItems( creativeTab, stacks ); - } - catch( final Exception ignored ) - { - AELog.warn( EXPORTING_SUBTYPES_FAILED_MESSAGE, input.getUnlocalizedName() ); - AELog.debug( ignored ); + // modifies the stacks list and adds the different sub types to it + try { + input.getSubItems(creativeTab, stacks); + } catch (final Exception ignored) { + AELog.warn(EXPORTING_SUBTYPES_FAILED_MESSAGE, input.getUnlocalizedName()); + AELog.debug(ignored); - // ignore if mods do bullshit in their code - return null; - } + // ignore if mods do bullshit in their code + return null; + } - // list can be empty, no clue why - if( stacks.isEmpty() ) - { - return null; - } + // list can be empty, no clue why + if (stacks.isEmpty()) { + return null; + } - final Joiner newLineJoiner = Joiner.on( '\n' ); - final Joiner typeJoiner = newLineJoiner.skipNulls(); - final List transformedTypes = Lists.transform( stacks, new TypeExtractFunction( itemName, this.mode ) ); + final Joiner newLineJoiner = Joiner.on('\n'); + final Joiner typeJoiner = newLineJoiner.skipNulls(); + final List transformedTypes = Lists.transform(stacks, new TypeExtractFunction(itemName, this.mode)); - return typeJoiner.join( transformedTypes ); - } + return typeJoiner.join(transformedTypes); + } - final List joinedBlockAttributes = Lists.newArrayListWithCapacity( 5 ); - final String unlocalizedItem = input.getUnlocalizedName(); - final String localization = I18n.translateToLocal( unlocalizedItem + LOCALIZATION_NAME_EXTENSION ); + final List joinedBlockAttributes = Lists.newArrayListWithCapacity(5); + final String unlocalizedItem = input.getUnlocalizedName(); + final String localization = I18n.translateToLocal(unlocalizedItem + LOCALIZATION_NAME_EXTENSION); - joinedBlockAttributes.add( itemName ); - joinedBlockAttributes.add( localization ); + joinedBlockAttributes.add(itemName); + joinedBlockAttributes.add(localization); - if( this.mode == ExportMode.VERBOSE ) - { - final Block block = Block.getBlockFromItem( input ); - final boolean isBlock = block != Blocks.AIR && !block.equals( Blocks.AIR ); - final Class itemClass = input.getClass(); - final String itemClassName = itemClass.getName(); + if (this.mode == ExportMode.VERBOSE) { + final Block block = Block.getBlockFromItem(input); + final boolean isBlock = block != Blocks.AIR && !block.equals(Blocks.AIR); + final Class itemClass = input.getClass(); + final String itemClassName = itemClass.getName(); - joinedBlockAttributes.add( unlocalizedItem ); - joinedBlockAttributes.add( Boolean.toString( isBlock ) ); - joinedBlockAttributes.add( itemClassName ); - } + joinedBlockAttributes.add(unlocalizedItem); + joinedBlockAttributes.add(Boolean.toString(isBlock)); + joinedBlockAttributes.add(itemClassName); + } - final Joiner csvJoiner = Joiner.on( ", " ); - final Joiner csvJoinerIgnoringNulls = csvJoiner.skipNulls(); + final Joiner csvJoiner = Joiner.on(", "); + final Joiner csvJoinerIgnoringNulls = csvJoiner.skipNulls(); - return csvJoinerIgnoringNulls.join( joinedBlockAttributes ); - } - } + return csvJoinerIgnoringNulls.join(joinedBlockAttributes); + } + } } diff --git a/src/main/java/appeng/services/export/ModListChecker.java b/src/main/java/appeng/services/export/ModListChecker.java index 2fff4921b..05fcc8170 100644 --- a/src/main/java/appeng/services/export/ModListChecker.java +++ b/src/main/java/appeng/services/export/ModListChecker.java @@ -19,15 +19,12 @@ package appeng.services.export; -import java.util.List; - -import javax.annotation.Nonnull; - import com.google.common.base.Preconditions; - +import net.minecraftforge.fml.common.ModContainer; import org.apache.commons.codec.digest.DigestUtils; -import net.minecraftforge.fml.common.ModContainer; +import javax.annotation.Nonnull; +import java.util.List; /** @@ -38,58 +35,50 @@ import net.minecraftforge.fml.common.ModContainer; * @version rv3 - 01.09.2015 * @since rv3 - 01.09.2015 */ -final class ModListChecker implements Checker> -{ - private final String configHashValue; +final class ModListChecker implements Checker> { + private final String configHashValue; - @Nonnull - private final ExportConfig config; + @Nonnull + private final ExportConfig config; - /** - * @param config uses the config to retrieve the old hash of the mod list - */ - ModListChecker( @Nonnull final ExportConfig config ) - { - this.config = Preconditions.checkNotNull( config ); - this.configHashValue = Preconditions.checkNotNull( config.getCache() ); - } + /** + * @param config uses the config to retrieve the old hash of the mod list + */ + ModListChecker(@Nonnull final ExportConfig config) { + this.config = Preconditions.checkNotNull(config); + this.configHashValue = Preconditions.checkNotNull(config.getCache()); + } - /** - * Compiles a list of all mods and their versions to a digest which is updated, if it differs from the config. This - * is used to elevate the need to export - * the csv once again, if no change was detected. - * - * @param modContainers all mods and their versions to check if a difference exists between the current instance and - * the previous instance - * - * @return CheckType.EQUAL if no change was detected - */ - @Nonnull - @Override - public CheckType isEqual( @Nonnull final List modContainers ) - { - Preconditions.checkNotNull( modContainers ); + /** + * Compiles a list of all mods and their versions to a digest which is updated, if it differs from the config. This + * is used to elevate the need to export + * the csv once again, if no change was detected. + * + * @param modContainers all mods and their versions to check if a difference exists between the current instance and + * the previous instance + * @return CheckType.EQUAL if no change was detected + */ + @Nonnull + @Override + public CheckType isEqual(@Nonnull final List modContainers) { + Preconditions.checkNotNull(modContainers); - final StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); - for( final ModContainer container : modContainers ) - { - builder.append( container.getModId() ); - builder.append( container.getVersion() ); - } + for (final ModContainer container : modContainers) { + builder.append(container.getModId()); + builder.append(container.getVersion()); + } - final String allModsAndVersions = builder.toString(); - final String hex = DigestUtils.md5Hex( allModsAndVersions ); + final String allModsAndVersions = builder.toString(); + final String hex = DigestUtils.md5Hex(allModsAndVersions); - if( hex.equals( this.configHashValue ) ) - { - return CheckType.EQUAL; - } - else - { - this.config.setCache( hex ); + if (hex.equals(this.configHashValue)) { + return CheckType.EQUAL; + } else { + this.config.setCache(hex); - return CheckType.UNEQUAL; - } - } + return CheckType.UNEQUAL; + } + } } diff --git a/src/main/java/appeng/services/export/package-info.java b/src/main/java/appeng/services/export/package-info.java index de426424c..8d212f17a 100644 --- a/src/main/java/appeng/services/export/package-info.java +++ b/src/main/java/appeng/services/export/package-info.java @@ -19,10 +19,10 @@ /** * the export package is to export all the required information for recipes into a convenient CSV file * often names are difficult to acquire without access to the internal names. - * + *

* To save from rescanning every start-up it can save a list of mods and their version * and if only something changed, it requires to update the CSV. - * + *

* There is no explicit check if it was manually tempered * * @author thatsIch diff --git a/src/main/java/appeng/services/version/BaseVersion.java b/src/main/java/appeng/services/version/BaseVersion.java index c5f5fbb6b..f6bb36db1 100644 --- a/src/main/java/appeng/services/version/BaseVersion.java +++ b/src/main/java/appeng/services/version/BaseVersion.java @@ -19,105 +19,91 @@ package appeng.services.version; +import com.google.common.base.Preconditions; + import javax.annotation.Nonnegative; import javax.annotation.Nonnull; -import com.google.common.base.Preconditions; - /** * Base version of {@link Version}. - * + *

* Provides a unified way to test for equality and print a formatted string */ -public abstract class BaseVersion implements Version -{ - @Nonnegative - private final int revision; - @Nonnull - private final Channel channel; - @Nonnegative - private final int build; +public abstract class BaseVersion implements Version { + @Nonnegative + private final int revision; + @Nonnull + private final Channel channel; + @Nonnegative + private final int build; - /** - * @param revision revision in natural number - * @param channel channel - * @param build build in natural number - * - * @throws AssertionError if assertion are enabled and revision or build are not natural numbers - */ - public BaseVersion( @Nonnegative final int revision, @Nonnull final Channel channel, @Nonnegative final int build ) - { - Preconditions.checkArgument( revision >= 0 ); - Preconditions.checkNotNull( channel ); - Preconditions.checkArgument( build >= 0 ); + /** + * @param revision revision in natural number + * @param channel channel + * @param build build in natural number + * @throws AssertionError if assertion are enabled and revision or build are not natural numbers + */ + public BaseVersion(@Nonnegative final int revision, @Nonnull final Channel channel, @Nonnegative final int build) { + Preconditions.checkArgument(revision >= 0); + Preconditions.checkNotNull(channel); + Preconditions.checkArgument(build >= 0); - this.revision = revision; - this.channel = channel; - this.build = build; - } + this.revision = revision; + this.channel = channel; + this.build = build; + } - @Override - public final int revision() - { - return this.revision; - } + @Override + public final int revision() { + return this.revision; + } - @Override - public final Channel channel() - { - return this.channel; - } + @Override + public final Channel channel() { + return this.channel; + } - @Override - public final int build() - { - return this.build; - } + @Override + public final int build() { + return this.build; + } - @Override - public String formatted() - { - return "rv" + this.revision + '-' + this.channel.name().toLowerCase() + '-' + this.build; - } + @Override + public String formatted() { + return "rv" + this.revision + '-' + this.channel.name().toLowerCase() + '-' + this.build; + } - @Override - public final int hashCode() - { - int result = this.revision; - result = 31 * result + this.channel.hashCode(); - result = 31 * result + this.build; - return result; - } + @Override + public final int hashCode() { + int result = this.revision; + result = 31 * result + this.channel.hashCode(); + result = 31 * result + this.build; + return result; + } - @Override - public final boolean equals( final Object o ) - { - if( this == o ) - { - return true; - } - if( !( o instanceof Version ) ) - { - return false; - } + @Override + public final boolean equals(final Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Version)) { + return false; + } - final Version that = (Version) o; + final Version that = (Version) o; - if( this.revision != that.revision() ) - { - return false; - } - if( this.build != that.build() ) - { - return false; - } - return this.channel == that.channel(); - } + if (this.revision != that.revision()) { + return false; + } + if (this.build != that.build()) { + return false; + } + return this.channel == that.channel(); + } - @Override - public final String toString() - { - return "Version{" + "revision=" + this.revision + ", channel=" + this.channel + ", build=" + this.build + '}'; - } + @Override + public final String toString() { + return "Version{" + "revision=" + this.revision + ", channel=" + this.channel + ", build=" + this.build + '}'; + } } diff --git a/src/main/java/appeng/services/version/Channel.java b/src/main/java/appeng/services/version/Channel.java index 7a97cd3e0..1522f68fa 100644 --- a/src/main/java/appeng/services/version/Channel.java +++ b/src/main/java/appeng/services/version/Channel.java @@ -23,7 +23,6 @@ package appeng.services.version; * Represents the release channel of Applied Energistics. The mod is either in Alpha, Beta or Stable channel. * Any more might be confusing to the end-user */ -public enum Channel -{ - Alpha, Beta, Stable +public enum Channel { + Alpha, Beta, Stable } diff --git a/src/main/java/appeng/services/version/DefaultVersion.java b/src/main/java/appeng/services/version/DefaultVersion.java index 6292f2a6a..05dc3662b 100644 --- a/src/main/java/appeng/services/version/DefaultVersion.java +++ b/src/main/java/appeng/services/version/DefaultVersion.java @@ -27,25 +27,22 @@ import javax.annotation.Nonnull; * AE prints version like rv2-beta-8 * GitHub prints version like rv2.beta.8 */ -public final class DefaultVersion extends BaseVersion -{ - /** - * @param revision natural number - * @param channel either alpha, beta or release - * @param build natural number - */ - public DefaultVersion( @Nonnegative final int revision, @Nonnull final Channel channel, @Nonnegative final int build ) - { - super( revision, channel, build ); - } +public final class DefaultVersion extends BaseVersion { + /** + * @param revision natural number + * @param channel either alpha, beta or release + * @param build natural number + */ + public DefaultVersion(@Nonnegative final int revision, @Nonnull final Channel channel, @Nonnegative final int build) { + super(revision, channel, build); + } - @Override - public boolean isNewerAs( final Version maybeOlder ) - { - final boolean isNewerRevision = this.revision() > maybeOlder.revision(); - final boolean isNewerChannel = this.channel().compareTo( maybeOlder.channel() ) > 0; - final boolean isNewerBuild = this.build() > maybeOlder.build(); + @Override + public boolean isNewerAs(final Version maybeOlder) { + final boolean isNewerRevision = this.revision() > maybeOlder.revision(); + final boolean isNewerChannel = this.channel().compareTo(maybeOlder.channel()) > 0; + final boolean isNewerBuild = this.build() > maybeOlder.build(); - return isNewerRevision || isNewerChannel || isNewerBuild; - } + return isNewerRevision || isNewerChannel || isNewerBuild; + } } diff --git a/src/main/java/appeng/services/version/DoNotCheckVersion.java b/src/main/java/appeng/services/version/DoNotCheckVersion.java index 9edff745e..8484205e7 100644 --- a/src/main/java/appeng/services/version/DoNotCheckVersion.java +++ b/src/main/java/appeng/services/version/DoNotCheckVersion.java @@ -22,22 +22,18 @@ package appeng.services.version; /** * Exceptional template for {@link Version}, when the mod does not want a check */ -public final class DoNotCheckVersion extends BaseVersion -{ - public DoNotCheckVersion() - { - super( Integer.MAX_VALUE, Channel.Stable, Integer.MAX_VALUE ); - } +public final class DoNotCheckVersion extends BaseVersion { + public DoNotCheckVersion() { + super(Integer.MAX_VALUE, Channel.Stable, Integer.MAX_VALUE); + } - @Override - public boolean isNewerAs( final Version maybeOlder ) - { - return true; - } + @Override + public boolean isNewerAs(final Version maybeOlder) { + return true; + } - @Override - public String formatted() - { - return "dev build"; - } + @Override + public String formatted() { + return "dev build"; + } } diff --git a/src/main/java/appeng/services/version/MissingVersion.java b/src/main/java/appeng/services/version/MissingVersion.java index 4928aeb66..789bfc494 100644 --- a/src/main/java/appeng/services/version/MissingVersion.java +++ b/src/main/java/appeng/services/version/MissingVersion.java @@ -22,27 +22,22 @@ package appeng.services.version; /** * Exceptional template when the {@link Version} could not be retrieved */ -public final class MissingVersion extends BaseVersion -{ - public MissingVersion() - { - super( 0, Channel.Alpha, 0 ); - } +public final class MissingVersion extends BaseVersion { + public MissingVersion() { + super(0, Channel.Alpha, 0); + } - /** - * @param maybeOlder ignored - * - * @return false - */ - @Override - public boolean isNewerAs( final Version maybeOlder ) - { - return false; - } + /** + * @param maybeOlder ignored + * @return false + */ + @Override + public boolean isNewerAs(final Version maybeOlder) { + return false; + } - @Override - public String formatted() - { - return "missing"; - } + @Override + public String formatted() { + return "missing"; + } } diff --git a/src/main/java/appeng/services/version/ModVersionFetcher.java b/src/main/java/appeng/services/version/ModVersionFetcher.java index eb5e80153..1f92724bd 100644 --- a/src/main/java/appeng/services/version/ModVersionFetcher.java +++ b/src/main/java/appeng/services/version/ModVersionFetcher.java @@ -19,57 +19,50 @@ package appeng.services.version; -import javax.annotation.Nonnull; - import appeng.core.AELog; import appeng.services.version.exceptions.VersionCheckerException; +import javax.annotation.Nonnull; + /** * Wrapper for {@link VersionParser} to check if the check is happening in developer environment or in a pull request. - * + *

* In that case ignore the check. */ -public final class ModVersionFetcher implements VersionFetcher -{ - private static final Version EXCEPTIONAL_VERSION = new MissingVersion(); +public final class ModVersionFetcher implements VersionFetcher { + private static final Version EXCEPTIONAL_VERSION = new MissingVersion(); - @Nonnull - private final String rawModVersion; - @Nonnull - private final VersionParser parser; + @Nonnull + private final String rawModVersion; + @Nonnull + private final VersionParser parser; - public ModVersionFetcher( @Nonnull final String rawModVersion, @Nonnull final VersionParser parser ) - { - this.rawModVersion = rawModVersion; - this.parser = parser; - } + public ModVersionFetcher(@Nonnull final String rawModVersion, @Nonnull final VersionParser parser) { + this.rawModVersion = rawModVersion; + this.parser = parser; + } - /** - * Parses only, if not checked in developer environment or in a pull request - * - * @return {@link DoNotCheckVersion} if in developer environment or pull request, {@link MissingVersion} in case of - * a parser exception or else the parsed {@link Version}. - */ - @Override - public Version get() - { - if( this.rawModVersion.equals( "@version@" ) || this.rawModVersion.contains( "pr" ) ) - { - return new DoNotCheckVersion(); - } + /** + * Parses only, if not checked in developer environment or in a pull request + * + * @return {@link DoNotCheckVersion} if in developer environment or pull request, {@link MissingVersion} in case of + * a parser exception or else the parsed {@link Version}. + */ + @Override + public Version get() { + if (this.rawModVersion.equals("@version@") || this.rawModVersion.contains("pr")) { + return new DoNotCheckVersion(); + } - try - { - final Version version = this.parser.parse( this.rawModVersion ); + try { + final Version version = this.parser.parse(this.rawModVersion); - return version; - } - catch( final VersionCheckerException e ) - { - AELog.debug( e ); + return version; + } catch (final VersionCheckerException e) { + AELog.debug(e); - return EXCEPTIONAL_VERSION; - } - } + return EXCEPTIONAL_VERSION; + } + } } diff --git a/src/main/java/appeng/services/version/Version.java b/src/main/java/appeng/services/version/Version.java index 125f254af..d45d5c1ae 100644 --- a/src/main/java/appeng/services/version/Version.java +++ b/src/main/java/appeng/services/version/Version.java @@ -22,39 +22,38 @@ package appeng.services.version; /** * Stores version information, which are easily compared */ -public interface Version -{ - /** - * @return revision of this version - */ - int revision(); +public interface Version { + /** + * @return revision of this version + */ + int revision(); - /** - * @return channel of this version - */ - Channel channel(); + /** + * @return channel of this version + */ + Channel channel(); - /** - * @return build of this version - */ - int build(); + /** + * @return build of this version + */ + int build(); - /** - * A version is never if these criteria are met: - * if the current revision is higher than the compared revision OR - * if revision are equal and the current channel is higher than the compared channel (Stable > Beta > Alpha) OR - * if revision, channel are equal and the build is higher than the compared build - * - * @return true if criteria are met - */ - boolean isNewerAs( Version maybeOlder ); + /** + * A version is never if these criteria are met: + * if the current revision is higher than the compared revision OR + * if revision are equal and the current channel is higher than the compared channel (Stable > Beta > Alpha) OR + * if revision, channel are equal and the build is higher than the compared build + * + * @return true if criteria are met + */ + boolean isNewerAs(Version maybeOlder); - /** - * Prints the revision, channel and build into a common displayed way - * - * rv2-beta-8 - * - * @return formatted version - */ - String formatted(); + /** + * Prints the revision, channel and build into a common displayed way + *

+ * rv2-beta-8 + * + * @return formatted version + */ + String formatted(); } diff --git a/src/main/java/appeng/services/version/VersionCheckerConfig.java b/src/main/java/appeng/services/version/VersionCheckerConfig.java index 996d76509..78323bfa3 100644 --- a/src/main/java/appeng/services/version/VersionCheckerConfig.java +++ b/src/main/java/appeng/services/version/VersionCheckerConfig.java @@ -19,116 +19,103 @@ package appeng.services.version; -import java.io.File; -import java.util.Date; +import com.google.common.base.Preconditions; +import net.minecraftforge.common.config.Configuration; import javax.annotation.Nonnull; - -import com.google.common.base.Preconditions; - -import net.minecraftforge.common.config.Configuration; +import java.io.File; +import java.util.Date; /** * Separate config file to handle the version checker */ -public final class VersionCheckerConfig -{ - private static final int DEFAULT_INTERVAL_HOURS = 24; - private static final int MIN_INTERVAL_HOURS = 0; - private static final int MAX_INTERVAL_HOURS = 7 * 24; +public final class VersionCheckerConfig { + private static final int DEFAULT_INTERVAL_HOURS = 24; + private static final int MIN_INTERVAL_HOURS = 0; + private static final int MAX_INTERVAL_HOURS = 7 * 24; - @Nonnull - private final Configuration config; + @Nonnull + private final Configuration config; - private final boolean isEnabled; + private final boolean isEnabled; - @Nonnull - private final String lastCheck; - private final int interval; + @Nonnull + private final String lastCheck; + private final int interval; - @Nonnull - private final String level; + @Nonnull + private final String level; - private final boolean shouldNotifyPlayer; - private final boolean shouldPostChangelog; + private final boolean shouldNotifyPlayer; + private final boolean shouldPostChangelog; - /** - * @param file requires fully qualified file in which the config is saved - */ - public VersionCheckerConfig( @Nonnull final File file ) - { - Preconditions.checkNotNull( file ); - Preconditions.checkState( !file.isDirectory() ); + /** + * @param file requires fully qualified file in which the config is saved + */ + public VersionCheckerConfig(@Nonnull final File file) { + Preconditions.checkNotNull(file); + Preconditions.checkState(!file.isDirectory()); - this.config = new Configuration( file ); + this.config = new Configuration(file); - // initializes default values by caching - this.isEnabled = this.config.getBoolean( "enabled", "general", true, "If true, the version checker is enabled. Acts as a master switch." ); + // initializes default values by caching + this.isEnabled = this.config.getBoolean("enabled", "general", true, "If true, the version checker is enabled. Acts as a master switch."); - this.lastCheck = this.config.getString( "lastCheck", "cache", "0", - "The number of milliseconds since January 1, 1970, 00:00:00 GMT of the last successful check." ); - this.interval = this.config.getInt( "interval", "cache", DEFAULT_INTERVAL_HOURS, MIN_INTERVAL_HOURS, MAX_INTERVAL_HOURS, - "Waits as many hours, until it checks again." ); + this.lastCheck = this.config.getString("lastCheck", "cache", "0", + "The number of milliseconds since January 1, 1970, 00:00:00 GMT of the last successful check."); + this.interval = this.config.getInt("interval", "cache", DEFAULT_INTERVAL_HOURS, MIN_INTERVAL_HOURS, MAX_INTERVAL_HOURS, + "Waits as many hours, until it checks again."); - this.level = this.config.getString( "level", "channel", "Beta", - "Determines the channel level which should be checked for updates. Can be either Stable, Beta or Alpha." ); + this.level = this.config.getString("level", "channel", "Beta", + "Determines the channel level which should be checked for updates. Can be either Stable, Beta or Alpha."); - this.shouldNotifyPlayer = this.config.getBoolean( "notify", "client", true, - "If true, the player is getting a notification, that a new version is available." ); - this.shouldPostChangelog = this.config.getBoolean( "changelog", "client", true, - "If true, the player is getting a notification including changelog. Only happens if notification are enabled." ); - } + this.shouldNotifyPlayer = this.config.getBoolean("notify", "client", true, + "If true, the player is getting a notification, that a new version is available."); + this.shouldPostChangelog = this.config.getBoolean("changelog", "client", true, + "If true, the player is getting a notification including changelog. Only happens if notification are enabled."); + } - public boolean isVersionCheckingEnabled() - { - return this.isEnabled; - } + public boolean isVersionCheckingEnabled() { + return this.isEnabled; + } - public String lastCheck() - { - return this.lastCheck; - } + public String lastCheck() { + return this.lastCheck; + } - /** - * Stores the current date in milli seconds into the "lastCheck" field of the config and makes it persistent. - */ - public void updateLastCheck() - { - final Date now = new Date(); - final long nowInMs = now.getTime(); - final String nowAsString = Long.toString( nowInMs ); + /** + * Stores the current date in milli seconds into the "lastCheck" field of the config and makes it persistent. + */ + public void updateLastCheck() { + final Date now = new Date(); + final long nowInMs = now.getTime(); + final String nowAsString = Long.toString(nowInMs); - this.config.get( "cache", "lastCheck", "0" ).set( nowAsString ); + this.config.get("cache", "lastCheck", "0").set(nowAsString); - this.config.save(); - } + this.config.save(); + } - public int interval() - { - return this.interval; - } + public int interval() { + return this.interval; + } - public String level() - { - return this.level; - } + public String level() { + return this.level; + } - public boolean shouldNotifyPlayer() - { - return this.shouldNotifyPlayer; - } + public boolean shouldNotifyPlayer() { + return this.shouldNotifyPlayer; + } - public boolean shouldPostChangelog() - { - return this.shouldPostChangelog; - } + public boolean shouldPostChangelog() { + return this.shouldPostChangelog; + } - public void save() - { - if( this.config.hasChanged() ) - { - this.config.save(); - } - } + public void save() { + if (this.config.hasChanged()) { + this.config.save(); + } + } } diff --git a/src/main/java/appeng/services/version/VersionFetcher.java b/src/main/java/appeng/services/version/VersionFetcher.java index c30faddf0..513eee239 100644 --- a/src/main/java/appeng/services/version/VersionFetcher.java +++ b/src/main/java/appeng/services/version/VersionFetcher.java @@ -22,7 +22,6 @@ package appeng.services.version; /** * Processes base information to retrieve a {@link Version} */ -public interface VersionFetcher -{ - Version get(); +public interface VersionFetcher { + Version get(); } diff --git a/src/main/java/appeng/services/version/VersionParser.java b/src/main/java/appeng/services/version/VersionParser.java index baed475f4..65998dc01 100644 --- a/src/main/java/appeng/services/version/VersionParser.java +++ b/src/main/java/appeng/services/version/VersionParser.java @@ -19,182 +19,148 @@ package appeng.services.version; -import java.util.Scanner; -import java.util.regex.Pattern; - -import javax.annotation.Nonnull; - +import appeng.services.version.exceptions.*; import com.google.common.base.Preconditions; -import appeng.services.version.exceptions.InvalidBuildException; -import appeng.services.version.exceptions.InvalidChannelException; -import appeng.services.version.exceptions.InvalidRevisionException; -import appeng.services.version.exceptions.InvalidVersionException; -import appeng.services.version.exceptions.MissingSeparatorException; -import appeng.services.version.exceptions.VersionCheckerException; +import javax.annotation.Nonnull; +import java.util.Scanner; +import java.util.regex.Pattern; /** * can parse a version in form of rv2-beta-8 or rv2.beta.8 */ -public final class VersionParser -{ - private static final Pattern PATTERN_DOT = Pattern.compile( "\\." ); - private static final Pattern PATTERN_DASH = Pattern.compile( "-" ); - private static final Pattern PATTERN_REVISION = Pattern.compile( "[^0-9]+" ); - private static final Pattern PATTERN_BUILD = Pattern.compile( "[^0-9]+" ); - private static final Pattern PATTERN_NATURAL = Pattern.compile( "[0-9]+" ); - private static final Pattern PATTERN_VALID_REVISION = Pattern.compile( "^rv\\d+$" ); +public final class VersionParser { + private static final Pattern PATTERN_DOT = Pattern.compile("\\."); + private static final Pattern PATTERN_DASH = Pattern.compile("-"); + private static final Pattern PATTERN_REVISION = Pattern.compile("[^0-9]+"); + private static final Pattern PATTERN_BUILD = Pattern.compile("[^0-9]+"); + private static final Pattern PATTERN_NATURAL = Pattern.compile("[0-9]+"); + private static final Pattern PATTERN_VALID_REVISION = Pattern.compile("^rv\\d+$"); - /** - * Parses the {@link Version} out of a String - * - * @param raw String in form of rv2-beta-8 or rv2.beta.8 - * - * @return {@link Version} encoded in the raw String - * - * @throws VersionCheckerException if parsing the raw string was not successful. - * - */ - public Version parse( @Nonnull final String raw ) throws VersionCheckerException - { - Preconditions.checkNotNull( raw ); + /** + * Parses the {@link Version} out of a String + * + * @param raw String in form of rv2-beta-8 or rv2.beta.8 + * @return {@link Version} encoded in the raw String + * @throws VersionCheckerException if parsing the raw string was not successful. + */ + public Version parse(@Nonnull final String raw) throws VersionCheckerException { + Preconditions.checkNotNull(raw); - final String transformed = this.transformDelimiter( raw ); - final String[] split = transformed.split( "_" ); + final String transformed = this.transformDelimiter(raw); + final String[] split = transformed.split("_"); - return this.parseVersion( split ); - } + return this.parseVersion(split); + } - /** - * Replaces all "." and "-" into "_" to make them uniform - * - * @param raw raw version string containing "." or "-" - * - * @return transformed raw, where "." and "-" are replaced by "_" - * - * @throws MissingSeparatorException if not containing valid separators - */ - private String transformDelimiter( @Nonnull final String raw ) throws MissingSeparatorException - { - if( !( raw.contains( "." ) || raw.contains( "-" ) ) ) - { - throw new MissingSeparatorException(); - } + /** + * Replaces all "." and "-" into "_" to make them uniform + * + * @param raw raw version string containing "." or "-" + * @return transformed raw, where "." and "-" are replaced by "_" + * @throws MissingSeparatorException if not containing valid separators + */ + private String transformDelimiter(@Nonnull final String raw) throws MissingSeparatorException { + if (!(raw.contains(".") || raw.contains("-"))) { + throw new MissingSeparatorException(); + } - final String withoutDot = PATTERN_DOT.matcher( raw ).replaceAll( "_" ); - final String withoutDash = PATTERN_DASH.matcher( withoutDot ).replaceAll( "_" ); + final String withoutDot = PATTERN_DOT.matcher(raw).replaceAll("_"); + final String withoutDash = PATTERN_DASH.matcher(withoutDot).replaceAll("_"); - return withoutDash; - } + return withoutDash; + } - /** - * parses the {@link Version} out of the split. - * The split must have a length of 3, - * representing revision, channel and build. - * - * @param splitRaw raw version split with length of 3 - * - * @return {@link Version} represented by the splitRaw - * - * @throws InvalidVersionException when length not 3 - * @throws InvalidRevisionException {@link VersionParser#parseRevision(String)} - * @throws InvalidChannelException {@link VersionParser#parseChannel(String)} - * @throws InvalidBuildException {@link VersionParser#parseBuild(String)} - */ - private Version parseVersion( @Nonnull final String[] splitRaw ) throws InvalidVersionException, InvalidRevisionException, InvalidChannelException, InvalidBuildException - { - if( splitRaw.length != 3 ) - { - throw new InvalidVersionException(); - } + /** + * parses the {@link Version} out of the split. + * The split must have a length of 3, + * representing revision, channel and build. + * + * @param splitRaw raw version split with length of 3 + * @return {@link Version} represented by the splitRaw + * @throws InvalidVersionException when length not 3 + * @throws InvalidRevisionException {@link VersionParser#parseRevision(String)} + * @throws InvalidChannelException {@link VersionParser#parseChannel(String)} + * @throws InvalidBuildException {@link VersionParser#parseBuild(String)} + */ + private Version parseVersion(@Nonnull final String[] splitRaw) throws InvalidVersionException, InvalidRevisionException, InvalidChannelException, InvalidBuildException { + if (splitRaw.length != 3) { + throw new InvalidVersionException(); + } - final String rawRevision = splitRaw[0]; - final String rawChannel = splitRaw[1]; - final String rawBuild = splitRaw[2]; + final String rawRevision = splitRaw[0]; + final String rawChannel = splitRaw[1]; + final String rawBuild = splitRaw[2]; - final int revision = this.parseRevision( rawRevision ); - final Channel channel = this.parseChannel( rawChannel ); - final int build = this.parseBuild( rawBuild ); + final int revision = this.parseRevision(rawRevision); + final Channel channel = this.parseChannel(rawChannel); + final int build = this.parseBuild(rawBuild); - return new DefaultVersion( revision, channel, build ); - } + return new DefaultVersion(revision, channel, build); + } - /** - * A revision starts with the keyword "rv", followed by a natural number - * - * @param rawRevision String containing the revision number - * - * @return revision number - * - * @throws InvalidRevisionException if not matching "rv" followed by a natural number. - */ - private int parseRevision( @Nonnull final String rawRevision ) throws InvalidRevisionException - { - if( !PATTERN_VALID_REVISION.matcher( rawRevision ).matches() ) - { - throw new InvalidRevisionException(); - } + /** + * A revision starts with the keyword "rv", followed by a natural number + * + * @param rawRevision String containing the revision number + * @return revision number + * @throws InvalidRevisionException if not matching "rv" followed by a natural number. + */ + private int parseRevision(@Nonnull final String rawRevision) throws InvalidRevisionException { + if (!PATTERN_VALID_REVISION.matcher(rawRevision).matches()) { + throw new InvalidRevisionException(); + } - final Scanner scanner = new Scanner( rawRevision ); + final Scanner scanner = new Scanner(rawRevision); - final int revision = scanner.useDelimiter( PATTERN_REVISION ).nextInt(); + final int revision = scanner.useDelimiter(PATTERN_REVISION).nextInt(); - scanner.close(); + scanner.close(); - return revision; - } + return revision; + } - /** - * A channel is atm either one of {@link Channel#Alpha}, {@link Channel#Beta} or {@link Channel#Stable} - * - * @param rawChannel String containing the channel - * - * @return matching {@link Channel} to the String - * - * @throws InvalidChannelException if not one of {@link Channel} values. - */ - private Channel parseChannel( @Nonnull final String rawChannel ) throws InvalidChannelException - { - if( !( rawChannel.equalsIgnoreCase( Channel.Alpha.name() ) || rawChannel.equalsIgnoreCase( Channel.Beta.name() ) || rawChannel - .equalsIgnoreCase( Channel.Stable.name() ) ) ) - { - throw new InvalidChannelException(); - } + /** + * A channel is atm either one of {@link Channel#Alpha}, {@link Channel#Beta} or {@link Channel#Stable} + * + * @param rawChannel String containing the channel + * @return matching {@link Channel} to the String + * @throws InvalidChannelException if not one of {@link Channel} values. + */ + private Channel parseChannel(@Nonnull final String rawChannel) throws InvalidChannelException { + if (!(rawChannel.equalsIgnoreCase(Channel.Alpha.name()) || rawChannel.equalsIgnoreCase(Channel.Beta.name()) || rawChannel + .equalsIgnoreCase(Channel.Stable.name()))) { + throw new InvalidChannelException(); + } - for( final Channel channel : Channel.values() ) - { - if( channel.name().equalsIgnoreCase( rawChannel ) ) - { - return channel; - } - } + for (final Channel channel : Channel.values()) { + if (channel.name().equalsIgnoreCase(rawChannel)) { + return channel; + } + } - throw new InvalidChannelException(); - } + throw new InvalidChannelException(); + } - /** - * A build is just a natural number - * - * @param rawBuild String containing the build number - * - * @return build number - * - * @throws InvalidBuildException if not a natural number. - */ - private int parseBuild( @Nonnull final String rawBuild ) throws InvalidBuildException - { - if( !PATTERN_NATURAL.matcher( rawBuild ).matches() ) - { - throw new InvalidBuildException(); - } + /** + * A build is just a natural number + * + * @param rawBuild String containing the build number + * @return build number + * @throws InvalidBuildException if not a natural number. + */ + private int parseBuild(@Nonnull final String rawBuild) throws InvalidBuildException { + if (!PATTERN_NATURAL.matcher(rawBuild).matches()) { + throw new InvalidBuildException(); + } - final Scanner scanner = new Scanner( rawBuild ); + final Scanner scanner = new Scanner(rawBuild); - final int build = scanner.useDelimiter( PATTERN_BUILD ).nextInt(); + final int build = scanner.useDelimiter(PATTERN_BUILD).nextInt(); - scanner.close(); + scanner.close(); - return build; - } + return build; + } } diff --git a/src/main/java/appeng/services/version/exceptions/InvalidBuildException.java b/src/main/java/appeng/services/version/exceptions/InvalidBuildException.java index b70490160..1590766c9 100644 --- a/src/main/java/appeng/services/version/exceptions/InvalidBuildException.java +++ b/src/main/java/appeng/services/version/exceptions/InvalidBuildException.java @@ -22,12 +22,10 @@ package appeng.services.version.exceptions; /** * Indicates a invalid build number, which is any string except a natural number. */ -public class InvalidBuildException extends VersionCheckerException -{ - private static final long serialVersionUID = 3015432444672364991L; +public class InvalidBuildException extends VersionCheckerException { + private static final long serialVersionUID = 3015432444672364991L; - public InvalidBuildException() - { - super( "Invalid Build: Needs to be a natural number." ); - } + public InvalidBuildException() { + super("Invalid Build: Needs to be a natural number."); + } } diff --git a/src/main/java/appeng/services/version/exceptions/InvalidChannelException.java b/src/main/java/appeng/services/version/exceptions/InvalidChannelException.java index 824d1f87d..525714a1c 100644 --- a/src/main/java/appeng/services/version/exceptions/InvalidChannelException.java +++ b/src/main/java/appeng/services/version/exceptions/InvalidChannelException.java @@ -25,12 +25,10 @@ import appeng.services.version.Channel; /** * Indicates an invalid {@link Channel} value. */ -public class InvalidChannelException extends VersionCheckerException -{ - private static final long serialVersionUID = -1306378515002341620L; +public class InvalidChannelException extends VersionCheckerException { + private static final long serialVersionUID = -1306378515002341620L; - public InvalidChannelException() - { - super( "Invalid Channel: Needs to be one of the following values; alpha, beta, or stable." ); - } + public InvalidChannelException() { + super("Invalid Channel: Needs to be one of the following values; alpha, beta, or stable."); + } } diff --git a/src/main/java/appeng/services/version/exceptions/InvalidRevisionException.java b/src/main/java/appeng/services/version/exceptions/InvalidRevisionException.java index 02a155ce0..1c5f35a49 100644 --- a/src/main/java/appeng/services/version/exceptions/InvalidRevisionException.java +++ b/src/main/java/appeng/services/version/exceptions/InvalidRevisionException.java @@ -22,13 +22,11 @@ package appeng.services.version.exceptions; /** * Indicates a invalid revision, which does not match the pattern "rv" followed by a natural number. */ -public class InvalidRevisionException extends VersionCheckerException -{ +public class InvalidRevisionException extends VersionCheckerException { - private static final long serialVersionUID = 4828906902143875942L; + private static final long serialVersionUID = 4828906902143875942L; - public InvalidRevisionException() - { - super( "Invalid Revision: Needs to be 'rv' followd by a natural number." ); - } + public InvalidRevisionException() { + super("Invalid Revision: Needs to be 'rv' followd by a natural number."); + } } diff --git a/src/main/java/appeng/services/version/exceptions/InvalidVersionException.java b/src/main/java/appeng/services/version/exceptions/InvalidVersionException.java index 1985bc760..c5dbb19a8 100644 --- a/src/main/java/appeng/services/version/exceptions/InvalidVersionException.java +++ b/src/main/java/appeng/services/version/exceptions/InvalidVersionException.java @@ -22,13 +22,11 @@ package appeng.services.version.exceptions; /** * Indicates an invalid version, which does not consists of 3 parts matching /(rv\d+)-(alpha|beta|stable)-(b\d+)/. */ -public class InvalidVersionException extends VersionCheckerException -{ +public class InvalidVersionException extends VersionCheckerException { - private static final long serialVersionUID = 4828906902143875942L; + private static final long serialVersionUID = 4828906902143875942L; - public InvalidVersionException() - { - super( "Invalid Version Format: Need to consist of exactly 3 parts separated by a dash." ); - } + public InvalidVersionException() { + super("Invalid Version Format: Need to consist of exactly 3 parts separated by a dash."); + } } diff --git a/src/main/java/appeng/services/version/exceptions/MissingSeparatorException.java b/src/main/java/appeng/services/version/exceptions/MissingSeparatorException.java index f3fc4b35e..f50a266a3 100644 --- a/src/main/java/appeng/services/version/exceptions/MissingSeparatorException.java +++ b/src/main/java/appeng/services/version/exceptions/MissingSeparatorException.java @@ -21,15 +21,13 @@ package appeng.services.version.exceptions; /** * Indicates a version without a valid separator. - * + *

* Valid separators are a dash ("-") or dot (".") */ -public class MissingSeparatorException extends VersionCheckerException -{ - private static final long serialVersionUID = 8366370192017020750L; +public class MissingSeparatorException extends VersionCheckerException { + private static final long serialVersionUID = 8366370192017020750L; - public MissingSeparatorException() - { - super( "Invalid Revision: Needs to match 'rv' followed by a natural number." ); - } + public MissingSeparatorException() { + super("Invalid Revision: Needs to match 'rv' followed by a natural number."); + } } diff --git a/src/main/java/appeng/services/version/exceptions/VersionCheckerException.java b/src/main/java/appeng/services/version/exceptions/VersionCheckerException.java index 190c1da41..1540d7543 100644 --- a/src/main/java/appeng/services/version/exceptions/VersionCheckerException.java +++ b/src/main/java/appeng/services/version/exceptions/VersionCheckerException.java @@ -25,12 +25,10 @@ import javax.annotation.Nonnull; /** * A super class for any exception thrown by the version checker for easier handling. */ -public class VersionCheckerException extends Exception -{ - private static final long serialVersionUID = 4582501864800542884L; +public class VersionCheckerException extends Exception { + private static final long serialVersionUID = 4582501864800542884L; - public VersionCheckerException( @Nonnull final String string ) - { - super( string ); - } + public VersionCheckerException(@Nonnull final String string) { + super(string); + } } diff --git a/src/main/java/appeng/services/version/github/DefaultFormattedRelease.java b/src/main/java/appeng/services/version/github/DefaultFormattedRelease.java index c194a296e..bfef120c3 100644 --- a/src/main/java/appeng/services/version/github/DefaultFormattedRelease.java +++ b/src/main/java/appeng/services/version/github/DefaultFormattedRelease.java @@ -19,36 +19,32 @@ package appeng.services.version.github; -import javax.annotation.Nonnull; - import appeng.services.version.Version; +import javax.annotation.Nonnull; + /** * Default template when a {@link FormattedRelease} is needed. */ -public final class DefaultFormattedRelease implements FormattedRelease -{ - @Nonnull - private final Version version; - @Nonnull - private final String changelog; +public final class DefaultFormattedRelease implements FormattedRelease { + @Nonnull + private final Version version; + @Nonnull + private final String changelog; - public DefaultFormattedRelease( @Nonnull final Version version, @Nonnull final String changelog ) - { - this.version = version; - this.changelog = changelog; - } + public DefaultFormattedRelease(@Nonnull final Version version, @Nonnull final String changelog) { + this.version = version; + this.changelog = changelog; + } - @Override - public String changelog() - { - return this.changelog; - } + @Override + public String changelog() { + return this.changelog; + } - @Override - public Version version() - { - return this.version; - } + @Override + public Version version() { + return this.version; + } } diff --git a/src/main/java/appeng/services/version/github/FormattedRelease.java b/src/main/java/appeng/services/version/github/FormattedRelease.java index fef5ae2fa..f84bb568f 100644 --- a/src/main/java/appeng/services/version/github/FormattedRelease.java +++ b/src/main/java/appeng/services/version/github/FormattedRelease.java @@ -25,15 +25,14 @@ import appeng.services.version.Version; /** * Represents the acquired, processed information through github about a release of Applied Energistics 2 */ -public interface FormattedRelease -{ - /** - * @return changelog - */ - String changelog(); +public interface FormattedRelease { + /** + * @return changelog + */ + String changelog(); - /** - * @return processed version - */ - Version version(); + /** + * @return processed version + */ + Version version(); } diff --git a/src/main/java/appeng/services/version/github/MissingFormattedRelease.java b/src/main/java/appeng/services/version/github/MissingFormattedRelease.java index cbe836cda..08d7744bf 100644 --- a/src/main/java/appeng/services/version/github/MissingFormattedRelease.java +++ b/src/main/java/appeng/services/version/github/MissingFormattedRelease.java @@ -19,40 +19,36 @@ package appeng.services.version.github; -import javax.annotation.Nonnull; - import appeng.services.version.MissingVersion; import appeng.services.version.Version; +import javax.annotation.Nonnull; + /** * Exceptional template, when no meaningful {@link FormattedRelease} could be obtained */ -public final class MissingFormattedRelease implements FormattedRelease -{ - @Nonnull - private final Version version; +public final class MissingFormattedRelease implements FormattedRelease { + @Nonnull + private final Version version; - public MissingFormattedRelease() - { - this.version = new MissingVersion(); - } + public MissingFormattedRelease() { + this.version = new MissingVersion(); + } - /** - * @return empty string - */ - @Override - public String changelog() - { - return ""; - } + /** + * @return empty string + */ + @Override + public String changelog() { + return ""; + } - /** - * @return {@link MissingVersion} - */ - @Override - public Version version() - { - return this.version; - } + /** + * @return {@link MissingVersion} + */ + @Override + public Version version() { + return this.version; + } } diff --git a/src/main/java/appeng/services/version/github/Release.java b/src/main/java/appeng/services/version/github/Release.java index 9dc0f6519..01aafa1c8 100644 --- a/src/main/java/appeng/services/version/github/Release.java +++ b/src/main/java/appeng/services/version/github/Release.java @@ -22,16 +22,15 @@ package appeng.services.version.github; /** * Template class for Gson to write values from the Json Object into an actual class */ -@SuppressWarnings( "all" ) -public class Release -{ - /** - * name of the tag it is saved - */ - public String tag_name; +@SuppressWarnings("all") +public class Release { + /** + * name of the tag it is saved + */ + public String tag_name; - /** - * Contains the changelog - */ - public String body; + /** + * Contains the changelog + */ + public String body; } diff --git a/src/main/java/appeng/services/version/github/ReleaseFetcher.java b/src/main/java/appeng/services/version/github/ReleaseFetcher.java index 30a337d54..652fed42e 100644 --- a/src/main/java/appeng/services/version/github/ReleaseFetcher.java +++ b/src/main/java/appeng/services/version/github/ReleaseFetcher.java @@ -19,104 +19,86 @@ package appeng.services.version.github; -import java.io.IOException; -import java.lang.reflect.Type; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; - -import javax.annotation.Nonnull; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -import org.apache.commons.io.IOUtils; - import appeng.core.AELog; import appeng.services.version.Channel; import appeng.services.version.Version; import appeng.services.version.VersionCheckerConfig; import appeng.services.version.VersionParser; import appeng.services.version.exceptions.VersionCheckerException; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import org.apache.commons.io.IOUtils; + +import javax.annotation.Nonnull; +import java.io.IOException; +import java.lang.reflect.Type; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; -public final class ReleaseFetcher -{ - private static final String GITHUB_RELEASES_URL = "https://api.github.com/repos/AppliedEnergistics/Applied-Energistics-2/releases"; - private static final FormattedRelease EXCEPTIONAL_RELEASE = new MissingFormattedRelease(); +public final class ReleaseFetcher { + private static final String GITHUB_RELEASES_URL = "https://api.github.com/repos/AppliedEnergistics/Applied-Energistics-2/releases"; + private static final FormattedRelease EXCEPTIONAL_RELEASE = new MissingFormattedRelease(); - @Nonnull - private final VersionCheckerConfig config; - @Nonnull - private final VersionParser parser; + @Nonnull + private final VersionCheckerConfig config; + @Nonnull + private final VersionParser parser; - public ReleaseFetcher( @Nonnull final VersionCheckerConfig config, @Nonnull final VersionParser parser ) - { - this.config = config; - this.parser = parser; - } + public ReleaseFetcher(@Nonnull final VersionCheckerConfig config, @Nonnull final VersionParser parser) { + this.config = config; + this.parser = parser; + } - public FormattedRelease get() - { - final Gson gson = new Gson(); - final Type type = new ReleasesTypeToken().getType(); + public FormattedRelease get() { + final Gson gson = new Gson(); + final Type type = new ReleasesTypeToken().getType(); - try - { - final URL releasesURL = new URL( GITHUB_RELEASES_URL ); - final String rawReleases = this.getRawReleases( releasesURL ); + try { + final URL releasesURL = new URL(GITHUB_RELEASES_URL); + final String rawReleases = this.getRawReleases(releasesURL); - this.config.updateLastCheck(); + this.config.updateLastCheck(); - final List releases = gson.fromJson( rawReleases, type ); - final FormattedRelease latestFitRelease = this.getLatestFitRelease( releases ); + final List releases = gson.fromJson(rawReleases, type); + final FormattedRelease latestFitRelease = this.getLatestFitRelease(releases); - return latestFitRelease; - } - catch( final VersionCheckerException e ) - { - AELog.debug( e ); - } - catch( final MalformedURLException e ) - { - AELog.debug( e ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } + return latestFitRelease; + } catch (final VersionCheckerException e) { + AELog.debug(e); + } catch (final MalformedURLException e) { + AELog.debug(e); + } catch (final IOException e) { + AELog.debug(e); + } - return EXCEPTIONAL_RELEASE; - } + return EXCEPTIONAL_RELEASE; + } - private String getRawReleases( final URL url ) throws IOException - { - return IOUtils.toString( url ); - } + private String getRawReleases(final URL url) throws IOException { + return IOUtils.toString(url); + } - private FormattedRelease getLatestFitRelease( final Iterable releases ) throws VersionCheckerException - { - final String levelInConfig = this.config.level(); - final Channel level = Channel.valueOf( levelInConfig ); - final int levelOrdinal = level.ordinal(); + private FormattedRelease getLatestFitRelease(final Iterable releases) throws VersionCheckerException { + final String levelInConfig = this.config.level(); + final Channel level = Channel.valueOf(levelInConfig); + final int levelOrdinal = level.ordinal(); - for( final Release release : releases ) - { - final String rawVersion = release.tag_name; - final String changelog = release.body; + for (final Release release : releases) { + final String rawVersion = release.tag_name; + final String changelog = release.body; - final Version version = this.parser.parse( rawVersion ); + final Version version = this.parser.parse(rawVersion); - if( version.channel().ordinal() >= levelOrdinal ) - { - return new DefaultFormattedRelease( version, changelog ); - } - } + if (version.channel().ordinal() >= levelOrdinal) { + return new DefaultFormattedRelease(version, changelog); + } + } - return EXCEPTIONAL_RELEASE; - } + return EXCEPTIONAL_RELEASE; + } - private static final class ReleasesTypeToken extends TypeToken> - { - } + private static final class ReleasesTypeToken extends TypeToken> { + } } diff --git a/src/main/java/appeng/spatial/BiomeGenStorage.java b/src/main/java/appeng/spatial/BiomeGenStorage.java index a831b20cc..46e6b33ca 100644 --- a/src/main/java/appeng/spatial/BiomeGenStorage.java +++ b/src/main/java/appeng/spatial/BiomeGenStorage.java @@ -22,20 +22,18 @@ package appeng.spatial; import net.minecraft.world.biome.Biome; -public class BiomeGenStorage extends Biome -{ +public class BiomeGenStorage extends Biome { - public BiomeGenStorage() - { - super( new BiomeProperties( "Storage Cell" ).setBaseBiome( "void" ).setRainDisabled().setTemperature( -100 ) ); + public BiomeGenStorage() { + super(new BiomeProperties("Storage Cell").setBaseBiome("void").setRainDisabled().setTemperature(-100)); - this.decorator.treesPerChunk = 0; - this.decorator.flowersPerChunk = 0; - this.decorator.grassPerChunk = 0; + this.decorator.treesPerChunk = 0; + this.decorator.flowersPerChunk = 0; + this.decorator.grassPerChunk = 0; - this.spawnableMonsterList.clear(); - this.spawnableCreatureList.clear(); - this.spawnableWaterCreatureList.clear(); - this.spawnableCaveCreatureList.clear(); - } + this.spawnableMonsterList.clear(); + this.spawnableCreatureList.clear(); + this.spawnableWaterCreatureList.clear(); + this.spawnableCaveCreatureList.clear(); + } } diff --git a/src/main/java/appeng/spatial/CachedPlane.java b/src/main/java/appeng/spatial/CachedPlane.java index b8ee6de75..ca0fd3068 100644 --- a/src/main/java/appeng/spatial/CachedPlane.java +++ b/src/main/java/appeng/spatial/CachedPlane.java @@ -19,11 +19,14 @@ package appeng.spatial; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map.Entry; - +import appeng.api.AEApi; +import appeng.api.movable.IMovableHandler; +import appeng.api.movable.IMovableRegistry; +import appeng.api.util.AEPartLocation; +import appeng.api.util.WorldCoord; +import appeng.core.AELog; +import appeng.core.worlddata.WorldData; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.tileentity.TileEntity; @@ -34,435 +37,357 @@ import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; -import appeng.api.AEApi; -import appeng.api.movable.IMovableHandler; -import appeng.api.movable.IMovableRegistry; -import appeng.api.util.AEPartLocation; -import appeng.api.util.WorldCoord; -import appeng.core.AELog; -import appeng.core.worlddata.WorldData; -import appeng.util.Platform; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map.Entry; -public class CachedPlane -{ - private final int x_size; - private final int z_size; - private final int cx_size; - private final int cz_size; - private final int x_offset; - private final int y_offset; - private final int z_offset; - private final int y_size; - private final Chunk[][] myChunks; - private final Column[][] myColumns; - private final List tiles = new ArrayList<>(); - private final List ticks = new ArrayList<>(); - private final World world; - private final IMovableRegistry reg = AEApi.instance().registries().movable(); - private final List updates = new ArrayList<>(); - private int verticalBits; - private final IBlockState matrixBlockState; +public class CachedPlane { + private final int x_size; + private final int z_size; + private final int cx_size; + private final int cz_size; + private final int x_offset; + private final int y_offset; + private final int z_offset; + private final int y_size; + private final Chunk[][] myChunks; + private final Column[][] myColumns; + private final List tiles = new ArrayList<>(); + private final List ticks = new ArrayList<>(); + private final World world; + private final IMovableRegistry reg = AEApi.instance().registries().movable(); + private final List updates = new ArrayList<>(); + private int verticalBits; + private final IBlockState matrixBlockState; - public CachedPlane( final World w, final int minX, final int minY, final int minZ, final int maxX, final int maxY, final int maxZ ) - { + public CachedPlane(final World w, final int minX, final int minY, final int minZ, final int maxX, final int maxY, final int maxZ) { - Block matrixFrameBlock = AEApi.instance().definitions().blocks().matrixFrame().maybeBlock().orElse( null ); - if( matrixFrameBlock != null ) - { - this.matrixBlockState = matrixFrameBlock.getDefaultState(); - } - else - { - this.matrixBlockState = null; - } + Block matrixFrameBlock = AEApi.instance().definitions().blocks().matrixFrame().maybeBlock().orElse(null); + if (matrixFrameBlock != null) { + this.matrixBlockState = matrixFrameBlock.getDefaultState(); + } else { + this.matrixBlockState = null; + } - this.world = w; + this.world = w; - this.x_size = maxX - minX + 1; - this.y_size = maxY - minY + 1; - this.z_size = maxZ - minZ + 1; + this.x_size = maxX - minX + 1; + this.y_size = maxY - minY + 1; + this.z_size = maxZ - minZ + 1; - this.x_offset = minX; - this.y_offset = minY; - this.z_offset = minZ; + this.x_offset = minX; + this.y_offset = minY; + this.z_offset = minZ; - final int minCX = minX >> 4; - final int minCY = minY >> 4; - final int minCZ = minZ >> 4; - final int maxCX = maxX >> 4; - final int maxCY = maxY >> 4; - final int maxCZ = maxZ >> 4; + final int minCX = minX >> 4; + final int minCY = minY >> 4; + final int minCZ = minZ >> 4; + final int maxCX = maxX >> 4; + final int maxCY = maxY >> 4; + final int maxCZ = maxZ >> 4; - this.cx_size = maxCX - minCX + 1; - final int cy_size = maxCY - minCY + 1; - this.cz_size = maxCZ - minCZ + 1; + this.cx_size = maxCX - minCX + 1; + final int cy_size = maxCY - minCY + 1; + this.cz_size = maxCZ - minCZ + 1; - this.myChunks = new Chunk[this.cx_size][this.cz_size]; - this.myColumns = new Column[this.x_size][this.z_size]; + this.myChunks = new Chunk[this.cx_size][this.cz_size]; + this.myColumns = new Column[this.x_size][this.z_size]; - this.verticalBits = 0; - for( int cy = 0; cy < cy_size; cy++ ) - { - this.verticalBits |= 1 << ( minCY + cy ); - } + this.verticalBits = 0; + for (int cy = 0; cy < cy_size; cy++) { + this.verticalBits |= 1 << (minCY + cy); + } - for( int x = 0; x < this.x_size; x++ ) - { - for( int z = 0; z < this.z_size; z++ ) - { - this.myColumns[x][z] = new Column( w.getChunkFromChunkCoords( ( minX + x ) >> 4, - ( minZ + z ) >> 4 ), ( minX + x ) & 0xF, ( minZ + z ) & 0xF, minCY, cy_size ); - } - } + for (int x = 0; x < this.x_size; x++) { + for (int z = 0; z < this.z_size; z++) { + this.myColumns[x][z] = new Column(w.getChunkFromChunkCoords((minX + x) >> 4, + (minZ + z) >> 4), (minX + x) & 0xF, (minZ + z) & 0xF, minCY, cy_size); + } + } - final IMovableRegistry mr = AEApi.instance().registries().movable(); + final IMovableRegistry mr = AEApi.instance().registries().movable(); - for( int cx = 0; cx < this.cx_size; cx++ ) - { - for( int cz = 0; cz < this.cz_size; cz++ ) - { - final List> rawTiles = new ArrayList<>(); - final List deadTiles = new ArrayList<>(); + for (int cx = 0; cx < this.cx_size; cx++) { + for (int cz = 0; cz < this.cz_size; cz++) { + final List> rawTiles = new ArrayList<>(); + final List deadTiles = new ArrayList<>(); - final Chunk c = w.getChunkFromChunkCoords( minCX + cx, minCZ + cz ); - this.myChunks[cx][cz] = c; + final Chunk c = w.getChunkFromChunkCoords(minCX + cx, minCZ + cz); + this.myChunks[cx][cz] = c; - rawTiles.addAll( ( (HashMap) c.getTileEntityMap() ).entrySet() ); - for( final Entry tx : rawTiles ) - { - final BlockPos cp = tx.getKey(); - final TileEntity te = tx.getValue(); + rawTiles.addAll(c.getTileEntityMap().entrySet()); + for (final Entry tx : rawTiles) { + final BlockPos cp = tx.getKey(); + final TileEntity te = tx.getValue(); - final BlockPos tePOS = te.getPos(); - if( tePOS.getX() >= minX && tePOS.getX() <= maxX && tePOS.getY() >= minY && tePOS.getY() <= maxY && tePOS.getZ() >= minZ && tePOS - .getZ() <= maxZ ) - { - if( mr.askToMove( te ) ) - { - this.tiles.add( te ); - deadTiles.add( cp ); - } - else - { - final BlockStorageData details = new BlockStorageData(); - this.myColumns[tePOS.getX() - minX][tePOS.getZ() - minZ].fillData( tePOS.getY(), details ); + final BlockPos tePOS = te.getPos(); + if (tePOS.getX() >= minX && tePOS.getX() <= maxX && tePOS.getY() >= minY && tePOS.getY() <= maxY && tePOS.getZ() >= minZ && tePOS + .getZ() <= maxZ) { + if (mr.askToMove(te)) { + this.tiles.add(te); + deadTiles.add(cp); + } else { + final BlockStorageData details = new BlockStorageData(); + this.myColumns[tePOS.getX() - minX][tePOS.getZ() - minZ].fillData(tePOS.getY(), details); - // don't skip air, just let the code replace it... - if( details.state != null && details.state.getBlock() == Platform.AIR_BLOCK && details.state.getMaterial().isReplaceable() ) - { - w.setBlockToAir( tePOS ); - } - else - { - this.myColumns[tePOS.getX() - minX][tePOS.getZ() - minZ].setSkip( tePOS.getY() ); - } - } - } - } + // don't skip air, just let the code replace it... + if (details.state != null && details.state.getBlock() == Platform.AIR_BLOCK && details.state.getMaterial().isReplaceable()) { + w.setBlockToAir(tePOS); + } else { + this.myColumns[tePOS.getX() - minX][tePOS.getZ() - minZ].setSkip(tePOS.getY()); + } + } + } + } - for( final BlockPos cp : deadTiles ) - { - c.getTileEntityMap().remove( cp ); - } + for (final BlockPos cp : deadTiles) { + c.getTileEntityMap().remove(cp); + } - final long k = this.getWorld().getTotalWorldTime(); - final List list = this.getWorld().getPendingBlockUpdates( c, false ); - if( list != null ) - { - for( final NextTickListEntry entry : list ) - { - final BlockPos tePOS = entry.position; - if( tePOS.getX() >= minX && tePOS.getX() <= maxX && tePOS.getY() >= minY && tePOS.getY() <= maxY && tePOS.getZ() >= minZ && tePOS - .getZ() <= maxZ ) - { - final NextTickListEntry newEntry = new NextTickListEntry( tePOS, entry.getBlock() ); - newEntry.scheduledTime = entry.scheduledTime - k; - this.ticks.add( newEntry ); - } - } - } - } - } + final long k = this.getWorld().getTotalWorldTime(); + final List list = this.getWorld().getPendingBlockUpdates(c, false); + if (list != null) { + for (final NextTickListEntry entry : list) { + final BlockPos tePOS = entry.position; + if (tePOS.getX() >= minX && tePOS.getX() <= maxX && tePOS.getY() >= minY && tePOS.getY() <= maxY && tePOS.getZ() >= minZ && tePOS + .getZ() <= maxZ) { + final NextTickListEntry newEntry = new NextTickListEntry(tePOS, entry.getBlock()); + newEntry.scheduledTime = entry.scheduledTime - k; + this.ticks.add(newEntry); + } + } + } + } + } - for( final TileEntity te : this.tiles ) - { - try - { - this.getWorld().loadedTileEntityList.remove( te ); - if( te instanceof ITickable ) - { - this.getWorld().tickableTileEntities.remove( te ); - } - } - catch( final Exception e ) - { - AELog.debug( e ); - } - } - } + for (final TileEntity te : this.tiles) { + try { + this.getWorld().loadedTileEntityList.remove(te); + if (te instanceof ITickable) { + this.getWorld().tickableTileEntities.remove(te); + } + } catch (final Exception e) { + AELog.debug(e); + } + } + } - private IMovableHandler getHandler( final TileEntity te ) - { - final IMovableRegistry mr = AEApi.instance().registries().movable(); - return mr.getHandler( te ); - } + private IMovableHandler getHandler(final TileEntity te) { + final IMovableRegistry mr = AEApi.instance().registries().movable(); + return mr.getHandler(te); + } - void swap( final CachedPlane dst ) - { - final IMovableRegistry mr = AEApi.instance().registries().movable(); + void swap(final CachedPlane dst) { + final IMovableRegistry mr = AEApi.instance().registries().movable(); - if( dst.x_size == this.x_size && dst.y_size == this.y_size && dst.z_size == this.z_size ) - { - AELog.info( "Block Copy Scale: " + this.x_size + ", " + this.y_size + ", " + this.z_size ); + if (dst.x_size == this.x_size && dst.y_size == this.y_size && dst.z_size == this.z_size) { + AELog.info("Block Copy Scale: " + this.x_size + ", " + this.y_size + ", " + this.z_size); - long startTime = System.nanoTime(); - final BlockStorageData aD = new BlockStorageData(); - final BlockStorageData bD = new BlockStorageData(); + long startTime = System.nanoTime(); + final BlockStorageData aD = new BlockStorageData(); + final BlockStorageData bD = new BlockStorageData(); - for( int x = 0; x < this.x_size; x++ ) - { - for( int z = 0; z < this.z_size; z++ ) - { - final Column a = this.myColumns[x][z]; - final Column b = dst.myColumns[x][z]; + for (int x = 0; x < this.x_size; x++) { + for (int z = 0; z < this.z_size; z++) { + final Column a = this.myColumns[x][z]; + final Column b = dst.myColumns[x][z]; - for( int y = 0; y < this.y_size; y++ ) - { - final int src_y = y + this.y_offset; - final int dst_y = y + dst.y_offset; + for (int y = 0; y < this.y_size; y++) { + final int src_y = y + this.y_offset; + final int dst_y = y + dst.y_offset; - if( a.doNotSkip( src_y ) && b.doNotSkip( dst_y ) ) - { - a.fillData( src_y, aD ); - b.fillData( dst_y, bD ); + if (a.doNotSkip(src_y) && b.doNotSkip(dst_y)) { + a.fillData(src_y, aD); + b.fillData(dst_y, bD); - a.setBlockIDWithMetadata( src_y, bD ); - b.setBlockIDWithMetadata( dst_y, aD ); - } - else - { - this.markForUpdate( x + this.x_offset, src_y, z + this.z_offset ); - dst.markForUpdate( x + dst.x_offset, dst_y, z + dst.z_offset ); - } - } - } - } + a.setBlockIDWithMetadata(src_y, bD); + b.setBlockIDWithMetadata(dst_y, aD); + } else { + this.markForUpdate(x + this.x_offset, src_y, z + this.z_offset); + dst.markForUpdate(x + dst.x_offset, dst_y, z + dst.z_offset); + } + } + } + } - long endTime = System.nanoTime(); - long duration = endTime - startTime; - AELog.info( "Block Copy Time: " + duration ); + long endTime = System.nanoTime(); + long duration = endTime - startTime; + AELog.info("Block Copy Time: " + duration); - for( final TileEntity te : this.tiles ) - { - final BlockPos tePOS = te.getPos(); - dst.addTile( tePOS.getX() - this.x_offset, tePOS.getY() - this.y_offset, tePOS.getZ() - this.z_offset, te, this, mr ); - } + for (final TileEntity te : this.tiles) { + final BlockPos tePOS = te.getPos(); + dst.addTile(tePOS.getX() - this.x_offset, tePOS.getY() - this.y_offset, tePOS.getZ() - this.z_offset, te, this, mr); + } - for( final TileEntity te : dst.tiles ) - { - final BlockPos tePOS = te.getPos(); - this.addTile( tePOS.getX() - dst.x_offset, tePOS.getY() - dst.y_offset, tePOS.getZ() - dst.z_offset, te, dst, mr ); - } + for (final TileEntity te : dst.tiles) { + final BlockPos tePOS = te.getPos(); + this.addTile(tePOS.getX() - dst.x_offset, tePOS.getY() - dst.y_offset, tePOS.getZ() - dst.z_offset, te, dst, mr); + } - for( final NextTickListEntry entry : this.ticks ) - { - final BlockPos tePOS = entry.position; - dst.addTick( tePOS.getX() - this.x_offset, tePOS.getY() - this.y_offset, tePOS.getZ() - this.z_offset, entry ); - } + for (final NextTickListEntry entry : this.ticks) { + final BlockPos tePOS = entry.position; + dst.addTick(tePOS.getX() - this.x_offset, tePOS.getY() - this.y_offset, tePOS.getZ() - this.z_offset, entry); + } - for( final NextTickListEntry entry : dst.ticks ) - { - final BlockPos tePOS = entry.position; - this.addTick( tePOS.getX() - dst.x_offset, tePOS.getY() - dst.y_offset, tePOS.getZ() - dst.z_offset, entry ); - } + for (final NextTickListEntry entry : dst.ticks) { + final BlockPos tePOS = entry.position; + this.addTick(tePOS.getX() - dst.x_offset, tePOS.getY() - dst.y_offset, tePOS.getZ() - dst.z_offset, entry); + } - startTime = System.nanoTime(); - this.updateChunks(); - dst.updateChunks(); - endTime = System.nanoTime(); + startTime = System.nanoTime(); + this.updateChunks(); + dst.updateChunks(); + endTime = System.nanoTime(); - duration = endTime - startTime; - AELog.info( "Update Time: " + duration ); - } - } + duration = endTime - startTime; + AELog.info("Update Time: " + duration); + } + } - private void markForUpdate( final int x, final int y, final int z ) - { - this.updates.add( new WorldCoord( x, y, z ) ); - for( final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS ) - { - this.updates.add( new WorldCoord( x + d.xOffset, y + d.yOffset, z + d.zOffset ) ); - } - } + private void markForUpdate(final int x, final int y, final int z) { + this.updates.add(new WorldCoord(x, y, z)); + for (final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS) { + this.updates.add(new WorldCoord(x + d.xOffset, y + d.yOffset, z + d.zOffset)); + } + } - private void addTick( final int x, final int y, final int z, final NextTickListEntry entry ) - { - this.world.scheduleUpdate( new BlockPos( x + this.x_offset, y + this.y_offset, z + this.z_offset ), entry.getBlock(), (int) entry.scheduledTime ); - } + private void addTick(final int x, final int y, final int z, final NextTickListEntry entry) { + this.world.scheduleUpdate(new BlockPos(x + this.x_offset, y + this.y_offset, z + this.z_offset), entry.getBlock(), (int) entry.scheduledTime); + } - private void addTile( final int x, final int y, final int z, final TileEntity te, final CachedPlane alternateDestination, final IMovableRegistry mr ) - { - try - { - final Column c = this.myColumns[x][z]; + private void addTile(final int x, final int y, final int z, final TileEntity te, final CachedPlane alternateDestination, final IMovableRegistry mr) { + try { + final Column c = this.myColumns[x][z]; - if( c.doNotSkip( y + this.y_offset ) || alternateDestination == null ) - { - final IMovableHandler handler = this.getHandler( te ); + if (c.doNotSkip(y + this.y_offset) || alternateDestination == null) { + final IMovableHandler handler = this.getHandler(te); - try - { - handler.moveTile( te, this.world, new BlockPos( x + this.x_offset, y + this.y_offset, z + this.z_offset ) ); - } - catch( final Throwable e ) - { - AELog.debug( e ); + try { + handler.moveTile(te, this.world, new BlockPos(x + this.x_offset, y + this.y_offset, z + this.z_offset)); + } catch (final Throwable e) { + AELog.debug(e); - final BlockPos pos = new BlockPos( x, y, z ); + final BlockPos pos = new BlockPos(x, y, z); - // attempt recovery... - te.setWorld( this.world ); - te.setPos( pos ); - c.c.addTileEntity( new BlockPos( c.x, y + y, c.z ), te ); - // c.c.setChunkTileEntity( c.x, y + y, c.z, te ); + // attempt recovery... + te.setWorld(this.world); + te.setPos(pos); + c.c.addTileEntity(new BlockPos(c.x, y + y, c.z), te); + // c.c.setChunkTileEntity( c.x, y + y, c.z, te ); - if( c.c.isLoaded() ) - { - this.world.addTileEntity( te ); - this.world.notifyBlockUpdate( pos, this.world.getBlockState( pos ), this.world.getBlockState( pos ), z ); - } - } + if (c.c.isLoaded()) { + this.world.addTileEntity(te); + this.world.notifyBlockUpdate(pos, this.world.getBlockState(pos), this.world.getBlockState(pos), z); + } + } - mr.doneMoving( te ); - } - else - { - alternateDestination.addTile( x, y, z, te, null, mr ); - } - } - catch( final Throwable e ) - { - AELog.debug( e ); - } - } + mr.doneMoving(te); + } else { + alternateDestination.addTile(x, y, z, te, null, mr); + } + } catch (final Throwable e) { + AELog.debug(e); + } + } - private void updateChunks() - { + private void updateChunks() { - // update shit.. - for( int x = 0; x < this.cx_size; x++ ) - { - for( int z = 0; z < this.cz_size; z++ ) - { - final Chunk c = this.myChunks[x][z]; - c.resetRelightChecks(); - c.generateSkylightMap(); - c.setModified( true ); - } - } + // update shit.. + for (int x = 0; x < this.cx_size; x++) { + for (int z = 0; z < this.cz_size; z++) { + final Chunk c = this.myChunks[x][z]; + c.resetRelightChecks(); + c.generateSkylightMap(); + c.setModified(true); + } + } - // send shit... - for( int x = 0; x < this.cx_size; x++ ) - { - for( int z = 0; z < this.cz_size; z++ ) - { + // send shit... + for (int x = 0; x < this.cx_size; x++) { + for (int z = 0; z < this.cz_size; z++) { - final Chunk c = this.myChunks[x][z]; + final Chunk c = this.myChunks[x][z]; - for( int y = 1; y < 255; y += 32 ) - { - WorldData.instance().compassData().service().updateArea( this.getWorld(), c.x << 4, y, c.z << 4 ); - } + for (int y = 1; y < 255; y += 32) { + WorldData.instance().compassData().service().updateArea(this.getWorld(), c.x << 4, y, c.z << 4); + } - Platform.sendChunk( c, this.verticalBits ); - } - } - } + Platform.sendChunk(c, this.verticalBits); + } + } + } - List getUpdates() - { - return this.updates; - } + List getUpdates() { + return this.updates; + } - World getWorld() - { - return this.world; - } + World getWorld() { + return this.world; + } - private static class BlockStorageData - { - public IBlockState state; - public int light; - } + private static class BlockStorageData { + public IBlockState state; + public int light; + } - private class Column - { - private final int x; - private final int z; - private final Chunk c; - private List skipThese = null; + private class Column { + private final int x; + private final int z; + private final Chunk c; + private List skipThese = null; - public Column( final Chunk chunk, final int x, final int z, final int chunkY, final int chunkHeight ) - { - this.x = x; - this.z = z; - this.c = chunk; + public Column(final Chunk chunk, final int x, final int z, final int chunkY, final int chunkHeight) { + this.x = x; + this.z = z; + this.c = chunk; - final ExtendedBlockStorage[] storage = this.c.getBlockStorageArray(); + final ExtendedBlockStorage[] storage = this.c.getBlockStorageArray(); - // make sure storage exists before hand... - for( int ay = 0; ay < chunkHeight; ay++ ) - { - final int by = ( ay + chunkY ); - ExtendedBlockStorage extendedblockstorage = storage[by]; - if( extendedblockstorage == null ) - { - extendedblockstorage = storage[by] = new ExtendedBlockStorage( by << 4, this.c.getWorld().provider.hasSkyLight() ); - } - } - } + // make sure storage exists before hand... + for (int ay = 0; ay < chunkHeight; ay++) { + final int by = (ay + chunkY); + ExtendedBlockStorage extendedblockstorage = storage[by]; + if (extendedblockstorage == null) { + extendedblockstorage = storage[by] = new ExtendedBlockStorage(by << 4, this.c.getWorld().provider.hasSkyLight()); + } + } + } - private void setBlockIDWithMetadata( final int y, BlockStorageData data ) - { - if( data.state == CachedPlane.this.matrixBlockState ) - { - data.state = Platform.AIR_BLOCK.getDefaultState(); - } - final ExtendedBlockStorage[] storage = this.c.getBlockStorageArray(); - final ExtendedBlockStorage extendedBlockStorage = storage[y >> 4]; - extendedBlockStorage.set( this.x, y & 15, this.z, data.state ); - extendedBlockStorage.setBlockLight( this.x, y & 15, this.z, data.light ); - } + private void setBlockIDWithMetadata(final int y, BlockStorageData data) { + if (data.state == CachedPlane.this.matrixBlockState) { + data.state = Platform.AIR_BLOCK.getDefaultState(); + } + final ExtendedBlockStorage[] storage = this.c.getBlockStorageArray(); + final ExtendedBlockStorage extendedBlockStorage = storage[y >> 4]; + extendedBlockStorage.set(this.x, y & 15, this.z, data.state); + extendedBlockStorage.setBlockLight(this.x, y & 15, this.z, data.light); + } - private void fillData( final int y, BlockStorageData data ) - { - final ExtendedBlockStorage[] storage = this.c.getBlockStorageArray(); - final ExtendedBlockStorage extendedblockstorage = storage[y >> 4]; + private void fillData(final int y, BlockStorageData data) { + final ExtendedBlockStorage[] storage = this.c.getBlockStorageArray(); + final ExtendedBlockStorage extendedblockstorage = storage[y >> 4]; - data.state = extendedblockstorage.get( this.x, y & 15, this.z ); - data.light = extendedblockstorage.getBlockLight( this.x, y & 15, this.z ); - } + data.state = extendedblockstorage.get(this.x, y & 15, this.z); + data.light = extendedblockstorage.getBlockLight(this.x, y & 15, this.z); + } - private boolean doNotSkip( final int y ) - { - final ExtendedBlockStorage[] storage = this.c.getBlockStorageArray(); - final ExtendedBlockStorage extendedblockstorage = storage[y >> 4]; - if( CachedPlane.this.reg.isBlacklisted( extendedblockstorage.get( this.x, y & 15, this.z ).getBlock() ) ) - { - return false; - } + private boolean doNotSkip(final int y) { + final ExtendedBlockStorage[] storage = this.c.getBlockStorageArray(); + final ExtendedBlockStorage extendedblockstorage = storage[y >> 4]; + if (CachedPlane.this.reg.isBlacklisted(extendedblockstorage.get(this.x, y & 15, this.z).getBlock())) { + return false; + } - return this.skipThese == null || !this.skipThese.contains( y ); - } + return this.skipThese == null || !this.skipThese.contains(y); + } - private void setSkip( final int yCoord ) - { - if( this.skipThese == null ) - { - this.skipThese = new ArrayList<>(); - } - this.skipThese.add( yCoord ); - } - } + private void setSkip(final int yCoord) { + if (this.skipThese == null) { + this.skipThese = new ArrayList<>(); + } + this.skipThese.add(yCoord); + } + } } diff --git a/src/main/java/appeng/spatial/DefaultSpatialHandler.java b/src/main/java/appeng/spatial/DefaultSpatialHandler.java index ad6893344..c9d8607de 100644 --- a/src/main/java/appeng/spatial/DefaultSpatialHandler.java +++ b/src/main/java/appeng/spatial/DefaultSpatialHandler.java @@ -19,45 +19,39 @@ package appeng.spatial; +import appeng.api.movable.IMovableHandler; import net.minecraft.block.state.IBlockState; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; -import appeng.api.movable.IMovableHandler; +public class DefaultSpatialHandler implements IMovableHandler { -public class DefaultSpatialHandler implements IMovableHandler -{ + /** + * never called for the default. + * + * @param tile tile entity + * @return true + */ + @Override + public boolean canHandle(final Class myClass, final TileEntity tile) { + return true; + } - /** - * never called for the default. - * - * @param tile tile entity - * - * @return true - */ - @Override - public boolean canHandle( final Class myClass, final TileEntity tile ) - { - return true; - } + @Override + public void moveTile(final TileEntity te, final World w, final BlockPos newPosition) { + te.setWorld(w); + te.setPos(newPosition); - @Override - public void moveTile( final TileEntity te, final World w, final BlockPos newPosition ) - { - te.setWorld( w ); - te.setPos( newPosition ); + final Chunk c = w.getChunkFromBlockCoords(newPosition); + c.addTileEntity(newPosition, te); - final Chunk c = w.getChunkFromBlockCoords( newPosition ); - c.addTileEntity( newPosition, te ); - - if( c.isLoaded() ) - { - final IBlockState state = w.getBlockState( newPosition ); - w.addTileEntity( te ); - w.notifyBlockUpdate( newPosition, state, state, 1 ); - } - } + if (c.isLoaded()) { + final IBlockState state = w.getBlockState(newPosition); + w.addTileEntity(te); + w.notifyBlockUpdate(newPosition, state, state, 1); + } + } } diff --git a/src/main/java/appeng/spatial/ISpatialVisitor.java b/src/main/java/appeng/spatial/ISpatialVisitor.java index dd2784526..76043b342 100644 --- a/src/main/java/appeng/spatial/ISpatialVisitor.java +++ b/src/main/java/appeng/spatial/ISpatialVisitor.java @@ -22,8 +22,7 @@ package appeng.spatial; import net.minecraft.util.math.BlockPos; -public interface ISpatialVisitor -{ +public interface ISpatialVisitor { - void visit( BlockPos pos ); + void visit(BlockPos pos); } diff --git a/src/main/java/appeng/spatial/StorageChunkProvider.java b/src/main/java/appeng/spatial/StorageChunkProvider.java index cc7c80567..0b110b81f 100644 --- a/src/main/java/appeng/spatial/StorageChunkProvider.java +++ b/src/main/java/appeng/spatial/StorageChunkProvider.java @@ -19,9 +19,8 @@ package appeng.spatial; -import java.util.ArrayList; -import java.util.List; - +import appeng.api.AEApi; +import appeng.core.AppEng; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EnumCreatureType; import net.minecraft.util.math.BlockPos; @@ -30,89 +29,75 @@ import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.gen.ChunkGeneratorOverworld; -import appeng.api.AEApi; -import appeng.core.AppEng; +import java.util.ArrayList; +import java.util.List; -public class StorageChunkProvider extends ChunkGeneratorOverworld -{ +public class StorageChunkProvider extends ChunkGeneratorOverworld { - private final World world; + private final World world; - public StorageChunkProvider( final World world, final long i ) - { - super( world, i, false, null ); - this.world = world; - } + public StorageChunkProvider(final World world, final long i) { + super(world, i, false, null); + this.world = world; + } - @Override - public Chunk generateChunk( final int x, final int z ) - { - final Chunk chunk = new Chunk( this.world, x, z ); + @Override + public Chunk generateChunk(final int x, final int z) { + final Chunk chunk = new Chunk(this.world, x, z); - final byte[] biomes = chunk.getBiomeArray(); - Biome biome = AppEng.instance().getStorageBiome(); - byte biomeId = (byte) Biome.getIdForBiome( biome ); + final byte[] biomes = chunk.getBiomeArray(); + Biome biome = AppEng.instance().getStorageBiome(); + byte biomeId = (byte) Biome.getIdForBiome(biome); - for( int k = 0; k < biomes.length; ++k ) - { - biomes[k] = biomeId; - } + for (int k = 0; k < biomes.length; ++k) { + biomes[k] = biomeId; + } - AEApi.instance().definitions().blocks().matrixFrame().maybeBlock().ifPresent( block -> this.fillChunk( chunk, block.getDefaultState() ) ); + AEApi.instance().definitions().blocks().matrixFrame().maybeBlock().ifPresent(block -> this.fillChunk(chunk, block.getDefaultState())); - chunk.setModified( false ); + chunk.setModified(false); - if( !chunk.isTerrainPopulated() ) - { - chunk.setTerrainPopulated( true ); - chunk.resetRelightChecks(); - } + if (!chunk.isTerrainPopulated()) { + chunk.setTerrainPopulated(true); + chunk.resetRelightChecks(); + } - return chunk; - } + return chunk; + } - private void fillChunk( Chunk chunk, IBlockState defaultState ) - { - for( int cx = 0; cx < 16; cx++ ) - { - for( int cz = 0; cz < 16; cz++ ) - { - for( int cy = 0; cy < 256; cy++ ) - { - chunk.setBlockState( new BlockPos( cx, cy, cz ), defaultState ); - } - } - } - } + private void fillChunk(Chunk chunk, IBlockState defaultState) { + for (int cx = 0; cx < 16; cx++) { + for (int cz = 0; cz < 16; cz++) { + for (int cy = 0; cy < 256; cy++) { + chunk.setBlockState(new BlockPos(cx, cy, cz), defaultState); + } + } + } + } - @Override - public void populate( final int par2, final int par3 ) - { + @Override + public void populate(final int par2, final int par3) { - } + } - @Override - public List getPossibleCreatures( final EnumCreatureType creatureType, final BlockPos pos ) - { - return new ArrayList(); - } + @Override + public List getPossibleCreatures(final EnumCreatureType creatureType, final BlockPos pos) { + return new ArrayList(); + } - @Override - public boolean generateStructures( Chunk chunkIn, int x, int z ) - { - return false; - } + @Override + public boolean generateStructures(Chunk chunkIn, int x, int z) { + return false; + } - @Override - public BlockPos getNearestStructurePos( World worldIn, String structureName, BlockPos position, boolean p_180513_4_ ) - { - return null; - } + @Override + public BlockPos getNearestStructurePos(World worldIn, String structureName, BlockPos position, boolean p_180513_4_) { + return null; + } - @Override - public void recreateStructures( Chunk chunkIn, int x, int z ) - { + @Override + public void recreateStructures(Chunk chunkIn, int x, int z) { - } + } } diff --git a/src/main/java/appeng/spatial/StorageHelper.java b/src/main/java/appeng/spatial/StorageHelper.java index a697cdbb7..28ae3f391 100644 --- a/src/main/java/appeng/spatial/StorageHelper.java +++ b/src/main/java/appeng/spatial/StorageHelper.java @@ -19,9 +19,10 @@ package appeng.spatial; -import java.util.ArrayList; -import java.util.List; - +import appeng.api.AEApi; +import appeng.api.util.WorldCoord; +import appeng.core.AppEng; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; @@ -33,259 +34,217 @@ import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.ITeleporter; -import appeng.api.AEApi; -import appeng.api.util.WorldCoord; -import appeng.core.AppEng; -import appeng.util.Platform; +import java.util.ArrayList; +import java.util.List; -public class StorageHelper -{ +public class StorageHelper { - private static StorageHelper instance; + private static StorageHelper instance; - public static StorageHelper getInstance() - { - if( instance == null ) - { - instance = new StorageHelper(); - } - return instance; - } + public static StorageHelper getInstance() { + if (instance == null) { + instance = new StorageHelper(); + } + return instance; + } - /** - * Mostly from dimensional doors.. which mostly got it form X-Comp. - * - * @param entity to be teleported entity - * @param link destination - * - * @return teleported entity - */ - private Entity teleportEntity( Entity entity, final TelDestination link ) - { - final WorldServer oldWorld; - final WorldServer newWorld; + /** + * Mostly from dimensional doors.. which mostly got it form X-Comp. + * + * @param entity to be teleported entity + * @param link destination + * @return teleported entity + */ + private Entity teleportEntity(Entity entity, final TelDestination link) { + final WorldServer oldWorld; + final WorldServer newWorld; - try - { - oldWorld = (WorldServer) entity.world; - newWorld = (WorldServer) link.dim; - } - catch( final Throwable e ) - { - return entity; - } + try { + oldWorld = (WorldServer) entity.world; + newWorld = (WorldServer) link.dim; + } catch (final Throwable e) { + return entity; + } - if( oldWorld == null ) - { - return entity; - } - if( newWorld == null ) - { - return entity; - } - if( newWorld == oldWorld ) - { - return entity; - } + if (oldWorld == null) { + return entity; + } + if (newWorld == null) { + return entity; + } + if (newWorld == oldWorld) { + return entity; + } - // Are we riding something? Teleport it instead. - if( entity.isRiding() ) - { - return this.teleportEntity( entity.getRidingEntity(), link ); - } + // Are we riding something? Teleport it instead. + if (entity.isRiding()) { + return this.teleportEntity(entity.getRidingEntity(), link); + } - // Is something riding us? Handle it first. - final List passangers = entity.getPassengers(); - final List passangersOnOtherSide = new ArrayList<>(); - if( !passangers.isEmpty() ) - { - for( Entity passanger : passangers ) - { - passanger.dismountRidingEntity(); - passangersOnOtherSide.add( this.teleportEntity( passanger, link ) ); - } - // We keep track of all so we can remount them on the other side. - } + // Is something riding us? Handle it first. + final List passangers = entity.getPassengers(); + final List passangersOnOtherSide = new ArrayList<>(); + if (!passangers.isEmpty()) { + for (Entity passanger : passangers) { + passanger.dismountRidingEntity(); + passangersOnOtherSide.add(this.teleportEntity(passanger, link)); + } + // We keep track of all so we can remount them on the other side. + } - // load the chunk! - newWorld.getChunkProvider().provideChunk( MathHelper.floor( link.x ) >> 4, MathHelper.floor( link.z ) >> 4 ); + // load the chunk! + newWorld.getChunkProvider().provideChunk(MathHelper.floor(link.x) >> 4, MathHelper.floor(link.z) >> 4); - if( entity instanceof EntityPlayerMP && link.dim.provider instanceof StorageWorldProvider ) - { - AppEng.instance().getAdvancementTriggers().getSpatialExplorer().trigger( (EntityPlayerMP) entity ); - } + if (entity instanceof EntityPlayerMP && link.dim.provider instanceof StorageWorldProvider) { + AppEng.instance().getAdvancementTriggers().getSpatialExplorer().trigger((EntityPlayerMP) entity); + } - entity.changeDimension( link.dim.provider.getDimension(), new METeleporter( link ) ); + entity.changeDimension(link.dim.provider.getDimension(), new METeleporter(link)); - if( !passangersOnOtherSide.isEmpty() ) - { - for( Entity passanger : passangersOnOtherSide ) - { - passanger.startRiding( entity, true ); - } - } + if (!passangersOnOtherSide.isEmpty()) { + for (Entity passanger : passangersOnOtherSide) { + passanger.startRiding(entity, true); + } + } - return entity; - } + return entity; + } - private void transverseEdges( final int minX, final int minY, final int minZ, final int maxX, final int maxY, final int maxZ, final ISpatialVisitor visitor ) - { - for( int y = minY; y < maxY; y++ ) - { - for( int z = minZ; z < maxZ; z++ ) - { - visitor.visit( new BlockPos( minX, y, z ) ); - visitor.visit( new BlockPos( maxX, y, z ) ); - } - } + private void transverseEdges(final int minX, final int minY, final int minZ, final int maxX, final int maxY, final int maxZ, final ISpatialVisitor visitor) { + for (int y = minY; y < maxY; y++) { + for (int z = minZ; z < maxZ; z++) { + visitor.visit(new BlockPos(minX, y, z)); + visitor.visit(new BlockPos(maxX, y, z)); + } + } - for( int x = minX; x < maxX; x++ ) - { - for( int z = minZ; z < maxZ; z++ ) - { - visitor.visit( new BlockPos( x, minY, z ) ); - visitor.visit( new BlockPos( x, maxY, z ) ); - } - } + for (int x = minX; x < maxX; x++) { + for (int z = minZ; z < maxZ; z++) { + visitor.visit(new BlockPos(x, minY, z)); + visitor.visit(new BlockPos(x, maxY, z)); + } + } - for( int x = minX; x < maxX; x++ ) - { - for( int y = minY; y < maxY; y++ ) - { - visitor.visit( new BlockPos( x, y, minZ ) ); - visitor.visit( new BlockPos( x, y, maxZ ) ); - } - } - } + for (int x = minX; x < maxX; x++) { + for (int y = minY; y < maxY; y++) { + visitor.visit(new BlockPos(x, y, minZ)); + visitor.visit(new BlockPos(x, y, maxZ)); + } + } + } - public void swapRegions( final World srcWorld, final int srcX, final int srcY, final int srcZ, final World dstWorld, final int dstX, final int dstY, final int dstZ, final int scaleX, final int scaleY, final int scaleZ ) - { - AEApi.instance() - .definitions() - .blocks() - .matrixFrame() - .maybeBlock() - .ifPresent( matrixFrameBlock -> this.transverseEdges( dstX - 1, dstY - 1, dstZ - 1, - dstX + scaleX + 1, dstY + scaleY + 1, dstZ + scaleZ + 1, new WrapInMatrixFrame( matrixFrameBlock.getDefaultState(), dstWorld ) ) ); + public void swapRegions(final World srcWorld, final int srcX, final int srcY, final int srcZ, final World dstWorld, final int dstX, final int dstY, final int dstZ, final int scaleX, final int scaleY, final int scaleZ) { + AEApi.instance() + .definitions() + .blocks() + .matrixFrame() + .maybeBlock() + .ifPresent(matrixFrameBlock -> this.transverseEdges(dstX - 1, dstY - 1, dstZ - 1, + dstX + scaleX + 1, dstY + scaleY + 1, dstZ + scaleZ + 1, new WrapInMatrixFrame(matrixFrameBlock.getDefaultState(), dstWorld))); - final AxisAlignedBB srcBox = new AxisAlignedBB( srcX, srcY, srcZ, srcX + scaleX + 1, srcY + scaleY + 1, srcZ + scaleZ + 1 ); + final AxisAlignedBB srcBox = new AxisAlignedBB(srcX, srcY, srcZ, srcX + scaleX + 1, srcY + scaleY + 1, srcZ + scaleZ + 1); - final AxisAlignedBB dstBox = new AxisAlignedBB( dstX, dstY, dstZ, dstX + scaleX + 1, dstY + scaleY + 1, dstZ + scaleZ + 1 ); + final AxisAlignedBB dstBox = new AxisAlignedBB(dstX, dstY, dstZ, dstX + scaleX + 1, dstY + scaleY + 1, dstZ + scaleZ + 1); - final CachedPlane cDst = new CachedPlane( dstWorld, dstX, dstY, dstZ, dstX + scaleX, dstY + scaleY, dstZ + scaleZ ); - final CachedPlane cSrc = new CachedPlane( srcWorld, srcX, srcY, srcZ, srcX + scaleX, srcY + scaleY, srcZ + scaleZ ); + final CachedPlane cDst = new CachedPlane(dstWorld, dstX, dstY, dstZ, dstX + scaleX, dstY + scaleY, dstZ + scaleZ); + final CachedPlane cSrc = new CachedPlane(srcWorld, srcX, srcY, srcZ, srcX + scaleX, srcY + scaleY, srcZ + scaleZ); - // do nearly all the work... swaps blocks, tiles, and block ticks - cSrc.swap( cDst ); + // do nearly all the work... swaps blocks, tiles, and block ticks + cSrc.swap(cDst); - final List srcE = srcWorld.getEntitiesWithinAABB( Entity.class, srcBox ); - final List dstE = dstWorld.getEntitiesWithinAABB( Entity.class, dstBox ); + final List srcE = srcWorld.getEntitiesWithinAABB(Entity.class, srcBox); + final List dstE = dstWorld.getEntitiesWithinAABB(Entity.class, dstBox); - for( final Entity e : dstE ) - { - this.teleportEntity( e, new TelDestination( srcWorld, srcBox, e.posX, e.posY, e.posZ, -dstX + srcX, -dstY + srcY, -dstZ + srcZ ) ); - } + for (final Entity e : dstE) { + this.teleportEntity(e, new TelDestination(srcWorld, srcBox, e.posX, e.posY, e.posZ, -dstX + srcX, -dstY + srcY, -dstZ + srcZ)); + } - for( final Entity e : srcE ) - { - this.teleportEntity( e, new TelDestination( dstWorld, dstBox, e.posX, e.posY, e.posZ, -srcX + dstX, -srcY + dstY, -srcZ + dstZ ) ); - } + for (final Entity e : srcE) { + this.teleportEntity(e, new TelDestination(dstWorld, dstBox, e.posX, e.posY, e.posZ, -srcX + dstX, -srcY + dstY, -srcZ + dstZ)); + } - for( final WorldCoord wc : cDst.getUpdates() ) - { - cSrc.getWorld().notifyNeighborsOfStateChange( wc.getPos(), Platform.AIR_BLOCK, true ); - } + for (final WorldCoord wc : cDst.getUpdates()) { + cSrc.getWorld().notifyNeighborsOfStateChange(wc.getPos(), Platform.AIR_BLOCK, true); + } - for( final WorldCoord wc : cSrc.getUpdates() ) - { - cSrc.getWorld().notifyNeighborsOfStateChange( wc.getPos(), Platform.AIR_BLOCK, true ); - } + for (final WorldCoord wc : cSrc.getUpdates()) { + cSrc.getWorld().notifyNeighborsOfStateChange(wc.getPos(), Platform.AIR_BLOCK, true); + } - this.transverseEdges( srcX - 1, srcY - 1, srcZ - 1, srcX + scaleX + 1, srcY + scaleY + 1, srcZ + scaleZ + 1, new TriggerUpdates( srcWorld ) ); - this.transverseEdges( dstX - 1, dstY - 1, dstZ - 1, dstX + scaleX + 1, dstY + scaleY + 1, dstZ + scaleZ + 1, new TriggerUpdates( dstWorld ) ); + this.transverseEdges(srcX - 1, srcY - 1, srcZ - 1, srcX + scaleX + 1, srcY + scaleY + 1, srcZ + scaleZ + 1, new TriggerUpdates(srcWorld)); + this.transverseEdges(dstX - 1, dstY - 1, dstZ - 1, dstX + scaleX + 1, dstY + scaleY + 1, dstZ + scaleZ + 1, new TriggerUpdates(dstWorld)); - this.transverseEdges( srcX, srcY, srcZ, srcX + scaleX, srcY + scaleY, srcZ + scaleZ, new TriggerUpdates( srcWorld ) ); - this.transverseEdges( dstX, dstY, dstZ, dstX + scaleX, dstY + scaleY, dstZ + scaleZ, new TriggerUpdates( dstWorld ) ); + this.transverseEdges(srcX, srcY, srcZ, srcX + scaleX, srcY + scaleY, srcZ + scaleZ, new TriggerUpdates(srcWorld)); + this.transverseEdges(dstX, dstY, dstZ, dstX + scaleX, dstY + scaleY, dstZ + scaleZ, new TriggerUpdates(dstWorld)); - /* - * IChunkProvider cp = destination.getChunkProvider(); if ( cp instanceof ChunkProviderServer ) { - * ChunkProviderServer - * srv = (ChunkProviderServer) cp; srv.unloadAllChunks(); } - * cp.unloadQueuedChunks(); - */ + /* + * IChunkProvider cp = destination.getChunkProvider(); if ( cp instanceof ChunkProviderServer ) { + * ChunkProviderServer + * srv = (ChunkProviderServer) cp; srv.unloadAllChunks(); } + * cp.unloadQueuedChunks(); + */ - } + } - private static class TriggerUpdates implements ISpatialVisitor - { + private static class TriggerUpdates implements ISpatialVisitor { - private final World dst; + private final World dst; - public TriggerUpdates( final World dst2 ) - { - this.dst = dst2; - } + public TriggerUpdates(final World dst2) { + this.dst = dst2; + } - @Override - public void visit( final BlockPos pos ) - { - final IBlockState state = this.dst.getBlockState( pos ); - final Block blk = state.getBlock(); - blk.neighborChanged( state, this.dst, pos, blk, pos ); - } - } + @Override + public void visit(final BlockPos pos) { + final IBlockState state = this.dst.getBlockState(pos); + final Block blk = state.getBlock(); + blk.neighborChanged(state, this.dst, pos, blk, pos); + } + } - private static class WrapInMatrixFrame implements ISpatialVisitor - { + private static class WrapInMatrixFrame implements ISpatialVisitor { - private final World dst; - private final IBlockState state; + private final World dst; + private final IBlockState state; - public WrapInMatrixFrame( final IBlockState state, final World dst2 ) - { - this.dst = dst2; - this.state = state; - } + public WrapInMatrixFrame(final IBlockState state, final World dst2) { + this.dst = dst2; + this.state = state; + } - @Override - public void visit( final BlockPos pos ) - { - this.dst.setBlockState( pos, this.state ); - } - } + @Override + public void visit(final BlockPos pos) { + this.dst.setBlockState(pos, this.state); + } + } - private static class TelDestination - { - private final World dim; - private final double x; - private final double y; - private final double z; + private static class TelDestination { + private final World dim; + private final double x; + private final double y; + private final double z; - TelDestination( final World dimension, final AxisAlignedBB srcBox, final double x, final double y, final double z, final int tileX, final int tileY, final int tileZ ) - { - this.dim = dimension; - this.x = Math.min( srcBox.maxX - 0.5, Math.max( srcBox.minX + 0.5, x + tileX ) ); - this.y = Math.min( srcBox.maxY - 0.5, Math.max( srcBox.minY + 0.5, y + tileY ) ); - this.z = Math.min( srcBox.maxZ - 0.5, Math.max( srcBox.minZ + 0.5, z + tileZ ) ); - } - } + TelDestination(final World dimension, final AxisAlignedBB srcBox, final double x, final double y, final double z, final int tileX, final int tileY, final int tileZ) { + this.dim = dimension; + this.x = Math.min(srcBox.maxX - 0.5, Math.max(srcBox.minX + 0.5, x + tileX)); + this.y = Math.min(srcBox.maxY - 0.5, Math.max(srcBox.minY + 0.5, y + tileY)); + this.z = Math.min(srcBox.maxZ - 0.5, Math.max(srcBox.minZ + 0.5, z + tileZ)); + } + } - private static class METeleporter implements ITeleporter - { + private static class METeleporter implements ITeleporter { - private final TelDestination destination; + private final TelDestination destination; - METeleporter( final TelDestination d ) - { - this.destination = d; - } + METeleporter(final TelDestination d) { + this.destination = d; + } - @Override - public void placeEntity( World world, Entity entity, float yaw ) - { - entity.setLocationAndAngles( this.destination.x, this.destination.y, this.destination.z, yaw, entity.rotationPitch ); - entity.motionX = entity.motionY = entity.motionZ = 0.0D; - } - } + @Override + public void placeEntity(World world, Entity entity, float yaw) { + entity.setLocationAndAngles(this.destination.x, this.destination.y, this.destination.z, yaw, entity.rotationPitch); + entity.motionX = entity.motionY = entity.motionZ = 0.0D; + } + } } diff --git a/src/main/java/appeng/spatial/StorageWorldProvider.java b/src/main/java/appeng/spatial/StorageWorldProvider.java index b6e141bf1..66f65003e 100644 --- a/src/main/java/appeng/spatial/StorageWorldProvider.java +++ b/src/main/java/appeng/spatial/StorageWorldProvider.java @@ -19,6 +19,8 @@ package appeng.spatial; +import appeng.client.render.SpatialSkyRender; +import appeng.core.AppEng; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; @@ -32,130 +34,107 @@ import net.minecraftforge.client.IRenderHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.client.render.SpatialSkyRender; -import appeng.core.AppEng; +public class StorageWorldProvider extends WorldProvider { -public class StorageWorldProvider extends WorldProvider -{ + private final Biome biome; - private final Biome biome; + public StorageWorldProvider() { + this.hasSkyLight = true; + this.biome = AppEng.instance().getStorageBiome(); + this.biomeProvider = new BiomeProviderSingle(this.biome); + } - public StorageWorldProvider() - { - this.hasSkyLight = true; - this.biome = AppEng.instance().getStorageBiome(); - this.biomeProvider = new BiomeProviderSingle( this.biome ); - } + @Override + public IChunkGenerator createChunkGenerator() { + return new StorageChunkProvider(this.world, 0); + } - @Override - public IChunkGenerator createChunkGenerator() - { - return new StorageChunkProvider( this.world, 0 ); - } + @Override + public float calculateCelestialAngle(final long par1, final float par3) { + return 0; + } - @Override - public float calculateCelestialAngle( final long par1, final float par3 ) - { - return 0; - } + @Override + public boolean isSurfaceWorld() { + return false; + } - @Override - public boolean isSurfaceWorld() - { - return false; - } + @Override + @SideOnly(Side.CLIENT) + public float[] calcSunriseSunsetColors(final float celestialAngle, final float partialTicks) { + return null; + } - @Override - @SideOnly( Side.CLIENT ) - public float[] calcSunriseSunsetColors( final float celestialAngle, final float partialTicks ) - { - return null; - } + @Override + public Vec3d getFogColor(final float par1, final float par2) { + return new Vec3d(0.07, 0.07, 0.07); + } - @Override - public Vec3d getFogColor( final float par1, final float par2 ) - { - return new Vec3d( 0.07, 0.07, 0.07 ); - } + @Override + public boolean canRespawnHere() { + return false; + } - @Override - public boolean canRespawnHere() - { - return false; - } + @Override + @SideOnly(Side.CLIENT) + public boolean isSkyColored() { + return true; + } - @Override - @SideOnly( Side.CLIENT ) - public boolean isSkyColored() - { - return true; - } + @Override + public boolean doesXZShowFog(final int par1, final int par2) { + return false; + } - @Override - public boolean doesXZShowFog( final int par1, final int par2 ) - { - return false; - } + @Override + public DimensionType getDimensionType() { + return AppEng.instance().getStorageDimensionType(); + } - @Override - public DimensionType getDimensionType() - { - return AppEng.instance().getStorageDimensionType(); - } + @Override + public IRenderHandler getSkyRenderer() { + return SpatialSkyRender.getInstance(); + } - @Override - public IRenderHandler getSkyRenderer() - { - return SpatialSkyRender.getInstance(); - } + @Override + public boolean isDaytime() { + return false; + } - @Override - public boolean isDaytime() - { - return false; - } + @Override + public Vec3d getSkyColor(final Entity cameraEntity, final float partialTicks) { + return new Vec3d(0.07, 0.07, 0.07); + } - @Override - public Vec3d getSkyColor( final Entity cameraEntity, final float partialTicks ) - { - return new Vec3d( 0.07, 0.07, 0.07 ); - } + @Override + public float getStarBrightness(final float par1) { + return 0; + } - @Override - public float getStarBrightness( final float par1 ) - { - return 0; - } + @Override + public boolean canSnowAt(final BlockPos pos, final boolean checkLight) { + return false; + } - @Override - public boolean canSnowAt( final BlockPos pos, final boolean checkLight ) - { - return false; - } + @Override + public BlockPos getSpawnCoordinate() { + return new BlockPos(0, 0, 0); + } - @Override - public BlockPos getSpawnCoordinate() - { - return new BlockPos( 0, 0, 0 ); - } + @Override + public boolean isBlockHighHumidity(final BlockPos pos) { + return false; + } - @Override - public boolean isBlockHighHumidity( final BlockPos pos ) - { - return false; - } + @Override + public boolean canDoLightning(final Chunk chunk) { + return false; + } - @Override - public boolean canDoLightning( final Chunk chunk ) - { - return false; - } - - @Override - public Biome getBiomeForCoords( BlockPos pos ) - { - return this.biome; - } + @Override + public Biome getBiomeForCoords(BlockPos pos) { + return this.biome; + } } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/math/InterpHelper.java b/src/main/java/appeng/thirdparty/codechicken/lib/math/InterpHelper.java index 2f6a72c93..751656a66 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/math/InterpHelper.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/math/InterpHelper.java @@ -22,108 +22,96 @@ package appeng.thirdparty.codechicken.lib.math; /** * @author covers1624 */ -public class InterpHelper -{ +public class InterpHelper { - private float[][] posCache = new float[4][2]; - private float[] valCache = new float[4]; + private final float[][] posCache = new float[4][2]; + private final float[] valCache = new float[4]; - private float x0; - private float x1; - private float y0; - private float y1; + private float x0; + private float x1; + private float y0; + private float y1; - private float rX; - private float rY; + private float rX; + private float rY; - private int p00; - private int p10; - private int p11; - private int p01; + private int p00; + private int p10; + private int p11; + private int p01; - /** - * Resets the interp helper with the given quad. Does not care what order the vertices are in. - */ - public void reset( float dx0, float dy0, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3 ) - { + /** + * Resets the interp helper with the given quad. Does not care what order the vertices are in. + */ + public void reset(float dx0, float dy0, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) { - float[] vec0 = this.posCache[0]; - float[] vec1 = this.posCache[1]; - float[] vec2 = this.posCache[2]; - float[] vec3 = this.posCache[3]; + float[] vec0 = this.posCache[0]; + float[] vec1 = this.posCache[1]; + float[] vec2 = this.posCache[2]; + float[] vec3 = this.posCache[3]; - vec0[0] = dx0; - vec1[0] = dx1; - vec2[0] = dx2; - vec3[0] = dx3; + vec0[0] = dx0; + vec1[0] = dx1; + vec2[0] = dx2; + vec3[0] = dx3; - vec0[1] = dy0; - vec1[1] = dy1; - vec2[1] = dy2; - vec3[1] = dy3; - } + vec0[1] = dy0; + vec1[1] = dy1; + vec2[1] = dy2; + vec3[1] = dy3; + } - /** - * Call when you are ready to use the InterpHelper. - */ - public void setup() - { - this.p00 = 0;// Bottom Left is always first. - this.x0 = this.posCache[this.p00][0]; - this.y0 = this.posCache[this.p00][1]; - for( int i = 1; i < 4; i++ ) - { - float x = this.posCache[i][0]; - float y = this.posCache[i][1]; - if( this.y0 == y ) - { - this.p10 = i;// Bottom right. - this.x1 = x; - } - else if( this.x0 == x ) - { - this.p01 = i;// Top left. - this.y1 = y; - } - else - { - // Top right. - this.p11 = i; - } - } - } + /** + * Call when you are ready to use the InterpHelper. + */ + public void setup() { + this.p00 = 0;// Bottom Left is always first. + this.x0 = this.posCache[this.p00][0]; + this.y0 = this.posCache[this.p00][1]; + for (int i = 1; i < 4; i++) { + float x = this.posCache[i][0]; + float y = this.posCache[i][1]; + if (this.y0 == y) { + this.p10 = i;// Bottom right. + this.x1 = x; + } else if (this.x0 == x) { + this.p01 = i;// Top left. + this.y1 = y; + } else { + // Top right. + this.p11 = i; + } + } + } - /** - * Computes the coefficients for the interpolation. - * - * @param x X interp location. - * @param y Y interp location. - */ - public void locate( float x, float y ) - { - this.rX = ( x - this.x0 ) / ( this.x1 - this.x0 ); - this.rY = ( y - this.y0 ) / ( this.y1 - this.y0 ); - } + /** + * Computes the coefficients for the interpolation. + * + * @param x X interp location. + * @param y Y interp location. + */ + public void locate(float x, float y) { + this.rX = (x - this.x0) / (this.x1 - this.x0); + this.rY = (y - this.y0) / (this.y1 - this.y0); + } - /** - * Interpolates using the already computed coefficients. - * - * @param q0 Value at dx0 dy0 - * @param q1 Value at dx1 dy1 - * @param q2 Value at dx2 dy2 - * @param q3 Value at dx3 dy3 - * - * @return The result. - */ - public float interpolate( float q0, float q1, float q2, float q3 ) - { - this.valCache[0] = q0; - this.valCache[1] = q1; - this.valCache[2] = q2; - this.valCache[3] = q3; - float f0 = ( this.valCache[this.p00] * ( 1 - this.rX ) ) + ( this.valCache[this.p10] * this.rX ); - float f1 = ( this.valCache[this.p01] * ( 1 - this.rX ) ) + ( this.valCache[this.p11] * this.rX ); + /** + * Interpolates using the already computed coefficients. + * + * @param q0 Value at dx0 dy0 + * @param q1 Value at dx1 dy1 + * @param q2 Value at dx2 dy2 + * @param q3 Value at dx3 dy3 + * @return The result. + */ + public float interpolate(float q0, float q1, float q2, float q3) { + this.valCache[0] = q0; + this.valCache[1] = q1; + this.valCache[2] = q2; + this.valCache[3] = q3; + float f0 = (this.valCache[this.p00] * (1 - this.rX)) + (this.valCache[this.p10] * this.rX); + float f1 = (this.valCache[this.p01] * (1 - this.rX)) + (this.valCache[this.p11] * this.rX); - return ( f0 * ( 1 - this.rY ) ) + ( f1 * this.rY ); - } + return (f0 * (1 - this.rY)) + (f1 * this.rY); + } } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/model/CachedFormat.java b/src/main/java/appeng/thirdparty/codechicken/lib/model/CachedFormat.java index 0c407a6c6..fb60a2204 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/model/CachedFormat.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/model/CachedFormat.java @@ -19,12 +19,12 @@ package appeng.thirdparty.codechicken.lib.model; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.client.renderer.vertex.VertexFormatElement; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + /** * A simple VertexFormat cache. @@ -32,133 +32,115 @@ import net.minecraft.client.renderer.vertex.VertexFormatElement; * * @author covers1624 */ -public class CachedFormat -{ +public class CachedFormat { - public static final Map formatCache = new ConcurrentHashMap<>(); + public static final Map formatCache = new ConcurrentHashMap<>(); - /** - * Lookup or create the CachedFormat for a given VertexFormat. - * - * @param format The format to lookup. - * - * @return The CachedFormat. - */ - public static CachedFormat lookup( VertexFormat format ) - { - return formatCache.computeIfAbsent( format, CachedFormat::new ); - } + /** + * Lookup or create the CachedFormat for a given VertexFormat. + * + * @param format The format to lookup. + * @return The CachedFormat. + */ + public static CachedFormat lookup(VertexFormat format) { + return formatCache.computeIfAbsent(format, CachedFormat::new); + } - public VertexFormat format; + public VertexFormat format; - public boolean hasPosition; - public boolean hasNormal; - public boolean hasColor; - public boolean hasUV; - public boolean hasLightMap; + public boolean hasPosition; + public boolean hasNormal; + public boolean hasColor; + public boolean hasUV; + public boolean hasLightMap; - public int positionIndex = -1; - public int normalIndex = -1; - public int colorIndex = -1; - public int uvIndex = -1; - public int lightMapIndex = -1; + public int positionIndex = -1; + public int normalIndex = -1; + public int colorIndex = -1; + public int uvIndex = -1; + public int lightMapIndex = -1; - public int elementCount; + public int elementCount; - /** - * Caches the vertex format element indexes for efficiency. - * - * @param format The format. - */ - public CachedFormat( VertexFormat format ) - { - this.format = format; - this.elementCount = format.getElementCount(); - for( int i = 0; i < this.elementCount; i++ ) - { - VertexFormatElement element = format.getElement( i ); - switch( element.getUsage() ) - { - case POSITION: - if( this.hasPosition ) - { - throw new IllegalStateException( "Found 2 position elements.." ); - } - this.hasPosition = true; - this.positionIndex = i; - break; - case NORMAL: - if( this.hasNormal ) - { - throw new IllegalStateException( "Found 2 normal elements.." ); - } - this.hasNormal = true; - this.normalIndex = i; - break; - case COLOR: - if( this.hasColor ) - { - throw new IllegalStateException( "Found 2 color elements.." ); - } - this.hasColor = true; - this.colorIndex = i; - break; - case UV: - if( element.getIndex() == 0 ) - { - if( this.hasUV ) - { - throw new IllegalStateException( "Found 2 UV elements.." ); - } - this.hasUV = true; - this.uvIndex = i; - break; - } - else if( element.getIndex() == 1 ) - { - if( this.hasLightMap ) - { - throw new IllegalStateException( "Found 2 LightMap elements.." ); - } - this.hasLightMap = true; - this.lightMapIndex = i; - break; - } - break; - } - } - } + /** + * Caches the vertex format element indexes for efficiency. + * + * @param format The format. + */ + public CachedFormat(VertexFormat format) { + this.format = format; + this.elementCount = format.getElementCount(); + for (int i = 0; i < this.elementCount; i++) { + VertexFormatElement element = format.getElement(i); + switch (element.getUsage()) { + case POSITION: + if (this.hasPosition) { + throw new IllegalStateException("Found 2 position elements.."); + } + this.hasPosition = true; + this.positionIndex = i; + break; + case NORMAL: + if (this.hasNormal) { + throw new IllegalStateException("Found 2 normal elements.."); + } + this.hasNormal = true; + this.normalIndex = i; + break; + case COLOR: + if (this.hasColor) { + throw new IllegalStateException("Found 2 color elements.."); + } + this.hasColor = true; + this.colorIndex = i; + break; + case UV: + if (element.getIndex() == 0) { + if (this.hasUV) { + throw new IllegalStateException("Found 2 UV elements.."); + } + this.hasUV = true; + this.uvIndex = i; + break; + } else if (element.getIndex() == 1) { + if (this.hasLightMap) { + throw new IllegalStateException("Found 2 LightMap elements.."); + } + this.hasLightMap = true; + this.lightMapIndex = i; + break; + } + break; + } + } + } - @Override - public boolean equals( Object obj ) - { - if( this == obj ) - { - return true; - } - if( !( obj instanceof CachedFormat ) ) - { - return false; - } - CachedFormat other = (CachedFormat) obj; - return other.elementCount == this.elementCount && // - other.positionIndex == this.positionIndex && // - other.normalIndex == this.normalIndex && // - other.colorIndex == this.colorIndex && // - other.uvIndex == this.uvIndex && // - other.lightMapIndex == this.lightMapIndex; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof CachedFormat)) { + return false; + } + CachedFormat other = (CachedFormat) obj; + return other.elementCount == this.elementCount && // + other.positionIndex == this.positionIndex && // + other.normalIndex == this.normalIndex && // + other.colorIndex == this.colorIndex && // + other.uvIndex == this.uvIndex && // + other.lightMapIndex == this.lightMapIndex; + } - @Override - public int hashCode() - { - int result = 1; - result = 31 * result + this.elementCount; - result = 31 * result + this.positionIndex; - result = 31 * result + this.normalIndex; - result = 31 * result + this.colorIndex; - result = 31 * result + this.uvIndex; - result = 31 * result + this.lightMapIndex; - return result; - } + @Override + public int hashCode() { + int result = 1; + result = 31 * result + this.elementCount; + result = 31 * result + this.positionIndex; + result = 31 * result + this.normalIndex; + result = 31 * result + this.colorIndex; + result = 31 * result + this.uvIndex; + result = 31 * result + this.lightMapIndex; + return result; + } } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/model/ISmartVertexConsumer.java b/src/main/java/appeng/thirdparty/codechicken/lib/model/ISmartVertexConsumer.java index b09676f09..92ef9c7d5 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/model/ISmartVertexConsumer.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/model/ISmartVertexConsumer.java @@ -27,16 +27,15 @@ import net.minecraftforge.client.model.pipeline.IVertexConsumer; * * @author covers1624 */ -public interface ISmartVertexConsumer extends IVertexConsumer -{ +public interface ISmartVertexConsumer extends IVertexConsumer { - /** - * Assumes the data is already completely unpacked. - * You must always copy the data from the quad provided to an internal cache. - * basically: - * this.quad.put(quad); - * - * @param quad The quad to copy data from. - */ - void put( Quad quad ); + /** + * Assumes the data is already completely unpacked. + * You must always copy the data from the quad provided to an internal cache. + * basically: + * this.quad.put(quad); + * + * @param quad The quad to copy data from. + */ + void put(Quad quad); } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/model/Quad.java b/src/main/java/appeng/thirdparty/codechicken/lib/model/Quad.java index e9725992a..1c6e2eae8 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/model/Quad.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/model/Quad.java @@ -19,8 +19,7 @@ package appeng.thirdparty.codechicken.lib.model; -import javax.vecmath.Vector3f; - +import appeng.thirdparty.codechicken.lib.math.InterpHelper; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; @@ -32,7 +31,7 @@ import net.minecraftforge.client.model.pipeline.IVertexProducer; import net.minecraftforge.client.model.pipeline.LightUtil; import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad; -import appeng.thirdparty.codechicken.lib.math.InterpHelper; +import javax.vecmath.Vector3f; /** @@ -40,166 +39,141 @@ import appeng.thirdparty.codechicken.lib.math.InterpHelper; * * @author covers1624 */ -public class Quad implements IVertexProducer, ISmartVertexConsumer -{ +public class Quad implements IVertexProducer, ISmartVertexConsumer { - public CachedFormat format; + public CachedFormat format; - public int tintIndex = -1; - public EnumFacing orientation; - public boolean diffuseLighting = true; - public TextureAtlasSprite sprite; + public int tintIndex = -1; + public EnumFacing orientation; + public boolean diffuseLighting = true; + public TextureAtlasSprite sprite; - public Vertex[] vertices = new Vertex[4]; - public boolean full; + public Vertex[] vertices = new Vertex[4]; + public boolean full; - // Not copied. - private int vertexIndex = 0; - // Cache for normal computation. - private Vector3f v1 = new Vector3f(); - private Vector3f v2 = new Vector3f(); - private Vector3f t = new Vector3f(); - private Vector3f normal = new Vector3f(); + // Not copied. + private int vertexIndex = 0; + // Cache for normal computation. + private final Vector3f v1 = new Vector3f(); + private final Vector3f v2 = new Vector3f(); + private final Vector3f t = new Vector3f(); + private final Vector3f normal = new Vector3f(); - /** - * Use this if you reset the quad each time you use it. - */ - public Quad() - { - } + /** + * Use this if you reset the quad each time you use it. + */ + public Quad() { + } - /** - * use this if you want to initialize the quad with a format. - * - * @param format The format. - */ - public Quad( CachedFormat format ) - { - this.format = format; - } + /** + * use this if you want to initialize the quad with a format. + * + * @param format The format. + */ + public Quad(CachedFormat format) { + this.format = format; + } - @Override - public VertexFormat getVertexFormat() - { - return this.format.format; - } + @Override + public VertexFormat getVertexFormat() { + return this.format.format; + } - @Override - public void setQuadTint( int tint ) - { - this.tintIndex = tint; - } + @Override + public void setQuadTint(int tint) { + this.tintIndex = tint; + } - @Override - public void setQuadOrientation( EnumFacing orientation ) - { - this.orientation = orientation; - } + @Override + public void setQuadOrientation(EnumFacing orientation) { + this.orientation = orientation; + } - @Override - public void setApplyDiffuseLighting( boolean diffuse ) - { - this.diffuseLighting = diffuse; - } + @Override + public void setApplyDiffuseLighting(boolean diffuse) { + this.diffuseLighting = diffuse; + } - @Override - public void setTexture( TextureAtlasSprite texture ) - { - this.sprite = texture; - } + @Override + public void setTexture(TextureAtlasSprite texture) { + this.sprite = texture; + } - @Override - public void put( int element, float... data ) - { - if( this.full ) - { - throw new RuntimeException( "Unable to add data when full." ); - } - Vertex v = this.vertices[this.vertexIndex]; - if( v == null ) - { - v = new Vertex( this.format ); - this.vertices[this.vertexIndex] = v; - } - System.arraycopy( data, 0, v.raw[element], 0, data.length ); - if( element == ( this.format.elementCount - 1 ) ) - { - this.vertexIndex++; - if( this.vertexIndex == 4 ) - { - this.vertexIndex = 0; - this.full = true; - if(orientation == null) - { - calculateOrientation(false); + @Override + public void put(int element, float... data) { + if (this.full) { + throw new RuntimeException("Unable to add data when full."); + } + Vertex v = this.vertices[this.vertexIndex]; + if (v == null) { + v = new Vertex(this.format); + this.vertices[this.vertexIndex] = v; + } + System.arraycopy(data, 0, v.raw[element], 0, data.length); + if (element == (this.format.elementCount - 1)) { + this.vertexIndex++; + if (this.vertexIndex == 4) { + this.vertexIndex = 0; + this.full = true; + if (orientation == null) { + calculateOrientation(false); } - } - } - } + } + } + } - @Override - public void put( Quad quad ) - { - this.copyFrom( quad ); - } + @Override + public void put(Quad quad) { + this.copyFrom(quad); + } - @Override - public void pipe( IVertexConsumer consumer ) - { - if( consumer instanceof ISmartVertexConsumer ) - { - ( (ISmartVertexConsumer) consumer ).put( this ); - } - else - { - consumer.setQuadTint( this.tintIndex ); - consumer.setQuadOrientation( this.orientation ); - consumer.setApplyDiffuseLighting( this.diffuseLighting ); - consumer.setTexture( this.sprite ); - for( Vertex v : this.vertices ) - { - for( int e = 0; e < this.format.elementCount; e++ ) - { - consumer.put( e, v.raw[e] ); - } - } - } - } + @Override + public void pipe(IVertexConsumer consumer) { + if (consumer instanceof ISmartVertexConsumer) { + ((ISmartVertexConsumer) consumer).put(this); + } else { + consumer.setQuadTint(this.tintIndex); + consumer.setQuadOrientation(this.orientation); + consumer.setApplyDiffuseLighting(this.diffuseLighting); + consumer.setTexture(this.sprite); + for (Vertex v : this.vertices) { + for (int e = 0; e < this.format.elementCount; e++) { + consumer.put(e, v.raw[e]); + } + } + } + } - /** - * Used to reset the interpolation values inside the provided helper. - * - * @param helper The helper. - * @param s The axis. side >> 1; - * - * @return The same helper. - */ - public InterpHelper resetInterp( InterpHelper helper, int s ) - { - helper.reset( // - this.vertices[0].dx( s ), this.vertices[0].dy( s ), // - this.vertices[1].dx( s ), this.vertices[1].dy( s ), // - this.vertices[2].dx( s ), this.vertices[2].dy( s ), // - this.vertices[3].dx( s ), this.vertices[3].dy( s ) ); - return helper; - } + /** + * Used to reset the interpolation values inside the provided helper. + * + * @param helper The helper. + * @param s The axis. side >> 1; + * @return The same helper. + */ + public InterpHelper resetInterp(InterpHelper helper, int s) { + helper.reset( // + this.vertices[0].dx(s), this.vertices[0].dy(s), // + this.vertices[1].dx(s), this.vertices[1].dy(s), // + this.vertices[2].dx(s), this.vertices[2].dy(s), // + this.vertices[3].dx(s), this.vertices[3].dy(s)); + return helper; + } - /** - * Clamps the Quad inside the box. - * - * @param bb The box. - */ - public void clamp( AxisAlignedBB bb ) - { - for( Vertex vertex : this.vertices ) - { - float[] vec = vertex.vec; - vec[0] = (float) MathHelper.clamp( vec[0], bb.minX, bb.maxX ); - vec[1] = (float) MathHelper.clamp( vec[1], bb.minY, bb.maxY ); - vec[2] = (float) MathHelper.clamp( vec[2], bb.minZ, bb.maxZ ); - } - calculateOrientation(true); - } + /** + * Clamps the Quad inside the box. + * + * @param bb The box. + */ + public void clamp(AxisAlignedBB bb) { + for (Vertex vertex : this.vertices) { + float[] vec = vertex.vec; + vec[0] = (float) MathHelper.clamp(vec[0], bb.minX, bb.maxX); + vec[1] = (float) MathHelper.clamp(vec[1], bb.minY, bb.maxY); + vec[2] = (float) MathHelper.clamp(vec[2], bb.minZ, bb.maxZ); + } + calculateOrientation(true); + } /** * Re-calculates the Orientation of this quad, @@ -207,358 +181,306 @@ public class Quad implements IVertexProducer, ISmartVertexConsumer * * @param setNormal If the normal vector should be updated. */ - public void calculateOrientation( boolean setNormal ) - { - this.v1.set( this.vertices[3].vec ); - this.t.set( this.vertices[1].vec ); - this.v1.sub( this.t ); + public void calculateOrientation(boolean setNormal) { + this.v1.set(this.vertices[3].vec); + this.t.set(this.vertices[1].vec); + this.v1.sub(this.t); - this.v2.set( this.vertices[2].vec ); - this.t.set( this.vertices[0].vec ); - this.v2.sub( this.t ); + this.v2.set(this.vertices[2].vec); + this.t.set(this.vertices[0].vec); + this.v2.sub(this.t); - this.normal.cross( this.v2, this.v1 ); + this.normal.cross(this.v2, this.v1); this.normal.normalize(); - if( this.format.hasNormal && setNormal) - { - for( Vertex vertex : this.vertices ) - { + if (this.format.hasNormal && setNormal) { + for (Vertex vertex : this.vertices) { vertex.normal[0] = this.normal.x; vertex.normal[1] = this.normal.y; vertex.normal[2] = this.normal.z; vertex.normal[3] = 0; } } - this.orientation = EnumFacing.getFacingFromVector( this.normal.x, this.normal.y, this.normal.z ); + this.orientation = EnumFacing.getFacingFromVector(this.normal.x, this.normal.y, this.normal.z); } - /** - * Used to create a new quad complete copy of this one. - * - * @return The new quad. - */ - public Quad copy() - { - if( !this.full ) - { - throw new RuntimeException( "Only copying full quads is supported." ); - } - Quad quad = new Quad( this.format ); - quad.tintIndex = this.tintIndex; - quad.orientation = this.orientation; - quad.diffuseLighting = this.diffuseLighting; - quad.sprite = this.sprite; - quad.full = true; - for( int i = 0; i < 4; i++ ) - { - quad.vertices[i] = this.vertices[i].copy(); - } - return quad; - } + /** + * Used to create a new quad complete copy of this one. + * + * @return The new quad. + */ + public Quad copy() { + if (!this.full) { + throw new RuntimeException("Only copying full quads is supported."); + } + Quad quad = new Quad(this.format); + quad.tintIndex = this.tintIndex; + quad.orientation = this.orientation; + quad.diffuseLighting = this.diffuseLighting; + quad.sprite = this.sprite; + quad.full = true; + for (int i = 0; i < 4; i++) { + quad.vertices[i] = this.vertices[i].copy(); + } + return quad; + } - /** - * Copies the data inside the given quad to this one. This ignores VertexFormat, please make sure your quads are in - * the same format. - * - * @param quad The Quad to copy from. - * - * @return This quad. - */ - public Quad copyFrom( Quad quad ) - { - this.tintIndex = quad.tintIndex; - this.orientation = quad.orientation; - this.diffuseLighting = quad.diffuseLighting; - this.sprite = quad.sprite; - this.full = quad.full; - for( int v = 0; v < 4; v++ ) - { - for( int e = 0; e < this.format.elementCount; e++ ) - { - System.arraycopy( quad.vertices[v].raw[e], 0, this.vertices[v].raw[e], 0, 4 ); - } - } - return this; - } + /** + * Copies the data inside the given quad to this one. This ignores VertexFormat, please make sure your quads are in + * the same format. + * + * @param quad The Quad to copy from. + * @return This quad. + */ + public Quad copyFrom(Quad quad) { + this.tintIndex = quad.tintIndex; + this.orientation = quad.orientation; + this.diffuseLighting = quad.diffuseLighting; + this.sprite = quad.sprite; + this.full = quad.full; + for (int v = 0; v < 4; v++) { + for (int e = 0; e < this.format.elementCount; e++) { + System.arraycopy(quad.vertices[v].raw[e], 0, this.vertices[v].raw[e], 0, 4); + } + } + return this; + } - /** - * Reset the quad to the new format. - * - * @param format The new format. - */ - public void reset( CachedFormat format ) - { - this.format = format; - this.tintIndex = -1; - this.orientation = null; - this.diffuseLighting = true; - this.sprite = null; - for( int i = 0; i < this.vertices.length; i++ ) - { - Vertex v = this.vertices[i]; - if( v == null ) - { - this.vertices[i] = v = new Vertex( format ); - } - v.reset( format ); - } - this.vertexIndex = 0; - this.full = false; - } + /** + * Reset the quad to the new format. + * + * @param format The new format. + */ + public void reset(CachedFormat format) { + this.format = format; + this.tintIndex = -1; + this.orientation = null; + this.diffuseLighting = true; + this.sprite = null; + for (int i = 0; i < this.vertices.length; i++) { + Vertex v = this.vertices[i]; + if (v == null) { + this.vertices[i] = v = new Vertex(format); + } + v.reset(format); + } + this.vertexIndex = 0; + this.full = false; + } - /** - * Bakes this Quad to a BakedQuad. - * - * @return The BakedQuad. - */ - public BakedQuad bake() - { - int[] packedData = new int[this.format.format.getNextOffset()]; - for( int v = 0; v < 4; v++ ) - { - for( int e = 0; e < this.format.elementCount; e++ ) - { - LightUtil.pack( this.vertices[v].raw[e], packedData, this.format.format, v, e ); - } - } - return new BakedQuad( packedData, this.tintIndex, this.orientation, this.sprite, this.diffuseLighting, this.format.format ); - } + /** + * Bakes this Quad to a BakedQuad. + * + * @return The BakedQuad. + */ + public BakedQuad bake() { + int[] packedData = new int[this.format.format.getNextOffset()]; + for (int v = 0; v < 4; v++) { + for (int e = 0; e < this.format.elementCount; e++) { + LightUtil.pack(this.vertices[v].raw[e], packedData, this.format.format, v, e); + } + } + return new BakedQuad(packedData, this.tintIndex, this.orientation, this.sprite, this.diffuseLighting, this.format.format); + } - /** - * Bakes this quad to an UnpackedBakedQuad. - * - * @return The UnpackedBakedQuad. - */ - public UnpackedBakedQuad bakeUnpacked() - { - UnpackedBakedQuad.Builder quad = new UnpackedBakedQuad.Builder( this.format.format ); - this.pipe( quad ); - return quad.build(); - } + /** + * Bakes this quad to an UnpackedBakedQuad. + * + * @return The UnpackedBakedQuad. + */ + public UnpackedBakedQuad bakeUnpacked() { + UnpackedBakedQuad.Builder quad = new UnpackedBakedQuad.Builder(this.format.format); + this.pipe(quad); + return quad.build(); + } - /** - * A simple vertex format. - */ - public static class Vertex - { + /** + * A simple vertex format. + */ + public static class Vertex { - public CachedFormat format; + public CachedFormat format; - /** - * The raw data. - */ - public float[][] raw; + /** + * The raw data. + */ + public float[][] raw; - // References to the arrays inside raw. - public float[] vec; - public float[] normal; - public float[] color; - public float[] uv; - public float[] lightmap; + // References to the arrays inside raw. + public float[] vec; + public float[] normal; + public float[] color; + public float[] uv; + public float[] lightmap; - /** - * Create a new Vertex. - * - * @param format The format for the vertex. - */ - public Vertex( CachedFormat format ) - { - this.format = format; - this.raw = new float[format.elementCount][4]; - this.preProcess(); - } + /** + * Create a new Vertex. + * + * @param format The format for the vertex. + */ + public Vertex(CachedFormat format) { + this.format = format; + this.raw = new float[format.elementCount][4]; + this.preProcess(); + } - /** - * Creates a new Vertex using the data inside the other. A copy! - * - * @param other The other. - */ - public Vertex( Vertex other ) - { - this.format = other.format; - this.raw = other.raw.clone(); - for( int v = 0; v < this.format.elementCount; v++ ) - { - this.raw[v] = other.raw[v].clone(); - } - this.preProcess(); - } + /** + * Creates a new Vertex using the data inside the other. A copy! + * + * @param other The other. + */ + public Vertex(Vertex other) { + this.format = other.format; + this.raw = other.raw.clone(); + for (int v = 0; v < this.format.elementCount; v++) { + this.raw[v] = other.raw[v].clone(); + } + this.preProcess(); + } - /** - * Pulls references to the individual element's arrays inside raw. Modifying the individual element arrays will - * update raw. - */ - public void preProcess() - { - if( this.format.hasPosition ) - { - this.vec = this.raw[this.format.positionIndex]; - } - if( this.format.hasNormal ) - { - this.normal = this.raw[this.format.normalIndex]; - } - if( this.format.hasColor ) - { - this.color = this.raw[this.format.colorIndex]; - } - if( this.format.hasUV ) - { - this.uv = this.raw[this.format.uvIndex]; - } - if( this.format.hasLightMap ) - { - this.lightmap = this.raw[this.format.lightMapIndex]; - } - } + /** + * Pulls references to the individual element's arrays inside raw. Modifying the individual element arrays will + * update raw. + */ + public void preProcess() { + if (this.format.hasPosition) { + this.vec = this.raw[this.format.positionIndex]; + } + if (this.format.hasNormal) { + this.normal = this.raw[this.format.normalIndex]; + } + if (this.format.hasColor) { + this.color = this.raw[this.format.colorIndex]; + } + if (this.format.hasUV) { + this.uv = this.raw[this.format.uvIndex]; + } + if (this.format.hasLightMap) { + this.lightmap = this.raw[this.format.lightMapIndex]; + } + } - /** - * Gets the 2d X coord for the given axis. - * - * @param s The axis. side >> 1 - * - * @return The x coord. - */ - public float dx( int s ) - { - if( s <= 1 ) - { - return this.vec[0]; - } - else - { - return this.vec[2]; - } - } + /** + * Gets the 2d X coord for the given axis. + * + * @param s The axis. side >> 1 + * @return The x coord. + */ + public float dx(int s) { + if (s <= 1) { + return this.vec[0]; + } else { + return this.vec[2]; + } + } - /** - * Gets the 2d Y coord for the given axis. - * - * @param s The axis. side >> 1 - * - * @return The y coord. - */ - public float dy( int s ) - { - if( s > 0 ) - { - return this.vec[1]; - } - else - { - return this.vec[2]; - } - } + /** + * Gets the 2d Y coord for the given axis. + * + * @param s The axis. side >> 1 + * @return The y coord. + */ + public float dy(int s) { + if (s > 0) { + return this.vec[1]; + } else { + return this.vec[2]; + } + } - /** - * Interpolates the new color values for this Vertex using the others as a reference. - * - * @param interpHelper The InterpHelper to use. - * @param others The other Vertices to use as a template. - * - * @return The same Vertex. - */ - public Vertex interpColorFrom( InterpHelper interpHelper, Vertex[] others ) - { - for( int e = 0; e < 4; e++ ) - { - float p1 = others[0].color[e]; - float p2 = others[1].color[e]; - float p3 = others[2].color[e]; - float p4 = others[3].color[e]; - // Only interpolate if colors are different. - if( p1 != p2 || p2 != p3 || p3 != p4 ) - { - this.color[e] = interpHelper.interpolate( p1, p2, p3, p4 ); - } - } - return this; - } + /** + * Interpolates the new color values for this Vertex using the others as a reference. + * + * @param interpHelper The InterpHelper to use. + * @param others The other Vertices to use as a template. + * @return The same Vertex. + */ + public Vertex interpColorFrom(InterpHelper interpHelper, Vertex[] others) { + for (int e = 0; e < 4; e++) { + float p1 = others[0].color[e]; + float p2 = others[1].color[e]; + float p3 = others[2].color[e]; + float p4 = others[3].color[e]; + // Only interpolate if colors are different. + if (p1 != p2 || p2 != p3 || p3 != p4) { + this.color[e] = interpHelper.interpolate(p1, p2, p3, p4); + } + } + return this; + } - /** - * Interpolates the new UV values for this Vertex using the others as a reference. - * - * @param interpHelper The InterpHelper to use. - * @param others The other Vertices to use as a template. - * - * @return The same Vertex. - */ - public Vertex interpUVFrom( InterpHelper interpHelper, Vertex[] others ) - { - for( int e = 0; e < 2; e++ ) - { - float p1 = others[0].uv[e]; - float p2 = others[1].uv[e]; - float p3 = others[2].uv[e]; - float p4 = others[3].uv[e]; - if( p1 != p2 || p2 != p3 || p3 != p4 ) - { - this.uv[e] = interpHelper.interpolate( p1, p2, p3, p4 ); - } - } - return this; - } + /** + * Interpolates the new UV values for this Vertex using the others as a reference. + * + * @param interpHelper The InterpHelper to use. + * @param others The other Vertices to use as a template. + * @return The same Vertex. + */ + public Vertex interpUVFrom(InterpHelper interpHelper, Vertex[] others) { + for (int e = 0; e < 2; e++) { + float p1 = others[0].uv[e]; + float p2 = others[1].uv[e]; + float p3 = others[2].uv[e]; + float p4 = others[3].uv[e]; + if (p1 != p2 || p2 != p3 || p3 != p4) { + this.uv[e] = interpHelper.interpolate(p1, p2, p3, p4); + } + } + return this; + } - /** - * Interpolates the new LightMap values for this Vertex using the others as a reference. - * - * @param interpHelper The InterpHelper to use. - * @param others The other Vertices to use as a template. - * - * @return The same Vertex. - */ - public Vertex interpLightMapFrom( InterpHelper interpHelper, Vertex[] others ) - { - for( int e = 0; e < 2; e++ ) - { - float p1 = others[0].lightmap[e]; - float p2 = others[1].lightmap[e]; - float p3 = others[2].lightmap[e]; - float p4 = others[3].lightmap[e]; - if( p1 != p2 || p2 != p3 || p3 != p4 ) - { - this.lightmap[e] = interpHelper.interpolate( p1, p2, p3, p4 ); - } - } - return this; - } + /** + * Interpolates the new LightMap values for this Vertex using the others as a reference. + * + * @param interpHelper The InterpHelper to use. + * @param others The other Vertices to use as a template. + * @return The same Vertex. + */ + public Vertex interpLightMapFrom(InterpHelper interpHelper, Vertex[] others) { + for (int e = 0; e < 2; e++) { + float p1 = others[0].lightmap[e]; + float p2 = others[1].lightmap[e]; + float p3 = others[2].lightmap[e]; + float p4 = others[3].lightmap[e]; + if (p1 != p2 || p2 != p3 || p3 != p4) { + this.lightmap[e] = interpHelper.interpolate(p1, p2, p3, p4); + } + } + return this; + } - /** - * Copies this Vertex to a new one. - * - * @return The new Vertex. - */ - public Vertex copy() - { - return new Vertex( this ); - } + /** + * Copies this Vertex to a new one. + * + * @return The new Vertex. + */ + public Vertex copy() { + return new Vertex(this); + } - /** - * Resets the Vertex to a new format. Expands the raw array if needed. - * - * @param format The format to reset to. - */ - public void reset( CachedFormat format ) - { - // If the format is different and our raw array is smaller, then expand it. - if( !this.format.equals( format ) && format.elementCount > this.raw.length ) - { - this.raw = new float[format.elementCount][4]; - } - this.format = format; + /** + * Resets the Vertex to a new format. Expands the raw array if needed. + * + * @param format The format to reset to. + */ + public void reset(CachedFormat format) { + // If the format is different and our raw array is smaller, then expand it. + if (!this.format.equals(format) && format.elementCount > this.raw.length) { + this.raw = new float[format.elementCount][4]; + } + this.format = format; - this.vec = null; - this.normal = null; - this.color = null; - this.uv = null; - this.lightmap = null; + this.vec = null; + this.normal = null; + this.color = null; + this.uv = null; + this.lightmap = null; - // for (float[] f : raw) { - // Arrays.fill(f, 0F); - // } + // for (float[] f : raw) { + // Arrays.fill(f, 0F); + // } - this.preProcess(); - } - } + this.preProcess(); + } + } } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/BakedPipeline.java b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/BakedPipeline.java index 735373e99..32b97d52c 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/BakedPipeline.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/BakedPipeline.java @@ -19,21 +19,20 @@ package appeng.thirdparty.codechicken.lib.model.pipeline; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.Map; -import java.util.function.Consumer; -import java.util.stream.Collectors; - +import appeng.thirdparty.codechicken.lib.model.CachedFormat; +import appeng.thirdparty.codechicken.lib.model.ISmartVertexConsumer; +import appeng.thirdparty.codechicken.lib.model.Quad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.EnumFacing; import net.minecraftforge.client.model.pipeline.IVertexConsumer; import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad; -import appeng.thirdparty.codechicken.lib.model.CachedFormat; -import appeng.thirdparty.codechicken.lib.model.ISmartVertexConsumer; -import appeng.thirdparty.codechicken.lib.model.Quad; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.Map; +import java.util.function.Consumer; +import java.util.stream.Collectors; /** @@ -42,19 +41,19 @@ import appeng.thirdparty.codechicken.lib.model.Quad; * the Pipeline has Elements, each element has a name, state and a transformer, * you can enable and disable elements easily, you can also grab the underlying * transformer for the element if you need to set its state before rendering. - * + *

* The BakedPipeline is final once created, you cannot add or remove elements, * you should not need to add or remove them runtime, enable and disable exist. - * + *

* You must use the Builder class to construct a BakedPipeline, see {@link #builder} - * + *

* Transformers run on a mutable state inside each transformer, allowing for easy reuse. * It is recommended to store your pipeline inside a ThreadLocal because 'minecraft'. - * + *

* Each Transformer should be smart enough to expand itself for each newly sized VertexFormat it comes across, * meaning that the internal states for the transformers can be safely shared across VertexFormats, this reduces * array creations, and generally makes the system as efficient as it is. - * + *

* To use the system: * Grab any elements you need to set state data on first, using {@link #getElement(String, Class)} * transformers should NOT clear their state on pipeline Reset's so set any global data on elements now. @@ -70,367 +69,318 @@ import appeng.thirdparty.codechicken.lib.model.Quad; * * @author covers1624 */ -public class BakedPipeline implements ISmartVertexConsumer -{ +public class BakedPipeline implements ISmartVertexConsumer { - private PipelineElement[] elements; - private Map nameLookup; - private IPipelineConsumer first; + private final PipelineElement[] elements; + private final Map nameLookup; + private IPipelineConsumer first; - private Quad unpacker = new Quad(); + private final Quad unpacker = new Quad(); - private BakedPipeline( PipelineElement[] elements ) - { - this.elements = elements; - this.nameLookup = Arrays.stream( elements ).collect( Collectors.toMap( e -> e.name, e -> e ) ); - } + private BakedPipeline(PipelineElement[] elements) { + this.elements = elements; + this.nameLookup = Arrays.stream(elements).collect(Collectors.toMap(e -> e.name, e -> e)); + } - /** - * Used to create a BakedPipeline. - * - * @return The builder. - */ - public static Builder builder() - { - return new Builder(); - } + /** + * Used to create a BakedPipeline. + * + * @return The builder. + */ + public static Builder builder() { + return new Builder(); + } - /** - * Used to reset the pipeline for the next quad. - * MUST be called between quads. - * - * @param format The format. - */ - public void reset( VertexFormat format ) - { - this.reset( CachedFormat.lookup( format ) ); - } + /** + * Used to reset the pipeline for the next quad. + * MUST be called between quads. + * + * @param format The format. + */ + public void reset(VertexFormat format) { + this.reset(CachedFormat.lookup(format)); + } - /** - * Used to reset the pipeline for the next quad. - * MUST be called between quads. - * - * @param format The format. - */ - public void reset( CachedFormat format ) - { - this.unpacker.reset( format ); - for( PipelineElement element : this.elements ) - { - element.reset( format ); - } - this.first = null; - } + /** + * Used to reset the pipeline for the next quad. + * MUST be called between quads. + * + * @param format The format. + */ + public void reset(CachedFormat format) { + this.unpacker.reset(format); + for (PipelineElement element : this.elements) { + element.reset(format); + } + this.first = null; + } - /** - * Get an element from the pipeline. - * - * @param name The name of the element. - * @param clazz The Class of the element, used to safe cast. - * - * @return The element. - */ - public T getElement( String name, Class clazz ) - { - PipelineElement element = this.nameLookup.get( name ); - if( element != null ) - { - if( !clazz.isAssignableFrom( element.consumer.getClass() ) ) - { - throw new IllegalArgumentException( "Element with name " + name + " is not assignable from reference class." ); - } - return clazz.cast( element.consumer ); - } - throw new IllegalArgumentException( "Element with name " + name + " does not exist." ); - } + /** + * Get an element from the pipeline. + * + * @param name The name of the element. + * @param clazz The Class of the element, used to safe cast. + * @return The element. + */ + public T getElement(String name, Class clazz) { + PipelineElement element = this.nameLookup.get(name); + if (element != null) { + if (!clazz.isAssignableFrom(element.consumer.getClass())) { + throw new IllegalArgumentException("Element with name " + name + " is not assignable from reference class."); + } + return clazz.cast(element.consumer); + } + throw new IllegalArgumentException("Element with name " + name + " does not exist."); + } - /** - * Used to enable an element on the pipeline with the specified name. - * - * @param name The elements name. - */ - public void enableElement( String name ) - { - this.setElementState( name, true ); - } + /** + * Used to enable an element on the pipeline with the specified name. + * + * @param name The elements name. + */ + public void enableElement(String name) { + this.setElementState(name, true); + } - /** - * Used to disable an element on the pipeline with the specified name. - * - * @param name The elements name. - */ - public void disableElement( String name ) - { - this.setElementState( name, false ); - } + /** + * Used to disable an element on the pipeline with the specified name. + * + * @param name The elements name. + */ + public void disableElement(String name) { + this.setElementState(name, false); + } - /** - * Used to set the state of an element on the pipeline. - * - * @param name The name of the element. - * @param enabled The state to set it to. - */ - public void setElementState( String name, boolean enabled ) - { - PipelineElement element = this.nameLookup.get( name ); - if( element != null ) - { - element.isEnabled = enabled; - return; - } - throw new IllegalArgumentException( "Element with name " + name + " does not exist." ); - } + /** + * Used to set the state of an element on the pipeline. + * + * @param name The name of the element. + * @param enabled The state to set it to. + */ + public void setElementState(String name, boolean enabled) { + PipelineElement element = this.nameLookup.get(name); + if (element != null) { + element.isEnabled = enabled; + return; + } + throw new IllegalArgumentException("Element with name " + name + " does not exist."); + } - /** - * Call when you are ready to use the pipeline. - * This builds the internal state of the Elements getting things ready to transform. - * - * @param collector The IVertexConsumer that should collect the transformed quad. - */ - public void prepare( IVertexConsumer collector ) - { - IPipelineConsumer next = null; - for( PipelineElement element : this.elements ) - { - if( element.isEnabled ) - { - if( this.first == null ) - { - this.first = element.consumer; - } - else - { - next.setParent( element.consumer ); - } - next = element.consumer; - } - } - next.setParent( collector ); - } + /** + * Call when you are ready to use the pipeline. + * This builds the internal state of the Elements getting things ready to transform. + * + * @param collector The IVertexConsumer that should collect the transformed quad. + */ + public void prepare(IVertexConsumer collector) { + IPipelineConsumer next = null; + for (PipelineElement element : this.elements) { + if (element.isEnabled) { + if (this.first == null) { + this.first = element.consumer; + } else { + next.setParent(element.consumer); + } + next = element.consumer; + } + } + next.setParent(collector); + } - @Override - public VertexFormat getVertexFormat() - { - this.check(); - return this.first.getVertexFormat(); - } + @Override + public VertexFormat getVertexFormat() { + this.check(); + return this.first.getVertexFormat(); + } - @Override - public void setQuadTint( int tint ) - { - this.check(); - this.unpacker.setQuadTint( tint ); - } + @Override + public void setQuadTint(int tint) { + this.check(); + this.unpacker.setQuadTint(tint); + } - @Override - public void setQuadOrientation( EnumFacing orientation ) - { - this.check(); - this.unpacker.setQuadOrientation( orientation ); - } + @Override + public void setQuadOrientation(EnumFacing orientation) { + this.check(); + this.unpacker.setQuadOrientation(orientation); + } - @Override - public void setApplyDiffuseLighting( boolean diffuse ) - { - this.check(); - this.unpacker.setApplyDiffuseLighting( diffuse ); - } + @Override + public void setApplyDiffuseLighting(boolean diffuse) { + this.check(); + this.unpacker.setApplyDiffuseLighting(diffuse); + } - @Override - public void setTexture( TextureAtlasSprite texture ) - { - this.check(); - this.unpacker.setTexture( texture ); - } + @Override + public void setTexture(TextureAtlasSprite texture) { + this.check(); + this.unpacker.setTexture(texture); + } - @Override - public void put( int element, float... data ) - { - this.check(); - this.unpacker.put( element, data ); - if( this.unpacker.full ) - { - this.onFull(); - } - } + @Override + public void put(int element, float... data) { + this.check(); + this.unpacker.put(element, data); + if (this.unpacker.full) { + this.onFull(); + } + } - @Override - public void put( Quad quad ) - { - this.check(); - this.unpacker.put( quad ); - } + @Override + public void put(Quad quad) { + this.check(); + this.unpacker.put(quad); + } - private void check() - { - if( this.first == null ) - { - throw new IllegalStateException( "Pipeline used before prepare was called." ); - } - } + private void check() { + if (this.first == null) { + throw new IllegalStateException("Pipeline used before prepare was called."); + } + } - private void onFull() - { - this.first.setInputQuad( this.unpacker ); - this.first.put( this.unpacker ); - } + private void onFull() { + this.first.setInputQuad(this.unpacker); + this.first.put(this.unpacker); + } - /** - * Internal class, used to hold a PipelineElement's state. - */ - public static class PipelineElement - { + /** + * Internal class, used to hold a PipelineElement's state. + */ + public static class PipelineElement { - public String name; - public boolean defaultState; - public T consumer; - public boolean isEnabled; + public String name; + public boolean defaultState; + public T consumer; + public boolean isEnabled; - public void reset( CachedFormat format ) - { - this.isEnabled = this.defaultState; - this.consumer.setParent( null ); - this.consumer.reset( format ); - } - } + public void reset(CachedFormat format) { + this.isEnabled = this.defaultState; + this.consumer.setParent(null); + this.consumer.reset(format); + } + } - /** - * The builder associated with the BakedPipeline. - * You must create a BakedPipeline with this, - * once created a pipeline cannot be modified, - * modifying should not be needed as you can enable - * and disable elements with ease. - */ - public static class Builder - { + /** + * The builder associated with the BakedPipeline. + * You must create a BakedPipeline with this, + * once created a pipeline cannot be modified, + * modifying should not be needed as you can enable + * and disable elements with ease. + */ + public static class Builder { - private LinkedList elements = new LinkedList<>(); + private final LinkedList elements = new LinkedList<>(); - /** - * Inserts an element to the front of the list, Useful if you have a more complex system - * and each system need to be independent from each other, but this element must be first. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * - * @return The same builder. - */ - public Builder addFirst( String name, IPipelineElementFactory factory ) - { - return this.addFirst( name, factory, true ); - } + /** + * Inserts an element to the front of the list, Useful if you have a more complex system + * and each system need to be independent from each other, but this element must be first. + * + * @param name The name to identify this element, used as an identifier when setting state, and retrieving the + * element. + * @param factory The factory used to create the Transformer. + * @return The same builder. + */ + public Builder addFirst(String name, IPipelineElementFactory factory) { + return this.addFirst(name, factory, true); + } - /** - * Inserts an element to the front of the list, Useful if you have a more complex system - * and each system need to be independent from each other, but this element must be first. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @param defaultState The default state for this element. - * - * @return The same builder. - */ - public Builder addFirst( String name, IPipelineElementFactory factory, boolean defaultState ) - { - return this.addFirst( name, factory, defaultState, e -> - { - } ); - } + /** + * Inserts an element to the front of the list, Useful if you have a more complex system + * and each system need to be independent from each other, but this element must be first. + * + * @param name The name to identify this element, used as an identifier when setting state, and retrieving the + * element. + * @param factory The factory used to create the Transformer. + * @param defaultState The default state for this element. + * @return The same builder. + */ + public Builder addFirst(String name, IPipelineElementFactory factory, boolean defaultState) { + return this.addFirst(name, factory, defaultState, e -> + { + }); + } - /** - * Inserts an element to the front of the list, Useful if you have a more complex system - * and each system need to be independent from each other, but this element must be first. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @param defaultState The default state for this element. - * @param defaultsSetter A callback used to set any defaults on the transformer. - * - * @return The same builder. - */ - public Builder addFirst( String name, IPipelineElementFactory factory, boolean defaultState, Consumer defaultsSetter ) - { - PipelineElement element = this.makeElement( name, factory, defaultState ); - defaultsSetter.accept( element.consumer ); - this.elements.addFirst( element ); - return this; - } + /** + * Inserts an element to the front of the list, Useful if you have a more complex system + * and each system need to be independent from each other, but this element must be first. + * + * @param name The name to identify this element, used as an identifier when setting state, and retrieving the + * element. + * @param factory The factory used to create the Transformer. + * @param defaultState The default state for this element. + * @param defaultsSetter A callback used to set any defaults on the transformer. + * @return The same builder. + */ + public Builder addFirst(String name, IPipelineElementFactory factory, boolean defaultState, Consumer defaultsSetter) { + PipelineElement element = this.makeElement(name, factory, defaultState); + defaultsSetter.accept(element.consumer); + this.elements.addFirst(element); + return this; + } - /** - * Adds an element at the end of the transform list, Suitable for 99% of cases. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * - * @return The same builder. - */ - public Builder addElement( String name, IPipelineElementFactory factory ) - { - return this.addElement( name, factory, true ); - } + /** + * Adds an element at the end of the transform list, Suitable for 99% of cases. + * + * @param name The name to identify this element, used as an identifier when setting state, and retrieving the + * element. + * @param factory The factory used to create the Transformer. + * @return The same builder. + */ + public Builder addElement(String name, IPipelineElementFactory factory) { + return this.addElement(name, factory, true); + } - /** - * Adds an element at the end of the transform list, Suitable for 99% of cases. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @param defaultState The default state for this element. - * - * @return The same builder. - */ - public Builder addElement( String name, IPipelineElementFactory factory, boolean defaultState ) - { - return this.addElement( name, factory, defaultState, e -> - { - } ); - } + /** + * Adds an element at the end of the transform list, Suitable for 99% of cases. + * + * @param name The name to identify this element, used as an identifier when setting state, and retrieving the + * element. + * @param factory The factory used to create the Transformer. + * @param defaultState The default state for this element. + * @return The same builder. + */ + public Builder addElement(String name, IPipelineElementFactory factory, boolean defaultState) { + return this.addElement(name, factory, defaultState, e -> + { + }); + } - /** - * Adds an element at the end of the transform list, Suitable for 99% of cases. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @param defaultState The default state for this element. - * @param defaultsSetter A callback used to set any defaults on the transformer. - * - * @return The same builder. - */ - public Builder addElement( String name, IPipelineElementFactory factory, boolean defaultState, Consumer defaultsSetter ) - { - PipelineElement element = this.makeElement( name, factory, defaultState ); - defaultsSetter.accept( element.consumer ); - this.elements.add( element ); - return this; - } + /** + * Adds an element at the end of the transform list, Suitable for 99% of cases. + * + * @param name The name to identify this element, used as an identifier when setting state, and retrieving the + * element. + * @param factory The factory used to create the Transformer. + * @param defaultState The default state for this element. + * @param defaultsSetter A callback used to set any defaults on the transformer. + * @return The same builder. + */ + public Builder addElement(String name, IPipelineElementFactory factory, boolean defaultState, Consumer defaultsSetter) { + PipelineElement element = this.makeElement(name, factory, defaultState); + defaultsSetter.accept(element.consumer); + this.elements.add(element); + return this; + } - // Internal method, used to construct the PipelineElement class. - private PipelineElement makeElement( String name, IPipelineElementFactory factory, boolean defaultState ) - { - if( this.elements.stream().anyMatch( p -> p.name.equals( name ) ) ) - { - throw new IllegalArgumentException( "Unable to add element with duplicate name: " + name ); - } - PipelineElement element = new PipelineElement<>(); - element.name = name; - element.consumer = factory.create(); - element.defaultState = defaultState; - return element; - } + // Internal method, used to construct the PipelineElement class. + private PipelineElement makeElement(String name, IPipelineElementFactory factory, boolean defaultState) { + if (this.elements.stream().anyMatch(p -> p.name.equals(name))) { + throw new IllegalArgumentException("Unable to add element with duplicate name: " + name); + } + PipelineElement element = new PipelineElement<>(); + element.name = name; + element.consumer = factory.create(); + element.defaultState = defaultState; + return element; + } - /** - * Call this once you are finished to build your BakedPipeline! - * - * @return The new Pipeline. - */ - public BakedPipeline build() - { - return new BakedPipeline( this.elements.toArray( new PipelineElement[0] ) ); - } - } + /** + * Call this once you are finished to build your BakedPipeline! + * + * @return The new Pipeline. + */ + public BakedPipeline build() { + return new BakedPipeline(this.elements.toArray(new PipelineElement[0])); + } + } } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/IPipelineConsumer.java b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/IPipelineConsumer.java index 1eca87fa8..e1633a0f3 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/IPipelineConsumer.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/IPipelineConsumer.java @@ -19,12 +19,11 @@ package appeng.thirdparty.codechicken.lib.model.pipeline; -import net.minecraftforge.client.model.pipeline.IVertexConsumer; - import appeng.thirdparty.codechicken.lib.model.CachedFormat; import appeng.thirdparty.codechicken.lib.model.ISmartVertexConsumer; import appeng.thirdparty.codechicken.lib.model.Quad; import appeng.thirdparty.codechicken.lib.model.pipeline.transformers.QuadReInterpolator; +import net.minecraftforge.client.model.pipeline.IVertexConsumer; /** @@ -32,33 +31,32 @@ import appeng.thirdparty.codechicken.lib.model.pipeline.transformers.QuadReInter * * @author covers1624 */ -public interface IPipelineConsumer extends ISmartVertexConsumer -{ +public interface IPipelineConsumer extends ISmartVertexConsumer { - /** - * The quad at the start of the transformation. - * This is useful for obtaining the vertex data before any transformations have been applied, - * such as interpolation, See {@link QuadReInterpolator}. - * When overriding this make sure you call setInputQuad on your parent consumer too. - * - * @param quad The quad. - */ - void setInputQuad( Quad quad ); + /** + * The quad at the start of the transformation. + * This is useful for obtaining the vertex data before any transformations have been applied, + * such as interpolation, See {@link QuadReInterpolator}. + * When overriding this make sure you call setInputQuad on your parent consumer too. + * + * @param quad The quad. + */ + void setInputQuad(Quad quad); - /** - * Resets the Consumer to the new format. - * This should resize any internal arrays if needed, ready for the new vertex data. - * - * @param format The format to reset to. - */ - void reset( CachedFormat format ); + /** + * Resets the Consumer to the new format. + * This should resize any internal arrays if needed, ready for the new vertex data. + * + * @param format The format to reset to. + */ + void reset(CachedFormat format); - /** - * Sets the parent consumer. - * This consumer may choose to not pipe any data, - * that's fine, but if it does, it MUST pipe the data to the one provided here. - * - * @param parent The parent. - */ - void setParent( IVertexConsumer parent ); + /** + * Sets the parent consumer. + * This consumer may choose to not pipe any data, + * that's fine, but if it does, it MUST pipe the data to the one provided here. + * + * @param parent The parent. + */ + void setParent(IVertexConsumer parent); } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/IPipelineElementFactory.java b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/IPipelineElementFactory.java index d2fec2541..c040dd54a 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/IPipelineElementFactory.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/IPipelineElementFactory.java @@ -23,8 +23,7 @@ package appeng.thirdparty.codechicken.lib.model.pipeline; * @author covers1624 */ @FunctionalInterface -public interface IPipelineElementFactory -{ +public interface IPipelineElementFactory { - T create(); + T create(); } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/QuadTransformer.java b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/QuadTransformer.java index 4749481c2..c76496d8d 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/QuadTransformer.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/QuadTransformer.java @@ -19,16 +19,15 @@ package appeng.thirdparty.codechicken.lib.model.pipeline; -import javax.annotation.OverridingMethodsMustInvokeSuper; - +import appeng.thirdparty.codechicken.lib.model.CachedFormat; +import appeng.thirdparty.codechicken.lib.model.ISmartVertexConsumer; +import appeng.thirdparty.codechicken.lib.model.Quad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.EnumFacing; import net.minecraftforge.client.model.pipeline.IVertexConsumer; -import appeng.thirdparty.codechicken.lib.model.CachedFormat; -import appeng.thirdparty.codechicken.lib.model.ISmartVertexConsumer; -import appeng.thirdparty.codechicken.lib.model.Quad; +import javax.annotation.OverridingMethodsMustInvokeSuper; /** @@ -38,138 +37,115 @@ import appeng.thirdparty.codechicken.lib.model.Quad; * * @author covers1624 */ -public abstract class QuadTransformer implements IVertexConsumer, ISmartVertexConsumer, IPipelineConsumer -{ +public abstract class QuadTransformer implements IVertexConsumer, ISmartVertexConsumer, IPipelineConsumer { - protected CachedFormat format; - protected IVertexConsumer consumer; - protected Quad quad; + protected CachedFormat format; + protected IVertexConsumer consumer; + protected Quad quad; - /** - * Used for the BakedPipeline. - */ - protected QuadTransformer() - { - this.quad = new Quad(); - } + /** + * Used for the BakedPipeline. + */ + protected QuadTransformer() { + this.quad = new Quad(); + } - public QuadTransformer( IVertexConsumer consumer ) - { - this( consumer.getVertexFormat(), consumer ); - } + public QuadTransformer(IVertexConsumer consumer) { + this(consumer.getVertexFormat(), consumer); + } - public QuadTransformer( VertexFormat format, IVertexConsumer consumer ) - { - this( CachedFormat.lookup( format ), consumer ); - } + public QuadTransformer(VertexFormat format, IVertexConsumer consumer) { + this(CachedFormat.lookup(format), consumer); + } - public QuadTransformer( CachedFormat format, IVertexConsumer consumer ) - { - this.format = format; - this.consumer = consumer; - this.quad = new Quad( format ); - } + public QuadTransformer(CachedFormat format, IVertexConsumer consumer) { + this.format = format; + this.consumer = consumer; + this.quad = new Quad(format); + } - @Override - @OverridingMethodsMustInvokeSuper - public void reset( CachedFormat format ) - { - this.format = format; - this.quad.reset( format ); - } + @Override + @OverridingMethodsMustInvokeSuper + public void reset(CachedFormat format) { + this.format = format; + this.quad.reset(format); + } - @Override - public void setParent( IVertexConsumer parent ) - { - this.consumer = parent; - } + @Override + public void setParent(IVertexConsumer parent) { + this.consumer = parent; + } - @Override - @OverridingMethodsMustInvokeSuper - public void setInputQuad( Quad quad ) - { - if( this.consumer instanceof IPipelineConsumer ) - { - ( (IPipelineConsumer) this.consumer ).setInputQuad( quad ); - } - } + @Override + @OverridingMethodsMustInvokeSuper + public void setInputQuad(Quad quad) { + if (this.consumer instanceof IPipelineConsumer) { + ((IPipelineConsumer) this.consumer).setInputQuad(quad); + } + } - // @formatter:off - @Override - public VertexFormat getVertexFormat() - { - return this.format.format; - } + // @formatter:off + @Override + public VertexFormat getVertexFormat() { + return this.format.format; + } - @Override - public void setQuadTint( int tint ) - { - this.quad.setQuadTint( tint ); - } + @Override + public void setQuadTint(int tint) { + this.quad.setQuadTint(tint); + } - @Override - public void setQuadOrientation( EnumFacing orientation ) - { - this.quad.setQuadOrientation( orientation ); - } + @Override + public void setQuadOrientation(EnumFacing orientation) { + this.quad.setQuadOrientation(orientation); + } - @Override - public void setApplyDiffuseLighting( boolean diffuse ) - { - this.quad.setApplyDiffuseLighting( diffuse ); - } + @Override + public void setApplyDiffuseLighting(boolean diffuse) { + this.quad.setApplyDiffuseLighting(diffuse); + } - @Override - public void setTexture( TextureAtlasSprite texture ) - { - this.quad.setTexture( texture ); - } - // @formatter:on + @Override + public void setTexture(TextureAtlasSprite texture) { + this.quad.setTexture(texture); + } + // @formatter:on - @Override - public void put( int element, float... data ) - { - this.quad.put( element, data ); - if( this.quad.full ) - { - this.onFull(); - } - } + @Override + public void put(int element, float... data) { + this.quad.put(element, data); + if (this.quad.full) { + this.onFull(); + } + } - @Override - public void put( Quad quad ) - { - this.quad.put( quad ); - this.onFull(); - } + @Override + public void put(Quad quad) { + this.quad.put(quad); + this.onFull(); + } - /** - * Called to transform the vertices. - * - * @return If the transformer should pipe the quad. - */ - public abstract boolean transform(); + /** + * Called to transform the vertices. + * + * @return If the transformer should pipe the quad. + */ + public abstract boolean transform(); - public void onFull() - { - if( this.transform() ) - { - this.quad.pipe( this.consumer ); - } - } + public void onFull() { + if (this.transform()) { + this.quad.pipe(this.consumer); + } + } - // Should be small enough. - private final static double EPSILON = 0.00001; + // Should be small enough. + private final static double EPSILON = 0.00001; - public static boolean epsComp( float a, float b ) - { - if( a == b ) - { - return true; - } - else - { - return Math.abs( a - b ) < EPSILON; - } - } + public static boolean epsComp(float a, float b) { + if (a == b) { + return true; + } else { + return Math.abs(a - b) < EPSILON; + } + } } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java index 37bbeb03a..1b5f97c2f 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java @@ -19,11 +19,10 @@ package appeng.thirdparty.codechicken.lib.model.pipeline.transformers; -import net.minecraftforge.client.model.pipeline.IVertexConsumer; - import appeng.thirdparty.codechicken.lib.model.Quad.Vertex; import appeng.thirdparty.codechicken.lib.model.pipeline.IPipelineElementFactory; import appeng.thirdparty.codechicken.lib.model.pipeline.QuadTransformer; +import net.minecraftforge.client.model.pipeline.IVertexConsumer; /** @@ -32,40 +31,33 @@ import appeng.thirdparty.codechicken.lib.model.pipeline.QuadTransformer; * * @author covers1624 */ -public class QuadAlphaOverride extends QuadTransformer -{ +public class QuadAlphaOverride extends QuadTransformer { - public static final IPipelineElementFactory FACTORY = QuadAlphaOverride::new; + public static final IPipelineElementFactory FACTORY = QuadAlphaOverride::new; - private float alphaOverride; + private float alphaOverride; - QuadAlphaOverride() - { - super(); - } + QuadAlphaOverride() { + super(); + } - public QuadAlphaOverride( IVertexConsumer consumer, float alphaOverride ) - { - super( consumer ); - this.alphaOverride = alphaOverride; - } + public QuadAlphaOverride(IVertexConsumer consumer, float alphaOverride) { + super(consumer); + this.alphaOverride = alphaOverride; + } - public QuadAlphaOverride setAlphaOverride( float alphaOverride ) - { - this.alphaOverride = alphaOverride; - return this; - } + public QuadAlphaOverride setAlphaOverride(float alphaOverride) { + this.alphaOverride = alphaOverride; + return this; + } - @Override - public boolean transform() - { - if( this.format.hasColor ) - { - for( Vertex v : this.quad.vertices ) - { - v.color[3] = this.alphaOverride; - } - } - return true; - } + @Override + public boolean transform() { + if (this.format.hasColor) { + for (Vertex v : this.quad.vertices) { + v.color[3] = this.alphaOverride; + } + } + return true; + } } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadClamper.java b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadClamper.java index a460fa4fa..f14013192 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadClamper.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadClamper.java @@ -19,12 +19,11 @@ package appeng.thirdparty.codechicken.lib.model.pipeline.transformers; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraftforge.client.model.pipeline.IVertexConsumer; - import appeng.thirdparty.codechicken.lib.model.Quad.Vertex; import appeng.thirdparty.codechicken.lib.model.pipeline.IPipelineElementFactory; import appeng.thirdparty.codechicken.lib.model.pipeline.QuadTransformer; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraftforge.client.model.pipeline.IVertexConsumer; /** @@ -33,51 +32,46 @@ import appeng.thirdparty.codechicken.lib.model.pipeline.QuadTransformer; * * @author covers1624 */ -public class QuadClamper extends QuadTransformer -{ +public class QuadClamper extends QuadTransformer { - public static IPipelineElementFactory FACTORY = QuadClamper::new; + public static IPipelineElementFactory FACTORY = QuadClamper::new; - private AxisAlignedBB clampBounds; + private AxisAlignedBB clampBounds; - QuadClamper() - { - super(); - } + QuadClamper() { + super(); + } - public QuadClamper( IVertexConsumer parent, AxisAlignedBB bounds ) - { - super( parent ); - this.clampBounds = bounds; - } + public QuadClamper(IVertexConsumer parent, AxisAlignedBB bounds) { + super(parent); + this.clampBounds = bounds; + } - public void setClampBounds( AxisAlignedBB bounds ) - { - this.clampBounds = bounds; - } + public void setClampBounds(AxisAlignedBB bounds) { + this.clampBounds = bounds; + } - @Override - public boolean transform() - { - int s = this.quad.orientation.ordinal() >> 1; + @Override + public boolean transform() { + int s = this.quad.orientation.ordinal() >> 1; - this.quad.clamp( this.clampBounds ); + this.quad.clamp(this.clampBounds); - // Check if the quad would be invisible and cull it. - Vertex[] vertices = this.quad.vertices; - float x1 = vertices[0].dx( s ); - float x2 = vertices[1].dx( s ); - float x3 = vertices[2].dx( s ); - float x4 = vertices[3].dx( s ); + // Check if the quad would be invisible and cull it. + Vertex[] vertices = this.quad.vertices; + float x1 = vertices[0].dx(s); + float x2 = vertices[1].dx(s); + float x3 = vertices[2].dx(s); + float x4 = vertices[3].dx(s); - float y1 = vertices[0].dy( s ); - float y2 = vertices[1].dy( s ); - float y3 = vertices[2].dy( s ); - float y4 = vertices[3].dy( s ); + float y1 = vertices[0].dy(s); + float y2 = vertices[1].dy(s); + float y3 = vertices[2].dy(s); + float y4 = vertices[3].dy(s); - // These comparisons are safe as we are comparing clamped values. - boolean flag1 = x1 == x2 && x2 == x3 && x3 == x4; - boolean flag2 = y1 == y2 && y2 == y3 && y3 == y4; - return !flag1 && !flag2; - } + // These comparisons are safe as we are comparing clamped values. + boolean flag1 = x1 == x2 && x2 == x3 && x3 == x4; + boolean flag2 = y1 == y2 && y2 == y3 && y3 == y4; + return !flag1 && !flag2; + } } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java index 523cdd75e..2b0f1de65 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java @@ -19,17 +19,16 @@ package appeng.thirdparty.codechicken.lib.model.pipeline.transformers; -import static net.minecraft.util.EnumFacing.AxisDirection.NEGATIVE; -import static net.minecraft.util.EnumFacing.AxisDirection.POSITIVE; - +import appeng.thirdparty.codechicken.lib.model.Quad.Vertex; +import appeng.thirdparty.codechicken.lib.model.pipeline.IPipelineElementFactory; +import appeng.thirdparty.codechicken.lib.model.pipeline.QuadTransformer; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing.AxisDirection; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.Vec3i; -import appeng.thirdparty.codechicken.lib.model.Quad.Vertex; -import appeng.thirdparty.codechicken.lib.model.pipeline.IPipelineElementFactory; -import appeng.thirdparty.codechicken.lib.model.pipeline.QuadTransformer; +import static net.minecraft.util.EnumFacing.AxisDirection.NEGATIVE; +import static net.minecraft.util.EnumFacing.AxisDirection.POSITIVE; /** @@ -44,176 +43,156 @@ import appeng.thirdparty.codechicken.lib.model.pipeline.QuadTransformer; * * @author covers1624 */ -public class QuadCornerKicker extends QuadTransformer -{ +public class QuadCornerKicker extends QuadTransformer { - // The factory for pipeline creation. - public static final IPipelineElementFactory FACTORY = QuadCornerKicker::new; + // The factory for pipeline creation. + public static final IPipelineElementFactory FACTORY = QuadCornerKicker::new; - // Simple horizonal lookups. - public static int[][] horizonals = new int[][] { - // Around Y axis, NSWE. - { 2, 3, 4, 5 }, // - { 2, 3, 4, 5 }, // + // Simple horizonal lookups. + public static int[][] horizonals = new int[][]{ + // Around Y axis, NSWE. + {2, 3, 4, 5}, // + {2, 3, 4, 5}, // - // Around Z axis, DUWE. - { 0, 1, 4, 5 }, // - { 0, 1, 4, 5 }, // + // Around Z axis, DUWE. + {0, 1, 4, 5}, // + {0, 1, 4, 5}, // - // Around X axis, DUNS. - { 0, 1, 2, 3 }, // - { 0, 1, 2, 3 } - }; + // Around X axis, DUNS. + {0, 1, 2, 3}, // + {0, 1, 2, 3} + }; - private int mySide; - private int facadeMask; - private AxisAlignedBB box; - private double thickness; + private int mySide; + private int facadeMask; + private AxisAlignedBB box; + private double thickness; - QuadCornerKicker() - { - super(); - } + QuadCornerKicker() { + super(); + } - /** - * Set's the side this Facade / Cover is attached to. - * - * @param side The side. - */ - public void setSide( int side ) - { - this.mySide = side; - } + /** + * Set's the side this Facade / Cover is attached to. + * + * @param side The side. + */ + public void setSide(int side) { + this.mySide = side; + } - /** - * Sets the bitmask of Facades / Covers in the blockspace. - * This is as simple as, mask = (1 << side) - * - * @param mask The mask. - */ - public void setFacadeMask( int mask ) - { - this.facadeMask = mask; - } + /** + * Sets the bitmask of Facades / Covers in the blockspace. + * This is as simple as, mask = (1 << side) + * + * @param mask The mask. + */ + public void setFacadeMask(int mask) { + this.facadeMask = mask; + } - /** - * Sets the bounding box of the Facade / Cover, - * this should be the full box, not just a piece - * of the hole's 'ring'. - * - * @param box The BoundingBox. - */ - public void setBox( AxisAlignedBB box ) - { - this.box = box; - } + /** + * Sets the bounding box of the Facade / Cover, + * this should be the full box, not just a piece + * of the hole's 'ring'. + * + * @param box The BoundingBox. + */ + public void setBox(AxisAlignedBB box) { + this.box = box; + } - /** - * Sets the amount to kick the vertex in by, - * this is your facades thickness. - * - * @param thickness The thickness. - */ - public void setThickness( double thickness ) - { - this.thickness = thickness; - } + /** + * Sets the amount to kick the vertex in by, + * this is your facades thickness. + * + * @param thickness The thickness. + */ + public void setThickness(double thickness) { + this.thickness = thickness; + } - @Override - public boolean transform() - { + @Override + public boolean transform() { - int side = this.quad.orientation.ordinal(); - if( side != this.mySide && side != ( this.mySide ^ 1 ) ) - { - for( int hoz : horizonals[this.mySide] ) - { - if( side != hoz && side != ( hoz ^ 1 ) ) - { - if( ( this.facadeMask & ( 1 << hoz ) ) != 0 ) - { - Corner corner = Corner.fromSides( this.mySide ^ 1, side, hoz ); - for( Vertex vertex : this.quad.vertices ) - { - float x = vertex.vec[0]; - float y = vertex.vec[1]; - float z = vertex.vec[2]; - if( epsComp( x, corner.pX( this.box ) ) && epsComp( y, corner.pY( this.box ) ) && epsComp( z, corner.pZ( this.box ) ) ) - { - Vec3i vec = EnumFacing.VALUES[hoz].getDirectionVec(); - x -= vec.getX() * this.thickness; - y -= vec.getY() * this.thickness; - z -= vec.getZ() * this.thickness; - vertex.vec[0] = x; - vertex.vec[1] = y; - vertex.vec[2] = z; - } - } - } - } - } - } + int side = this.quad.orientation.ordinal(); + if (side != this.mySide && side != (this.mySide ^ 1)) { + for (int hoz : horizonals[this.mySide]) { + if (side != hoz && side != (hoz ^ 1)) { + if ((this.facadeMask & (1 << hoz)) != 0) { + Corner corner = Corner.fromSides(this.mySide ^ 1, side, hoz); + for (Vertex vertex : this.quad.vertices) { + float x = vertex.vec[0]; + float y = vertex.vec[1]; + float z = vertex.vec[2]; + if (epsComp(x, corner.pX(this.box)) && epsComp(y, corner.pY(this.box)) && epsComp(z, corner.pZ(this.box))) { + Vec3i vec = EnumFacing.VALUES[hoz].getDirectionVec(); + x -= vec.getX() * this.thickness; + y -= vec.getY() * this.thickness; + z -= vec.getZ() * this.thickness; + vertex.vec[0] = x; + vertex.vec[1] = y; + vertex.vec[2] = z; + } + } + } + } + } + } - return true; - } + return true; + } - public enum Corner - { + public enum Corner { - MIN_X_MIN_Y_MIN_Z( NEGATIVE, NEGATIVE, NEGATIVE ), - MIN_X_MIN_Y_MAX_Z( NEGATIVE, NEGATIVE, POSITIVE ), - MIN_X_MAX_Y_MIN_Z( NEGATIVE, POSITIVE, NEGATIVE ), - MIN_X_MAX_Y_MAX_Z( NEGATIVE, POSITIVE, POSITIVE ), + MIN_X_MIN_Y_MIN_Z(NEGATIVE, NEGATIVE, NEGATIVE), + MIN_X_MIN_Y_MAX_Z(NEGATIVE, NEGATIVE, POSITIVE), + MIN_X_MAX_Y_MIN_Z(NEGATIVE, POSITIVE, NEGATIVE), + MIN_X_MAX_Y_MAX_Z(NEGATIVE, POSITIVE, POSITIVE), - MAX_X_MIN_Y_MIN_Z( POSITIVE, NEGATIVE, NEGATIVE ), - MAX_X_MIN_Y_MAX_Z( POSITIVE, NEGATIVE, POSITIVE ), - MAX_X_MAX_Y_MIN_Z( POSITIVE, POSITIVE, NEGATIVE ), - MAX_X_MAX_Y_MAX_Z( POSITIVE, POSITIVE, POSITIVE ); + MAX_X_MIN_Y_MIN_Z(POSITIVE, NEGATIVE, NEGATIVE), + MAX_X_MIN_Y_MAX_Z(POSITIVE, NEGATIVE, POSITIVE), + MAX_X_MAX_Y_MIN_Z(POSITIVE, POSITIVE, NEGATIVE), + MAX_X_MAX_Y_MAX_Z(POSITIVE, POSITIVE, POSITIVE); - private AxisDirection xAxis; - private AxisDirection yAxis; - private AxisDirection zAxis; + private final AxisDirection xAxis; + private final AxisDirection yAxis; + private final AxisDirection zAxis; - private static final int[] sideMask = { 0, 2, 0, 1, 0, 4 }; + private static final int[] sideMask = {0, 2, 0, 1, 0, 4}; - Corner( AxisDirection xAxis, AxisDirection yAxis, AxisDirection zAxis ) - { - this.xAxis = xAxis; - this.yAxis = yAxis; - this.zAxis = zAxis; - } + Corner(AxisDirection xAxis, AxisDirection yAxis, AxisDirection zAxis) { + this.xAxis = xAxis; + this.yAxis = yAxis; + this.zAxis = zAxis; + } - /** - * Used to find what corner is at the 3 sides. - * This method assumes you pass in the X axis side, Y axis side, and Z axis side, - * it will NOT complain about an invalid side, you will just get garbage data. - * This method also does not care what order the 3 axes are in. - * - * @param sideA Side one. - * @param sideB Side two. - * @param sideC Side three. - * - * @return The corner at the 3 sides. - */ - public static Corner fromSides( int sideA, int sideB, int sideC ) - { - // <3 Chicken-Bones. - return values()[sideMask[sideA] | sideMask[sideB] | sideMask[sideC]]; - } + /** + * Used to find what corner is at the 3 sides. + * This method assumes you pass in the X axis side, Y axis side, and Z axis side, + * it will NOT complain about an invalid side, you will just get garbage data. + * This method also does not care what order the 3 axes are in. + * + * @param sideA Side one. + * @param sideB Side two. + * @param sideC Side three. + * @return The corner at the 3 sides. + */ + public static Corner fromSides(int sideA, int sideB, int sideC) { + // <3 Chicken-Bones. + return values()[sideMask[sideA] | sideMask[sideB] | sideMask[sideC]]; + } - public float pX( AxisAlignedBB box ) - { - return (float) ( this.xAxis == NEGATIVE ? box.minX : box.maxX ); - } + public float pX(AxisAlignedBB box) { + return (float) (this.xAxis == NEGATIVE ? box.minX : box.maxX); + } - public float pY( AxisAlignedBB box ) - { - return (float) ( this.yAxis == NEGATIVE ? box.minY : box.maxY ); - } + public float pY(AxisAlignedBB box) { + return (float) (this.yAxis == NEGATIVE ? box.minY : box.maxY); + } - public float pZ( AxisAlignedBB box ) - { - return (float) ( this.zAxis == NEGATIVE ? box.minZ : box.maxZ ); - } - } + public float pZ(AxisAlignedBB box) { + return (float) (this.zAxis == NEGATIVE ? box.minZ : box.maxZ); + } + } } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java index e9f52ee22..d9a480d45 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java @@ -19,15 +19,14 @@ package appeng.thirdparty.codechicken.lib.model.pipeline.transformers; -import static net.minecraft.util.EnumFacing.AxisDirection.POSITIVE; - +import appeng.thirdparty.codechicken.lib.model.Quad.Vertex; +import appeng.thirdparty.codechicken.lib.model.pipeline.IPipelineElementFactory; +import appeng.thirdparty.codechicken.lib.model.pipeline.QuadTransformer; import net.minecraft.util.EnumFacing.AxisDirection; import net.minecraft.util.math.AxisAlignedBB; import net.minecraftforge.client.model.pipeline.IVertexConsumer; -import appeng.thirdparty.codechicken.lib.model.Quad.Vertex; -import appeng.thirdparty.codechicken.lib.model.pipeline.IPipelineElementFactory; -import appeng.thirdparty.codechicken.lib.model.pipeline.QuadTransformer; +import static net.minecraft.util.EnumFacing.AxisDirection.POSITIVE; /** @@ -36,93 +35,81 @@ import appeng.thirdparty.codechicken.lib.model.pipeline.QuadTransformer; * * @author covers1624 */ -public class QuadFaceStripper extends QuadTransformer -{ +public class QuadFaceStripper extends QuadTransformer { - public static final IPipelineElementFactory FACTORY = QuadFaceStripper::new; + public static final IPipelineElementFactory FACTORY = QuadFaceStripper::new; - private AxisAlignedBB bounds; - private int mask; + private AxisAlignedBB bounds; + private int mask; - QuadFaceStripper() - { - super(); - } + QuadFaceStripper() { + super(); + } - public QuadFaceStripper( IVertexConsumer parent, AxisAlignedBB bounds, int mask ) - { - super( parent ); - this.bounds = bounds; - this.mask = mask; - } + public QuadFaceStripper(IVertexConsumer parent, AxisAlignedBB bounds, int mask) { + super(parent); + this.bounds = bounds; + this.mask = mask; + } - /** - * The bounds of the faces, - * used as the .. bounds, if all vertices of a quad - * lay on the bounds, it is up for stripping. - * - * @param bounds The bounds. - */ - public void setBounds( AxisAlignedBB bounds ) - { - this.bounds = bounds; - } + /** + * The bounds of the faces, + * used as the .. bounds, if all vertices of a quad + * lay on the bounds, it is up for stripping. + * + * @param bounds The bounds. + */ + public void setBounds(AxisAlignedBB bounds) { + this.bounds = bounds; + } - /** - * The mask to strip edges. - * This is an opt in system, - * the mask is simple 'mask = (1 << side)'. - * - * @param mask The mask. - */ - public void setMask( int mask ) - { - this.mask = mask; - } + /** + * The mask to strip edges. + * This is an opt in system, + * the mask is simple 'mask = (1 << side)'. + * + * @param mask The mask. + */ + public void setMask(int mask) { + this.mask = mask; + } - @Override - public boolean transform() - { - if( this.mask == 0 ) - { - return true;// No mask, nothing changes. - } - // If the bit for this quad is set, then check if we should strip. - if( ( this.mask & ( 1 << this.quad.orientation.ordinal() ) ) != 0 ) - { - AxisDirection dir = this.quad.orientation.getAxisDirection(); - Vertex[] vertices = this.quad.vertices; - switch( this.quad.orientation.getAxis() ) - { - case X: - { - float bound = (float) ( dir == POSITIVE ? this.bounds.maxX : this.bounds.minX ); - float x1 = vertices[0].vec[0]; - float x2 = vertices[1].vec[0]; - float x3 = vertices[2].vec[0]; - float x4 = vertices[3].vec[0]; - return x1 != x2 || x2 != x3 || x3 != x4 || x4 != bound; - } - case Y: - { - float bound = (float) ( dir == POSITIVE ? this.bounds.maxY : this.bounds.minY ); - float y1 = vertices[0].vec[1]; - float y2 = vertices[1].vec[1]; - float y3 = vertices[2].vec[1]; - float y4 = vertices[3].vec[1]; - return y1 != y2 || y2 != y3 || y3 != y4 || y4 != bound; - } - case Z: - { - float bound = (float) ( dir == POSITIVE ? this.bounds.maxZ : this.bounds.minZ ); - float z1 = vertices[0].vec[2]; - float z2 = vertices[1].vec[2]; - float z3 = vertices[2].vec[2]; - float z4 = vertices[3].vec[2]; - return z1 != z2 || z2 != z3 || z3 != z4 || z4 != bound; - } - } - } - return true; - } + @Override + public boolean transform() { + if (this.mask == 0) { + return true;// No mask, nothing changes. + } + // If the bit for this quad is set, then check if we should strip. + if ((this.mask & (1 << this.quad.orientation.ordinal())) != 0) { + AxisDirection dir = this.quad.orientation.getAxisDirection(); + Vertex[] vertices = this.quad.vertices; + switch (this.quad.orientation.getAxis()) { + case X: { + float bound = (float) (dir == POSITIVE ? this.bounds.maxX : this.bounds.minX); + float x1 = vertices[0].vec[0]; + float x2 = vertices[1].vec[0]; + float x3 = vertices[2].vec[0]; + float x4 = vertices[3].vec[0]; + return x1 != x2 || x2 != x3 || x3 != x4 || x4 != bound; + } + case Y: { + float bound = (float) (dir == POSITIVE ? this.bounds.maxY : this.bounds.minY); + float y1 = vertices[0].vec[1]; + float y2 = vertices[1].vec[1]; + float y3 = vertices[2].vec[1]; + float y4 = vertices[3].vec[1]; + return y1 != y2 || y2 != y3 || y3 != y4 || y4 != bound; + } + case Z: { + float bound = (float) (dir == POSITIVE ? this.bounds.maxZ : this.bounds.minZ); + float z1 = vertices[0].vec[2]; + float z2 = vertices[1].vec[2]; + float z3 = vertices[2].vec[2]; + float z4 = vertices[3].vec[2]; + return z1 != z2 || z2 != z3 || z3 != z4 || z4 != bound; + } + } + } + return true; + } } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java index 95e52fe3c..258eb67f0 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java @@ -30,63 +30,53 @@ import appeng.thirdparty.codechicken.lib.model.pipeline.QuadTransformer; /** * This transformer Re-Interpolates the Color, UV's and LightMaps. * Use this after all transformations that translate vertices in the pipeline. - * + *

* This Transformation can only be used in the BakedPipeline. * * @author covers1624 */ -public class QuadReInterpolator extends QuadTransformer -{ +public class QuadReInterpolator extends QuadTransformer { - public static final IPipelineElementFactory FACTORY = QuadReInterpolator::new; + public static final IPipelineElementFactory FACTORY = QuadReInterpolator::new; - private Quad interpCache = new Quad(); - private InterpHelper interpHelper = new InterpHelper(); + private final Quad interpCache = new Quad(); + private final InterpHelper interpHelper = new InterpHelper(); - QuadReInterpolator() - { - super(); - } + QuadReInterpolator() { + super(); + } - @Override - public void reset( CachedFormat format ) - { - super.reset( format ); - this.interpCache.reset( format ); - } + @Override + public void reset(CachedFormat format) { + super.reset(format); + this.interpCache.reset(format); + } - @Override - public void setInputQuad( Quad quad ) - { - super.setInputQuad( quad ); - quad.resetInterp( this.interpHelper, quad.orientation.ordinal() >> 1 ); - } + @Override + public void setInputQuad(Quad quad) { + super.setInputQuad(quad); + quad.resetInterp(this.interpHelper, quad.orientation.ordinal() >> 1); + } - @Override - public boolean transform() - { - int s = this.quad.orientation.ordinal() >> 1; - if( this.format.hasColor || this.format.hasUV || this.format.hasLightMap ) - { - this.interpCache.copyFrom( this.quad ); - this.interpHelper.setup(); - for( Vertex v : this.quad.vertices ) - { - this.interpHelper.locate( v.dx( s ), v.dy( s ) ); - if( this.format.hasColor ) - { - v.interpColorFrom( this.interpHelper, this.interpCache.vertices ); - } - if( this.format.hasUV ) - { - v.interpUVFrom( this.interpHelper, this.interpCache.vertices ); - } - if( this.format.hasLightMap ) - { - v.interpLightMapFrom( this.interpHelper, this.interpCache.vertices ); - } - } - } - return true; - } + @Override + public boolean transform() { + int s = this.quad.orientation.ordinal() >> 1; + if (this.format.hasColor || this.format.hasUV || this.format.hasLightMap) { + this.interpCache.copyFrom(this.quad); + this.interpHelper.setup(); + for (Vertex v : this.quad.vertices) { + this.interpHelper.locate(v.dx(s), v.dy(s)); + if (this.format.hasColor) { + v.interpColorFrom(this.interpHelper, this.interpCache.vertices); + } + if (this.format.hasUV) { + v.interpUVFrom(this.interpHelper, this.interpCache.vertices); + } + if (this.format.hasLightMap) { + v.interpLightMapFrom(this.interpHelper, this.interpCache.vertices); + } + } + } + return true; + } } diff --git a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadTinter.java b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadTinter.java index 760fbb6df..f221bc479 100644 --- a/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadTinter.java +++ b/src/main/java/appeng/thirdparty/codechicken/lib/model/pipeline/transformers/QuadTinter.java @@ -19,11 +19,10 @@ package appeng.thirdparty.codechicken.lib.model.pipeline.transformers; -import net.minecraftforge.client.model.pipeline.IVertexConsumer; - import appeng.thirdparty.codechicken.lib.model.Quad.Vertex; import appeng.thirdparty.codechicken.lib.model.pipeline.IPipelineElementFactory; import appeng.thirdparty.codechicken.lib.model.pipeline.QuadTransformer; +import net.minecraftforge.client.model.pipeline.IVertexConsumer; /** @@ -32,47 +31,40 @@ import appeng.thirdparty.codechicken.lib.model.pipeline.QuadTransformer; * * @author covers1624 */ -public class QuadTinter extends QuadTransformer -{ +public class QuadTinter extends QuadTransformer { - public static final IPipelineElementFactory FACTORY = QuadTinter::new; + public static final IPipelineElementFactory FACTORY = QuadTinter::new; - private int tint; + private int tint; - QuadTinter() - { - super(); - } + QuadTinter() { + super(); + } - public QuadTinter( IVertexConsumer consumer, int tint ) - { - super( consumer ); - this.tint = tint; - } + public QuadTinter(IVertexConsumer consumer, int tint) { + super(consumer); + this.tint = tint; + } - public QuadTinter setTint( int tint ) - { - this.tint = tint; - return this; - } + public QuadTinter setTint(int tint) { + this.tint = tint; + return this; + } - @Override - public boolean transform() - { - // Nuke tintIndex. - this.quad.tintIndex = -1; - if( this.format.hasColor ) - { - float r = ( this.tint >> 0x10 & 0xFF ) / 255F; - float g = ( this.tint >> 0x08 & 0xFF ) / 255F; - float b = ( this.tint & 0xFF ) / 255F; - for( Vertex v : this.quad.vertices ) - { - v.color[0] *= r; - v.color[1] *= g; - v.color[2] *= b; - } - } - return true; - } + @Override + public boolean transform() { + // Nuke tintIndex. + this.quad.tintIndex = -1; + if (this.format.hasColor) { + float r = (this.tint >> 0x10 & 0xFF) / 255F; + float g = (this.tint >> 0x08 & 0xFF) / 255F; + float b = (this.tint & 0xFF) / 255F; + for (Vertex v : this.quad.vertices) { + v.color[0] *= r; + v.color[1] *= g; + v.color[2] *= b; + } + } + return true; + } } diff --git a/src/main/java/appeng/tile/AEBaseInvTile.java b/src/main/java/appeng/tile/AEBaseInvTile.java index 7a5f128e4..f33dd20d6 100644 --- a/src/main/java/appeng/tile/AEBaseInvTile.java +++ b/src/main/java/appeng/tile/AEBaseInvTile.java @@ -19,11 +19,9 @@ package appeng.tile; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - +import appeng.util.helpers.ItemHandlerUtil; +import appeng.util.inv.IAEAppEngInventory; +import appeng.util.inv.InvOperation; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; @@ -37,121 +35,99 @@ import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.wrapper.EmptyHandler; -import appeng.util.helpers.ItemHandlerUtil; -import appeng.util.inv.IAEAppEngInventory; -import appeng.util.inv.InvOperation; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.List; -public abstract class AEBaseInvTile extends AEBaseTile implements IAEAppEngInventory -{ +public abstract class AEBaseInvTile extends AEBaseTile implements IAEAppEngInventory { - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - final IItemHandler inv = this.getInternalInventory(); - if( inv != EmptyHandler.INSTANCE ) - { - final NBTTagCompound opt = data.getCompoundTag( "inv" ); - for( int x = 0; x < inv.getSlots(); x++ ) - { - final NBTTagCompound item = opt.getCompoundTag( "item" + x ); - ItemHandlerUtil.setStackInSlot( inv, x, new ItemStack( item ) ); - } - } - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + final IItemHandler inv = this.getInternalInventory(); + if (inv != EmptyHandler.INSTANCE) { + final NBTTagCompound opt = data.getCompoundTag("inv"); + for (int x = 0; x < inv.getSlots(); x++) { + final NBTTagCompound item = opt.getCompoundTag("item" + x); + ItemHandlerUtil.setStackInSlot(inv, x, new ItemStack(item)); + } + } + } - public abstract @Nonnull IItemHandler getInternalInventory(); + public abstract @Nonnull + IItemHandler getInternalInventory(); - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - final IItemHandler inv = this.getInternalInventory(); - if( inv != EmptyHandler.INSTANCE ) - { - final NBTTagCompound opt = new NBTTagCompound(); - for( int x = 0; x < inv.getSlots(); x++ ) - { - final NBTTagCompound item = new NBTTagCompound(); - final ItemStack is = inv.getStackInSlot( x ); - if( !is.isEmpty() ) - { - is.writeToNBT( item ); - } - opt.setTag( "item" + x, item ); - } - data.setTag( "inv", opt ); - } - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + final IItemHandler inv = this.getInternalInventory(); + if (inv != EmptyHandler.INSTANCE) { + final NBTTagCompound opt = new NBTTagCompound(); + for (int x = 0; x < inv.getSlots(); x++) { + final NBTTagCompound item = new NBTTagCompound(); + final ItemStack is = inv.getStackInSlot(x); + if (!is.isEmpty()) { + is.writeToNBT(item); + } + opt.setTag("item" + x, item); + } + data.setTag("inv", opt); + } + return data; + } - @Override - public void getDrops( final World w, final BlockPos pos, final List drops ) - { - final IItemHandler inv = this.getInternalInventory(); + @Override + public void getDrops(final World w, final BlockPos pos, final List drops) { + final IItemHandler inv = this.getInternalInventory(); - for( int l = 0; l < inv.getSlots(); l++ ) - { - final ItemStack is = inv.getStackInSlot( l ); - if( !is.isEmpty() ) - { - drops.add( is ); - } - } - } + for (int l = 0; l < inv.getSlots(); l++) { + final ItemStack is = inv.getStackInSlot(l); + if (!is.isEmpty()) { + drops.add(is); + } + } + } - @Override - public abstract void onChangeInventory( IItemHandler inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ); + @Override + public abstract void onChangeInventory(IItemHandler inv, int slot, InvOperation mc, ItemStack removed, ItemStack added); - @Override - public ITextComponent getDisplayName() - { - if( this.hasCustomInventoryName() ) - { - return new TextComponentString( this.getCustomInventoryName() ); - } - return new TextComponentTranslation( this.getBlockType().getUnlocalizedName() ); - } + @Override + public ITextComponent getDisplayName() { + if (this.hasCustomInventoryName()) { + return new TextComponentString(this.getCustomInventoryName()); + } + return new TextComponentTranslation(this.getBlockType().getUnlocalizedName()); + } - protected @Nonnull IItemHandler getItemHandlerForSide( @Nonnull EnumFacing side ) - { - return this.getInternalInventory(); - } + protected @Nonnull + IItemHandler getItemHandlerForSide(@Nonnull EnumFacing side) { + return this.getInternalInventory(); + } - @Override - public boolean hasCapability( Capability capability, EnumFacing facing ) - { - if( capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY ) - { - if( facing == null ) - { - return this.getInternalInventory() != EmptyHandler.INSTANCE; - } - else - { - return this.getItemHandlerForSide( facing ) != EmptyHandler.INSTANCE; - } - } - return super.hasCapability( capability, facing ); - } + @Override + public boolean hasCapability(Capability capability, EnumFacing facing) { + if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { + if (facing == null) { + return this.getInternalInventory() != EmptyHandler.INSTANCE; + } else { + return this.getItemHandlerForSide(facing) != EmptyHandler.INSTANCE; + } + } + return super.hasCapability(capability, facing); + } - @SuppressWarnings( "unchecked" ) - @Override - public T getCapability( Capability capability, @Nullable EnumFacing facing ) - { - if( capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY ) - { - if( facing == null ) - { - return (T) this.getInternalInventory(); - } - else - { - return (T) this.getItemHandlerForSide( facing ); - } - } - return super.getCapability( capability, facing ); - } + @SuppressWarnings("unchecked") + @Override + public T getCapability(Capability capability, @Nullable EnumFacing facing) { + if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { + if (facing == null) { + return (T) this.getInternalInventory(); + } else { + return (T) this.getItemHandlerForSide(facing); + } + } + return super.getCapability(capability, facing); + } } diff --git a/src/main/java/appeng/tile/AEBaseTile.java b/src/main/java/appeng/tile/AEBaseTile.java index 97cc49b14..722fab9b2 100644 --- a/src/main/java/appeng/tile/AEBaseTile.java +++ b/src/main/java/appeng/tile/AEBaseTile.java @@ -19,20 +19,23 @@ package appeng.tile; -import java.io.IOException; -import java.lang.ref.WeakReference; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - +import appeng.api.implementations.tiles.ISegmentedInventory; +import appeng.api.util.ICommonTile; +import appeng.api.util.IConfigManager; +import appeng.api.util.IConfigurableObject; +import appeng.api.util.IOrientable; +import appeng.core.AELog; +import appeng.core.features.IStackSrc; import appeng.fluids.helper.IConfigurableFluidInventory; import appeng.fluids.util.AEFluidInventory; +import appeng.helpers.ICustomNameObject; +import appeng.helpers.IPriorityHost; +import appeng.hooks.TickHandler; +import appeng.tile.inventory.AppEngInternalAEInventory; +import appeng.util.Platform; +import appeng.util.SettingsFrom; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; - import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -46,499 +49,410 @@ import net.minecraft.world.World; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.items.IItemHandler; -import appeng.api.implementations.tiles.ISegmentedInventory; -import appeng.api.util.ICommonTile; -import appeng.api.util.IConfigManager; -import appeng.api.util.IConfigurableObject; -import appeng.api.util.IOrientable; -import appeng.core.AELog; -import appeng.core.features.IStackSrc; -import appeng.helpers.ICustomNameObject; -import appeng.helpers.IPriorityHost; -import appeng.hooks.TickHandler; -import appeng.tile.inventory.AppEngInternalAEInventory; -import appeng.util.Platform; -import appeng.util.SettingsFrom; - - -public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, ICustomNameObject -{ - - private static final ThreadLocal> DROP_NO_ITEMS = new ThreadLocal<>(); - private static final Map, IStackSrc> ITEM_STACKS = new HashMap<>(); - private int renderFragment = 0; - @Nullable - private String customName; - private EnumFacing forward = null; - private EnumFacing up = null; - private IBlockState state; - private boolean markDirtyQueued = false; - - @Override - public boolean shouldRefresh( final World world, final BlockPos pos, final IBlockState oldState, final IBlockState newSate ) - { - return newSate.getBlock() != oldState.getBlock(); // state doesn't change tile entities in AE2. - } - - public static void registerTileItem( final Class c, final IStackSrc wat ) - { - ITEM_STACKS.put( c, wat ); - } - - public boolean dropItems() - { - final WeakReference what = DROP_NO_ITEMS.get(); - return what == null || what.get() != this; - } - - public boolean notLoaded() - { - return !this.world.isBlockLoaded( this.pos ); - } - - @Nonnull - public TileEntity getTile() - { - return this; - } - - @Nullable - protected ItemStack getItemFromTile( final Object obj ) - { - final IStackSrc src = ITEM_STACKS.get( obj.getClass() ); - if( src == null ) - { - return ItemStack.EMPTY; - } - return src.stack( 1 ); - } - - @Nonnull - public IBlockState getBlockState() - { - if( this.state == null ) - { - this.state = this.world.getBlockState( this.getPos() ); - } - return this.state; - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - - if( data.hasKey( "customName" ) ) - { - this.customName = data.getString( "customName" ); - } - else - { - this.customName = null; - } - - try - { - if( this.canBeRotated() ) - { - this.forward = EnumFacing.valueOf( data.getString( "forward" ) ); - this.up = EnumFacing.valueOf( data.getString( "up" ) ); - } - } - catch( final IllegalArgumentException ignored ) - { - } - } - - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - - if( this.canBeRotated() ) - { - data.setString( "forward", this.getForward().name() ); - data.setString( "up", this.getUp().name() ); - } - - if( this.customName != null ) - { - data.setString( "customName", this.customName ); - } - - return data; - } - - @Override - public SPacketUpdateTileEntity getUpdatePacket() - { - return new SPacketUpdateTileEntity( this.pos, 64, this.getUpdateTag() ); - } - - @Override - public void onDataPacket( final NetworkManager net, final SPacketUpdateTileEntity pkt ) - { - // / pkt.actionType - if( pkt.getTileEntityType() == 64 ) - { - this.handleUpdateTag( pkt.getNbtCompound() ); - } - } - - public void onReady() - { - } - - /** - * This builds a tag with the actual data that should be sent to the client for update syncs. - * If the tile entity doesn't need update syncs, it returns null. - */ - private NBTTagCompound writeUpdateData() - { - final NBTTagCompound data = new NBTTagCompound(); - - final ByteBuf stream = Unpooled.buffer(); - - try - { - this.writeToStream( stream ); - if( stream.readableBytes() == 0 ) - { - return null; - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - - stream.capacity( stream.readableBytes() ); - data.setByteArray( "X", stream.array() ); - return data; - } - - private boolean readUpdateData( ByteBuf stream ) - { - boolean output = false; - - try - { - this.renderFragment = 100; - - output = this.readFromStream( stream ); - - if( ( this.renderFragment & 1 ) == 1 ) - { - output = true; - } - this.renderFragment = 0; - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - - return output; - } - - /** - * Handles tile entites that are being sent to the client as part of a full chunk. - */ - @Override - public NBTTagCompound getUpdateTag() - { - final NBTTagCompound data = this.writeUpdateData(); - - if( data == null ) - { - return new NBTTagCompound(); - } - - data.setInteger( "x", this.pos.getX() ); - data.setInteger( "y", this.pos.getY() ); - data.setInteger( "z", this.pos.getZ() ); - return data; - } - - /** - * Handles tile entites that are being received by the client as part of a full chunk. - */ - @Override - public void handleUpdateTag( NBTTagCompound tag ) - { - final ByteBuf stream = Unpooled.copiedBuffer( tag.getByteArray( "X" ) ); - - if( this.readUpdateData( stream ) ) - { - this.markForUpdate(); - } - } - - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - if( this.canBeRotated() ) - { - final EnumFacing old_Forward = this.forward; - final EnumFacing old_Up = this.up; - - final byte orientation = data.readByte(); - this.forward = EnumFacing.VALUES[orientation & 0x7]; - this.up = EnumFacing.VALUES[orientation >> 3]; - - return this.forward != old_Forward || this.up != old_Up; - } - return false; - } - - protected void writeToStream( final ByteBuf data ) throws IOException - { - if( this.canBeRotated() ) - { - final byte orientation = (byte) ( ( this.up.ordinal() << 3 ) | this.forward.ordinal() ); - data.writeByte( orientation ); - } - } - - public void markForUpdate() - { - if( this.renderFragment > 0 ) - { - this.renderFragment |= 1; - } - else - { - // TODO: Optimize Network Load - if( this.world != null ) - { - AELog.blockUpdate( this.pos, this ); - this.world.notifyBlockUpdate( this.pos, this.getBlockState(), this.getBlockState(), 3 ); - } - } - } - - /** - * By default all blocks can have orientation, this handles saving, and loading, as well as synchronization. - * - * @return true if tile can be rotated - */ - @Override - public boolean canBeRotated() - { - return true; - } - - @Override - public EnumFacing getForward() - { - if( this.forward == null ) - { - return EnumFacing.NORTH; - } - return this.forward; - } - - @Override - public EnumFacing getUp() - { - if( this.up == null ) - { - return EnumFacing.UP; - } - return this.up; - } - - @Override - public void setOrientation( final EnumFacing inForward, final EnumFacing inUp ) - { - this.forward = inForward; - this.up = inUp; - this.markForUpdate(); - Platform.notifyBlocksOfNeighbors( this.world, this.pos ); - } - - public void onPlacement( final ItemStack stack, final EntityPlayer player, final EnumFacing side ) - { - if( stack.hasTagCompound() ) - { - this.uploadSettings( SettingsFrom.DISMANTLE_ITEM, stack.getTagCompound() ); - } - } - - /** - * depending on the from, different settings will be accepted, don't call this with null - * - * @param from source of settings - * @param compound compound of source - */ - public void uploadSettings( final SettingsFrom from, final NBTTagCompound compound ) - { - if( compound != null && this instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) this ).getConfigManager(); - if( cm != null ) - { - cm.readFromNBT( compound ); - } - } - - if( this instanceof IPriorityHost ) - { - final IPriorityHost pHost = (IPriorityHost) this; - pHost.setPriority( compound.getInteger( "priority" ) ); - } - - if( this instanceof ISegmentedInventory ) - { - final IItemHandler inv = ( (ISegmentedInventory) this ).getInventoryByName( "config" ); - if( inv instanceof AppEngInternalAEInventory ) - { - final AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; - final AppEngInternalAEInventory tmp = new AppEngInternalAEInventory( null, target.getSlots() ); - tmp.readFromNBT( compound, "config" ); - for( int x = 0; x < tmp.getSlots(); x++ ) - { - target.setStackInSlot( x, tmp.getStackInSlot( x ) ); - } - } - } - - if (this instanceof IConfigurableFluidInventory ) { - final IFluidHandler tank = ((IConfigurableFluidInventory) this).getFluidInventoryByName("config"); - if (tank instanceof AEFluidInventory) { - final AEFluidInventory target = (AEFluidInventory) tank; - final AEFluidInventory tmp = new AEFluidInventory(null, target.getSlots()); - tmp.readFromNBT(compound, "config"); - for (int x = 0; x < tmp.getSlots(); x++) { - target.setFluidInSlot(x, tmp.getFluidInSlot(x)); - } - } - } - } - - /** - * returns the contents of the tile entity, into the world, defaults to dropping everything in the inventory. - * - * @param w world - * @param drops drops of tile entity - */ - @Override - public void getDrops( final World w, final BlockPos pos, final List drops ) - { - - } - - public void getNoDrops( final World w, final BlockPos pos, final List drops ) - { - - } - - /** - * null means nothing to store... - * - * @param from source of settings - * - * @return compound of source - */ - public NBTTagCompound downloadSettings( final SettingsFrom from ) - { - final NBTTagCompound output = new NBTTagCompound(); - - if( this.hasCustomInventoryName() ) - { - final NBTTagCompound dsp = new NBTTagCompound(); - dsp.setString( "Name", this.getCustomInventoryName() ); - output.setTag( "display", dsp ); - } - - if( this instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) this ).getConfigManager(); - if( cm != null ) - { - cm.writeToNBT( output ); - } - } - - if( this instanceof IPriorityHost ) - { - final IPriorityHost pHost = (IPriorityHost) this; - output.setInteger( "priority", pHost.getPriority() ); - } - - if( this instanceof ISegmentedInventory ) - { - final IItemHandler inv = ( (ISegmentedInventory) this ).getInventoryByName( "config" ); - if( inv instanceof AppEngInternalAEInventory ) - { - ( (AppEngInternalAEInventory) inv ).writeToNBT( output, "config" ); - } - } - - if (this instanceof IConfigurableFluidInventory) { - final IFluidHandler tank = ((IConfigurableFluidInventory) this).getFluidInventoryByName("config"); - if (tank instanceof AEFluidInventory ) { - ((AEFluidInventory) tank).writeToNBT(output, "config"); - } - } - - return output.hasNoTags() ? null : output; - } - - @Override - public String getCustomInventoryName() - { - return this.hasCustomInventoryName() ? this.customName : this.getClass().getSimpleName(); - } - - @Override - public boolean hasCustomInventoryName() - { - return this.customName != null && this.customName.length() > 0; - } - - @Override - public void setCustomName(@Nullable String customName) { - setName(customName); - } - - public void securityBreak() - { - this.world.destroyBlock( this.pos, true ); - this.disableDrops(); - } - - public void disableDrops() - { - DROP_NO_ITEMS.set( new WeakReference<>( this ) ); - } - - public void saveChanges() - { - if( this.world != null ) - { - this.world.markChunkDirty( this.pos, this ); - if( !this.markDirtyQueued ) - { - TickHandler.INSTANCE.addCallable( null, this::markDirtyAtEndOfTick ); - this.markDirtyQueued = true; - } - } - } - - private Object markDirtyAtEndOfTick( final World w ) - { - this.markDirty(); - this.markDirtyQueued = false; - return null; - } - - public boolean requiresTESR() - { - return false; - } - - public void setName( final String name ) - { - this.customName = name; - } +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.IOException; +import java.lang.ref.WeakReference; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, ICustomNameObject { + + private static final ThreadLocal> DROP_NO_ITEMS = new ThreadLocal<>(); + private static final Map, IStackSrc> ITEM_STACKS = new HashMap<>(); + private int renderFragment = 0; + @Nullable + private String customName; + private EnumFacing forward = null; + private EnumFacing up = null; + private IBlockState state; + private boolean markDirtyQueued = false; + + @Override + public boolean shouldRefresh(final World world, final BlockPos pos, final IBlockState oldState, final IBlockState newSate) { + return newSate.getBlock() != oldState.getBlock(); // state doesn't change tile entities in AE2. + } + + public static void registerTileItem(final Class c, final IStackSrc wat) { + ITEM_STACKS.put(c, wat); + } + + public boolean dropItems() { + final WeakReference what = DROP_NO_ITEMS.get(); + return what == null || what.get() != this; + } + + public boolean notLoaded() { + return !this.world.isBlockLoaded(this.pos); + } + + @Nonnull + public TileEntity getTile() { + return this; + } + + @Nullable + protected ItemStack getItemFromTile(final Object obj) { + final IStackSrc src = ITEM_STACKS.get(obj.getClass()); + if (src == null) { + return ItemStack.EMPTY; + } + return src.stack(1); + } + + @Nonnull + public IBlockState getBlockState() { + if (this.state == null) { + this.state = this.world.getBlockState(this.getPos()); + } + return this.state; + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + + if (data.hasKey("customName")) { + this.customName = data.getString("customName"); + } else { + this.customName = null; + } + + try { + if (this.canBeRotated()) { + this.forward = EnumFacing.valueOf(data.getString("forward")); + this.up = EnumFacing.valueOf(data.getString("up")); + } + } catch (final IllegalArgumentException ignored) { + } + } + + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + + if (this.canBeRotated()) { + data.setString("forward", this.getForward().name()); + data.setString("up", this.getUp().name()); + } + + if (this.customName != null) { + data.setString("customName", this.customName); + } + + return data; + } + + @Override + public SPacketUpdateTileEntity getUpdatePacket() { + return new SPacketUpdateTileEntity(this.pos, 64, this.getUpdateTag()); + } + + @Override + public void onDataPacket(final NetworkManager net, final SPacketUpdateTileEntity pkt) { + // / pkt.actionType + if (pkt.getTileEntityType() == 64) { + this.handleUpdateTag(pkt.getNbtCompound()); + } + } + + public void onReady() { + } + + /** + * This builds a tag with the actual data that should be sent to the client for update syncs. + * If the tile entity doesn't need update syncs, it returns null. + */ + private NBTTagCompound writeUpdateData() { + final NBTTagCompound data = new NBTTagCompound(); + + final ByteBuf stream = Unpooled.buffer(); + + try { + this.writeToStream(stream); + if (stream.readableBytes() == 0) { + return null; + } + } catch (final Throwable t) { + AELog.debug(t); + } + + stream.capacity(stream.readableBytes()); + data.setByteArray("X", stream.array()); + return data; + } + + private boolean readUpdateData(ByteBuf stream) { + boolean output = false; + + try { + this.renderFragment = 100; + + output = this.readFromStream(stream); + + if ((this.renderFragment & 1) == 1) { + output = true; + } + this.renderFragment = 0; + } catch (final Throwable t) { + AELog.debug(t); + } + + return output; + } + + /** + * Handles tile entites that are being sent to the client as part of a full chunk. + */ + @Override + public NBTTagCompound getUpdateTag() { + final NBTTagCompound data = this.writeUpdateData(); + + if (data == null) { + return new NBTTagCompound(); + } + + data.setInteger("x", this.pos.getX()); + data.setInteger("y", this.pos.getY()); + data.setInteger("z", this.pos.getZ()); + return data; + } + + /** + * Handles tile entites that are being received by the client as part of a full chunk. + */ + @Override + public void handleUpdateTag(NBTTagCompound tag) { + final ByteBuf stream = Unpooled.copiedBuffer(tag.getByteArray("X")); + + if (this.readUpdateData(stream)) { + this.markForUpdate(); + } + } + + protected boolean readFromStream(final ByteBuf data) throws IOException { + if (this.canBeRotated()) { + final EnumFacing old_Forward = this.forward; + final EnumFacing old_Up = this.up; + + final byte orientation = data.readByte(); + this.forward = EnumFacing.VALUES[orientation & 0x7]; + this.up = EnumFacing.VALUES[orientation >> 3]; + + return this.forward != old_Forward || this.up != old_Up; + } + return false; + } + + protected void writeToStream(final ByteBuf data) throws IOException { + if (this.canBeRotated()) { + final byte orientation = (byte) ((this.up.ordinal() << 3) | this.forward.ordinal()); + data.writeByte(orientation); + } + } + + public void markForUpdate() { + if (this.renderFragment > 0) { + this.renderFragment |= 1; + } else { + // TODO: Optimize Network Load + if (this.world != null) { + AELog.blockUpdate(this.pos, this); + this.world.notifyBlockUpdate(this.pos, this.getBlockState(), this.getBlockState(), 3); + } + } + } + + /** + * By default all blocks can have orientation, this handles saving, and loading, as well as synchronization. + * + * @return true if tile can be rotated + */ + @Override + public boolean canBeRotated() { + return true; + } + + @Override + public EnumFacing getForward() { + if (this.forward == null) { + return EnumFacing.NORTH; + } + return this.forward; + } + + @Override + public EnumFacing getUp() { + if (this.up == null) { + return EnumFacing.UP; + } + return this.up; + } + + @Override + public void setOrientation(final EnumFacing inForward, final EnumFacing inUp) { + this.forward = inForward; + this.up = inUp; + this.markForUpdate(); + Platform.notifyBlocksOfNeighbors(this.world, this.pos); + } + + public void onPlacement(final ItemStack stack, final EntityPlayer player, final EnumFacing side) { + if (stack.hasTagCompound()) { + this.uploadSettings(SettingsFrom.DISMANTLE_ITEM, stack.getTagCompound()); + } + } + + /** + * depending on the from, different settings will be accepted, don't call this with null + * + * @param from source of settings + * @param compound compound of source + */ + public void uploadSettings(final SettingsFrom from, final NBTTagCompound compound) { + if (compound != null && this instanceof IConfigurableObject) { + final IConfigManager cm = ((IConfigurableObject) this).getConfigManager(); + if (cm != null) { + cm.readFromNBT(compound); + } + } + + if (this instanceof IPriorityHost) { + final IPriorityHost pHost = (IPriorityHost) this; + pHost.setPriority(compound.getInteger("priority")); + } + + if (this instanceof ISegmentedInventory) { + final IItemHandler inv = ((ISegmentedInventory) this).getInventoryByName("config"); + if (inv instanceof AppEngInternalAEInventory) { + final AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; + final AppEngInternalAEInventory tmp = new AppEngInternalAEInventory(null, target.getSlots()); + tmp.readFromNBT(compound, "config"); + for (int x = 0; x < tmp.getSlots(); x++) { + target.setStackInSlot(x, tmp.getStackInSlot(x)); + } + } + } + + if (this instanceof IConfigurableFluidInventory) { + final IFluidHandler tank = ((IConfigurableFluidInventory) this).getFluidInventoryByName("config"); + if (tank instanceof AEFluidInventory) { + final AEFluidInventory target = (AEFluidInventory) tank; + final AEFluidInventory tmp = new AEFluidInventory(null, target.getSlots()); + tmp.readFromNBT(compound, "config"); + for (int x = 0; x < tmp.getSlots(); x++) { + target.setFluidInSlot(x, tmp.getFluidInSlot(x)); + } + } + } + } + + /** + * returns the contents of the tile entity, into the world, defaults to dropping everything in the inventory. + * + * @param w world + * @param drops drops of tile entity + */ + @Override + public void getDrops(final World w, final BlockPos pos, final List drops) { + + } + + public void getNoDrops(final World w, final BlockPos pos, final List drops) { + + } + + /** + * null means nothing to store... + * + * @param from source of settings + * @return compound of source + */ + public NBTTagCompound downloadSettings(final SettingsFrom from) { + final NBTTagCompound output = new NBTTagCompound(); + + if (this.hasCustomInventoryName()) { + final NBTTagCompound dsp = new NBTTagCompound(); + dsp.setString("Name", this.getCustomInventoryName()); + output.setTag("display", dsp); + } + + if (this instanceof IConfigurableObject) { + final IConfigManager cm = ((IConfigurableObject) this).getConfigManager(); + if (cm != null) { + cm.writeToNBT(output); + } + } + + if (this instanceof IPriorityHost) { + final IPriorityHost pHost = (IPriorityHost) this; + output.setInteger("priority", pHost.getPriority()); + } + + if (this instanceof ISegmentedInventory) { + final IItemHandler inv = ((ISegmentedInventory) this).getInventoryByName("config"); + if (inv instanceof AppEngInternalAEInventory) { + ((AppEngInternalAEInventory) inv).writeToNBT(output, "config"); + } + } + + if (this instanceof IConfigurableFluidInventory) { + final IFluidHandler tank = ((IConfigurableFluidInventory) this).getFluidInventoryByName("config"); + if (tank instanceof AEFluidInventory) { + ((AEFluidInventory) tank).writeToNBT(output, "config"); + } + } + + return output.hasNoTags() ? null : output; + } + + @Override + public String getCustomInventoryName() { + return this.hasCustomInventoryName() ? this.customName : this.getClass().getSimpleName(); + } + + @Override + public boolean hasCustomInventoryName() { + return this.customName != null && this.customName.length() > 0; + } + + @Override + public void setCustomName(@Nullable String customName) { + setName(customName); + } + + public void securityBreak() { + this.world.destroyBlock(this.pos, true); + this.disableDrops(); + } + + public void disableDrops() { + DROP_NO_ITEMS.set(new WeakReference<>(this)); + } + + public void saveChanges() { + if (this.world != null) { + this.world.markChunkDirty(this.pos, this); + if (!this.markDirtyQueued) { + TickHandler.INSTANCE.addCallable(null, this::markDirtyAtEndOfTick); + this.markDirtyQueued = true; + } + } + } + + private Object markDirtyAtEndOfTick(final World w) { + this.markDirty(); + this.markDirtyQueued = false; + return null; + } + + public boolean requiresTESR() { + return false; + } + + public void setName(final String name) { + this.customName = name; + } } diff --git a/src/main/java/appeng/tile/crafting/TileCraftingMonitorTile.java b/src/main/java/appeng/tile/crafting/TileCraftingMonitorTile.java index b4124026e..1dd00f624 100644 --- a/src/main/java/appeng/tile/crafting/TileCraftingMonitorTile.java +++ b/src/main/java/appeng/tile/crafting/TileCraftingMonitorTile.java @@ -19,11 +19,12 @@ package appeng.tile.crafting; -import java.io.IOException; -import java.util.Optional; - +import appeng.api.AEApi; +import appeng.api.implementations.tiles.IColorableTile; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.util.AEColor; +import appeng.util.item.AEItemStack; import io.netty.buffer.ByteBuf; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -31,167 +32,135 @@ import net.minecraft.util.EnumFacing; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import appeng.api.AEApi; -import appeng.api.implementations.tiles.IColorableTile; -import appeng.api.storage.data.IAEItemStack; -import appeng.api.util.AEColor; -import appeng.util.item.AEItemStack; +import java.io.IOException; +import java.util.Optional; -public class TileCraftingMonitorTile extends TileCraftingTile implements IColorableTile -{ +public class TileCraftingMonitorTile extends TileCraftingTile implements IColorableTile { - @SideOnly( Side.CLIENT ) - private Integer dspList; + @SideOnly(Side.CLIENT) + private Integer dspList; - @SideOnly( Side.CLIENT ) - private boolean updateList; + @SideOnly(Side.CLIENT) + private boolean updateList; - private IAEItemStack dspPlay; - private AEColor paintedColor = AEColor.TRANSPARENT; + private IAEItemStack dspPlay; + private AEColor paintedColor = AEColor.TRANSPARENT; - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - final AEColor oldPaintedColor = this.paintedColor; - this.paintedColor = AEColor.values()[data.readByte()]; + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + final AEColor oldPaintedColor = this.paintedColor; + this.paintedColor = AEColor.values()[data.readByte()]; - final boolean hasItem = data.readBoolean(); + final boolean hasItem = data.readBoolean(); - if( hasItem ) - { - this.dspPlay = AEItemStack.fromPacket( data ); - } - else - { - this.dspPlay = null; - } + if (hasItem) { + this.dspPlay = AEItemStack.fromPacket(data); + } else { + this.dspPlay = null; + } - this.setUpdateList( true ); - return oldPaintedColor != this.paintedColor || c; // tesr! - } + this.setUpdateList(true); + return oldPaintedColor != this.paintedColor || c; // tesr! + } - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - data.writeByte( this.paintedColor.ordinal() ); + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeByte(this.paintedColor.ordinal()); - if( this.dspPlay == null ) - { - data.writeBoolean( false ); - } - else - { - data.writeBoolean( true ); - this.dspPlay.writeToPacket( data ); - } - } + if (this.dspPlay == null) { + data.writeBoolean(false); + } else { + data.writeBoolean(true); + this.dspPlay.writeToPacket(data); + } + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - if( data.hasKey( "paintedColor" ) ) - { - this.paintedColor = AEColor.values()[data.getByte( "paintedColor" )]; - } - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + if (data.hasKey("paintedColor")) { + this.paintedColor = AEColor.values()[data.getByte("paintedColor")]; + } + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setByte( "paintedColor", (byte) this.paintedColor.ordinal() ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setByte("paintedColor", (byte) this.paintedColor.ordinal()); + return data; + } - @Override - public boolean isAccelerator() - { - return false; - } + @Override + public boolean isAccelerator() { + return false; + } - @Override - public boolean isStatus() - { - return true; - } + @Override + public boolean isStatus() { + return true; + } - public void setJob( final IAEItemStack is ) - { - if( ( is == null ) != ( this.dspPlay == null ) ) - { - this.dspPlay = is == null ? null : is.copy(); - this.markForUpdate(); - } - else if( is != null && this.dspPlay != null ) - { - if( is.getStackSize() != this.dspPlay.getStackSize() ) - { - this.dspPlay = is.copy(); - this.markForUpdate(); - } - } - } + public void setJob(final IAEItemStack is) { + if ((is == null) != (this.dspPlay == null)) { + this.dspPlay = is == null ? null : is.copy(); + this.markForUpdate(); + } else if (is != null && this.dspPlay != null) { + if (is.getStackSize() != this.dspPlay.getStackSize()) { + this.dspPlay = is.copy(); + this.markForUpdate(); + } + } + } - public IAEItemStack getJobProgress() - { - return this.dspPlay; // AEItemStack.create( new ItemStack( Items.DIAMOND, 64 ) ); - } + public IAEItemStack getJobProgress() { + return this.dspPlay; // AEItemStack.create( new ItemStack( Items.DIAMOND, 64 ) ); + } - @Override - public boolean requiresTESR() - { - return this.dspPlay != null; - } + @Override + public boolean requiresTESR() { + return this.dspPlay != null; + } - @Override - public AEColor getColor() - { - return this.paintedColor; - } + @Override + public AEColor getColor() { + return this.paintedColor; + } - @Override - public boolean recolourBlock( final EnumFacing side, final AEColor newPaintedColor, final EntityPlayer who ) - { - if( this.paintedColor == newPaintedColor ) - { - return false; - } + @Override + public boolean recolourBlock(final EnumFacing side, final AEColor newPaintedColor, final EntityPlayer who) { + if (this.paintedColor == newPaintedColor) { + return false; + } - this.paintedColor = newPaintedColor; - this.saveChanges(); - this.markForUpdate(); - return true; - } + this.paintedColor = newPaintedColor; + this.saveChanges(); + this.markForUpdate(); + return true; + } - public Integer getDisplayList() - { - return this.dspList; - } + public Integer getDisplayList() { + return this.dspList; + } - public void setDisplayList( final Integer dspList ) - { - this.dspList = dspList; - } + public void setDisplayList(final Integer dspList) { + this.dspList = dspList; + } - public boolean isUpdateList() - { - return this.updateList; - } + public boolean isUpdateList() { + return this.updateList; + } - public void setUpdateList( final boolean updateList ) - { - this.updateList = updateList; - } + public void setUpdateList(final boolean updateList) { + this.updateList = updateList; + } - @Override - protected ItemStack getItemFromTile( final Object obj ) - { - final Optional is = AEApi.instance().definitions().blocks().craftingMonitor().maybeStack( 1 ); + @Override + protected ItemStack getItemFromTile(final Object obj) { + final Optional is = AEApi.instance().definitions().blocks().craftingMonitor().maybeStack(1); - return is.orElseGet( () -> super.getItemFromTile( obj ) ); - } + return is.orElseGet(() -> super.getItemFromTile(obj)); + } } diff --git a/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java b/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java index 712bc1986..8f482eaa7 100644 --- a/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java +++ b/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java @@ -19,81 +19,72 @@ package appeng.tile.crafting; -import java.util.Optional; - -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.api.definitions.IBlocks; import appeng.block.crafting.BlockCraftingUnit; +import net.minecraft.item.ItemStack; + +import java.util.Optional; -public class TileCraftingStorageTile extends TileCraftingTile -{ - private static final int KILO_SCALAR = 1024; +public class TileCraftingStorageTile extends TileCraftingTile { + private static final int KILO_SCALAR = 1024; - @Override - protected ItemStack getItemFromTile( final Object obj ) - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); - final int storage = ( (TileCraftingTile) obj ).getStorageBytes() / KILO_SCALAR; + @Override + protected ItemStack getItemFromTile(final Object obj) { + final IBlocks blocks = AEApi.instance().definitions().blocks(); + final int storage = ((TileCraftingTile) obj).getStorageBytes() / KILO_SCALAR; - Optional is; + Optional is; - switch( storage ) - { - case 1: - is = blocks.craftingStorage1k().maybeStack( 1 ); - break; - case 4: - is = blocks.craftingStorage4k().maybeStack( 1 ); - break; - case 16: - is = blocks.craftingStorage16k().maybeStack( 1 ); - break; - case 64: - is = blocks.craftingStorage64k().maybeStack( 1 ); - break; - default: - is = Optional.empty(); - break; - } + switch (storage) { + case 1: + is = blocks.craftingStorage1k().maybeStack(1); + break; + case 4: + is = blocks.craftingStorage4k().maybeStack(1); + break; + case 16: + is = blocks.craftingStorage16k().maybeStack(1); + break; + case 64: + is = blocks.craftingStorage64k().maybeStack(1); + break; + default: + is = Optional.empty(); + break; + } - return is.orElseGet( () -> super.getItemFromTile( obj ) ); - } + return is.orElseGet(() -> super.getItemFromTile(obj)); + } - @Override - public boolean isAccelerator() - { - return false; - } + @Override + public boolean isAccelerator() { + return false; + } - @Override - public boolean isStorage() - { - return true; - } + @Override + public boolean isStorage() { + return true; + } - @Override - public int getStorageBytes() - { - if( this.world == null || this.notLoaded() || this.isInvalid() ) - { - return 0; - } + @Override + public int getStorageBytes() { + if (this.world == null || this.notLoaded() || this.isInvalid()) { + return 0; + } - final BlockCraftingUnit unit = (BlockCraftingUnit) this.world.getBlockState( this.pos ).getBlock(); - switch( unit.type ) - { - default: - case STORAGE_1K: - return 1024; - case STORAGE_4K: - return 4 * 1024; - case STORAGE_16K: - return 16 * 1024; - case STORAGE_64K: - return 64 * 1024; - } - } + final BlockCraftingUnit unit = (BlockCraftingUnit) this.world.getBlockState(this.pos).getBlock(); + switch (unit.type) { + default: + case STORAGE_1K: + return 1024; + case STORAGE_4K: + return 4 * 1024; + case STORAGE_16K: + return 16 * 1024; + case STORAGE_64K: + return 64 * 1024; + } + } } diff --git a/src/main/java/appeng/tile/crafting/TileCraftingTile.java b/src/main/java/appeng/tile/crafting/TileCraftingTile.java index 9734f591f..2eea30be2 100644 --- a/src/main/java/appeng/tile/crafting/TileCraftingTile.java +++ b/src/main/java/appeng/tile/crafting/TileCraftingTile.java @@ -19,18 +19,6 @@ package appeng.tile.crafting; -import java.util.Collections; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Optional; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.implementations.IPowerChannelState; @@ -54,331 +42,274 @@ import appeng.me.helpers.AENetworkProxy; import appeng.me.helpers.AENetworkProxyMultiblock; import appeng.tile.grid.AENetworkTile; import appeng.util.Platform; +import net.minecraft.block.state.IBlockState; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; + +import java.util.*; -public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IPowerChannelState -{ +public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IPowerChannelState { - private final CraftingCPUCalculator calc = new CraftingCPUCalculator( this ); - private NBTTagCompound previousState = null; - private boolean isCoreBlock = false; - private CraftingCPUCluster cluster; + private final CraftingCPUCalculator calc = new CraftingCPUCalculator(this); + private NBTTagCompound previousState = null; + private boolean isCoreBlock = false; + private CraftingCPUCluster cluster; - public TileCraftingTile() - { - this.getProxy().setFlags( GridFlags.MULTIBLOCK, GridFlags.REQUIRE_CHANNEL ); - this.getProxy().setValidSides( EnumSet.noneOf( EnumFacing.class ) ); - } + public TileCraftingTile() { + this.getProxy().setFlags(GridFlags.MULTIBLOCK, GridFlags.REQUIRE_CHANNEL); + this.getProxy().setValidSides(EnumSet.noneOf(EnumFacing.class)); + } - @Override - protected AENetworkProxy createProxy() - { - return new AENetworkProxyMultiblock( this, "proxy", this.getItemFromTile( this ), true ); - } + @Override + protected AENetworkProxy createProxy() { + return new AENetworkProxyMultiblock(this, "proxy", this.getItemFromTile(this), true); + } - @Override - protected ItemStack getItemFromTile( final Object obj ) - { - Optional is = Optional.empty(); + @Override + protected ItemStack getItemFromTile(final Object obj) { + Optional is = Optional.empty(); - if( ( (TileCraftingTile) obj ).isAccelerator() ) - { - is = AEApi.instance().definitions().blocks().craftingAccelerator().maybeStack( 1 ); - } - else - { - is = AEApi.instance().definitions().blocks().craftingUnit().maybeStack( 1 ); - } + if (((TileCraftingTile) obj).isAccelerator()) { + is = AEApi.instance().definitions().blocks().craftingAccelerator().maybeStack(1); + } else { + is = AEApi.instance().definitions().blocks().craftingUnit().maybeStack(1); + } - return is.orElseGet( () -> super.getItemFromTile( obj ) ); - } + return is.orElseGet(() -> super.getItemFromTile(obj)); + } - @Override - public boolean canBeRotated() - { - return true;// return BlockCraftingUnit.checkType( world.getBlockMetadata( xCoord, yCoord, zCoord ), - // BlockCraftingUnit.BASE_MONITOR ); - } + @Override + public boolean canBeRotated() { + return true;// return BlockCraftingUnit.checkType( world.getBlockMetadata( xCoord, yCoord, zCoord ), + // BlockCraftingUnit.BASE_MONITOR ); + } - @Override - public void setName( final String name ) - { - super.setName( name ); - if( this.cluster != null ) - { - this.cluster.updateName(); - } - } + @Override + public void setName(final String name) { + super.setName(name); + if (this.cluster != null) { + this.cluster.updateName(); + } + } - public boolean isAccelerator() - { - if( this.world == null ) - { - return false; - } + public boolean isAccelerator() { + if (this.world == null) { + return false; + } - final BlockCraftingUnit unit = (BlockCraftingUnit) this.world.getBlockState( this.pos ).getBlock(); - return unit.type == CraftingUnitType.ACCELERATOR; - } + final BlockCraftingUnit unit = (BlockCraftingUnit) this.world.getBlockState(this.pos).getBlock(); + return unit.type == CraftingUnitType.ACCELERATOR; + } - @Override - public void onReady() - { - super.onReady(); - this.getProxy().setVisualRepresentation( this.getItemFromTile( this ) ); - this.updateMultiBlock(); - } + @Override + public void onReady() { + super.onReady(); + this.getProxy().setVisualRepresentation(this.getItemFromTile(this)); + this.updateMultiBlock(); + } - public void updateMultiBlock() - { - this.calc.calculateMultiblock( this.world, this.getLocation() ); - } + public void updateMultiBlock() { + this.calc.calculateMultiblock(this.world, this.getLocation()); + } - public void updateStatus( final CraftingCPUCluster c ) - { - if( this.cluster != null && this.cluster != c ) - { - this.cluster.breakCluster(); - } + public void updateStatus(final CraftingCPUCluster c) { + if (this.cluster != null && this.cluster != c) { + this.cluster.breakCluster(); + } - this.cluster = c; - this.updateMeta( true ); - } + this.cluster = c; + this.updateMeta(true); + } - public void updateMeta( final boolean updateFormed ) - { - if( this.world == null || this.notLoaded() || this.isInvalid() ) - { - return; - } + public void updateMeta(final boolean updateFormed) { + if (this.world == null || this.notLoaded() || this.isInvalid()) { + return; + } - final boolean formed = this.isFormed(); - boolean power = false; + final boolean formed = this.isFormed(); + boolean power = false; - if( this.getProxy().isReady() ) - { - power = this.getProxy().isActive(); - } + if (this.getProxy().isReady()) { + power = this.getProxy().isActive(); + } - final IBlockState current = this.world.getBlockState( this.pos ); + final IBlockState current = this.world.getBlockState(this.pos); - // The tile might try to update while being destroyed - if( current.getBlock() instanceof BlockCraftingUnit ) - { - final IBlockState newState = current.withProperty( BlockCraftingUnit.POWERED, power ).withProperty( BlockCraftingUnit.FORMED, formed ); + // The tile might try to update while being destroyed + if (current.getBlock() instanceof BlockCraftingUnit) { + final IBlockState newState = current.withProperty(BlockCraftingUnit.POWERED, power).withProperty(BlockCraftingUnit.FORMED, formed); - if( current != newState ) - { - // Not using flag 2 here (only send to clients, prevent block update) will cause infinite loops - // In case there is an inconsistency in the crafting clusters. - this.world.setBlockState( this.pos, newState, 2 ); - } - } + if (current != newState) { + // Not using flag 2 here (only send to clients, prevent block update) will cause infinite loops + // In case there is an inconsistency in the crafting clusters. + this.world.setBlockState(this.pos, newState, 2); + } + } - if( updateFormed ) - { - if( formed ) - { - this.getProxy().setValidSides( EnumSet.allOf( EnumFacing.class ) ); - } - else - { - this.getProxy().setValidSides( EnumSet.noneOf( EnumFacing.class ) ); - } - } - } + if (updateFormed) { + if (formed) { + this.getProxy().setValidSides(EnumSet.allOf(EnumFacing.class)); + } else { + this.getProxy().setValidSides(EnumSet.noneOf(EnumFacing.class)); + } + } + } - public boolean isFormed() - { - if( Platform.isClient() ) - { - return this.world.getBlockState( this.pos ).getValue( BlockCraftingUnit.FORMED ); - } - return this.cluster != null; - } + public boolean isFormed() { + if (Platform.isClient()) { + return this.world.getBlockState(this.pos).getValue(BlockCraftingUnit.FORMED); + } + return this.cluster != null; + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setBoolean( "core", this.isCoreBlock() ); - if( this.isCoreBlock() && this.cluster != null ) - { - this.cluster.writeToNBT( data ); - } - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setBoolean("core", this.isCoreBlock()); + if (this.isCoreBlock() && this.cluster != null) { + this.cluster.writeToNBT(data); + } + return data; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.setCoreBlock( data.getBoolean( "core" ) ); - if( this.isCoreBlock() ) - { - if( this.cluster != null ) - { - this.cluster.readFromNBT( data ); - } - else - { - this.setPreviousState( data.copy() ); - } - } - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.setCoreBlock(data.getBoolean("core")); + if (this.isCoreBlock()) { + if (this.cluster != null) { + this.cluster.readFromNBT(data); + } else { + this.setPreviousState(data.copy()); + } + } + } - @Override - public void disconnect( final boolean update ) - { - if( this.cluster != null ) - { - this.cluster.destroy(); - if( update ) - { - this.updateMeta( true ); - } - } - } + @Override + public void disconnect(final boolean update) { + if (this.cluster != null) { + this.cluster.destroy(); + if (update) { + this.updateMeta(true); + } + } + } - @Override - public IAECluster getCluster() - { - return this.cluster; - } + @Override + public IAECluster getCluster() { + return this.cluster; + } - @Override - public boolean isValid() - { - return true; - } + @Override + public boolean isValid() { + return true; + } - @MENetworkEventSubscribe - public void onPowerStateChange( final MENetworkChannelsChanged ev ) - { - this.updateMeta( false ); - } + @MENetworkEventSubscribe + public void onPowerStateChange(final MENetworkChannelsChanged ev) { + this.updateMeta(false); + } - @MENetworkEventSubscribe - public void onPowerStateChange( final MENetworkPowerStatusChange ev ) - { - this.updateMeta( false ); - } + @MENetworkEventSubscribe + public void onPowerStateChange(final MENetworkPowerStatusChange ev) { + this.updateMeta(false); + } - public boolean isStatus() - { - return false; - } + public boolean isStatus() { + return false; + } - public boolean isStorage() - { - return false; - } + public boolean isStorage() { + return false; + } - public int getStorageBytes() - { - return 0; - } + public int getStorageBytes() { + return 0; + } - public void breakCluster() - { - if( this.cluster != null ) - { - this.cluster.cancel(); - final IMEInventory inv = this.cluster.getInventory(); + public void breakCluster() { + if (this.cluster != null) { + this.cluster.cancel(); + final IMEInventory inv = this.cluster.getInventory(); - final LinkedList places = new LinkedList<>(); + final LinkedList places = new LinkedList<>(); - final Iterator i = this.cluster.getTiles(); - while( i.hasNext() ) - { - final IGridHost h = i.next(); - if( h == this ) - { - places.add( new WorldCoord( this ) ); - } - else - { - final TileEntity te = (TileEntity) h; + final Iterator i = this.cluster.getTiles(); + while (i.hasNext()) { + final IGridHost h = i.next(); + if (h == this) { + places.add(new WorldCoord(this)); + } else { + final TileEntity te = (TileEntity) h; - for( final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS ) - { - final WorldCoord wc = new WorldCoord( te ); - wc.add( d, 1 ); - if( this.world.isAirBlock( wc.getPos() ) ) - { - places.add( wc ); - } - } - } - } + for (final AEPartLocation d : AEPartLocation.SIDE_LOCATIONS) { + final WorldCoord wc = new WorldCoord(te); + wc.add(d, 1); + if (this.world.isAirBlock(wc.getPos())) { + places.add(wc); + } + } + } + } - Collections.shuffle( places ); + Collections.shuffle(places); - if( places.isEmpty() ) - { - throw new IllegalStateException( this.cluster + " does not contain any kind of blocks, which were destroyed." ); - } + if (places.isEmpty()) { + throw new IllegalStateException(this.cluster + " does not contain any kind of blocks, which were destroyed."); + } - for( IAEItemStack ais : inv.getAvailableItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList() ) ) - { - ais = ais.copy(); - ais.setStackSize( ais.getDefinition().getMaxStackSize() ); - while( true ) - { - final IAEItemStack g = inv.extractItems( ais.copy(), Actionable.MODULATE, this.cluster.getActionSource() ); - if( g == null ) - { - break; - } + for (IAEItemStack ais : inv.getAvailableItems(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList())) { + ais = ais.copy(); + ais.setStackSize(ais.getDefinition().getMaxStackSize()); + while (true) { + final IAEItemStack g = inv.extractItems(ais.copy(), Actionable.MODULATE, this.cluster.getActionSource()); + if (g == null) { + break; + } - final WorldCoord wc = places.poll(); - places.add( wc ); + final WorldCoord wc = places.poll(); + places.add(wc); - Platform.spawnDrops( this.world, wc.getPos(), Collections.singletonList( g.createItemStack() ) ); - } - } + Platform.spawnDrops(this.world, wc.getPos(), Collections.singletonList(g.createItemStack())); + } + } - this.cluster.destroy(); - } - } + this.cluster.destroy(); + } + } - @Override - public boolean isPowered() - { - if( Platform.isClient() ) - { - return this.world.getBlockState( this.pos ).getValue( BlockCraftingUnit.POWERED ); - } - return this.getProxy().isActive(); - } + @Override + public boolean isPowered() { + if (Platform.isClient()) { + return this.world.getBlockState(this.pos).getValue(BlockCraftingUnit.POWERED); + } + return this.getProxy().isActive(); + } - @Override - public boolean isActive() - { - if( Platform.isServer() ) - { - return this.getProxy().isActive(); - } - return this.isPowered() && this.isFormed(); - } + @Override + public boolean isActive() { + if (Platform.isServer()) { + return this.getProxy().isActive(); + } + return this.isPowered() && this.isFormed(); + } - public boolean isCoreBlock() - { - return this.isCoreBlock; - } + public boolean isCoreBlock() { + return this.isCoreBlock; + } - public void setCoreBlock( final boolean isCoreBlock ) - { - this.isCoreBlock = isCoreBlock; - } + public void setCoreBlock(final boolean isCoreBlock) { + this.isCoreBlock = isCoreBlock; + } - public NBTTagCompound getPreviousState() - { - return this.previousState; - } + public NBTTagCompound getPreviousState() { + return this.previousState; + } - public void setPreviousState( final NBTTagCompound previousState ) - { - this.previousState = previousState; - } + public void setPreviousState(final NBTTagCompound previousState) { + this.previousState = previousState; + } } diff --git a/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java b/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java index 931bb1e7f..ee706192a 100644 --- a/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java +++ b/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java @@ -19,40 +19,8 @@ package appeng.tile.crafting; -import java.io.IOException; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; - -import appeng.api.networking.security.IActionSource; -import appeng.api.storage.IMEMonitor; -import appeng.api.storage.IStorageMonitorable; -import appeng.api.storage.IStorageMonitorableAccessor; -import appeng.api.storage.channels.IItemStorageChannel; -import appeng.capabilities.Capabilities; -import appeng.helpers.PatternHelper; -import appeng.me.helpers.MachineSource; -import io.netty.buffer.ByteBuf; - -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; -import net.minecraft.world.WorldServer; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; -import appeng.api.config.Actionable; -import appeng.api.config.PowerMultiplier; -import appeng.api.config.RedstoneMode; -import appeng.api.config.Settings; -import appeng.api.config.Upgrades; +import appeng.api.config.*; import appeng.api.definitions.ITileDefinition; import appeng.api.implementations.IPowerChannelState; import appeng.api.implementations.IUpgradeableHost; @@ -61,19 +29,26 @@ import appeng.api.networking.IGridNode; import appeng.api.networking.crafting.ICraftingPatternDetails; import appeng.api.networking.events.MENetworkEventSubscribe; import appeng.api.networking.events.MENetworkPowerStatusChange; +import appeng.api.networking.security.IActionSource; import appeng.api.networking.ticking.IGridTickable; import appeng.api.networking.ticking.TickRateModulation; import appeng.api.networking.ticking.TickingRequest; +import appeng.api.storage.IMEMonitor; +import appeng.api.storage.IStorageMonitorable; +import appeng.api.storage.IStorageMonitorableAccessor; +import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEItemStack; import appeng.api.util.AECableType; import appeng.api.util.AEPartLocation; import appeng.api.util.DimensionalCoord; import appeng.api.util.IConfigManager; +import appeng.capabilities.Capabilities; import appeng.container.ContainerNull; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketAssemblerAnimation; import appeng.items.misc.ItemEncodedPattern; import appeng.me.GridAccessException; +import appeng.me.helpers.MachineSource; import appeng.parts.automation.DefinitionUpgradeInventory; import appeng.parts.automation.UpgradeInventory; import appeng.tile.grid.AENetworkInvTile; @@ -88,721 +63,593 @@ import appeng.util.inv.WrapperChainedItemHandler; import appeng.util.inv.WrapperFilteredItemHandler; import appeng.util.inv.filter.IAEItemFilter; import appeng.util.item.AEItemStack; - - -public class TileMolecularAssembler extends AENetworkInvTile implements IUpgradeableHost, IConfigManagerHost, IGridTickable, ICraftingMachine, IPowerChannelState -{ - private final InventoryCrafting craftingInv; - private final AppEngInternalInventory gridInv = new AppEngInternalInventory( this, 9 + 1, 1 ); - private final AppEngInternalInventory patternInv = new AppEngInternalInventory( this, 1, 1 ); - private final IItemHandler gridInvExt = new WrapperFilteredItemHandler( this.gridInv, new CraftingGridFilter() ); - private final IItemHandler internalInv = new WrapperChainedItemHandler( this.gridInv, this.patternInv ); - private final EnumMap neighbors = new EnumMap<>( EnumFacing.class ); - private final IConfigManager settings; - private final UpgradeInventory upgrades; - private boolean isPowered = false; - private AEPartLocation pushDirection = AEPartLocation.INTERNAL; - private ItemStack myPattern = ItemStack.EMPTY; - private ICraftingPatternDetails myPlan = null; - private double progress = 0; - private boolean isAwake = false; - private boolean forcePlan = false; - private boolean reboot = true; - private final IActionSource mySrc = new MachineSource( this ); - - public TileMolecularAssembler() - { - final ITileDefinition assembler = AEApi.instance().definitions().blocks().molecularAssembler(); - - this.settings = new ConfigManager( this ); - this.settings.registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.getProxy().setIdlePowerUsage( 0.0 ); - this.upgrades = new DefinitionUpgradeInventory( assembler, this, this.getUpgradeSlots() ); - this.craftingInv = new InventoryCrafting( new ContainerNull(), 3, 3 ); - - } - - private int getUpgradeSlots() - { - return 5; - } - - public void updateNeighbors() - { - for( EnumFacing f : EnumFacing.VALUES ) - { - TileEntity te = world.getTileEntity( pos.offset( f ) ); - Object capability = null; - if( te != null ) - { - // Prioritize a handler to directly link to another ME network - IStorageMonitorableAccessor accessor = te.getCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, f.getOpposite() ); - - if( accessor != null ) - { - IStorageMonitorable inventory = accessor.getInventory( this.mySrc ); - if( inventory != null ) - { - capability = inventory; - } - } - - if( capability == null ) - { - capability = InventoryAdaptor.getAdaptor( te, f.getOpposite() ); - } - } - - if( capability != null ) - { - neighbors.put( f, capability ); - } - else - { - neighbors.remove( f ); - } - } - } - - @Override - public void onReady() - { - super.onReady(); - updateNeighbors(); - } - - public void updateNeighbors( IBlockAccess w, BlockPos pos, BlockPos neighbor ) - { - EnumFacing updateFromFacing; - if( pos.getX() != neighbor.getX() ) - { - if( pos.getX() > neighbor.getX() ) - { - updateFromFacing = EnumFacing.WEST; - } - else - { - updateFromFacing = EnumFacing.EAST; - } - } - else if( pos.getY() != neighbor.getY() ) - { - if( pos.getY() > neighbor.getY() ) - { - updateFromFacing = EnumFacing.DOWN; - } - else - { - updateFromFacing = EnumFacing.UP; - } - } - else if( pos.getZ() != neighbor.getZ() ) - { - if( pos.getZ() > neighbor.getZ() ) - { - updateFromFacing = EnumFacing.NORTH; - } - else - { - updateFromFacing = EnumFacing.SOUTH; - } - } - else - { - return; - } - - if( pos.offset( updateFromFacing ).equals( neighbor ) ) - { - TileEntity te = w.getTileEntity( neighbor ); - Object capability = null; - if( te != null ) - { - // Prioritize a handler to directly link to another ME network - IStorageMonitorableAccessor accessor = te.getCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, updateFromFacing.getOpposite() ); - - if( accessor != null ) - { - IStorageMonitorable inventory = accessor.getInventory( this.mySrc ); - if( inventory != null ) - { - capability = inventory; - } - } - - if( capability == null ) - { - capability = InventoryAdaptor.getAdaptor( te, updateFromFacing.getOpposite() ); - } - } - - if( capability != null ) - { - neighbors.put( updateFromFacing, capability ); - } - else - { - neighbors.remove( updateFromFacing ); - } - } - } - - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table, final EnumFacing where ) - { - if( this.myPattern.isEmpty() ) - { - boolean isEmpty = ItemHandlerUtil.isEmpty( this.gridInv ) && ItemHandlerUtil.isEmpty( this.patternInv ); - - if( isEmpty && patternDetails.isCraftable() ) - { - this.forcePlan = true; - this.myPlan = patternDetails; - this.pushDirection = AEPartLocation.fromFacing( where ); - - for( int x = 0; x < table.getSizeInventory(); x++ ) - { - this.gridInv.setStackInSlot( x, table.getStackInSlot( x ) ); - } - - this.updateSleepiness(); - this.saveChanges(); - return true; - } - } - return false; - } - - private void updateSleepiness() - { - final boolean wasEnabled = this.isAwake; - this.isAwake = this.canPush() || this.myPlan != null && this.hasMats(); - if( wasEnabled != this.isAwake ) - { - try - { - if( this.isAwake ) - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - else - { - this.getProxy().getTick().sleepDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - } - - private boolean canPush() - { - return !this.gridInv.getStackInSlot( 9 ).isEmpty(); - } - - private boolean hasMats() - { - if( this.myPlan == null ) - { - return false; - } - - for( int x = 0; x < this.craftingInv.getSizeInventory(); x++ ) - { - this.craftingInv.setInventorySlotContents( x, this.gridInv.getStackInSlot( x ) ); - if( !myPlan.isValidItemForSlot( x, craftingInv.getStackInSlot( x ), world ) ) - { - return false; - } - } - - return this.myPlan.getOutputs().length > 0; - } - - @Override - public boolean acceptsPlans() - { - return ItemHandlerUtil.isEmpty( this.patternInv ); - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.upgrades.getInstalledUpgrades( u ); - } - - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - final boolean oldPower = this.isPowered; - this.isPowered = data.readBoolean(); - return this.isPowered != oldPower || c; - } - - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - data.writeBoolean( this.isPowered ); - } - - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - if( this.forcePlan && this.myPlan != null ) - { - final ItemStack pattern = this.myPlan.getPattern(); - if( !pattern.isEmpty() ) - { - final NBTTagCompound compound = new NBTTagCompound(); - pattern.writeToNBT( compound ); - data.setTag( "myPlan", compound ); - data.setInteger( "pushDirection", this.pushDirection.ordinal() ); - } - } - - this.upgrades.writeToNBT( data, "upgrades" ); - this.settings.writeToNBT( data ); - return data; - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - if( data.hasKey( "myPlan" ) ) - { - final ItemStack myPat = new ItemStack( data.getCompoundTag( "myPlan" ) ); - - if( !myPat.isEmpty() && myPat.getItem() instanceof ItemEncodedPattern ) - { - final World w = this.getWorld(); - final ItemEncodedPattern iep = (ItemEncodedPattern) myPat.getItem(); - final ICraftingPatternDetails ph = iep.getPatternForItem( myPat, w ); - if( ph != null && ph.isCraftable() ) - { - this.forcePlan = true; - this.myPlan = ph; - this.pushDirection = AEPartLocation.fromOrdinal( data.getInteger( "pushDirection" ) ); - } - } - } - - this.upgrades.readFromNBT( data, "upgrades" ); - this.settings.readFromNBT( data ); - this.recalculatePlan(); - } - - private void recalculatePlan() - { - this.reboot = true; - - if( this.forcePlan ) - { - return; - } - - final ItemStack is = this.patternInv.getStackInSlot( 0 ); - - if( !is.isEmpty() && is.getItem() instanceof ItemEncodedPattern ) - { - if( !ItemStack.areItemsEqual( is, this.myPattern ) ) - { - final World w = this.getWorld(); - final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - final ICraftingPatternDetails ph = iep.getPatternForItem( is, w ); - - if( ph != null && ph.isCraftable() ) - { - this.progress = 0; - this.myPattern = is; - this.myPlan = ph; - } - } - } - else - { - this.progress = 0; - this.forcePlan = false; - this.myPlan = null; - this.myPattern = ItemStack.EMPTY; - this.pushDirection = AEPartLocation.INTERNAL; - } - - this.updateSleepiness(); - } - - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.COVERED; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - @Override - public IConfigManager getConfigManager() - { - return this.settings; - } - - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - if( name.equals( "mac" ) ) - { - return this.internalInv; - } - - return null; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - - } - - @Override - public IItemHandler getInternalInventory() - { - return this.internalInv; - } - - @Override - protected IItemHandler getItemHandlerForSide( EnumFacing side ) - { - return this.gridInvExt; - } - - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( inv == this.gridInv || inv == this.patternInv ) - { - this.recalculatePlan(); - } - } - - public int getCraftingProgress() - { - return (int) this.progress; - } - - @Override - public void getDrops( final World w, final BlockPos pos, final List drops ) - { - super.getDrops( w, pos, drops ); - - for( int h = 0; h < this.upgrades.getSlots(); h++ ) - { - final ItemStack is = this.upgrades.getStackInSlot( h ); - if( !is.isEmpty() ) - { - drops.add( is ); - } - } - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - this.recalculatePlan(); - this.updateSleepiness(); - return new TickingRequest( 1, 1, !this.isAwake, false ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, int ticksSinceLastCall ) - { - if( !this.gridInv.getStackInSlot( 9 ).isEmpty() ) - { - this.pushOut( this.gridInv.getStackInSlot( 9 ) ); - - // did it eject? - if( this.gridInv.getStackInSlot( 9 ).isEmpty() ) - { - this.saveChanges(); - } - - this.ejectHeldItems(); - this.updateSleepiness(); - this.progress = 0; - return this.isAwake ? TickRateModulation.IDLE : TickRateModulation.SLEEP; - } - - if( this.myPlan == null ) - { - this.updateSleepiness(); - return TickRateModulation.SLEEP; - } - - if( this.reboot ) - { - ticksSinceLastCall = 1; - } - - if( !this.isAwake ) - { - return TickRateModulation.SLEEP; - } - - this.reboot = false; - int speed = 10; - switch ( this.upgrades.getInstalledUpgrades( Upgrades.SPEED ) ) - { - case 0: - this.progress += this.userPower( ticksSinceLastCall, speed = 10, 1.0 ); - break; - case 1: - this.progress += this.userPower( ticksSinceLastCall, speed = 13, 1.3 ); - break; - case 2: - this.progress += this.userPower( ticksSinceLastCall, speed = 17, 1.7 ); - break; - case 3: - this.progress += this.userPower( ticksSinceLastCall, speed = 20, 2.0 ); - break; - case 4: - this.progress += this.userPower( ticksSinceLastCall, speed = 25, 2.5 ); - break; - case 5: - this.progress += this.userPower( ticksSinceLastCall, speed = 50, 5.0 ); - break; - } - - if( this.progress >= 100 ) - { - for( int x = 0; x < this.craftingInv.getSizeInventory(); x++ ) - { - this.craftingInv.setInventorySlotContents( x, this.gridInv.getStackInSlot( x ) ); - } - - this.progress = 0; - final ItemStack output = this.myPlan.getOutput( this.craftingInv, this.getWorld() ); - if( !output.isEmpty() ) - { - this.pushOut( output ); - - for( int x = 0; x < this.craftingInv.getSizeInventory(); x++ ) - { - this.gridInv.setStackInSlot( x, Platform.getContainerItem( this.craftingInv.getStackInSlot( x ) ) ); - } - - if( ItemHandlerUtil.isEmpty( this.patternInv ) ) - { - this.forcePlan = false; - this.myPlan = null; - this.pushDirection = AEPartLocation.INTERNAL; - } - - this.ejectHeldItems(); - - try - { - final TargetPoint where = new TargetPoint( this.world.provider.getDimension(), this.pos.getX(), this.pos.getY(), this.pos.getZ(), 32 ); - final IAEItemStack item = AEItemStack.fromItemStack( output ); - NetworkHandler.instance().sendToAllAround( new PacketAssemblerAnimation( this.pos, (byte) speed, item ), where ); - } - catch( final IOException e ) - { - // ;P - } - - this.saveChanges(); - this.updateSleepiness(); - return this.isAwake ? TickRateModulation.IDLE : TickRateModulation.SLEEP; - } - } - - return TickRateModulation.FASTER; - } - - private void ejectHeldItems() - { - if( this.gridInv.getStackInSlot( 9 ).isEmpty() ) - { - for( int x = 0; x < 9; x++ ) - { - final ItemStack is = this.gridInv.getStackInSlot( x ); - if( !is.isEmpty() ) - { - if( this.myPlan == null || !this.myPlan.isValidItemForSlot( x, is, this.world ) ) - { - this.gridInv.setStackInSlot( 9, is ); - this.gridInv.setStackInSlot( x, ItemStack.EMPTY ); - this.saveChanges(); - return; - } - } - } - } - } - - private int userPower( final int ticksPassed, final int bonusValue, final double acceleratorTax ) - { - try - { - return (int) ( this.getProxy().getEnergy().extractAEPower( ticksPassed * bonusValue * acceleratorTax, Actionable.MODULATE, PowerMultiplier.CONFIG ) / acceleratorTax ); - } - catch( final GridAccessException e ) - { - return 0; - } - } - - private void pushOut( ItemStack output ) - { - if( this.pushDirection == AEPartLocation.INTERNAL ) - { - for( final Map.Entry d : neighbors.entrySet() ) - { - output = this.pushTo( output, d.getKey() ); - if( output.isEmpty() ) - { - break; - } - } - } - else - { - output = this.pushTo( output, this.pushDirection.getFacing() ); - } - - if( output.isEmpty() && this.forcePlan ) - { - this.forcePlan = false; - this.recalculatePlan(); - } - - this.gridInv.setStackInSlot( 9, output ); - } - - private ItemStack pushTo( ItemStack output, final EnumFacing d ) - { - if( output.isEmpty() ) - { - return output; - } - - Object capability = neighbors.get( d ); - if( capability instanceof IStorageMonitorable ) - { - // Prioritize a handler to directly link to another ME network - IStorageMonitorable inventory = (IStorageMonitorable) capability; - IAEItemStack toInsert = AEItemStack.fromItemStack( output ); - IMEMonitor inv = inventory.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); - IAEItemStack remainder = inv.injectItems( toInsert, Actionable.SIMULATE, this.mySrc ); - if( remainder == null ) - { - inv.injectItems( toInsert, Actionable.MODULATE, this.mySrc ); - return ItemStack.EMPTY; - } - else - { - if( remainder.getStackSize() == toInsert.getStackSize() ) - { - return output; - } - inv.injectItems( toInsert.setStackSize( toInsert.getStackSize() - remainder.getStackSize() ), Actionable.MODULATE, this.mySrc ); - this.saveChanges(); - return remainder.createItemStack(); - } - } - else if( capability instanceof InventoryAdaptor ) - { - InventoryAdaptor adaptor = (InventoryAdaptor) capability; - - final int size = output.getCount(); - output = adaptor.addItems( output ); - final int newSize = output.isEmpty() ? 0 : output.getCount(); - - if( size != newSize ) - { - this.saveChanges(); - } - } - - return output; - } - - @MENetworkEventSubscribe - public void onPowerEvent( final MENetworkPowerStatusChange p ) - { - this.updatePowerState(); - } - - private void updatePowerState() - { - boolean newState = false; - - try - { - newState = this.getProxy().isActive() && this.getProxy().getEnergy().extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.0001; - } - catch( final GridAccessException ignored ) - { - - } - - if( newState != this.isPowered ) - { - this.isPowered = newState; - this.markForUpdate(); - } - } - - @Override - public boolean isPowered() - { - return this.isPowered; - } - - @Override - public boolean isActive() - { - return this.isPowered; - } - - private class CraftingGridFilter implements IAEItemFilter - { - private boolean hasPattern() - { - return TileMolecularAssembler.this.myPlan != null && !ItemHandlerUtil.isEmpty( TileMolecularAssembler.this.patternInv ); - } - - @Override - public boolean allowExtract( IItemHandler inv, int slot, int amount ) - { - return slot == 9; - } - - @Override - public boolean allowInsert( IItemHandler inv, int slot, ItemStack stack ) - { - if( slot >= 9 ) - { - return false; - } - - if( this.hasPattern() ) - { - return TileMolecularAssembler.this.myPlan.isValidItemForSlot( slot, stack, TileMolecularAssembler.this.getWorld() ); - } - return false; - } - } +import io.netty.buffer.ByteBuf; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint; +import net.minecraftforge.items.IItemHandler; + +import java.io.IOException; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + + +public class TileMolecularAssembler extends AENetworkInvTile implements IUpgradeableHost, IConfigManagerHost, IGridTickable, ICraftingMachine, IPowerChannelState { + private final InventoryCrafting craftingInv; + private final AppEngInternalInventory gridInv = new AppEngInternalInventory(this, 9 + 1, 1); + private final AppEngInternalInventory patternInv = new AppEngInternalInventory(this, 1, 1); + private final IItemHandler gridInvExt = new WrapperFilteredItemHandler(this.gridInv, new CraftingGridFilter()); + private final IItemHandler internalInv = new WrapperChainedItemHandler(this.gridInv, this.patternInv); + private final EnumMap neighbors = new EnumMap<>(EnumFacing.class); + private final IConfigManager settings; + private final UpgradeInventory upgrades; + private boolean isPowered = false; + private AEPartLocation pushDirection = AEPartLocation.INTERNAL; + private ItemStack myPattern = ItemStack.EMPTY; + private ICraftingPatternDetails myPlan = null; + private double progress = 0; + private boolean isAwake = false; + private boolean forcePlan = false; + private boolean reboot = true; + private final IActionSource mySrc = new MachineSource(this); + + public TileMolecularAssembler() { + final ITileDefinition assembler = AEApi.instance().definitions().blocks().molecularAssembler(); + + this.settings = new ConfigManager(this); + this.settings.registerSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.getProxy().setIdlePowerUsage(0.0); + this.upgrades = new DefinitionUpgradeInventory(assembler, this, this.getUpgradeSlots()); + this.craftingInv = new InventoryCrafting(new ContainerNull(), 3, 3); + + } + + private int getUpgradeSlots() { + return 5; + } + + public void updateNeighbors() { + for (EnumFacing f : EnumFacing.VALUES) { + TileEntity te = world.getTileEntity(pos.offset(f)); + Object capability = null; + if (te != null) { + // Prioritize a handler to directly link to another ME network + IStorageMonitorableAccessor accessor = te.getCapability(Capabilities.STORAGE_MONITORABLE_ACCESSOR, f.getOpposite()); + + if (accessor != null) { + IStorageMonitorable inventory = accessor.getInventory(this.mySrc); + if (inventory != null) { + capability = inventory; + } + } + + if (capability == null) { + capability = InventoryAdaptor.getAdaptor(te, f.getOpposite()); + } + } + + if (capability != null) { + neighbors.put(f, capability); + } else { + neighbors.remove(f); + } + } + } + + @Override + public void onReady() { + super.onReady(); + updateNeighbors(); + } + + public void updateNeighbors(IBlockAccess w, BlockPos pos, BlockPos neighbor) { + EnumFacing updateFromFacing; + if (pos.getX() != neighbor.getX()) { + if (pos.getX() > neighbor.getX()) { + updateFromFacing = EnumFacing.WEST; + } else { + updateFromFacing = EnumFacing.EAST; + } + } else if (pos.getY() != neighbor.getY()) { + if (pos.getY() > neighbor.getY()) { + updateFromFacing = EnumFacing.DOWN; + } else { + updateFromFacing = EnumFacing.UP; + } + } else if (pos.getZ() != neighbor.getZ()) { + if (pos.getZ() > neighbor.getZ()) { + updateFromFacing = EnumFacing.NORTH; + } else { + updateFromFacing = EnumFacing.SOUTH; + } + } else { + return; + } + + if (pos.offset(updateFromFacing).equals(neighbor)) { + TileEntity te = w.getTileEntity(neighbor); + Object capability = null; + if (te != null) { + // Prioritize a handler to directly link to another ME network + IStorageMonitorableAccessor accessor = te.getCapability(Capabilities.STORAGE_MONITORABLE_ACCESSOR, updateFromFacing.getOpposite()); + + if (accessor != null) { + IStorageMonitorable inventory = accessor.getInventory(this.mySrc); + if (inventory != null) { + capability = inventory; + } + } + + if (capability == null) { + capability = InventoryAdaptor.getAdaptor(te, updateFromFacing.getOpposite()); + } + } + + if (capability != null) { + neighbors.put(updateFromFacing, capability); + } else { + neighbors.remove(updateFromFacing); + } + } + } + + @Override + public boolean pushPattern(final ICraftingPatternDetails patternDetails, final InventoryCrafting table, final EnumFacing where) { + if (this.myPattern.isEmpty()) { + boolean isEmpty = ItemHandlerUtil.isEmpty(this.gridInv) && ItemHandlerUtil.isEmpty(this.patternInv); + + if (isEmpty && patternDetails.isCraftable()) { + this.forcePlan = true; + this.myPlan = patternDetails; + this.pushDirection = AEPartLocation.fromFacing(where); + + for (int x = 0; x < table.getSizeInventory(); x++) { + this.gridInv.setStackInSlot(x, table.getStackInSlot(x)); + } + + this.updateSleepiness(); + this.saveChanges(); + return true; + } + } + return false; + } + + private void updateSleepiness() { + final boolean wasEnabled = this.isAwake; + this.isAwake = this.canPush() || this.myPlan != null && this.hasMats(); + if (wasEnabled != this.isAwake) { + try { + if (this.isAwake) { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } else { + this.getProxy().getTick().sleepDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + } + + private boolean canPush() { + return !this.gridInv.getStackInSlot(9).isEmpty(); + } + + private boolean hasMats() { + if (this.myPlan == null) { + return false; + } + + for (int x = 0; x < this.craftingInv.getSizeInventory(); x++) { + this.craftingInv.setInventorySlotContents(x, this.gridInv.getStackInSlot(x)); + if (!myPlan.isValidItemForSlot(x, craftingInv.getStackInSlot(x), world)) { + return false; + } + } + + return this.myPlan.getOutputs().length > 0; + } + + @Override + public boolean acceptsPlans() { + return ItemHandlerUtil.isEmpty(this.patternInv); + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.upgrades.getInstalledUpgrades(u); + } + + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + final boolean oldPower = this.isPowered; + this.isPowered = data.readBoolean(); + return this.isPowered != oldPower || c; + } + + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeBoolean(this.isPowered); + } + + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + if (this.forcePlan && this.myPlan != null) { + final ItemStack pattern = this.myPlan.getPattern(); + if (!pattern.isEmpty()) { + final NBTTagCompound compound = new NBTTagCompound(); + pattern.writeToNBT(compound); + data.setTag("myPlan", compound); + data.setInteger("pushDirection", this.pushDirection.ordinal()); + } + } + + this.upgrades.writeToNBT(data, "upgrades"); + this.settings.writeToNBT(data); + return data; + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + if (data.hasKey("myPlan")) { + final ItemStack myPat = new ItemStack(data.getCompoundTag("myPlan")); + + if (!myPat.isEmpty() && myPat.getItem() instanceof ItemEncodedPattern) { + final World w = this.getWorld(); + final ItemEncodedPattern iep = (ItemEncodedPattern) myPat.getItem(); + final ICraftingPatternDetails ph = iep.getPatternForItem(myPat, w); + if (ph != null && ph.isCraftable()) { + this.forcePlan = true; + this.myPlan = ph; + this.pushDirection = AEPartLocation.fromOrdinal(data.getInteger("pushDirection")); + } + } + } + + this.upgrades.readFromNBT(data, "upgrades"); + this.settings.readFromNBT(data); + this.recalculatePlan(); + } + + private void recalculatePlan() { + this.reboot = true; + + if (this.forcePlan) { + return; + } + + final ItemStack is = this.patternInv.getStackInSlot(0); + + if (!is.isEmpty() && is.getItem() instanceof ItemEncodedPattern) { + if (!ItemStack.areItemsEqual(is, this.myPattern)) { + final World w = this.getWorld(); + final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + final ICraftingPatternDetails ph = iep.getPatternForItem(is, w); + + if (ph != null && ph.isCraftable()) { + this.progress = 0; + this.myPattern = is; + this.myPlan = ph; + } + } + } else { + this.progress = 0; + this.forcePlan = false; + this.myPlan = null; + this.myPattern = ItemStack.EMPTY; + this.pushDirection = AEPartLocation.INTERNAL; + } + + this.updateSleepiness(); + } + + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.COVERED; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + @Override + public IConfigManager getConfigManager() { + return this.settings; + } + + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("upgrades")) { + return this.upgrades; + } + + if (name.equals("mac")) { + return this.internalInv; + } + + return null; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + + } + + @Override + public IItemHandler getInternalInventory() { + return this.internalInv; + } + + @Override + protected IItemHandler getItemHandlerForSide(EnumFacing side) { + return this.gridInvExt; + } + + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { + if (inv == this.gridInv || inv == this.patternInv) { + this.recalculatePlan(); + } + } + + public int getCraftingProgress() { + return (int) this.progress; + } + + @Override + public void getDrops(final World w, final BlockPos pos, final List drops) { + super.getDrops(w, pos, drops); + + for (int h = 0; h < this.upgrades.getSlots(); h++) { + final ItemStack is = this.upgrades.getStackInSlot(h); + if (!is.isEmpty()) { + drops.add(is); + } + } + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + this.recalculatePlan(); + this.updateSleepiness(); + return new TickingRequest(1, 1, !this.isAwake, false); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, int ticksSinceLastCall) { + if (!this.gridInv.getStackInSlot(9).isEmpty()) { + this.pushOut(this.gridInv.getStackInSlot(9)); + + // did it eject? + if (this.gridInv.getStackInSlot(9).isEmpty()) { + this.saveChanges(); + } + + this.ejectHeldItems(); + this.updateSleepiness(); + this.progress = 0; + return this.isAwake ? TickRateModulation.IDLE : TickRateModulation.SLEEP; + } + + if (this.myPlan == null) { + this.updateSleepiness(); + return TickRateModulation.SLEEP; + } + + if (this.reboot) { + ticksSinceLastCall = 1; + } + + if (!this.isAwake) { + return TickRateModulation.SLEEP; + } + + this.reboot = false; + int speed = 10; + switch (this.upgrades.getInstalledUpgrades(Upgrades.SPEED)) { + case 0: + this.progress += this.userPower(ticksSinceLastCall, speed = 10, 1.0); + break; + case 1: + this.progress += this.userPower(ticksSinceLastCall, speed = 13, 1.3); + break; + case 2: + this.progress += this.userPower(ticksSinceLastCall, speed = 17, 1.7); + break; + case 3: + this.progress += this.userPower(ticksSinceLastCall, speed = 20, 2.0); + break; + case 4: + this.progress += this.userPower(ticksSinceLastCall, speed = 25, 2.5); + break; + case 5: + this.progress += this.userPower(ticksSinceLastCall, speed = 50, 5.0); + break; + } + + if (this.progress >= 100) { + for (int x = 0; x < this.craftingInv.getSizeInventory(); x++) { + this.craftingInv.setInventorySlotContents(x, this.gridInv.getStackInSlot(x)); + } + + this.progress = 0; + final ItemStack output = this.myPlan.getOutput(this.craftingInv, this.getWorld()); + if (!output.isEmpty()) { + this.pushOut(output); + + for (int x = 0; x < this.craftingInv.getSizeInventory(); x++) { + this.gridInv.setStackInSlot(x, Platform.getContainerItem(this.craftingInv.getStackInSlot(x))); + } + + if (ItemHandlerUtil.isEmpty(this.patternInv)) { + this.forcePlan = false; + this.myPlan = null; + this.pushDirection = AEPartLocation.INTERNAL; + } + + this.ejectHeldItems(); + + try { + final TargetPoint where = new TargetPoint(this.world.provider.getDimension(), this.pos.getX(), this.pos.getY(), this.pos.getZ(), 32); + final IAEItemStack item = AEItemStack.fromItemStack(output); + NetworkHandler.instance().sendToAllAround(new PacketAssemblerAnimation(this.pos, (byte) speed, item), where); + } catch (final IOException e) { + // ;P + } + + this.saveChanges(); + this.updateSleepiness(); + return this.isAwake ? TickRateModulation.IDLE : TickRateModulation.SLEEP; + } + } + + return TickRateModulation.FASTER; + } + + private void ejectHeldItems() { + if (this.gridInv.getStackInSlot(9).isEmpty()) { + for (int x = 0; x < 9; x++) { + final ItemStack is = this.gridInv.getStackInSlot(x); + if (!is.isEmpty()) { + if (this.myPlan == null || !this.myPlan.isValidItemForSlot(x, is, this.world)) { + this.gridInv.setStackInSlot(9, is); + this.gridInv.setStackInSlot(x, ItemStack.EMPTY); + this.saveChanges(); + return; + } + } + } + } + } + + private int userPower(final int ticksPassed, final int bonusValue, final double acceleratorTax) { + try { + return (int) (this.getProxy().getEnergy().extractAEPower(ticksPassed * bonusValue * acceleratorTax, Actionable.MODULATE, PowerMultiplier.CONFIG) / acceleratorTax); + } catch (final GridAccessException e) { + return 0; + } + } + + private void pushOut(ItemStack output) { + if (this.pushDirection == AEPartLocation.INTERNAL) { + for (final Map.Entry d : neighbors.entrySet()) { + output = this.pushTo(output, d.getKey()); + if (output.isEmpty()) { + break; + } + } + } else { + output = this.pushTo(output, this.pushDirection.getFacing()); + } + + if (output.isEmpty() && this.forcePlan) { + this.forcePlan = false; + this.recalculatePlan(); + } + + this.gridInv.setStackInSlot(9, output); + } + + private ItemStack pushTo(ItemStack output, final EnumFacing d) { + if (output.isEmpty()) { + return output; + } + + Object capability = neighbors.get(d); + if (capability instanceof IStorageMonitorable) { + // Prioritize a handler to directly link to another ME network + IStorageMonitorable inventory = (IStorageMonitorable) capability; + IAEItemStack toInsert = AEItemStack.fromItemStack(output); + IMEMonitor inv = inventory.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)); + IAEItemStack remainder = inv.injectItems(toInsert, Actionable.SIMULATE, this.mySrc); + if (remainder == null) { + inv.injectItems(toInsert, Actionable.MODULATE, this.mySrc); + return ItemStack.EMPTY; + } else { + if (remainder.getStackSize() == toInsert.getStackSize()) { + return output; + } + inv.injectItems(toInsert.setStackSize(toInsert.getStackSize() - remainder.getStackSize()), Actionable.MODULATE, this.mySrc); + this.saveChanges(); + return remainder.createItemStack(); + } + } else if (capability instanceof InventoryAdaptor) { + InventoryAdaptor adaptor = (InventoryAdaptor) capability; + + final int size = output.getCount(); + output = adaptor.addItems(output); + final int newSize = output.isEmpty() ? 0 : output.getCount(); + + if (size != newSize) { + this.saveChanges(); + } + } + + return output; + } + + @MENetworkEventSubscribe + public void onPowerEvent(final MENetworkPowerStatusChange p) { + this.updatePowerState(); + } + + private void updatePowerState() { + boolean newState = false; + + try { + newState = this.getProxy().isActive() && this.getProxy().getEnergy().extractAEPower(1, Actionable.SIMULATE, PowerMultiplier.CONFIG) > 0.0001; + } catch (final GridAccessException ignored) { + + } + + if (newState != this.isPowered) { + this.isPowered = newState; + this.markForUpdate(); + } + } + + @Override + public boolean isPowered() { + return this.isPowered; + } + + @Override + public boolean isActive() { + return this.isPowered; + } + + private class CraftingGridFilter implements IAEItemFilter { + private boolean hasPattern() { + return TileMolecularAssembler.this.myPlan != null && !ItemHandlerUtil.isEmpty(TileMolecularAssembler.this.patternInv); + } + + @Override + public boolean allowExtract(IItemHandler inv, int slot, int amount) { + return slot == 9; + } + + @Override + public boolean allowInsert(IItemHandler inv, int slot, ItemStack stack) { + if (slot >= 9) { + return false; + } + + if (this.hasPattern()) { + return TileMolecularAssembler.this.myPlan.isValidItemForSlot(slot, stack, TileMolecularAssembler.this.getWorld()); + } + return false; + } + } } diff --git a/src/main/java/appeng/tile/grid/AENetworkInvTile.java b/src/main/java/appeng/tile/grid/AENetworkInvTile.java index 567dea7ee..2ccdac7d0 100644 --- a/src/main/java/appeng/tile/grid/AENetworkInvTile.java +++ b/src/main/java/appeng/tile/grid/AENetworkInvTile.java @@ -19,85 +19,73 @@ package appeng.tile.grid; -import net.minecraft.nbt.NBTTagCompound; - import appeng.api.networking.IGridNode; import appeng.api.networking.security.IActionHost; import appeng.api.util.AEPartLocation; import appeng.me.helpers.AENetworkProxy; import appeng.me.helpers.IGridProxyable; import appeng.tile.AEBaseInvTile; +import net.minecraft.nbt.NBTTagCompound; -public abstract class AENetworkInvTile extends AEBaseInvTile implements IActionHost, IGridProxyable -{ +public abstract class AENetworkInvTile extends AEBaseInvTile implements IActionHost, IGridProxyable { - private final AENetworkProxy gridProxy = new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); + private final AENetworkProxy gridProxy = new AENetworkProxy(this, "proxy", this.getItemFromTile(this), true); - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.getProxy().readFromNBT( data ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.getProxy().readFromNBT(data); + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.getProxy().writeToNBT( data ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.getProxy().writeToNBT(data); + return data; + } - @Override - public AENetworkProxy getProxy() - { - return this.gridProxy; - } + @Override + public AENetworkProxy getProxy() { + return this.gridProxy; + } - @Override - public void gridChanged() - { + @Override + public void gridChanged() { - } + } - @Override - public IGridNode getGridNode( final AEPartLocation dir ) - { - return this.getProxy().getNode(); - } + @Override + public IGridNode getGridNode(final AEPartLocation dir) { + return this.getProxy().getNode(); + } - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.getProxy().onChunkUnload(); - } + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.getProxy().onChunkUnload(); + } - @Override - public void onReady() - { - super.onReady(); - this.getProxy().onReady(); - } + @Override + public void onReady() { + super.onReady(); + this.getProxy().onReady(); + } - @Override - public void invalidate() - { - super.invalidate(); - this.getProxy().invalidate(); - } + @Override + public void invalidate() { + super.invalidate(); + this.getProxy().invalidate(); + } - @Override - public void validate() - { - super.validate(); - this.getProxy().validate(); - } + @Override + public void validate() { + super.validate(); + this.getProxy().validate(); + } - @Override - public IGridNode getActionableNode() - { - return this.getProxy().getNode(); - } + @Override + public IGridNode getActionableNode() { + return this.getProxy().getNode(); + } } diff --git a/src/main/java/appeng/tile/grid/AENetworkPowerTile.java b/src/main/java/appeng/tile/grid/AENetworkPowerTile.java index 4bcdf3d2a..b96b36721 100644 --- a/src/main/java/appeng/tile/grid/AENetworkPowerTile.java +++ b/src/main/java/appeng/tile/grid/AENetworkPowerTile.java @@ -19,8 +19,6 @@ package appeng.tile.grid; -import net.minecraft.nbt.NBTTagCompound; - import appeng.api.networking.IGridNode; import appeng.api.networking.security.IActionHost; import appeng.api.util.AECableType; @@ -29,90 +27,78 @@ import appeng.api.util.DimensionalCoord; import appeng.me.helpers.AENetworkProxy; import appeng.me.helpers.IGridProxyable; import appeng.tile.powersink.AEBasePoweredTile; +import net.minecraft.nbt.NBTTagCompound; -public abstract class AENetworkPowerTile extends AEBasePoweredTile implements IActionHost, IGridProxyable -{ +public abstract class AENetworkPowerTile extends AEBasePoweredTile implements IActionHost, IGridProxyable { - private final AENetworkProxy gridProxy = new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); + private final AENetworkProxy gridProxy = new AENetworkProxy(this, "proxy", this.getItemFromTile(this), true); - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.getProxy().readFromNBT( data ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.getProxy().readFromNBT(data); + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.getProxy().writeToNBT( data ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.getProxy().writeToNBT(data); + return data; + } - @Override - public AENetworkProxy getProxy() - { - return this.gridProxy; - } + @Override + public AENetworkProxy getProxy() { + return this.gridProxy; + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - public void gridChanged() - { + @Override + public void gridChanged() { - } + } - @Override - public IGridNode getGridNode( final AEPartLocation dir ) - { - return this.getProxy().getNode(); - } + @Override + public IGridNode getGridNode(final AEPartLocation dir) { + return this.getProxy().getNode(); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.SMART; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.SMART; + } - @Override - public void validate() - { - super.validate(); - this.getProxy().validate(); - } + @Override + public void validate() { + super.validate(); + this.getProxy().validate(); + } - @Override - public void invalidate() - { - super.invalidate(); - this.getProxy().invalidate(); - } + @Override + public void invalidate() { + super.invalidate(); + this.getProxy().invalidate(); + } - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.getProxy().onChunkUnload(); - } + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.getProxy().onChunkUnload(); + } - @Override - public void onReady() - { - super.onReady(); - this.getProxy().onReady(); - } + @Override + public void onReady() { + super.onReady(); + this.getProxy().onReady(); + } - @Override - public IGridNode getActionableNode() - { - return this.getProxy().getNode(); - } + @Override + public IGridNode getActionableNode() { + return this.getProxy().getNode(); + } } diff --git a/src/main/java/appeng/tile/grid/AENetworkTile.java b/src/main/java/appeng/tile/grid/AENetworkTile.java index e7a6fb7f9..917be6e09 100644 --- a/src/main/java/appeng/tile/grid/AENetworkTile.java +++ b/src/main/java/appeng/tile/grid/AENetworkTile.java @@ -19,8 +19,6 @@ package appeng.tile.grid; -import net.minecraft.nbt.NBTTagCompound; - import appeng.api.networking.IGridNode; import appeng.api.networking.security.IActionHost; import appeng.api.util.AECableType; @@ -29,94 +27,81 @@ import appeng.api.util.DimensionalCoord; import appeng.me.helpers.AENetworkProxy; import appeng.me.helpers.IGridProxyable; import appeng.tile.AEBaseTile; +import net.minecraft.nbt.NBTTagCompound; -public class AENetworkTile extends AEBaseTile implements IActionHost, IGridProxyable -{ +public class AENetworkTile extends AEBaseTile implements IActionHost, IGridProxyable { - private final AENetworkProxy gridProxy = this.createProxy(); + private final AENetworkProxy gridProxy = this.createProxy(); - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.getProxy().readFromNBT( data ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.getProxy().readFromNBT(data); + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.getProxy().writeToNBT( data ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.getProxy().writeToNBT(data); + return data; + } - protected AENetworkProxy createProxy() - { - return new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); - } + protected AENetworkProxy createProxy() { + return new AENetworkProxy(this, "proxy", this.getItemFromTile(this), true); + } - @Override - public IGridNode getGridNode( final AEPartLocation dir ) - { - return this.getProxy().getNode(); - } + @Override + public IGridNode getGridNode(final AEPartLocation dir) { + return this.getProxy().getNode(); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.SMART; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.SMART; + } - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.getProxy().onChunkUnload(); - } + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.getProxy().onChunkUnload(); + } - @Override - public void onReady() - { - super.onReady(); - this.getProxy().onReady(); - } + @Override + public void onReady() { + super.onReady(); + this.getProxy().onReady(); + } - @Override - public void invalidate() - { - super.invalidate(); - this.getProxy().invalidate(); - } + @Override + public void invalidate() { + super.invalidate(); + this.getProxy().invalidate(); + } - @Override - public void validate() - { - super.validate(); - this.getProxy().validate(); - } + @Override + public void validate() { + super.validate(); + this.getProxy().validate(); + } - @Override - public AENetworkProxy getProxy() - { - return this.gridProxy; - } + @Override + public AENetworkProxy getProxy() { + return this.gridProxy; + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - public void gridChanged() - { + @Override + public void gridChanged() { - } + } - @Override - public IGridNode getActionableNode() - { - return this.getProxy().getNode(); - } + @Override + public IGridNode getActionableNode() { + return this.getProxy().getNode(); + } } diff --git a/src/main/java/appeng/tile/grindstone/TileCrank.java b/src/main/java/appeng/tile/grindstone/TileCrank.java index b73b9e59d..1b13cc24b 100644 --- a/src/main/java/appeng/tile/grindstone/TileCrank.java +++ b/src/main/java/appeng/tile/grindstone/TileCrank.java @@ -19,12 +19,11 @@ package appeng.tile.grindstone; -import java.io.IOException; -import java.util.Collections; -import java.util.List; - +import appeng.api.implementations.tiles.ICrankable; +import appeng.helpers.ICustomCollision; +import appeng.tile.AEBaseTile; +import appeng.util.Platform; import io.netty.buffer.ByteBuf; - import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.tileentity.TileEntity; @@ -34,152 +33,127 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.api.implementations.tiles.ICrankable; -import appeng.helpers.ICustomCollision; -import appeng.tile.AEBaseTile; -import appeng.util.Platform; +import java.io.IOException; +import java.util.Collections; +import java.util.List; -public class TileCrank extends AEBaseTile implements ICustomCollision, ITickable -{ +public class TileCrank extends AEBaseTile implements ICustomCollision, ITickable { - private final int ticksPerRotation = 18; + private final int ticksPerRotation = 18; - // sided values.. - private float visibleRotation = 0; - private int charge = 0; + // sided values.. + private float visibleRotation = 0; + private int charge = 0; - private int hits = 0; - private int rotation = 0; + private int hits = 0; + private int rotation = 0; - @Override - public void update() - { - if( this.rotation > 0 ) - { - this.setVisibleRotation( this.getVisibleRotation() - 360 / ( this.ticksPerRotation ) ); - this.charge++; - if( this.charge >= this.ticksPerRotation ) - { - this.charge -= this.ticksPerRotation; - final ICrankable g = this.getGrinder(); - if( g != null ) - { - g.applyTurn(); - } - } + @Override + public void update() { + if (this.rotation > 0) { + this.setVisibleRotation(this.getVisibleRotation() - 360 / (this.ticksPerRotation)); + this.charge++; + if (this.charge >= this.ticksPerRotation) { + this.charge -= this.ticksPerRotation; + final ICrankable g = this.getGrinder(); + if (g != null) { + g.applyTurn(); + } + } - this.rotation--; - } - } + this.rotation--; + } + } - private ICrankable getGrinder() - { - if( Platform.isClient() ) - { - return null; - } + private ICrankable getGrinder() { + if (Platform.isClient()) { + return null; + } - final EnumFacing grinder = this.getUp().getOpposite(); - final TileEntity te = this.world.getTileEntity( this.pos.offset( grinder ) ); - if( te instanceof ICrankable ) - { - return (ICrankable) te; - } - return null; - } + final EnumFacing grinder = this.getUp().getOpposite(); + final TileEntity te = this.world.getTileEntity(this.pos.offset(grinder)); + if (te instanceof ICrankable) { + return (ICrankable) te; + } + return null; + } - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - this.rotation = data.readInt(); - return c; - } + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + this.rotation = data.readInt(); + return c; + } - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - data.writeInt( this.rotation ); - } + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeInt(this.rotation); + } - @Override - public void setOrientation( final EnumFacing inForward, final EnumFacing inUp ) - { - super.setOrientation( inForward, inUp ); - final IBlockState state = this.world.getBlockState( this.pos ); - this.getBlockType().neighborChanged( state, this.world, this.pos, state.getBlock(), this.pos ); - } + @Override + public void setOrientation(final EnumFacing inForward, final EnumFacing inUp) { + super.setOrientation(inForward, inUp); + final IBlockState state = this.world.getBlockState(this.pos); + this.getBlockType().neighborChanged(state, this.world, this.pos, state.getBlock(), this.pos); + } - @Override - public boolean requiresTESR() - { - return true; - } + @Override + public boolean requiresTESR() { + return true; + } - /** - * return true if this should count towards stats. - */ - public boolean power() - { - if( Platform.isClient() ) - { - return false; - } + /** + * return true if this should count towards stats. + */ + public boolean power() { + if (Platform.isClient()) { + return false; + } - if( this.rotation < 3 ) - { - final ICrankable g = this.getGrinder(); - if( g != null ) - { - if( g.canTurn() ) - { - this.hits = 0; - this.rotation += this.ticksPerRotation; - this.markForUpdate(); - return true; - } - else - { - this.hits++; - if( this.hits > 10 ) - { - this.world.destroyBlock( this.pos, false ); - } - } - } - } + if (this.rotation < 3) { + final ICrankable g = this.getGrinder(); + if (g != null) { + if (g.canTurn()) { + this.hits = 0; + this.rotation += this.ticksPerRotation; + this.markForUpdate(); + return true; + } else { + this.hits++; + if (this.hits > 10) { + this.world.destroyBlock(this.pos, false); + } + } + } + } - return false; - } + return false; + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final BlockPos pos, final Entity thePlayer, final boolean b ) - { - final double xOff = -0.15 * this.getUp().getFrontOffsetX(); - final double yOff = -0.15 * this.getUp().getFrontOffsetY(); - final double zOff = -0.15 * this.getUp().getFrontOffsetZ(); - return Collections.singletonList( new AxisAlignedBB( xOff + 0.15, yOff + 0.15, zOff + 0.15, xOff + 0.85, yOff + 0.85, zOff + 0.85 ) ); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool(final World w, final BlockPos pos, final Entity thePlayer, final boolean b) { + final double xOff = -0.15 * this.getUp().getFrontOffsetX(); + final double yOff = -0.15 * this.getUp().getFrontOffsetY(); + final double zOff = -0.15 * this.getUp().getFrontOffsetZ(); + return Collections.singletonList(new AxisAlignedBB(xOff + 0.15, yOff + 0.15, zOff + 0.15, xOff + 0.85, yOff + 0.85, zOff + 0.85)); + } - @Override - public void addCollidingBlockToList( final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e ) - { - final double xOff = -0.15 * this.getUp().getFrontOffsetX(); - final double yOff = -0.15 * this.getUp().getFrontOffsetY(); - final double zOff = -0.15 * this.getUp().getFrontOffsetZ(); - out.add( new AxisAlignedBB( xOff + 0.15, yOff + 0.15, zOff + 0.15, // ahh - xOff + 0.85, yOff + 0.85, zOff + 0.85 ) ); - } + @Override + public void addCollidingBlockToList(final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e) { + final double xOff = -0.15 * this.getUp().getFrontOffsetX(); + final double yOff = -0.15 * this.getUp().getFrontOffsetY(); + final double zOff = -0.15 * this.getUp().getFrontOffsetZ(); + out.add(new AxisAlignedBB(xOff + 0.15, yOff + 0.15, zOff + 0.15, // ahh + xOff + 0.85, yOff + 0.85, zOff + 0.85)); + } - public float getVisibleRotation() - { - return this.visibleRotation; - } + public float getVisibleRotation() { + return this.visibleRotation; + } - private void setVisibleRotation( final float visibleRotation ) - { - this.visibleRotation = visibleRotation; - } + private void setVisibleRotation(final float visibleRotation) { + this.visibleRotation = visibleRotation; + } } diff --git a/src/main/java/appeng/tile/grindstone/TileGrinder.java b/src/main/java/appeng/tile/grindstone/TileGrinder.java index 8a1f83c49..7d6f2dee9 100644 --- a/src/main/java/appeng/tile/grindstone/TileGrinder.java +++ b/src/main/java/appeng/tile/grindstone/TileGrinder.java @@ -19,15 +19,6 @@ package appeng.tile.grindstone; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.wrapper.RangedWrapper; - import appeng.api.AEApi; import appeng.api.features.IGrinderRecipe; import appeng.api.implementations.tiles.ICrankable; @@ -39,172 +30,154 @@ import appeng.util.inv.AdaptorItemHandler; import appeng.util.inv.InvOperation; import appeng.util.inv.WrapperFilteredItemHandler; import appeng.util.inv.filter.IAEItemFilter; +import net.minecraft.block.state.IBlockState; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.wrapper.RangedWrapper; + +import java.util.ArrayList; +import java.util.List; -public class TileGrinder extends AEBaseInvTile implements ICrankable -{ - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 7 ); - private final IItemHandler invExt = new WrapperFilteredItemHandler( this.inv, new GrinderFilter() ); - private int points; +public class TileGrinder extends AEBaseInvTile implements ICrankable { + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 7); + private final IItemHandler invExt = new WrapperFilteredItemHandler(this.inv, new GrinderFilter()); + private int points; - @Override - public void setOrientation( final EnumFacing inForward, final EnumFacing inUp ) - { - super.setOrientation( inForward, inUp ); - final IBlockState state = this.world.getBlockState( this.pos ); - this.getBlockType().neighborChanged( state, this.world, this.pos, state.getBlock(), this.pos ); - } + @Override + public void setOrientation(final EnumFacing inForward, final EnumFacing inUp) { + super.setOrientation(inForward, inUp); + final IBlockState state = this.world.getBlockState(this.pos); + this.getBlockType().neighborChanged(state, this.world, this.pos, state.getBlock(), this.pos); + } - @Override - public IItemHandler getInternalInventory() - { - return this.inv; - } + @Override + public IItemHandler getInternalInventory() { + return this.inv; + } - @Override - protected IItemHandler getItemHandlerForSide( EnumFacing side ) - { - return this.invExt; - } + @Override + protected IItemHandler getItemHandlerForSide(EnumFacing side) { + return this.invExt; + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { - } + } - @Override - public boolean canTurn() - { - if( Platform.isClient() ) - { - return false; - } + @Override + public boolean canTurn() { + if (Platform.isClient()) { + return false; + } - if( this.inv.getStackInSlot( 6 ).isEmpty() ) // Add if there isn't one... - { - for( int x = 0; x < 3; x++ ) - { - ItemStack item = this.inv.getStackInSlot( x ); - if( item.isEmpty() ) - { - continue; - } + if (this.inv.getStackInSlot(6).isEmpty()) // Add if there isn't one... + { + for (int x = 0; x < 3; x++) { + ItemStack item = this.inv.getStackInSlot(x); + if (item.isEmpty()) { + continue; + } - final IGrinderRecipe r = AEApi.instance().registries().grinder().getRecipeForInput( item ); - if( r != null ) - { - if( item.getCount() >= r.getInput().getCount() ) - { - final ItemStack ais = item.copy(); - ais.setCount( r.getInput().getCount() ); - item.shrink( r.getInput().getCount() ); + final IGrinderRecipe r = AEApi.instance().registries().grinder().getRecipeForInput(item); + if (r != null) { + if (item.getCount() >= r.getInput().getCount()) { + final ItemStack ais = item.copy(); + ais.setCount(r.getInput().getCount()); + item.shrink(r.getInput().getCount()); - if( item.getCount() <= 0 ) - { - item = ItemStack.EMPTY; - } + if (item.getCount() <= 0) { + item = ItemStack.EMPTY; + } - this.inv.setStackInSlot( x, item ); - this.inv.setStackInSlot( 6, ais ); - return true; - } - } - } - return false; - } - return true; - } + this.inv.setStackInSlot(x, item); + this.inv.setStackInSlot(6, ais); + return true; + } + } + } + return false; + } + return true; + } - @Override - public void applyTurn() - { - if( Platform.isClient() ) - { - return; - } + @Override + public void applyTurn() { + if (Platform.isClient()) { + return; + } - this.points++; + this.points++; - final ItemStack processing = this.inv.getStackInSlot( 6 ); - final IGrinderRecipe r = AEApi.instance().registries().grinder().getRecipeForInput( processing ); - if( r != null ) - { - if( r.getRequiredTurns() > this.points ) - { - return; - } + final ItemStack processing = this.inv.getStackInSlot(6); + final IGrinderRecipe r = AEApi.instance().registries().grinder().getRecipeForInput(processing); + if (r != null) { + if (r.getRequiredTurns() > this.points) { + return; + } - this.points = 0; - final InventoryAdaptor sia = new AdaptorItemHandler( new RangedWrapper( this.inv, 3, 6 ) ); + this.points = 0; + final InventoryAdaptor sia = new AdaptorItemHandler(new RangedWrapper(this.inv, 3, 6)); - this.addItem( sia, r.getOutput() ); + this.addItem(sia, r.getOutput()); - r.getOptionalOutput().ifPresent( itemStack -> - { - final float chance = ( Platform.getRandomInt() % 2000 ) / 2000.0f; + r.getOptionalOutput().ifPresent(itemStack -> + { + final float chance = (Platform.getRandomInt() % 2000) / 2000.0f; - if( chance <= r.getOptionalChance() ) - { - this.addItem( sia, itemStack ); - } - } ); + if (chance <= r.getOptionalChance()) { + this.addItem(sia, itemStack); + } + }); - r.getSecondOptionalOutput().ifPresent( itemStack -> - { - final float chance = ( Platform.getRandomInt() % 2000 ) / 2000.0f; + r.getSecondOptionalOutput().ifPresent(itemStack -> + { + final float chance = (Platform.getRandomInt() % 2000) / 2000.0f; - if( chance <= r.getSecondOptionalChance() ) - { - this.addItem( sia, itemStack ); - } - } ); + if (chance <= r.getSecondOptionalChance()) { + this.addItem(sia, itemStack); + } + }); - this.inv.setStackInSlot( 6, ItemStack.EMPTY ); - } - } + this.inv.setStackInSlot(6, ItemStack.EMPTY); + } + } - private void addItem( final InventoryAdaptor sia, final ItemStack output ) - { - if( output.isEmpty() ) - { - return; - } + private void addItem(final InventoryAdaptor sia, final ItemStack output) { + if (output.isEmpty()) { + return; + } - final ItemStack notAdded = sia.addItems( output ); - if( !notAdded.isEmpty() ) - { - final List out = new ArrayList<>(); - out.add( notAdded ); + final ItemStack notAdded = sia.addItems(output); + if (!notAdded.isEmpty()) { + final List out = new ArrayList<>(); + out.add(notAdded); - Platform.spawnDrops( this.world, this.pos.offset( this.getForward() ), out ); - } - } + Platform.spawnDrops(this.world, this.pos.offset(this.getForward()), out); + } + } - @Override - public boolean canCrankAttach( final EnumFacing directionToCrank ) - { - return this.getUp() == directionToCrank; - } + @Override + public boolean canCrankAttach(final EnumFacing directionToCrank) { + return this.getUp() == directionToCrank; + } - private class GrinderFilter implements IAEItemFilter - { - @Override - public boolean allowExtract( IItemHandler inv, int slotIndex, int amount ) - { - return slotIndex >= 3 && slotIndex <= 5; - } + private class GrinderFilter implements IAEItemFilter { + @Override + public boolean allowExtract(IItemHandler inv, int slotIndex, int amount) { + return slotIndex >= 3 && slotIndex <= 5; + } - @Override - public boolean allowInsert( IItemHandler inv, int slotIndex, ItemStack stack ) - { - if( AEApi.instance().registries().grinder().getRecipeForInput( stack ) == null ) - { - return false; - } + @Override + public boolean allowInsert(IItemHandler inv, int slotIndex, ItemStack stack) { + if (AEApi.instance().registries().grinder().getRecipeForInput(stack) == null) { + return false; + } - return slotIndex >= 0 && slotIndex <= 2; - } - } + return slotIndex >= 0 && slotIndex <= 2; + } + } } diff --git a/src/main/java/appeng/tile/inventory/AppEngCellInventory.java b/src/main/java/appeng/tile/inventory/AppEngCellInventory.java index 1dff4422c..8baa84bf2 100644 --- a/src/main/java/appeng/tile/inventory/AppEngCellInventory.java +++ b/src/main/java/appeng/tile/inventory/AppEngCellInventory.java @@ -1,118 +1,97 @@ - package appeng.tile.inventory; -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandlerModifiable; - import appeng.api.storage.ICellInventory; import appeng.api.storage.ICellInventoryHandler; import appeng.util.inv.IAEAppEngInventory; import appeng.util.inv.filter.IAEItemFilter; +import net.minecraft.item.ItemStack; +import net.minecraftforge.items.IItemHandlerModifiable; -public class AppEngCellInventory implements IItemHandlerModifiable -{ - private final AppEngInternalInventory inv; - private final ICellInventoryHandler handlerForSlot[]; +public class AppEngCellInventory implements IItemHandlerModifiable { + private final AppEngInternalInventory inv; + private final ICellInventoryHandler[] handlerForSlot; - public AppEngCellInventory( final IAEAppEngInventory host, final int slots ) - { - this.inv = new AppEngInternalInventory( host, slots, 1 ); - this.handlerForSlot = new ICellInventoryHandler[slots]; - } + public AppEngCellInventory(final IAEAppEngInventory host, final int slots) { + this.inv = new AppEngInternalInventory(host, slots, 1); + this.handlerForSlot = new ICellInventoryHandler[slots]; + } - public void setHandler( final int slot, final ICellInventoryHandler handler ) - { - this.handlerForSlot[slot] = handler; - } + public void setHandler(final int slot, final ICellInventoryHandler handler) { + this.handlerForSlot[slot] = handler; + } - public void setFilter( IAEItemFilter filter ) - { - this.inv.setFilter( filter ); - } + public void setFilter(IAEItemFilter filter) { + this.inv.setFilter(filter); + } - @Override - public void setStackInSlot( int slot, ItemStack stack ) - { - this.persist( slot ); - this.inv.setStackInSlot( slot, stack ); - this.cleanup( slot ); - } + @Override + public void setStackInSlot(int slot, ItemStack stack) { + this.persist(slot); + this.inv.setStackInSlot(slot, stack); + this.cleanup(slot); + } - @Override - public int getSlots() - { - return this.inv.getSlots(); - } + @Override + public int getSlots() { + return this.inv.getSlots(); + } - @Override - public ItemStack getStackInSlot( int slot ) - { - this.persist( slot ); - return this.inv.getStackInSlot( slot ); - } + @Override + public ItemStack getStackInSlot(int slot) { + this.persist(slot); + return this.inv.getStackInSlot(slot); + } - @Override - public ItemStack insertItem( int slot, ItemStack stack, boolean simulate ) - { - this.persist( slot ); - final ItemStack ret = this.inv.insertItem( slot, stack, simulate ); - this.cleanup( slot ); - return ret; - } + @Override + public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { + this.persist(slot); + final ItemStack ret = this.inv.insertItem(slot, stack, simulate); + this.cleanup(slot); + return ret; + } - @Override - public ItemStack extractItem( int slot, int amount, boolean simulate ) - { - this.persist( slot ); - final ItemStack ret = this.inv.extractItem( slot, amount, simulate ); - this.cleanup( slot ); - return ret; - } + @Override + public ItemStack extractItem(int slot, int amount, boolean simulate) { + this.persist(slot); + final ItemStack ret = this.inv.extractItem(slot, amount, simulate); + this.cleanup(slot); + return ret; + } - @Override - public int getSlotLimit( int slot ) - { - return this.inv.getSlotLimit( slot ); - } + @Override + public int getSlotLimit(int slot) { + return this.inv.getSlotLimit(slot); + } - @Override - public boolean isItemValid( int slot, ItemStack stack ) - { - return this.inv.isItemValid( slot, stack ); - } + @Override + public boolean isItemValid(int slot, ItemStack stack) { + return this.inv.isItemValid(slot, stack); + } - public void persist() - { - for( int i = 0; i < this.getSlots(); ++i ) - { - this.persist( i ); - } - } + public void persist() { + for (int i = 0; i < this.getSlots(); ++i) { + this.persist(i); + } + } - private void persist( int slot ) - { - if( this.handlerForSlot[slot] != null ) - { - final ICellInventory ci = this.handlerForSlot[slot].getCellInv(); - if( ci != null ) - { - ci.persist(); - } - } - } + private void persist(int slot) { + if (this.handlerForSlot[slot] != null) { + final ICellInventory ci = this.handlerForSlot[slot].getCellInv(); + if (ci != null) { + ci.persist(); + } + } + } - private void cleanup( int slot ) - { - if( this.handlerForSlot[slot] != null ) - { - final ICellInventory ci = this.handlerForSlot[slot].getCellInv(); + private void cleanup(int slot) { + if (this.handlerForSlot[slot] != null) { + final ICellInventory ci = this.handlerForSlot[slot].getCellInv(); - if( ci == null || ci.getItemStack() != this.inv.getStackInSlot( slot ) ) - { - this.handlerForSlot[slot] = null; - } - } - } + if (ci == null || ci.getItemStack() != this.inv.getStackInSlot(slot)) { + this.handlerForSlot[slot] = null; + } + } + } } diff --git a/src/main/java/appeng/tile/inventory/AppEngInternalAEInventory.java b/src/main/java/appeng/tile/inventory/AppEngInternalAEInventory.java index f2e7adc43..d799912a4 100644 --- a/src/main/java/appeng/tile/inventory/AppEngInternalAEInventory.java +++ b/src/main/java/appeng/tile/inventory/AppEngInternalAEInventory.java @@ -19,15 +19,6 @@ package appeng.tile.inventory; -import java.util.Iterator; - -import javax.annotation.Nonnull; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.items.IItemHandlerModifiable; -import net.minecraftforge.items.ItemHandlerHelper; - import appeng.api.AEApi; import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEItemStack; @@ -38,251 +29,207 @@ import appeng.util.inv.InvOperation; import appeng.util.item.AEItemStack; import appeng.util.iterators.AEInvIterator; import appeng.util.iterators.InvIterator; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.items.IItemHandlerModifiable; +import net.minecraftforge.items.ItemHandlerHelper; + +import javax.annotation.Nonnull; +import java.util.Iterator; -public class AppEngInternalAEInventory implements IItemHandlerModifiable, Iterable -{ - private final IAEAppEngInventory te; - private final IAEItemStack[] inv; - private final int size; - private int maxStack; - private boolean dirtyFlag = false; +public class AppEngInternalAEInventory implements IItemHandlerModifiable, Iterable { + private final IAEAppEngInventory te; + private final IAEItemStack[] inv; + private final int size; + private int maxStack; + private boolean dirtyFlag = false; - public AppEngInternalAEInventory( final IAEAppEngInventory te, final int s ) - { - this.te = te; - this.size = s; - this.maxStack = 64; - this.inv = new IAEItemStack[s]; - } + public AppEngInternalAEInventory(final IAEAppEngInventory te, final int s) { + this.te = te; + this.size = s; + this.maxStack = 64; + this.inv = new IAEItemStack[s]; + } - public void setMaxStackSize( final int s ) - { - this.maxStack = s; - } + public void setMaxStackSize(final int s) { + this.maxStack = s; + } - public IAEItemStack getAEStackInSlot( final int var1 ) - { - return this.inv[var1]; - } + public IAEItemStack getAEStackInSlot(final int var1) { + return this.inv[var1]; + } - public void writeToNBT( final NBTTagCompound data, final String name ) - { - final NBTTagCompound c = new NBTTagCompound(); - this.writeToNBT( c ); - data.setTag( name, c ); - } + public void writeToNBT(final NBTTagCompound data, final String name) { + final NBTTagCompound c = new NBTTagCompound(); + this.writeToNBT(c); + data.setTag(name, c); + } - private void writeToNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.size; x++ ) - { - try - { - final NBTTagCompound c = new NBTTagCompound(); + private void writeToNBT(final NBTTagCompound target) { + for (int x = 0; x < this.size; x++) { + try { + final NBTTagCompound c = new NBTTagCompound(); - if( this.inv[x] != null ) - { - this.inv[x].writeToNBT( c ); - } + if (this.inv[x] != null) { + this.inv[x].writeToNBT(c); + } - target.setTag( "#" + x, c ); - } - catch( final Exception ignored ) - { - } - } - } + target.setTag("#" + x, c); + } catch (final Exception ignored) { + } + } + } - public void readFromNBT( final NBTTagCompound data, final String name ) - { - final NBTTagCompound c = data.getCompoundTag( name ); - if( c != null ) - { - this.readFromNBT( c ); - } - } + public void readFromNBT(final NBTTagCompound data, final String name) { + final NBTTagCompound c = data.getCompoundTag(name); + if (c != null) { + this.readFromNBT(c); + } + } - private void readFromNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.size; x++ ) - { - try - { - final NBTTagCompound c = target.getCompoundTag( "#" + x ); + private void readFromNBT(final NBTTagCompound target) { + for (int x = 0; x < this.size; x++) { + try { + final NBTTagCompound c = target.getCompoundTag("#" + x); - if( c != null ) - { - this.inv[x] = AEItemStack.fromNBT( c ); - } - } - catch( final Exception e ) - { - AELog.debug( e ); - } - } - } + if (c != null) { + this.inv[x] = AEItemStack.fromNBT(c); + } + } catch (final Exception e) { + AELog.debug(e); + } + } + } - protected int getStackLimit( int slot, @Nonnull ItemStack stack ) - { - return Math.min( this.getSlotLimit( slot ), stack.getMaxStackSize() ); - } + protected int getStackLimit(int slot, @Nonnull ItemStack stack) { + return Math.min(this.getSlotLimit(slot), stack.getMaxStackSize()); + } - @Override - public int getSlots() - { - return this.size; - } + @Override + public int getSlots() { + return this.size; + } - @Override - public ItemStack getStackInSlot( final int var1 ) - { - if( this.inv[var1] == null ) - { - return ItemStack.EMPTY; - } + @Override + public ItemStack getStackInSlot(final int var1) { + if (this.inv[var1] == null) { + return ItemStack.EMPTY; + } - return this.inv[var1].createItemStack(); - } + return this.inv[var1].createItemStack(); + } - @Override - public ItemStack insertItem( int slot, ItemStack stack, boolean simulate ) - { - if( stack.isEmpty() ) - { - return ItemStack.EMPTY; - } + @Override + public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { + if (stack.isEmpty()) { + return ItemStack.EMPTY; + } - ItemStack existing = this.getStackInSlot( slot ); - int limit = this.getStackLimit( slot, stack ); + ItemStack existing = this.getStackInSlot(slot); + int limit = this.getStackLimit(slot, stack); - if( !existing.isEmpty() ) - { - if( !ItemHandlerHelper.canItemStacksStack( stack, existing ) ) - { - return stack; - } + if (!existing.isEmpty()) { + if (!ItemHandlerHelper.canItemStacksStack(stack, existing)) { + return stack; + } - limit -= existing.getCount(); - } + limit -= existing.getCount(); + } - if( limit <= 0 ) - { - return stack; - } + if (limit <= 0) { + return stack; + } - boolean reachedLimit = stack.getCount() > limit; + boolean reachedLimit = stack.getCount() > limit; - if( !simulate ) - { - if( existing.isEmpty() ) - { - this.inv[slot] = AEApi.instance() - .storage() - .getStorageChannel( IItemStorageChannel.class ) - .createStack( - reachedLimit ? ItemHandlerHelper.copyStackWithSize( stack, limit ) : stack ); - } - else - { - existing.grow( reachedLimit ? limit : stack.getCount() ); - } - this.fireOnChangeInventory( slot, InvOperation.INSERT, ItemStack.EMPTY, - reachedLimit ? ItemHandlerHelper.copyStackWithSize( stack, limit ) : stack ); - } - return reachedLimit ? ItemHandlerHelper.copyStackWithSize( stack, stack.getCount() - limit ) : ItemStack.EMPTY; - } + if (!simulate) { + if (existing.isEmpty()) { + this.inv[slot] = AEApi.instance() + .storage() + .getStorageChannel(IItemStorageChannel.class) + .createStack( + reachedLimit ? ItemHandlerHelper.copyStackWithSize(stack, limit) : stack); + } else { + existing.grow(reachedLimit ? limit : stack.getCount()); + } + this.fireOnChangeInventory(slot, InvOperation.INSERT, ItemStack.EMPTY, + reachedLimit ? ItemHandlerHelper.copyStackWithSize(stack, limit) : stack); + } + return reachedLimit ? ItemHandlerHelper.copyStackWithSize(stack, stack.getCount() - limit) : ItemStack.EMPTY; + } - @Override - public ItemStack extractItem( int slot, int amount, boolean simulate ) - { - if( this.inv[slot] != null ) - { - final ItemStack split = this.getStackInSlot( slot ); + @Override + public ItemStack extractItem(int slot, int amount, boolean simulate) { + if (this.inv[slot] != null) { + final ItemStack split = this.getStackInSlot(slot); - if( amount >= split.getCount() ) - { - if( !simulate ) - { - this.inv[slot] = null; - this.fireOnChangeInventory( slot, InvOperation.EXTRACT, split, ItemStack.EMPTY ); - } - return split; - } - else - { - if( !simulate ) - { - split.grow( -amount ); - this.fireOnChangeInventory( slot, InvOperation.EXTRACT, ItemHandlerHelper.copyStackWithSize( split, amount ), ItemStack.EMPTY ); - } - return ItemHandlerHelper.copyStackWithSize( split, amount ); - } - } - return ItemStack.EMPTY; - } + if (amount >= split.getCount()) { + if (!simulate) { + this.inv[slot] = null; + this.fireOnChangeInventory(slot, InvOperation.EXTRACT, split, ItemStack.EMPTY); + } + return split; + } else { + if (!simulate) { + split.grow(-amount); + this.fireOnChangeInventory(slot, InvOperation.EXTRACT, ItemHandlerHelper.copyStackWithSize(split, amount), ItemStack.EMPTY); + } + return ItemHandlerHelper.copyStackWithSize(split, amount); + } + } + return ItemStack.EMPTY; + } - @Override - public void setStackInSlot( final int slot, final ItemStack newItemStack ) - { - ItemStack oldStack = this.getStackInSlot( slot ).copy(); - this.inv[slot] = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( newItemStack ); + @Override + public void setStackInSlot(final int slot, final ItemStack newItemStack) { + ItemStack oldStack = this.getStackInSlot(slot).copy(); + this.inv[slot] = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createStack(newItemStack); - if( this.te != null && Platform.isServer() ) - { - ItemStack newStack = newItemStack.copy(); - InvOperation op = InvOperation.SET; + if (this.te != null && Platform.isServer()) { + ItemStack newStack = newItemStack.copy(); + InvOperation op = InvOperation.SET; - if( ItemStack.areItemsEqual( oldStack, newStack ) ) - { - if( newStack.getCount() > oldStack.getCount() ) - { - newStack.shrink( oldStack.getCount() ); - oldStack = ItemStack.EMPTY; - op = InvOperation.INSERT; - } - else - { - oldStack.shrink( newStack.getCount() ); - newStack = ItemStack.EMPTY; - op = InvOperation.EXTRACT; - } - } - this.fireOnChangeInventory( slot, op, oldStack, newStack ); - } - } + if (ItemStack.areItemsEqual(oldStack, newStack)) { + if (newStack.getCount() > oldStack.getCount()) { + newStack.shrink(oldStack.getCount()); + oldStack = ItemStack.EMPTY; + op = InvOperation.INSERT; + } else { + oldStack.shrink(newStack.getCount()); + newStack = ItemStack.EMPTY; + op = InvOperation.EXTRACT; + } + } + this.fireOnChangeInventory(slot, op, oldStack, newStack); + } + } - private void fireOnChangeInventory( int slot, InvOperation op, ItemStack removed, ItemStack inserted ) - { - if( this.te != null && Platform.isServer() && !this.dirtyFlag ) - { - this.dirtyFlag = true; - this.te.onChangeInventory( this, slot, op, removed, inserted ); - this.te.saveChanges(); - this.dirtyFlag = false; - } - } + private void fireOnChangeInventory(int slot, InvOperation op, ItemStack removed, ItemStack inserted) { + if (this.te != null && Platform.isServer() && !this.dirtyFlag) { + this.dirtyFlag = true; + this.te.onChangeInventory(this, slot, op, removed, inserted); + this.te.saveChanges(); + this.dirtyFlag = false; + } + } - @Override - public int getSlotLimit( int slot ) - { - return this.maxStack > 64 ? 64 : this.maxStack; - } + @Override + public int getSlotLimit(int slot) { + return this.maxStack > 64 ? 64 : this.maxStack; + } - @Override - public Iterator iterator() - { - return new InvIterator( this ); - } + @Override + public Iterator iterator() { + return new InvIterator(this); + } - public Iterator getNewAEIterator() - { - return new AEInvIterator( this ); - } + public Iterator getNewAEIterator() { + return new AEInvIterator(this); + } - @Override - public boolean isItemValid( int slot, ItemStack stack ) - { - return true; - } + @Override + public boolean isItemValid(int slot, ItemStack stack) { + return true; + } } diff --git a/src/main/java/appeng/tile/inventory/AppEngInternalInventory.java b/src/main/java/appeng/tile/inventory/AppEngInternalInventory.java index f228f858e..a98227a88 100644 --- a/src/main/java/appeng/tile/inventory/AppEngInternalInventory.java +++ b/src/main/java/appeng/tile/inventory/AppEngInternalInventory.java @@ -19,204 +19,168 @@ package appeng.tile.inventory; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; - -import javax.annotation.Nonnull; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.items.ItemStackHandler; - import appeng.util.Platform; import appeng.util.inv.IAEAppEngInventory; import appeng.util.inv.InvOperation; import appeng.util.inv.filter.IAEItemFilter; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.items.ItemStackHandler; + +import javax.annotation.Nonnull; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; -public class AppEngInternalInventory extends ItemStackHandler implements Iterable -{ - private boolean enableClientEvents = false; - private IAEAppEngInventory te; - private final int[] maxStack; - private ItemStack previousStack = ItemStack.EMPTY; - private IAEItemFilter filter; - private boolean dirtyFlag = false; +public class AppEngInternalInventory extends ItemStackHandler implements Iterable { + private boolean enableClientEvents = false; + private IAEAppEngInventory te; + private final int[] maxStack; + private ItemStack previousStack = ItemStack.EMPTY; + private IAEItemFilter filter; + private boolean dirtyFlag = false; - public AppEngInternalInventory( final IAEAppEngInventory inventory, final int size, final int maxStack, IAEItemFilter filter ) - { - super( size ); - this.setTileEntity( inventory ); - this.setFilter( filter ); - this.maxStack = new int[size]; - Arrays.fill( this.maxStack, maxStack ); - } + public AppEngInternalInventory(final IAEAppEngInventory inventory, final int size, final int maxStack, IAEItemFilter filter) { + super(size); + this.setTileEntity(inventory); + this.setFilter(filter); + this.maxStack = new int[size]; + Arrays.fill(this.maxStack, maxStack); + } - public AppEngInternalInventory( final IAEAppEngInventory inventory, final int size, final int maxStack ) - { - this( inventory, size, maxStack, null ); - } + public AppEngInternalInventory(final IAEAppEngInventory inventory, final int size, final int maxStack) { + this(inventory, size, maxStack, null); + } - public AppEngInternalInventory( final IAEAppEngInventory inventory, final int size ) - { - this( inventory, size, 64 ); - } + public AppEngInternalInventory(final IAEAppEngInventory inventory, final int size) { + this(inventory, size, 64); + } - public void setFilter( IAEItemFilter filter ) - { - this.filter = filter; - } + public void setFilter(IAEItemFilter filter) { + this.filter = filter; + } - @Override - public int getSlotLimit( int slot ) - { - return this.maxStack[slot]; - } + @Override + public int getSlotLimit(int slot) { + return this.maxStack[slot]; + } - @Override - public void setStackInSlot( int slot, @Nonnull ItemStack stack ) - { - if( stack != this.getStackInSlot( slot ) ) - { - this.previousStack = this.getStackInSlot( slot ).copy(); - } - super.setStackInSlot( slot, stack ); - } + @Override + public void setStackInSlot(int slot, @Nonnull ItemStack stack) { + if (stack != this.getStackInSlot(slot)) { + this.previousStack = this.getStackInSlot(slot).copy(); + } + super.setStackInSlot(slot, stack); + } - @Override - @Nonnull - public ItemStack insertItem( int slot, @Nonnull ItemStack stack, boolean simulate ) - { - if( this.filter != null && !this.filter.allowInsert( this, slot, stack ) ) - { - return stack; - } + @Override + @Nonnull + public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) { + if (this.filter != null && !this.filter.allowInsert(this, slot, stack)) { + return stack; + } - if( !simulate ) - { - this.previousStack = this.getStackInSlot( slot ).copy(); - } - return super.insertItem( slot, stack, simulate ); - } + if (!simulate) { + this.previousStack = this.getStackInSlot(slot).copy(); + } + return super.insertItem(slot, stack, simulate); + } - @Override - @Nonnull - public ItemStack extractItem( int slot, int amount, boolean simulate ) - { - if( this.filter != null && !this.filter.allowExtract( this, slot, amount ) ) - { - return ItemStack.EMPTY; - } + @Override + @Nonnull + public ItemStack extractItem(int slot, int amount, boolean simulate) { + if (this.filter != null && !this.filter.allowExtract(this, slot, amount)) { + return ItemStack.EMPTY; + } - if( !simulate ) - { - this.previousStack = this.getStackInSlot( slot ).copy(); - } - return super.extractItem( slot, amount, simulate ); - } + if (!simulate) { + this.previousStack = this.getStackInSlot(slot).copy(); + } + return super.extractItem(slot, amount, simulate); + } - @Override - protected void onContentsChanged( int slot ) - { - if( this.getTileEntity() != null && this.eventsEnabled() && !this.dirtyFlag ) - { - this.dirtyFlag = true; - ItemStack newStack = this.getStackInSlot( slot ); - ItemStack oldStack = this.previousStack; - InvOperation op = InvOperation.SET; + @Override + protected void onContentsChanged(int slot) { + if (this.getTileEntity() != null && this.eventsEnabled() && !this.dirtyFlag) { + this.dirtyFlag = true; + ItemStack newStack = this.getStackInSlot(slot); + ItemStack oldStack = this.previousStack; + InvOperation op = InvOperation.SET; - if( newStack.isEmpty() || oldStack.isEmpty() || oldStack.getCount() != newStack.getCount() && ItemStack.areItemsEqual( newStack, oldStack ) ) - { - if( newStack.getCount() > oldStack.getCount() ) - { - newStack = newStack.copy(); - newStack.shrink( oldStack.getCount() ); - oldStack = ItemStack.EMPTY; - op = InvOperation.INSERT; - } - else - { - oldStack.shrink( newStack.getCount() ); - newStack = ItemStack.EMPTY; - op = InvOperation.EXTRACT; - } - } + if (newStack.isEmpty() || oldStack.isEmpty() || oldStack.getCount() != newStack.getCount() && ItemStack.areItemsEqual(newStack, oldStack)) { + if (newStack.getCount() > oldStack.getCount()) { + newStack = newStack.copy(); + newStack.shrink(oldStack.getCount()); + oldStack = ItemStack.EMPTY; + op = InvOperation.INSERT; + } else { + oldStack.shrink(newStack.getCount()); + newStack = ItemStack.EMPTY; + op = InvOperation.EXTRACT; + } + } - this.getTileEntity().onChangeInventory( this, slot, op, oldStack, newStack ); - this.getTileEntity().saveChanges(); - this.previousStack = ItemStack.EMPTY; - this.dirtyFlag = false; - } - super.onContentsChanged( slot ); - } + this.getTileEntity().onChangeInventory(this, slot, op, oldStack, newStack); + this.getTileEntity().saveChanges(); + this.previousStack = ItemStack.EMPTY; + this.dirtyFlag = false; + } + super.onContentsChanged(slot); + } - protected boolean eventsEnabled() - { - return Platform.isServer() || this.isEnableClientEvents(); - } + protected boolean eventsEnabled() { + return Platform.isServer() || this.isEnableClientEvents(); + } - public void setMaxStackSize( final int slot, final int size ) - { - this.maxStack[slot] = size; - } + public void setMaxStackSize(final int slot, final int size) { + this.maxStack[slot] = size; + } - @Override - public boolean isItemValid( int slot, ItemStack stack ) - { - if( this.maxStack[slot] == 0 ) - { - return false; - } - if( this.filter != null ) - { - return this.filter.allowInsert( this, slot, stack ); - } - return true; - } + @Override + public boolean isItemValid(int slot, ItemStack stack) { + if (this.maxStack[slot] == 0) { + return false; + } + if (this.filter != null) { + return this.filter.allowInsert(this, slot, stack); + } + return true; + } - public void writeToNBT( final NBTTagCompound data, final String name ) - { - data.setTag( name, this.serializeNBT() ); - } + public void writeToNBT(final NBTTagCompound data, final String name) { + data.setTag(name, this.serializeNBT()); + } - public void readFromNBT( final NBTTagCompound data, final String name ) - { - final NBTTagCompound c = data.getCompoundTag( name ); - if( c != null ) - { - this.readFromNBT( c ); - } - } + public void readFromNBT(final NBTTagCompound data, final String name) { + final NBTTagCompound c = data.getCompoundTag(name); + if (c != null) { + this.readFromNBT(c); + } + } - public void readFromNBT( final NBTTagCompound data ) - { - this.deserializeNBT( data ); - } + public void readFromNBT(final NBTTagCompound data) { + this.deserializeNBT(data); + } - @Override - public Iterator iterator() - { - return Collections.unmodifiableList( super.stacks ).iterator(); - } + @Override + public Iterator iterator() { + return Collections.unmodifiableList(super.stacks).iterator(); + } - private boolean isEnableClientEvents() - { - return this.enableClientEvents; - } + private boolean isEnableClientEvents() { + return this.enableClientEvents; + } - public void setEnableClientEvents( final boolean enableClientEvents ) - { - this.enableClientEvents = enableClientEvents; - } + public void setEnableClientEvents(final boolean enableClientEvents) { + this.enableClientEvents = enableClientEvents; + } - public IAEAppEngInventory getTileEntity() - { - return this.te; - } + public IAEAppEngInventory getTileEntity() { + return this.te; + } - public void setTileEntity( final IAEAppEngInventory te ) - { - this.te = te; - } + public void setTileEntity(final IAEAppEngInventory te) { + this.te = te; + } } diff --git a/src/main/java/appeng/tile/misc/CondenserItemInventory.java b/src/main/java/appeng/tile/misc/CondenserItemInventory.java index d9b121a3b..5f7c3c753 100644 --- a/src/main/java/appeng/tile/misc/CondenserItemInventory.java +++ b/src/main/java/appeng/tile/misc/CondenserItemInventory.java @@ -19,12 +19,6 @@ package appeng.tile.misc; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -40,166 +34,142 @@ import appeng.me.helpers.BaseActionSource; import appeng.me.storage.ITickingMonitor; import appeng.util.item.AEItemStack; import appeng.util.item.ItemList; +import net.minecraft.item.ItemStack; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; -class CondenserItemInventory implements IMEMonitor, ITickingMonitor -{ - private final HashMap, Object> listeners = new HashMap<>(); - private final TileCondenser target; - private boolean hasChanged = true; - private final ItemList cachedList = new ItemList(); - private IActionSource actionSource = new BaseActionSource(); - private ItemList changeSet = new ItemList(); +class CondenserItemInventory implements IMEMonitor, ITickingMonitor { + private final HashMap, Object> listeners = new HashMap<>(); + private final TileCondenser target; + private boolean hasChanged = true; + private final ItemList cachedList = new ItemList(); + private IActionSource actionSource = new BaseActionSource(); + private ItemList changeSet = new ItemList(); - CondenserItemInventory( final TileCondenser te ) - { - this.target = te; - } + CondenserItemInventory(final TileCondenser te) { + this.target = te; + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final IActionSource src ) - { - if( mode == Actionable.MODULATE && input != null ) - { - this.target.addPower( input.getStackSize() ); - } - return null; - } + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, final IActionSource src) { + if (mode == Actionable.MODULATE && input != null) { + this.target.addPower(input.getStackSize()); + } + return null; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final IActionSource src ) - { - AEItemStack ret = null; - ItemStack slotItem = this.target.getOutputSlot().getStackInSlot( 0 ); - if( !slotItem.isEmpty() && request.isSameType( slotItem ) ) - { - int count = (int) Math.min( request.getStackSize(), Integer.MAX_VALUE ); - ret = AEItemStack.fromItemStack( this.target.getOutputSlot().extractItem( 0, count, mode == Actionable.SIMULATE ) ); - } - return ret; - } + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final IActionSource src) { + AEItemStack ret = null; + ItemStack slotItem = this.target.getOutputSlot().getStackInSlot(0); + if (!slotItem.isEmpty() && request.isSameType(slotItem)) { + int count = (int) Math.min(request.getStackSize(), Integer.MAX_VALUE); + ret = AEItemStack.fromItemStack(this.target.getOutputSlot().extractItem(0, count, mode == Actionable.SIMULATE)); + } + return ret; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - if( !this.target.getOutputSlot().getStackInSlot( 0 ).isEmpty() ) - { - out.add( AEItemStack.fromItemStack( this.target.getOutputSlot().getStackInSlot( 0 ) ) ); - } - return out; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + if (!this.target.getOutputSlot().getStackInSlot(0).isEmpty()) { + out.add(AEItemStack.fromItemStack(this.target.getOutputSlot().getStackInSlot(0))); + } + return out; + } - @Override - public IItemList getStorageList() - { - if( this.hasChanged ) - { - this.hasChanged = false; - this.cachedList.resetStatus(); - return this.getAvailableItems( this.cachedList ); - } - return this.cachedList; - } + @Override + public IItemList getStorageList() { + if (this.hasChanged) { + this.hasChanged = false; + this.cachedList.resetStatus(); + return this.getAvailableItems(this.cachedList); + } + return this.cachedList; + } - @Override - public IStorageChannel getChannel() - { - return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - return false; - } + @Override + public boolean isPrioritized(final IAEItemStack input) { + return false; + } - @Override - public boolean canAccept( final IAEItemStack input ) - { - return true; - } + @Override + public boolean canAccept(final IAEItemStack input) { + return true; + } - @Override - public int getPriority() - { - return 0; - } + @Override + public int getPriority() { + return 0; + } - @Override - public int getSlot() - { - return 0; - } + @Override + public int getSlot() { + return 0; + } - @Override - public boolean validForPass( final int i ) - { - return i == 2; - } + @Override + public boolean validForPass(final int i) { + return i == 2; + } - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } - public void updateOutput( ItemStack added, ItemStack removed ) - { - this.hasChanged = true; - if( !added.isEmpty() ) - { - this.changeSet.add( AEItemStack.fromItemStack( added ) ); - } - if( !removed.isEmpty() ) - { - this.changeSet.add( AEItemStack.fromItemStack( removed ).setStackSize( -removed.getCount() ) ); - } - } + public void updateOutput(ItemStack added, ItemStack removed) { + this.hasChanged = true; + if (!added.isEmpty()) { + this.changeSet.add(AEItemStack.fromItemStack(added)); + } + if (!removed.isEmpty()) { + this.changeSet.add(AEItemStack.fromItemStack(removed).setStackSize(-removed.getCount())); + } + } - @Override - public TickRateModulation onTick() - { - final ItemList currentChanges = this.changeSet; + @Override + public TickRateModulation onTick() { + final ItemList currentChanges = this.changeSet; - if( currentChanges.isEmpty() ) - { - return TickRateModulation.IDLE; - } + if (currentChanges.isEmpty()) { + return TickRateModulation.IDLE; + } - this.changeSet = new ItemList(); - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while( i.hasNext() ) - { - final Entry, Object> l = i.next(); - final IMEMonitorHandlerReceiver key = l.getKey(); - if( key.isValid( l.getValue() ) ) - { - key.postChange( this, currentChanges, this.actionSource ); - } - else - { - i.remove(); - } - } + this.changeSet = new ItemList(); + final Iterator, Object>> i = this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Entry, Object> l = i.next(); + final IMEMonitorHandlerReceiver key = l.getKey(); + if (key.isValid(l.getValue())) { + key.postChange(this, currentChanges, this.actionSource); + } else { + i.remove(); + } + } - return TickRateModulation.URGENT; - } + return TickRateModulation.URGENT; + } - @Override - public void setActionSource( IActionSource actionSource ) - { - this.actionSource = actionSource; - } + @Override + public void setActionSource(IActionSource actionSource) { + this.actionSource = actionSource; + } } diff --git a/src/main/java/appeng/tile/misc/CondenserVoidInventory.java b/src/main/java/appeng/tile/misc/CondenserVoidInventory.java index 2f833c309..21fb9d9f2 100644 --- a/src/main/java/appeng/tile/misc/CondenserVoidInventory.java +++ b/src/main/java/appeng/tile/misc/CondenserVoidInventory.java @@ -29,102 +29,85 @@ import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; -class CondenserVoidInventory> implements IMEMonitor -{ +class CondenserVoidInventory> implements IMEMonitor { - private final TileCondenser target; - private final IStorageChannel channel; + private final TileCondenser target; + private final IStorageChannel channel; - CondenserVoidInventory( final TileCondenser te, final IStorageChannel channel ) - { - this.target = te; - this.channel = channel; - } + CondenserVoidInventory(final TileCondenser te, final IStorageChannel channel) { + this.target = te; + this.channel = channel; + } - @Override - public T injectItems( final T input, final Actionable mode, final IActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - return null; - } + @Override + public T injectItems(final T input, final Actionable mode, final IActionSource src) { + if (mode == Actionable.SIMULATE) { + return null; + } - if( input != null ) - { - this.target.addPower( input.getStackSize() / (double) this.channel.transferFactor() ); - } - return null; - } + if (input != null) { + this.target.addPower(input.getStackSize() / (double) this.channel.transferFactor()); + } + return null; + } - @Override - public T extractItems( final T request, final Actionable mode, final IActionSource src ) - { - return null; - } + @Override + public T extractItems(final T request, final Actionable mode, final IActionSource src) { + return null; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return out; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return out; + } - @Override - public IItemList getStorageList() - { - return this.channel.createList(); - } + @Override + public IItemList getStorageList() { + return this.channel.createList(); + } - @Override - public IStorageChannel getChannel() - { - return this.channel; - } + @Override + public IStorageChannel getChannel() { + return this.channel; + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.WRITE; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.WRITE; + } - @Override - public boolean isPrioritized( final T input ) - { - return false; - } + @Override + public boolean isPrioritized(final T input) { + return false; + } - @Override - public boolean canAccept( final T input ) - { - return true; - } + @Override + public boolean canAccept(final T input) { + return true; + } - @Override - public int getPriority() - { - return 0; - } + @Override + public int getPriority() { + return 0; + } - @Override - public int getSlot() - { - return 0; - } + @Override + public int getSlot() { + return 0; + } - @Override - public boolean validForPass( final int i ) - { - return i == 2; - } + @Override + public boolean validForPass(final int i) { + return i == 2; + } - @Override - public void addListener( IMEMonitorHandlerReceiver l, Object verificationToken ) - { - // Not implemented since the Condenser automatically voids everything, and there are no updates - } + @Override + public void addListener(IMEMonitorHandlerReceiver l, Object verificationToken) { + // Not implemented since the Condenser automatically voids everything, and there are no updates + } - @Override - public void removeListener( IMEMonitorHandlerReceiver l ) - { - // Not implemented since we don't remember registered listeners anyway - } + @Override + public void removeListener(IMEMonitorHandlerReceiver l) { + // Not implemented since we don't remember registered listeners anyway + } } diff --git a/src/main/java/appeng/tile/misc/TileCellWorkbench.java b/src/main/java/appeng/tile/misc/TileCellWorkbench.java index 8e102df0f..38142138a 100644 --- a/src/main/java/appeng/tile/misc/TileCellWorkbench.java +++ b/src/main/java/appeng/tile/misc/TileCellWorkbench.java @@ -19,14 +19,6 @@ package appeng.tile.misc; -import java.util.List; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.CopyMode; import appeng.api.config.Settings; import appeng.api.config.Upgrades; @@ -41,216 +33,183 @@ import appeng.util.IConfigManagerHost; import appeng.util.helpers.ItemHandlerUtil; import appeng.util.inv.IAEAppEngInventory; import appeng.util.inv.InvOperation; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.items.IItemHandler; + +import java.util.List; -public class TileCellWorkbench extends AEBaseTile implements IUpgradeableHost, IAEAppEngInventory, IConfigManagerHost -{ +public class TileCellWorkbench extends AEBaseTile implements IUpgradeableHost, IAEAppEngInventory, IConfigManagerHost { - private final AppEngInternalInventory cell = new AppEngInternalInventory( this, 1 ); - private final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, 63 ); - private final ConfigManager manager = new ConfigManager( this ); + private final AppEngInternalInventory cell = new AppEngInternalInventory(this, 1); + private final AppEngInternalAEInventory config = new AppEngInternalAEInventory(this, 63); + private final ConfigManager manager = new ConfigManager(this); - private IItemHandler cacheUpgrades = null; - private IItemHandler cacheConfig = null; - private boolean locked = false; + private IItemHandler cacheUpgrades = null; + private IItemHandler cacheConfig = null; + private boolean locked = false; - public TileCellWorkbench() - { - this.manager.registerSetting( Settings.COPY_MODE, CopyMode.CLEAR_ON_REMOVE ); - this.cell.setEnableClientEvents( true ); - } + public TileCellWorkbench() { + this.manager.registerSetting(Settings.COPY_MODE, CopyMode.CLEAR_ON_REMOVE); + this.cell.setEnableClientEvents(true); + } - public IItemHandler getCellUpgradeInventory() - { - if( this.cacheUpgrades == null ) - { - final ICellWorkbenchItem cell = this.getCell(); - if( cell == null ) - { - return null; - } + public IItemHandler getCellUpgradeInventory() { + if (this.cacheUpgrades == null) { + final ICellWorkbenchItem cell = this.getCell(); + if (cell == null) { + return null; + } - final ItemStack is = this.cell.getStackInSlot( 0 ); - if( is.isEmpty() ) - { - return null; - } + final ItemStack is = this.cell.getStackInSlot(0); + if (is.isEmpty()) { + return null; + } - final IItemHandler inv = cell.getUpgradesInventory( is ); - if( inv == null ) - { - return null; - } + final IItemHandler inv = cell.getUpgradesInventory(is); + if (inv == null) { + return null; + } - return this.cacheUpgrades = inv; - } - return this.cacheUpgrades; - } + return this.cacheUpgrades = inv; + } + return this.cacheUpgrades; + } - public ICellWorkbenchItem getCell() - { - if( this.cell.getStackInSlot( 0 ).isEmpty() ) - { - return null; - } + public ICellWorkbenchItem getCell() { + if (this.cell.getStackInSlot(0).isEmpty()) { + return null; + } - if( this.cell.getStackInSlot( 0 ).getItem() instanceof ICellWorkbenchItem ) - { - return( (ICellWorkbenchItem) this.cell.getStackInSlot( 0 ).getItem() ); - } + if (this.cell.getStackInSlot(0).getItem() instanceof ICellWorkbenchItem) { + return ((ICellWorkbenchItem) this.cell.getStackInSlot(0).getItem()); + } - return null; - } + return null; + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.cell.writeToNBT( data, "cell" ); - this.config.writeToNBT( data, "config" ); - this.manager.writeToNBT( data ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.cell.writeToNBT(data, "cell"); + this.config.writeToNBT(data, "config"); + this.manager.writeToNBT(data); + return data; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.cell.readFromNBT( data, "cell" ); - this.config.readFromNBT( data, "config" ); - this.manager.readFromNBT( data ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.cell.readFromNBT(data, "cell"); + this.config.readFromNBT(data, "config"); + this.manager.readFromNBT(data); + } - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.config; - } + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("config")) { + return this.config; + } - if( name.equals( "cell" ) ) - { - return this.cell; - } + if (name.equals("cell")) { + return this.cell; + } - return null; - } + return null; + } - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return 0; - } + @Override + public int getInstalledUpgrades(final Upgrades u) { + return 0; + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( inv == this.cell && !this.locked ) - { - this.locked = true; + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { + if (inv == this.cell && !this.locked) { + this.locked = true; - this.cacheUpgrades = null; - this.cacheConfig = null; + this.cacheUpgrades = null; + this.cacheConfig = null; - final IItemHandler configInventory = this.getCellConfigInventory(); - if( configInventory != null ) - { - boolean cellHasConfig = false; - for( int x = 0; x < configInventory.getSlots(); x++ ) - { - if( !configInventory.getStackInSlot( x ).isEmpty() ) - { - cellHasConfig = true; - break; - } - } + final IItemHandler configInventory = this.getCellConfigInventory(); + if (configInventory != null) { + boolean cellHasConfig = false; + for (int x = 0; x < configInventory.getSlots(); x++) { + if (!configInventory.getStackInSlot(x).isEmpty()) { + cellHasConfig = true; + break; + } + } - if( cellHasConfig ) - { - for( int x = 0; x < this.config.getSlots(); x++ ) - { - this.config.setStackInSlot( x, configInventory.getStackInSlot( x ) ); - } - } - else - { - ItemHandlerUtil.copy( this.config, configInventory, false ); - } - } - else if( this.manager.getSetting( Settings.COPY_MODE ) == CopyMode.CLEAR_ON_REMOVE ) - { - for( int x = 0; x < this.config.getSlots(); x++ ) - { - this.config.setStackInSlot( x, ItemStack.EMPTY ); - } + if (cellHasConfig) { + for (int x = 0; x < this.config.getSlots(); x++) { + this.config.setStackInSlot(x, configInventory.getStackInSlot(x)); + } + } else { + ItemHandlerUtil.copy(this.config, configInventory, false); + } + } else if (this.manager.getSetting(Settings.COPY_MODE) == CopyMode.CLEAR_ON_REMOVE) { + for (int x = 0; x < this.config.getSlots(); x++) { + this.config.setStackInSlot(x, ItemStack.EMPTY); + } - this.saveChanges(); - } + this.saveChanges(); + } - this.locked = false; - } - else if( inv == this.config && !this.locked ) - { - this.locked = true; - final IItemHandler c = this.getCellConfigInventory(); - if( c != null ) - { - ItemHandlerUtil.copy( this.config, c, false ); - // copy items back. The ConfigInventory may changed the items on insert - ItemHandlerUtil.copy( c, this.config, false ); - } - this.locked = false; - } - } + this.locked = false; + } else if (inv == this.config && !this.locked) { + this.locked = true; + final IItemHandler c = this.getCellConfigInventory(); + if (c != null) { + ItemHandlerUtil.copy(this.config, c, false); + // copy items back. The ConfigInventory may changed the items on insert + ItemHandlerUtil.copy(c, this.config, false); + } + this.locked = false; + } + } - private IItemHandler getCellConfigInventory() - { - if( this.cacheConfig == null ) - { - final ICellWorkbenchItem cell = this.getCell(); - if( cell == null ) - { - return null; - } + private IItemHandler getCellConfigInventory() { + if (this.cacheConfig == null) { + final ICellWorkbenchItem cell = this.getCell(); + if (cell == null) { + return null; + } - final ItemStack is = this.cell.getStackInSlot( 0 ); - if( is.isEmpty() ) - { - return null; - } + final ItemStack is = this.cell.getStackInSlot(0); + if (is.isEmpty()) { + return null; + } - final IItemHandler inv = cell.getConfigInventory( is ); - if( inv == null ) - { - return null; - } + final IItemHandler inv = cell.getConfigInventory(is); + if (inv == null) { + return null; + } - this.cacheConfig = inv; - } - return this.cacheConfig; - } + this.cacheConfig = inv; + } + return this.cacheConfig; + } - @Override - public void getDrops( final World w, final BlockPos pos, final List drops ) - { - super.getDrops( w, pos, drops ); + @Override + public void getDrops(final World w, final BlockPos pos, final List drops) { + super.getDrops(w, pos, drops); - if( this.cell.getStackInSlot( 0 ) != null ) - { - drops.add( this.cell.getStackInSlot( 0 ) ); - } - } + if (this.cell.getStackInSlot(0) != null) { + drops.add(this.cell.getStackInSlot(0)); + } + } - @Override - public IConfigManager getConfigManager() - { - return this.manager; - } + @Override + public IConfigManager getConfigManager() { + return this.manager; + } - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - // nothing here.. - } + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + // nothing here.. + } } diff --git a/src/main/java/appeng/tile/misc/TileCharger.java b/src/main/java/appeng/tile/misc/TileCharger.java index 960ac7879..45b93aae6 100644 --- a/src/main/java/appeng/tile/misc/TileCharger.java +++ b/src/main/java/appeng/tile/misc/TileCharger.java @@ -19,27 +19,10 @@ package appeng.tile.misc; -import java.io.IOException; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; - -import appeng.core.AEConfig; -import appeng.core.features.AEFeature; -import appeng.util.item.OreHelper; -import appeng.util.item.OreReference; -import io.netty.buffer.ByteBuf; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.config.PowerUnits; -import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.IMaterials; import appeng.api.implementations.items.IAEItemPowerStorage; import appeng.api.implementations.tiles.ICrankable; @@ -51,6 +34,8 @@ import appeng.api.storage.data.IAEItemStack; import appeng.api.util.AECableType; import appeng.api.util.AEPartLocation; import appeng.api.util.DimensionalCoord; +import appeng.core.AEConfig; +import appeng.core.features.AEFeature; import appeng.core.settings.TickRates; import appeng.me.GridAccessException; import appeng.tile.grid.AENetworkPowerTile; @@ -59,273 +44,232 @@ import appeng.util.Platform; import appeng.util.inv.InvOperation; import appeng.util.inv.filter.IAEItemFilter; import appeng.util.item.AEItemStack; +import io.netty.buffer.ByteBuf; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.items.IItemHandler; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; -public class TileCharger extends AENetworkPowerTile implements ICrankable, IGridTickable -{ - private static final int POWER_MAXIMUM_AMOUNT = 1600; - private static final int POWER_THRESHOLD = POWER_MAXIMUM_AMOUNT - 1; - private static final int POWER_PER_CRANK_TURN = 160; +public class TileCharger extends AENetworkPowerTile implements ICrankable, IGridTickable { + private static final int POWER_MAXIMUM_AMOUNT = 1600; + private static final int POWER_THRESHOLD = POWER_MAXIMUM_AMOUNT - 1; + private static final int POWER_PER_CRANK_TURN = 160; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 1, 1, new ChargerInvFilter() ); + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 1, 1, new ChargerInvFilter()); - public TileCharger() - { - this.getProxy().setValidSides( EnumSet.noneOf( EnumFacing.class ) ); - this.getProxy().setFlags(); - this.setInternalMaxPower( POWER_MAXIMUM_AMOUNT ); - this.getProxy().setIdlePowerUsage( 0 ); - } + public TileCharger() { + this.getProxy().setValidSides(EnumSet.noneOf(EnumFacing.class)); + this.getProxy().setFlags(); + this.setInternalMaxPower(POWER_MAXIMUM_AMOUNT); + this.getProxy().setIdlePowerUsage(0); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.COVERED; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.COVERED; + } - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - try - { - final IAEItemStack item = AEItemStack.fromPacket( data ); - final ItemStack is = item.createItemStack(); - this.inv.setStackInSlot( 0, is ); - } - catch( final Throwable t ) - { - this.inv.setStackInSlot( 0, ItemStack.EMPTY ); - } - return c; // TESR doesn't need updates! - } + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + try { + final IAEItemStack item = AEItemStack.fromPacket(data); + final ItemStack is = item.createItemStack(); + this.inv.setStackInSlot(0, is); + } catch (final Throwable t) { + this.inv.setStackInSlot(0, ItemStack.EMPTY); + } + return c; // TESR doesn't need updates! + } - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - final AEItemStack is = AEItemStack.fromItemStack( this.inv.getStackInSlot( 0 ) ); - if( is != null ) - { - is.writeToPacket( data ); - } - } + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + final AEItemStack is = AEItemStack.fromItemStack(this.inv.getStackInSlot(0)); + if (is != null) { + is.writeToPacket(data); + } + } - @Override - public void setOrientation( final EnumFacing inForward, final EnumFacing inUp ) - { - super.setOrientation( inForward, inUp ); - this.getProxy().setValidSides( EnumSet.of( this.getUp(), this.getUp().getOpposite() ) ); - this.setPowerSides( EnumSet.of( this.getUp(), this.getUp().getOpposite() ) ); - } + @Override + public void setOrientation(final EnumFacing inForward, final EnumFacing inUp) { + super.setOrientation(inForward, inUp); + this.getProxy().setValidSides(EnumSet.of(this.getUp(), this.getUp().getOpposite())); + this.setPowerSides(EnumSet.of(this.getUp(), this.getUp().getOpposite())); + } - @Override - public boolean requiresTESR() - { - return true; - } + @Override + public boolean requiresTESR() { + return true; + } - @Override - public boolean canTurn() - { - return this.getInternalCurrentPower() < this.getInternalMaxPower(); - } + @Override + public boolean canTurn() { + return this.getInternalCurrentPower() < this.getInternalMaxPower(); + } - @Override - public void applyTurn() - { - this.injectExternalPower( PowerUnits.AE, POWER_PER_CRANK_TURN, Actionable.MODULATE ); + @Override + public void applyTurn() { + this.injectExternalPower(PowerUnits.AE, POWER_PER_CRANK_TURN, Actionable.MODULATE); - final ItemStack myItem = this.inv.getStackInSlot( 0 ); - if( this.getInternalCurrentPower() > POWER_THRESHOLD ) - { - final IMaterials materials = AEApi.instance().definitions().materials(); + final ItemStack myItem = this.inv.getStackInSlot(0); + if (this.getInternalCurrentPower() > POWER_THRESHOLD) { + final IMaterials materials = AEApi.instance().definitions().materials(); - if( materials.certusQuartzCrystal().isSameAs( myItem ) ) - { - this.extractAEPower( this.getInternalMaxPower(), Actionable.MODULATE, PowerMultiplier.CONFIG ); + if (materials.certusQuartzCrystal().isSameAs(myItem)) { + this.extractAEPower(this.getInternalMaxPower(), Actionable.MODULATE, PowerMultiplier.CONFIG); - materials.certusQuartzCrystalCharged().maybeStack( myItem.getCount() ).ifPresent( charged -> this.inv.setStackInSlot( 0, charged ) ); - } - } - } + materials.certusQuartzCrystalCharged().maybeStack(myItem.getCount()).ifPresent(charged -> this.inv.setStackInSlot(0, charged)); + } + } + } - @Override - public boolean canCrankAttach( final EnumFacing directionToCrank ) - { - return this.getUp() == directionToCrank || this.getUp().getOpposite() == directionToCrank; - } + @Override + public boolean canCrankAttach(final EnumFacing directionToCrank) { + return this.getUp() == directionToCrank || this.getUp().getOpposite() == directionToCrank; + } - @Override - public IItemHandler getInternalInventory() - { - return this.inv; - } + @Override + public IItemHandler getInternalInventory() { + return this.inv; + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - try - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { + try { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // :P + } - this.markForUpdate(); - } + this.markForUpdate(); + } - public void activate( final EntityPlayer player ) - { - if( !Platform.hasPermissions( new DimensionalCoord( this ), player ) ) - { - return; - } + public void activate(final EntityPlayer player) { + if (!Platform.hasPermissions(new DimensionalCoord(this), player)) { + return; + } - final ItemStack myItem = this.inv.getStackInSlot( 0 ); - if( myItem.isEmpty() ) - { - ItemStack held = player.inventory.getCurrentItem(); - if( !held.isEmpty() ) - { - if( AEConfig.instance().isFeatureEnabled( AEFeature.CERTUS ) ) - { - final IMaterials materials = AEApi.instance().definitions().materials(); - if( AEItemStack.fromItemStack( held ).sameOre( AEItemStack.fromItemStack( materials.certusQuartzCrystal().maybeStack( 1 ).orElse( ItemStack.EMPTY ) ) ) || Platform.isChargeable( held ) ) - { - held = player.inventory.decrStackSize( player.inventory.currentItem, 1 ); - this.inv.setStackInSlot( 0, held ); - } - } - } - } - else - { - final List drops = new ArrayList<>(); - drops.add( myItem ); - this.inv.setStackInSlot( 0, ItemStack.EMPTY ); - Platform.spawnDrops( this.world, this.pos.offset( this.getForward() ), drops ); - } - } + final ItemStack myItem = this.inv.getStackInSlot(0); + if (myItem.isEmpty()) { + ItemStack held = player.inventory.getCurrentItem(); + if (!held.isEmpty()) { + if (AEConfig.instance().isFeatureEnabled(AEFeature.CERTUS)) { + final IMaterials materials = AEApi.instance().definitions().materials(); + if (AEItemStack.fromItemStack(held).sameOre(AEItemStack.fromItemStack(materials.certusQuartzCrystal().maybeStack(1).orElse(ItemStack.EMPTY))) || Platform.isChargeable(held)) { + held = player.inventory.decrStackSize(player.inventory.currentItem, 1); + this.inv.setStackInSlot(0, held); + } + } + } + } else { + final List drops = new ArrayList<>(); + drops.add(myItem); + this.inv.setStackInSlot(0, ItemStack.EMPTY); + Platform.spawnDrops(this.world, this.pos.offset(this.getForward()), drops); + } + } - @Override - public TickingRequest getTickingRequest( IGridNode node ) - { - return new TickingRequest( TickRates.Charger.getMin(), TickRates.Charger.getMin(), false, true ); - } + @Override + public TickingRequest getTickingRequest(IGridNode node) { + return new TickingRequest(TickRates.Charger.getMin(), TickRates.Charger.getMin(), false, true); + } - @Override - public TickRateModulation tickingRequest( IGridNode node, int TicksSinceLastCall ) - { - return this.doWork() ? TickRateModulation.FASTER : TickRateModulation.SLEEP; - } + @Override + public TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall) { + return this.doWork() ? TickRateModulation.FASTER : TickRateModulation.SLEEP; + } - private boolean doWork() - { - final ItemStack myItem = this.inv.getStackInSlot( 0 ); - boolean changed = false; + private boolean doWork() { + final ItemStack myItem = this.inv.getStackInSlot(0); + boolean changed = false; - if( !myItem.isEmpty() ) - { - final IMaterials materials = AEApi.instance().definitions().materials(); + if (!myItem.isEmpty()) { + final IMaterials materials = AEApi.instance().definitions().materials(); - if( Platform.isChargeable( myItem ) ) - { - final IAEItemPowerStorage ps = (IAEItemPowerStorage) myItem.getItem(); + if (Platform.isChargeable(myItem)) { + final IAEItemPowerStorage ps = (IAEItemPowerStorage) myItem.getItem(); - if( ps.getAEMaxPower( myItem ) > ps.getAECurrentPower( myItem ) ) - { - final double chargeRate = AEApi.instance().registries().charger().getChargeRate( myItem.getItem() ); + if (ps.getAEMaxPower(myItem) > ps.getAECurrentPower(myItem)) { + final double chargeRate = AEApi.instance().registries().charger().getChargeRate(myItem.getItem()); - double extractedAmount = this.extractAEPower( chargeRate, Actionable.MODULATE, PowerMultiplier.CONFIG ); + double extractedAmount = this.extractAEPower(chargeRate, Actionable.MODULATE, PowerMultiplier.CONFIG); - final double missingChargeRate = chargeRate - extractedAmount; - final double missingAEPower = ps.getAEMaxPower( myItem ) - ps.getAECurrentPower( myItem ); - final double toExtract = Math.min( missingChargeRate, missingAEPower ); + final double missingChargeRate = chargeRate - extractedAmount; + final double missingAEPower = ps.getAEMaxPower(myItem) - ps.getAECurrentPower(myItem); + final double toExtract = Math.min(missingChargeRate, missingAEPower); - try - { - extractedAmount += this.getProxy().getEnergy().extractAEPower( toExtract, Actionable.MODULATE, PowerMultiplier.ONE ); - } - catch( GridAccessException e1 ) - { - // Ignore. - } + try { + extractedAmount += this.getProxy().getEnergy().extractAEPower(toExtract, Actionable.MODULATE, PowerMultiplier.ONE); + } catch (GridAccessException e1) { + // Ignore. + } - if( extractedAmount > 0 ) - { - final double adjustment = ps.injectAEPower( myItem, extractedAmount, Actionable.MODULATE ); + if (extractedAmount > 0) { + final double adjustment = ps.injectAEPower(myItem, extractedAmount, Actionable.MODULATE); - this.setInternalCurrentPower( this.getInternalCurrentPower() + adjustment ); + this.setInternalCurrentPower(this.getInternalCurrentPower() + adjustment); - changed = true; - } - } - } - else if( this.getInternalCurrentPower() > POWER_THRESHOLD && ( materials.certusQuartzCrystal().isSameAs( myItem ) || AEItemStack.fromItemStack( myItem ).sameOre( AEItemStack.fromItemStack( materials.certusQuartzCrystal().maybeStack( 1 ).orElse( ItemStack.EMPTY ) ) ) ) ) - { - if( Platform.getRandomFloat() > 0.8f ) // simulate wait - { - this.extractAEPower( this.getInternalMaxPower(), Actionable.MODULATE, PowerMultiplier.CONFIG ); + changed = true; + } + } + } else if (this.getInternalCurrentPower() > POWER_THRESHOLD && (materials.certusQuartzCrystal().isSameAs(myItem) || AEItemStack.fromItemStack(myItem).sameOre(AEItemStack.fromItemStack(materials.certusQuartzCrystal().maybeStack(1).orElse(ItemStack.EMPTY))))) { + if (Platform.getRandomFloat() > 0.8f) // simulate wait + { + this.extractAEPower(this.getInternalMaxPower(), Actionable.MODULATE, PowerMultiplier.CONFIG); - materials.certusQuartzCrystalCharged().maybeStack( myItem.getCount() ).ifPresent( charged -> this.inv.setStackInSlot( 0, charged ) ); + materials.certusQuartzCrystalCharged().maybeStack(myItem.getCount()).ifPresent(charged -> this.inv.setStackInSlot(0, charged)); - changed = true; - } - } - } + changed = true; + } + } + } - // charge from the network! - if( this.getInternalCurrentPower() < POWER_THRESHOLD ) - { - try - { - final double toExtract = Math.min( 800.0, this.getInternalMaxPower() - this.getInternalCurrentPower() ); - final double extracted = this.getProxy().getEnergy().extractAEPower( toExtract, Actionable.MODULATE, PowerMultiplier.ONE ); + // charge from the network! + if (this.getInternalCurrentPower() < POWER_THRESHOLD) { + try { + final double toExtract = Math.min(800.0, this.getInternalMaxPower() - this.getInternalCurrentPower()); + final double extracted = this.getProxy().getEnergy().extractAEPower(toExtract, Actionable.MODULATE, PowerMultiplier.ONE); - this.injectExternalPower( PowerUnits.AE, extracted, Actionable.MODULATE ); - } - catch( final GridAccessException e ) - { - // continue! - } + this.injectExternalPower(PowerUnits.AE, extracted, Actionable.MODULATE); + } catch (final GridAccessException e) { + // continue! + } - changed = true; - } + changed = true; + } - if( changed ) - { - this.markForUpdate(); - } + if (changed) { + this.markForUpdate(); + } - return true; - } + return true; + } - private class ChargerInvFilter implements IAEItemFilter - { - @Override - public boolean allowInsert( IItemHandler inv, final int i, final ItemStack itemstack ) - { - return AEItemStack.fromItemStack( itemstack ).sameOre( AEItemStack.fromItemStack( AEApi.instance().definitions().materials().certusQuartzCrystal().maybeStack( 1 ).orElse( ItemStack.EMPTY ) ) ) || Platform.isChargeable( itemstack ); - } + private class ChargerInvFilter implements IAEItemFilter { + @Override + public boolean allowInsert(IItemHandler inv, final int i, final ItemStack itemstack) { + return AEItemStack.fromItemStack(itemstack).sameOre(AEItemStack.fromItemStack(AEApi.instance().definitions().materials().certusQuartzCrystal().maybeStack(1).orElse(ItemStack.EMPTY))) || Platform.isChargeable(itemstack); + } - @Override - public boolean allowExtract( IItemHandler inv, final int slotIndex, int amount ) - { - ItemStack extractedItem = inv.getStackInSlot( slotIndex ); + @Override + public boolean allowExtract(IItemHandler inv, final int slotIndex, int amount) { + ItemStack extractedItem = inv.getStackInSlot(slotIndex); - if( Platform.isChargeable( extractedItem ) ) - { - final IAEItemPowerStorage ips = (IAEItemPowerStorage) extractedItem.getItem(); - if( ips.getAECurrentPower( extractedItem ) >= ips.getAEMaxPower( extractedItem ) ) - { - return true; - } - } + if (Platform.isChargeable(extractedItem)) { + final IAEItemPowerStorage ips = (IAEItemPowerStorage) extractedItem.getItem(); + if (ips.getAECurrentPower(extractedItem) >= ips.getAEMaxPower(extractedItem)) { + return true; + } + } - return AEApi.instance().definitions().materials().certusQuartzCrystalCharged().isSameAs( extractedItem ); - } - } + return AEApi.instance().definitions().materials().certusQuartzCrystalCharged().isSameAs(extractedItem); + } + } } diff --git a/src/main/java/appeng/tile/misc/TileCondenser.java b/src/main/java/appeng/tile/misc/TileCondenser.java index f02fce023..987ed5c0b 100644 --- a/src/main/java/appeng/tile/misc/TileCondenser.java +++ b/src/main/java/appeng/tile/misc/TileCondenser.java @@ -19,21 +19,6 @@ package appeng.tile.misc; -import javax.annotation.Nullable; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; -import net.minecraftforge.fluids.capability.FluidTankProperties; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidTankProperties; -import net.minecraftforge.items.CapabilityItemHandler; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.CondenserOutput; import appeng.api.config.Settings; @@ -59,337 +44,289 @@ import appeng.util.inv.InvOperation; import appeng.util.inv.WrapperChainedItemHandler; import appeng.util.inv.WrapperFilteredItemHandler; import appeng.util.inv.filter.AEItemFilters; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; +import net.minecraftforge.fluids.capability.FluidTankProperties; +import net.minecraftforge.fluids.capability.IFluidHandler; +import net.minecraftforge.fluids.capability.IFluidTankProperties; +import net.minecraftforge.items.CapabilityItemHandler; +import net.minecraftforge.items.IItemHandler; + +import javax.annotation.Nullable; -public class TileCondenser extends AEBaseInvTile implements IConfigManagerHost, IConfigurableObject -{ +public class TileCondenser extends AEBaseInvTile implements IConfigManagerHost, IConfigurableObject { - public static final int BYTE_MULTIPLIER = 8; + public static final int BYTE_MULTIPLIER = 8; - private final ConfigManager cm = new ConfigManager( this ); + private final ConfigManager cm = new ConfigManager(this); - private final AppEngInternalInventory outputSlot = new AppEngInternalInventory( this, 1 ); - private final AppEngInternalInventory storageSlot = new AppEngInternalInventory( this, 1 ); - private final IItemHandler inputSlot = new CondenseItemHandler(); - private final IFluidHandler fluidHandler = new FluidHandler(); - private final MEHandler meHandler = new MEHandler(); + private final AppEngInternalInventory outputSlot = new AppEngInternalInventory(this, 1); + private final AppEngInternalInventory storageSlot = new AppEngInternalInventory(this, 1); + private final IItemHandler inputSlot = new CondenseItemHandler(); + private final IFluidHandler fluidHandler = new FluidHandler(); + private final MEHandler meHandler = new MEHandler(); - private final IItemHandler externalInv = new WrapperChainedItemHandler( this.inputSlot, new WrapperFilteredItemHandler( this.outputSlot, AEItemFilters.EXTRACT_ONLY ) ); - private final IItemHandler combinedInv = new WrapperChainedItemHandler( this.inputSlot, this.outputSlot, this.storageSlot ); + private final IItemHandler externalInv = new WrapperChainedItemHandler(this.inputSlot, new WrapperFilteredItemHandler(this.outputSlot, AEItemFilters.EXTRACT_ONLY)); + private final IItemHandler combinedInv = new WrapperChainedItemHandler(this.inputSlot, this.outputSlot, this.storageSlot); - private double storedPower = 0; + private double storedPower = 0; - public TileCondenser() - { - this.cm.registerSetting( Settings.CONDENSER_OUTPUT, CondenserOutput.TRASH ); - } + public TileCondenser() { + this.cm.registerSetting(Settings.CONDENSER_OUTPUT, CondenserOutput.TRASH); + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.cm.writeToNBT( data ); - data.setDouble( "storedPower", this.getStoredPower() ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.cm.writeToNBT(data); + data.setDouble("storedPower", this.getStoredPower()); + return data; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.cm.readFromNBT( data ); - this.setStoredPower( data.getDouble( "storedPower" ) ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.cm.readFromNBT(data); + this.setStoredPower(data.getDouble("storedPower")); + } - public double getStorage() - { - final ItemStack is = this.storageSlot.getStackInSlot( 0 ); - if( !is.isEmpty() ) - { - if( is.getItem() instanceof IStorageComponent ) - { - final IStorageComponent sc = (IStorageComponent) is.getItem(); - if( sc.isStorageComponent( is ) ) - { - return sc.getBytes( is ) * BYTE_MULTIPLIER; - } - } - } - return 0; - } + public double getStorage() { + final ItemStack is = this.storageSlot.getStackInSlot(0); + if (!is.isEmpty()) { + if (is.getItem() instanceof IStorageComponent) { + final IStorageComponent sc = (IStorageComponent) is.getItem(); + if (sc.isStorageComponent(is)) { + return sc.getBytes(is) * BYTE_MULTIPLIER; + } + } + } + return 0; + } - public void addPower( final double rawPower ) - { - this.setStoredPower( this.getStoredPower() + rawPower ); - this.setStoredPower( Math.max( 0.0, Math.min( this.getStorage(), this.getStoredPower() ) ) ); + public void addPower(final double rawPower) { + this.setStoredPower(this.getStoredPower() + rawPower); + this.setStoredPower(Math.max(0.0, Math.min(this.getStorage(), this.getStoredPower()))); - final double requiredPower = this.getRequiredPower(); - final ItemStack output = this.getOutput(); - while ( requiredPower <= this.getStoredPower() && !output.isEmpty() && requiredPower > 0 ) - { - if( this.canAddOutput( output ) ) - { - this.setStoredPower( this.getStoredPower() - requiredPower ); - this.addOutput( output ); - } - else - { - break; - } - } - } + final double requiredPower = this.getRequiredPower(); + final ItemStack output = this.getOutput(); + while (requiredPower <= this.getStoredPower() && !output.isEmpty() && requiredPower > 0) { + if (this.canAddOutput(output)) { + this.setStoredPower(this.getStoredPower() - requiredPower); + this.addOutput(output); + } else { + break; + } + } + } - private boolean canAddOutput( final ItemStack output ) - { - return this.outputSlot.insertItem( 0, output, true ).isEmpty(); - } + private boolean canAddOutput(final ItemStack output) { + return this.outputSlot.insertItem(0, output, true).isEmpty(); + } - /** - * make sure you validate with canAddOutput prior to this. - * - * @param output to be added output - */ - private void addOutput( final ItemStack output ) - { - this.outputSlot.insertItem( 0, output, false ); - } + /** + * make sure you validate with canAddOutput prior to this. + * + * @param output to be added output + */ + private void addOutput(final ItemStack output) { + this.outputSlot.insertItem(0, output, false); + } - IItemHandler getOutputSlot() - { - return this.outputSlot; - } + IItemHandler getOutputSlot() { + return this.outputSlot; + } - private ItemStack getOutput() - { - final IMaterials materials = AEApi.instance().definitions().materials(); + private ItemStack getOutput() { + final IMaterials materials = AEApi.instance().definitions().materials(); - switch ( (CondenserOutput) this.cm.getSetting( Settings.CONDENSER_OUTPUT ) ) - { - case MATTER_BALLS: - return materials.matterBall().maybeStack( 1 ).orElse( ItemStack.EMPTY ); + switch ((CondenserOutput) this.cm.getSetting(Settings.CONDENSER_OUTPUT)) { + case MATTER_BALLS: + return materials.matterBall().maybeStack(1).orElse(ItemStack.EMPTY); - case SINGULARITY: - return materials.singularity().maybeStack( 1 ).orElse( ItemStack.EMPTY ); + case SINGULARITY: + return materials.singularity().maybeStack(1).orElse(ItemStack.EMPTY); - case TRASH: - default: - return ItemStack.EMPTY; - } - } + case TRASH: + default: + return ItemStack.EMPTY; + } + } - public double getRequiredPower() - { - return ( (CondenserOutput) this.cm.getSetting( Settings.CONDENSER_OUTPUT ) ).requiredPower; - } + public double getRequiredPower() { + return ((CondenserOutput) this.cm.getSetting(Settings.CONDENSER_OUTPUT)).requiredPower; + } - @Override - public IItemHandler getInternalInventory() - { - return this.combinedInv; - } + @Override + public IItemHandler getInternalInventory() { + return this.combinedInv; + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( inv == this.outputSlot ) - { - if( !removed.isEmpty() ) - { - final double requiredPower = this.getRequiredPower(); - final ItemStack output = this.getOutput(); - while ( requiredPower <= this.getStoredPower() && !output.isEmpty() && requiredPower > 0 ) - { - if( this.canAddOutput( output ) ) - { - this.setStoredPower( this.getStoredPower() - requiredPower ); - this.addOutput( output ); - } - else - { - break; - } - removed.shrink( output.getCount() ); - } - } - this.meHandler.outputChanged( added, removed ); - } - } + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { + if (inv == this.outputSlot) { + if (!removed.isEmpty()) { + final double requiredPower = this.getRequiredPower(); + final ItemStack output = this.getOutput(); + while (requiredPower <= this.getStoredPower() && !output.isEmpty() && requiredPower > 0) { + if (this.canAddOutput(output)) { + this.setStoredPower(this.getStoredPower() - requiredPower); + this.addOutput(output); + } else { + break; + } + removed.shrink(output.getCount()); + } + } + this.meHandler.outputChanged(added, removed); + } + } - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.addPower( 0 ); - } + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + this.addPower(0); + } - @Override - public IConfigManager getConfigManager() - { - return this.cm; - } + @Override + public IConfigManager getConfigManager() { + return this.cm; + } - public double getStoredPower() - { - return this.storedPower; - } + public double getStoredPower() { + return this.storedPower; + } - private void setStoredPower( final double storedPower ) - { - this.storedPower = storedPower; - } + private void setStoredPower(final double storedPower) { + this.storedPower = storedPower; + } - @Override - public boolean hasCapability( Capability capability, EnumFacing facing ) - { - if( capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY ) - { - return true; - } - else if( capability == Capabilities.STORAGE_MONITORABLE_ACCESSOR ) - { - return true; - } - return super.hasCapability( capability, facing ); - } + @Override + public boolean hasCapability(Capability capability, EnumFacing facing) { + if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { + return true; + } else if (capability == Capabilities.STORAGE_MONITORABLE_ACCESSOR) { + return true; + } + return super.hasCapability(capability, facing); + } - @SuppressWarnings( "unchecked" ) - @Override - public T getCapability( Capability capability, @Nullable EnumFacing facing ) - { - if( capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY ) - { - return (T) this.externalInv; - } - else if( capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY ) - { - return (T) this.fluidHandler; - } - else if( capability == Capabilities.STORAGE_MONITORABLE_ACCESSOR ) - { - return (T) this.meHandler; - } - return super.getCapability( capability, facing ); - } + @SuppressWarnings("unchecked") + @Override + public T getCapability(Capability capability, @Nullable EnumFacing facing) { + if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { + return (T) this.externalInv; + } else if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { + return (T) this.fluidHandler; + } else if (capability == Capabilities.STORAGE_MONITORABLE_ACCESSOR) { + return (T) this.meHandler; + } + return super.getCapability(capability, facing); + } - private class CondenseItemHandler implements IItemHandler - { + private class CondenseItemHandler implements IItemHandler { - @Override - public int getSlots() - { - // We only expose the void slot - return 1; - } + @Override + public int getSlots() { + // We only expose the void slot + return 1; + } - @Override - public ItemStack getStackInSlot( int slot ) - { - // The void slot never has any content - return ItemStack.EMPTY; - } + @Override + public ItemStack getStackInSlot(int slot) { + // The void slot never has any content + return ItemStack.EMPTY; + } - @Override - public ItemStack insertItem( int slot, ItemStack stack, boolean simulate ) - { - if( slot != 0 ) - { - return stack; - } - if( !simulate && !stack.isEmpty() ) - { - TileCondenser.this.addPower( stack.getCount() ); - } - return ItemStack.EMPTY; - } + @Override + public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { + if (slot != 0) { + return stack; + } + if (!simulate && !stack.isEmpty()) { + TileCondenser.this.addPower(stack.getCount()); + } + return ItemStack.EMPTY; + } - @Override - public ItemStack extractItem( int slot, int amount, boolean simulate ) - { - return ItemStack.EMPTY; - } + @Override + public ItemStack extractItem(int slot, int amount, boolean simulate) { + return ItemStack.EMPTY; + } - @Override - public int getSlotLimit( int slot ) - { - return 64; - } - } + @Override + public int getSlotLimit(int slot) { + return 64; + } + } - private static final IFluidTankProperties[] EMPTY = {new FluidTankProperties( null, Fluid.BUCKET_VOLUME, true, false )}; + private static final IFluidTankProperties[] EMPTY = {new FluidTankProperties(null, Fluid.BUCKET_VOLUME, true, false)}; - /** - * A fluid handler that exposes a 1 bucket tank that can only be filled, and - when filled - will add power - * to this condenser. - */ - private class FluidHandler implements IFluidHandler - { + /** + * A fluid handler that exposes a 1 bucket tank that can only be filled, and - when filled - will add power + * to this condenser. + */ + private class FluidHandler implements IFluidHandler { - @Override - public IFluidTankProperties[] getTankProperties() - { - return EMPTY; - } + @Override + public IFluidTankProperties[] getTankProperties() { + return EMPTY; + } - @Override - public int fill( FluidStack resource, boolean doFill ) - { - if( doFill ) - { - final IStorageChannel chan = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ); - TileCondenser.this.addPower( ( resource == null ? 0.0 : (double) resource.amount ) / chan.transferFactor() ); - } + @Override + public int fill(FluidStack resource, boolean doFill) { + if (doFill) { + final IStorageChannel chan = AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class); + TileCondenser.this.addPower((resource == null ? 0.0 : (double) resource.amount) / chan.transferFactor()); + } - return resource == null ? 0 : resource.amount; - } + return resource == null ? 0 : resource.amount; + } - @Nullable - @Override - public FluidStack drain( FluidStack resource, boolean doDrain ) - { - return null; - } + @Nullable + @Override + public FluidStack drain(FluidStack resource, boolean doDrain) { + return null; + } - @Nullable - @Override - public FluidStack drain( int maxDrain, boolean doDrain ) - { - return null; - } - } + @Nullable + @Override + public FluidStack drain(int maxDrain, boolean doDrain) { + return null; + } + } - /** - * This is used to expose a fake ME subnetwork that is only composed of this condenser tile. The purpose of this is - * to enable the condenser to - * override the {@link appeng.api.storage.IMEInventoryHandler#validForPass(int)} method to make sure a condenser is - * only ever used if an item - * can't go anywhere else. - */ - private class MEHandler implements IStorageMonitorableAccessor, IStorageMonitorable - { - private final CondenserItemInventory itemInventory = new CondenserItemInventory( TileCondenser.this ); + /** + * This is used to expose a fake ME subnetwork that is only composed of this condenser tile. The purpose of this is + * to enable the condenser to + * override the {@link appeng.api.storage.IMEInventoryHandler#validForPass(int)} method to make sure a condenser is + * only ever used if an item + * can't go anywhere else. + */ + private class MEHandler implements IStorageMonitorableAccessor, IStorageMonitorable { + private final CondenserItemInventory itemInventory = new CondenserItemInventory(TileCondenser.this); - void outputChanged( ItemStack added, ItemStack removed ) - { - this.itemInventory.updateOutput( added, removed ); - } + void outputChanged(ItemStack added, ItemStack removed) { + this.itemInventory.updateOutput(added, removed); + } - @Nullable - @Override - public IStorageMonitorable getInventory( IActionSource src ) - { - return this; - } + @Nullable + @Override + public IStorageMonitorable getInventory(IActionSource src) { + return this; + } - @Override - public > IMEMonitor getInventory( IStorageChannel channel ) - { - if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - return (IMEMonitor) this.itemInventory; - } - else - { - return new CondenserVoidInventory<>( TileCondenser.this, channel ); - } - } - } + @Override + public > IMEMonitor getInventory(IStorageChannel channel) { + if (channel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + return (IMEMonitor) this.itemInventory; + } else { + return new CondenserVoidInventory<>(TileCondenser.this, channel); + } + } + } } diff --git a/src/main/java/appeng/tile/misc/TileInscriber.java b/src/main/java/appeng/tile/misc/TileInscriber.java index 7ed1ae4f7..e78e5a5a2 100644 --- a/src/main/java/appeng/tile/misc/TileInscriber.java +++ b/src/main/java/appeng/tile/misc/TileInscriber.java @@ -19,25 +19,6 @@ package appeng.tile.misc; -import java.io.IOException; -import java.util.EnumSet; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import com.google.common.collect.Lists; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.IItemHandlerModifiable; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -71,6 +52,21 @@ import appeng.util.inv.WrapperChainedItemHandler; import appeng.util.inv.WrapperFilteredItemHandler; import appeng.util.inv.filter.IAEItemFilter; import appeng.util.item.AEItemStack; +import com.google.common.collect.Lists; +import io.netty.buffer.ByteBuf; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.IItemHandlerModifiable; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.IOException; +import java.util.EnumSet; +import java.util.List; /** @@ -79,558 +75,455 @@ import appeng.util.item.AEItemStack; * @version rv2 * @since rv0 */ -public class TileInscriber extends AENetworkPowerTile implements IGridTickable, IUpgradeableHost, IConfigManagerHost -{ - private final int maxProcessingTime = 100; - - private final IConfigManager settings; - private final UpgradeInventory upgrades; - private int processingTime = 0; - // cycles from 0 - 16, at 8 it preforms the action, at 16 it re-enables the normal routine. - private boolean smash; - private int finalStep; - private long clientStart; - private final AppEngInternalInventory topItemHandler = new AppEngInternalInventory( this, 1, 1 ); - private final AppEngInternalInventory bottomItemHandler = new AppEngInternalInventory( this, 1, 1 ); - private final AppEngInternalInventory sideItemHandler = new AppEngInternalInventory( this, 2, 1 ); - - private final IItemHandler topItemHandlerExtern; - private final IItemHandler bottomItemHandlerExtern; - private final IItemHandler sideItemHandlerExtern; - - private IInscriberRecipe cachedTask = null; - - private final IItemHandlerModifiable inv = new WrapperChainedItemHandler( this.topItemHandler, this.bottomItemHandler, this.sideItemHandler ); - - public TileInscriber() - { - this.getProxy().setValidSides( EnumSet.noneOf( EnumFacing.class ) ); - this.setInternalMaxPower( 1600 ); - this.getProxy().setIdlePowerUsage( 0 ); - this.settings = new ConfigManager( this ); - - final ITileDefinition inscriberDefinition = AEApi.instance().definitions().blocks().inscriber(); - this.upgrades = new DefinitionUpgradeInventory( inscriberDefinition, this, this.getUpgradeSlots() ); - - this.sideItemHandler.setMaxStackSize( 1, 64 ); - - final IAEItemFilter filter = new ItemHandlerFilter(); - this.topItemHandlerExtern = new WrapperFilteredItemHandler( this.topItemHandler, filter ); - this.bottomItemHandlerExtern = new WrapperFilteredItemHandler( this.bottomItemHandler, filter ); - this.sideItemHandlerExtern = new WrapperFilteredItemHandler( this.sideItemHandler, filter ); - } - - private int getUpgradeSlots() - { - return 3; - } - - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.COVERED; - } - - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.upgrades.writeToNBT( data, "upgrades" ); - this.settings.writeToNBT( data ); - return data; - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.upgrades.readFromNBT( data, "upgrades" ); - this.settings.readFromNBT( data ); - } - - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - final int slot = data.readByte(); - - final boolean oldSmash = this.isSmash(); - final boolean newSmash = ( slot & 64 ) == 64; - - if( oldSmash != newSmash && newSmash ) - { - this.setSmash( true ); - this.setClientStart( System.currentTimeMillis() ); - } - - for( int num = 0; num < this.inv.getSlots(); num++ ) - { - if( ( slot & ( 1 << num ) ) > 0 ) - { - this.inv.setStackInSlot( num, AEItemStack.fromPacket( data ).createItemStack() ); - } - else - { - this.inv.setStackInSlot( num, ItemStack.EMPTY ); - } - } - this.cachedTask = null; - - return c; - } - - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - int slot = this.isSmash() ? 64 : 0; - - for( int num = 0; num < this.inv.getSlots(); num++ ) - { - if( !this.inv.getStackInSlot( num ).isEmpty() ) - { - slot |= ( 1 << num ); - } - } - - data.writeByte( slot ); - for( int num = 0; num < this.inv.getSlots(); num++ ) - { - if( ( slot & ( 1 << num ) ) > 0 ) - { - final AEItemStack st = AEItemStack.fromItemStack( this.inv.getStackInSlot( num ) ); - st.writeToPacket( data ); - } - } - } - - @Override - public void setOrientation( final EnumFacing inForward, final EnumFacing inUp ) - { - super.setOrientation( inForward, inUp ); - this.getProxy().setValidSides( EnumSet.complementOf( EnumSet.of( this.getForward() ) ) ); - this.setPowerSides( EnumSet.complementOf( EnumSet.of( this.getForward() ) ) ); - } - - @Override - public void getDrops( final World w, final BlockPos pos, final List drops ) - { - super.getDrops( w, pos, drops ); - - for( int h = 0; h < this.upgrades.getSlots(); h++ ) - { - final ItemStack is = this.upgrades.getStackInSlot( h ); - if( !is.isEmpty() ) - { - drops.add( is ); - } - } - } - - @Override - public boolean requiresTESR() - { - return true; - } - - @Override - public IItemHandler getInternalInventory() - { - return this.inv; - } - - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - try - { - if( slot == 0 ) - { - this.setProcessingTime( 0 ); - } - - if( !this.isSmash() ) - { - this.markForUpdate(); - } - - this.cachedTask = null; - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - // - // @Override - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.Inscriber.getMin(), TickRates.Inscriber.getMax(), !this.hasWork(), false ); - } - - private boolean hasWork() - { - if( this.getTask() != null ) - { - return true; - } - - this.setProcessingTime( 0 ); - return this.isSmash(); - } - - @Nullable - public IInscriberRecipe getTask() - { - if( this.cachedTask == null ) - { - this.cachedTask = this.getTask( this.sideItemHandler.getStackInSlot( 0 ), this.topItemHandler.getStackInSlot( 0 ), - this.bottomItemHandler.getStackInSlot( 0 ) ); - } - return this.cachedTask; - } - - @Nullable - private IInscriberRecipe getTask( final ItemStack input, final ItemStack plateA, final ItemStack plateB ) - { - if( input.isEmpty() || input.getCount() > 1 ) - { - return null; - } - - if( !plateA.isEmpty() && plateA.getCount() > 1 ) - { - return null; - } - - if( !plateB.isEmpty() && plateB.getCount() > 1 ) - { - return null; - } - - final IComparableDefinition namePress = AEApi.instance().definitions().materials().namePress(); - final boolean isNameA = namePress.isSameAs( plateA ); - final boolean isNameB = namePress.isSameAs( plateB ); - - if( ( isNameA && isNameB ) || isNameA && plateB.isEmpty() ) - { - return this.makeNamePressRecipe( input, plateA, plateB ); - } - else if( plateA.isEmpty() && isNameB ) - { - return this.makeNamePressRecipe( input, plateB, plateA ); - } - - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - - final boolean matchA = ( plateA.isEmpty() && !recipe.getTopOptional().isPresent() ) || ( Platform.itemComparisons() - .isSameItem( plateA, - recipe.getTopOptional().orElse( ItemStack.EMPTY ) ) ) && // and... - ( ( plateB.isEmpty() && !recipe.getBottomOptional().isPresent() ) || ( Platform.itemComparisons() - .isSameItem( plateB, - recipe.getBottomOptional().orElse( ItemStack.EMPTY ) ) ) ); - - final boolean matchB = ( plateB.isEmpty() && !recipe.getTopOptional().isPresent() ) || ( Platform.itemComparisons() - .isSameItem( plateB, - recipe.getTopOptional().orElse( ItemStack.EMPTY ) ) ) && // and... - ( ( plateA.isEmpty() && !recipe.getBottomOptional().isPresent() ) || ( Platform.itemComparisons() - .isSameItem( plateA, - recipe.getBottomOptional().orElse( ItemStack.EMPTY ) ) ) ); - - if( matchA || matchB ) - { - for( final ItemStack option : recipe.getInputs() ) - { - if( Platform.itemComparisons().isSameItem( input, option ) ) - { - return recipe; - } - } - } - } - - return null; - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( this.isSmash() ) - { - this.finalStep++; - if( this.finalStep == 8 ) - { - final IInscriberRecipe out = this.getTask(); - if( out != null ) - { - final ItemStack outputCopy = out.getOutput().copy(); - - if( this.sideItemHandler.insertItem( 1, outputCopy, false ).isEmpty() ) - { - this.setProcessingTime( 0 ); - if( out.getProcessType() == InscriberProcessType.PRESS ) - { - this.topItemHandler.setStackInSlot( 0, ItemStack.EMPTY ); - this.bottomItemHandler.setStackInSlot( 0, ItemStack.EMPTY ); - } - this.sideItemHandler.setStackInSlot( 0, ItemStack.EMPTY ); - } - } - this.saveChanges(); - } - else if( this.finalStep == 16 ) - { - this.finalStep = 0; - this.setSmash( false ); - this.markForUpdate(); - } - } - else - { - try - { - final IEnergyGrid eg = this.getProxy().getEnergy(); - IEnergySource src = this; - - // Base 1, increase by 1 for each card - final int speedFactor = 1 + this.upgrades.getInstalledUpgrades( Upgrades.SPEED ); - final int powerConsumption = 10 * speedFactor; - final double powerThreshold = powerConsumption - 0.01; - double powerReq = this.extractAEPower( powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - - if( powerReq <= powerThreshold ) - { - src = eg; - powerReq = eg.extractAEPower( powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - } - - if( powerReq > powerThreshold ) - { - src.extractAEPower( powerConsumption, Actionable.MODULATE, PowerMultiplier.CONFIG ); - - if( this.getProcessingTime() == 0 ) - { - this.setProcessingTime( this.getProcessingTime() + speedFactor ); - } - else - { - this.setProcessingTime( this.getProcessingTime() + ticksSinceLastCall * speedFactor ); - } - } - } - catch( final GridAccessException e ) - { - // :P - } - - if( this.getProcessingTime() > this.getMaxProcessingTime() ) - { - this.setProcessingTime( this.getMaxProcessingTime() ); - final IInscriberRecipe out = this.getTask(); - if( out != null ) - { - final ItemStack outputCopy = out.getOutput().copy(); - if( this.sideItemHandler.insertItem( 1, outputCopy, true ).isEmpty() ) - { - this.setSmash( true ); - this.finalStep = 0; - this.markForUpdate(); - } - } - } - } - - return this.hasWork() ? TickRateModulation.URGENT : TickRateModulation.SLEEP; - } - - @Override - public IConfigManager getConfigManager() - { - return this.settings; - } - - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "inv" ) ) - { - return this.getInternalInventory(); - } - - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - return null; - } - - @Override - protected IItemHandler getItemHandlerForSide( @Nonnull EnumFacing facing ) - { - if( facing == this.getUp() ) - { - return this.topItemHandlerExtern; - } - else if( facing == this.getUp().getOpposite() ) - { - return this.bottomItemHandlerExtern; - } - else - { - return this.sideItemHandlerExtern; - } - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.upgrades.getInstalledUpgrades( u ); - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - } - - public long getClientStart() - { - return this.clientStart; - } - - private void setClientStart( final long clientStart ) - { - this.clientStart = clientStart; - } - - public boolean isSmash() - { - return this.smash; - } - - public void setSmash( final boolean smash ) - { - this.smash = smash; - } - - public int getMaxProcessingTime() - { - return this.maxProcessingTime; - } - - public int getProcessingTime() - { - return this.processingTime; - } - - private void setProcessingTime( final int processingTime ) - { - this.processingTime = processingTime; - } - - private IInscriberRecipe makeNamePressRecipe( ItemStack input, ItemStack plateA, ItemStack plateB ) - { - String name = ""; - - if( !plateA.isEmpty() ) - { - final NBTTagCompound tag = Platform.openNbtData( plateA ); - name += tag.getString( "InscribeName" ); - } - - if( !plateB.isEmpty() ) - { - final NBTTagCompound tag = Platform.openNbtData( plateB ); - name += " " + tag.getString( "InscribeName" ); - } - - final ItemStack startingItem = input.copy(); - final ItemStack renamedItem = input.copy(); - final NBTTagCompound tag = Platform.openNbtData( renamedItem ); - - final NBTTagCompound display = tag.getCompoundTag( "display" ); - tag.setTag( "display", display ); - - if( name.length() > 0 ) - { - display.setString( "Name", name ); - } - else - { - display.removeTag( "Name" ); - } - - final List inputs = Lists.newArrayList( startingItem ); - final InscriberProcessType type = InscriberProcessType.INSCRIBE; - - final IInscriberRecipeBuilder builder = AEApi.instance().registries().inscriber().builder(); - builder.withInputs( inputs ).withOutput( renamedItem ).withProcessType( type ); - - if( !plateA.isEmpty() ) - { - builder.withTopOptional( plateA ); - } - - if( !plateB.isEmpty() ) - { - builder.withBottomOptional( plateB ); - } - - return builder.build(); - } - - /** - * This is an item handler that exposes the inscribers inventory while providing simulation capabilities that do not - * reset the progress if there's already an item in a slot. Previously, the progress of the inscriber was reset when - * another mod attempted insertion of items when there were already items in the slot. - */ - private class ItemHandlerFilter implements IAEItemFilter - { - @Override - public boolean allowExtract( IItemHandler inv, int slot, int amount ) - { - if( TileInscriber.this.isSmash() ) - { - return false; - } - - return inv == TileInscriber.this.topItemHandler || inv == TileInscriber.this.bottomItemHandler || slot == 1; - } - - @Override - public boolean allowInsert( IItemHandler inv, int slot, ItemStack stack ) - { - // output slot - if( slot == 1 ) - { - return false; - } - - if( TileInscriber.this.isSmash() ) - { - return false; - } - - if( inv == TileInscriber.this.topItemHandler || inv == TileInscriber.this.bottomItemHandler ) - { - if( AEApi.instance().definitions().materials().namePress().isSameAs( stack ) ) - { - return true; - } - for( final ItemStack optionals : AEApi.instance().registries().inscriber().getOptionals() ) - { - if( Platform.itemComparisons().isSameItem( stack, optionals ) ) - { - return true; - } - } - return false; - } - return true; - } - } +public class TileInscriber extends AENetworkPowerTile implements IGridTickable, IUpgradeableHost, IConfigManagerHost { + private final int maxProcessingTime = 100; + + private final IConfigManager settings; + private final UpgradeInventory upgrades; + private int processingTime = 0; + // cycles from 0 - 16, at 8 it preforms the action, at 16 it re-enables the normal routine. + private boolean smash; + private int finalStep; + private long clientStart; + private final AppEngInternalInventory topItemHandler = new AppEngInternalInventory(this, 1, 1); + private final AppEngInternalInventory bottomItemHandler = new AppEngInternalInventory(this, 1, 1); + private final AppEngInternalInventory sideItemHandler = new AppEngInternalInventory(this, 2, 1); + + private final IItemHandler topItemHandlerExtern; + private final IItemHandler bottomItemHandlerExtern; + private final IItemHandler sideItemHandlerExtern; + + private IInscriberRecipe cachedTask = null; + + private final IItemHandlerModifiable inv = new WrapperChainedItemHandler(this.topItemHandler, this.bottomItemHandler, this.sideItemHandler); + + public TileInscriber() { + this.getProxy().setValidSides(EnumSet.noneOf(EnumFacing.class)); + this.setInternalMaxPower(1600); + this.getProxy().setIdlePowerUsage(0); + this.settings = new ConfigManager(this); + + final ITileDefinition inscriberDefinition = AEApi.instance().definitions().blocks().inscriber(); + this.upgrades = new DefinitionUpgradeInventory(inscriberDefinition, this, this.getUpgradeSlots()); + + this.sideItemHandler.setMaxStackSize(1, 64); + + final IAEItemFilter filter = new ItemHandlerFilter(); + this.topItemHandlerExtern = new WrapperFilteredItemHandler(this.topItemHandler, filter); + this.bottomItemHandlerExtern = new WrapperFilteredItemHandler(this.bottomItemHandler, filter); + this.sideItemHandlerExtern = new WrapperFilteredItemHandler(this.sideItemHandler, filter); + } + + private int getUpgradeSlots() { + return 3; + } + + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.COVERED; + } + + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.upgrades.writeToNBT(data, "upgrades"); + this.settings.writeToNBT(data); + return data; + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.upgrades.readFromNBT(data, "upgrades"); + this.settings.readFromNBT(data); + } + + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + final int slot = data.readByte(); + + final boolean oldSmash = this.isSmash(); + final boolean newSmash = (slot & 64) == 64; + + if (oldSmash != newSmash && newSmash) { + this.setSmash(true); + this.setClientStart(System.currentTimeMillis()); + } + + for (int num = 0; num < this.inv.getSlots(); num++) { + if ((slot & (1 << num)) > 0) { + this.inv.setStackInSlot(num, AEItemStack.fromPacket(data).createItemStack()); + } else { + this.inv.setStackInSlot(num, ItemStack.EMPTY); + } + } + this.cachedTask = null; + + return c; + } + + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + int slot = this.isSmash() ? 64 : 0; + + for (int num = 0; num < this.inv.getSlots(); num++) { + if (!this.inv.getStackInSlot(num).isEmpty()) { + slot |= (1 << num); + } + } + + data.writeByte(slot); + for (int num = 0; num < this.inv.getSlots(); num++) { + if ((slot & (1 << num)) > 0) { + final AEItemStack st = AEItemStack.fromItemStack(this.inv.getStackInSlot(num)); + st.writeToPacket(data); + } + } + } + + @Override + public void setOrientation(final EnumFacing inForward, final EnumFacing inUp) { + super.setOrientation(inForward, inUp); + this.getProxy().setValidSides(EnumSet.complementOf(EnumSet.of(this.getForward()))); + this.setPowerSides(EnumSet.complementOf(EnumSet.of(this.getForward()))); + } + + @Override + public void getDrops(final World w, final BlockPos pos, final List drops) { + super.getDrops(w, pos, drops); + + for (int h = 0; h < this.upgrades.getSlots(); h++) { + final ItemStack is = this.upgrades.getStackInSlot(h); + if (!is.isEmpty()) { + drops.add(is); + } + } + } + + @Override + public boolean requiresTESR() { + return true; + } + + @Override + public IItemHandler getInternalInventory() { + return this.inv; + } + + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { + try { + if (slot == 0) { + this.setProcessingTime(0); + } + + if (!this.isSmash()) { + this.markForUpdate(); + } + + this.cachedTask = null; + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // :P + } + } + + // + // @Override + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.Inscriber.getMin(), TickRates.Inscriber.getMax(), !this.hasWork(), false); + } + + private boolean hasWork() { + if (this.getTask() != null) { + return true; + } + + this.setProcessingTime(0); + return this.isSmash(); + } + + @Nullable + public IInscriberRecipe getTask() { + if (this.cachedTask == null) { + this.cachedTask = this.getTask(this.sideItemHandler.getStackInSlot(0), this.topItemHandler.getStackInSlot(0), + this.bottomItemHandler.getStackInSlot(0)); + } + return this.cachedTask; + } + + @Nullable + private IInscriberRecipe getTask(final ItemStack input, final ItemStack plateA, final ItemStack plateB) { + if (input.isEmpty() || input.getCount() > 1) { + return null; + } + + if (!plateA.isEmpty() && plateA.getCount() > 1) { + return null; + } + + if (!plateB.isEmpty() && plateB.getCount() > 1) { + return null; + } + + final IComparableDefinition namePress = AEApi.instance().definitions().materials().namePress(); + final boolean isNameA = namePress.isSameAs(plateA); + final boolean isNameB = namePress.isSameAs(plateB); + + if ((isNameA && isNameB) || isNameA && plateB.isEmpty()) { + return this.makeNamePressRecipe(input, plateA, plateB); + } else if (plateA.isEmpty() && isNameB) { + return this.makeNamePressRecipe(input, plateB, plateA); + } + + for (final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes()) { + + final boolean matchA = (plateA.isEmpty() && !recipe.getTopOptional().isPresent()) || (Platform.itemComparisons() + .isSameItem(plateA, + recipe.getTopOptional().orElse(ItemStack.EMPTY))) && // and... + ((plateB.isEmpty() && !recipe.getBottomOptional().isPresent()) || (Platform.itemComparisons() + .isSameItem(plateB, + recipe.getBottomOptional().orElse(ItemStack.EMPTY)))); + + final boolean matchB = (plateB.isEmpty() && !recipe.getTopOptional().isPresent()) || (Platform.itemComparisons() + .isSameItem(plateB, + recipe.getTopOptional().orElse(ItemStack.EMPTY))) && // and... + ((plateA.isEmpty() && !recipe.getBottomOptional().isPresent()) || (Platform.itemComparisons() + .isSameItem(plateA, + recipe.getBottomOptional().orElse(ItemStack.EMPTY)))); + + if (matchA || matchB) { + for (final ItemStack option : recipe.getInputs()) { + if (Platform.itemComparisons().isSameItem(input, option)) { + return recipe; + } + } + } + } + + return null; + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (this.isSmash()) { + this.finalStep++; + if (this.finalStep == 8) { + final IInscriberRecipe out = this.getTask(); + if (out != null) { + final ItemStack outputCopy = out.getOutput().copy(); + + if (this.sideItemHandler.insertItem(1, outputCopy, false).isEmpty()) { + this.setProcessingTime(0); + if (out.getProcessType() == InscriberProcessType.PRESS) { + this.topItemHandler.setStackInSlot(0, ItemStack.EMPTY); + this.bottomItemHandler.setStackInSlot(0, ItemStack.EMPTY); + } + this.sideItemHandler.setStackInSlot(0, ItemStack.EMPTY); + } + } + this.saveChanges(); + } else if (this.finalStep == 16) { + this.finalStep = 0; + this.setSmash(false); + this.markForUpdate(); + } + } else { + try { + final IEnergyGrid eg = this.getProxy().getEnergy(); + IEnergySource src = this; + + // Base 1, increase by 1 for each card + final int speedFactor = 1 + this.upgrades.getInstalledUpgrades(Upgrades.SPEED); + final int powerConsumption = 10 * speedFactor; + final double powerThreshold = powerConsumption - 0.01; + double powerReq = this.extractAEPower(powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG); + + if (powerReq <= powerThreshold) { + src = eg; + powerReq = eg.extractAEPower(powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG); + } + + if (powerReq > powerThreshold) { + src.extractAEPower(powerConsumption, Actionable.MODULATE, PowerMultiplier.CONFIG); + + if (this.getProcessingTime() == 0) { + this.setProcessingTime(this.getProcessingTime() + speedFactor); + } else { + this.setProcessingTime(this.getProcessingTime() + ticksSinceLastCall * speedFactor); + } + } + } catch (final GridAccessException e) { + // :P + } + + if (this.getProcessingTime() > this.getMaxProcessingTime()) { + this.setProcessingTime(this.getMaxProcessingTime()); + final IInscriberRecipe out = this.getTask(); + if (out != null) { + final ItemStack outputCopy = out.getOutput().copy(); + if (this.sideItemHandler.insertItem(1, outputCopy, true).isEmpty()) { + this.setSmash(true); + this.finalStep = 0; + this.markForUpdate(); + } + } + } + } + + return this.hasWork() ? TickRateModulation.URGENT : TickRateModulation.SLEEP; + } + + @Override + public IConfigManager getConfigManager() { + return this.settings; + } + + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("inv")) { + return this.getInternalInventory(); + } + + if (name.equals("upgrades")) { + return this.upgrades; + } + + return null; + } + + @Override + protected IItemHandler getItemHandlerForSide(@Nonnull EnumFacing facing) { + if (facing == this.getUp()) { + return this.topItemHandlerExtern; + } else if (facing == this.getUp().getOpposite()) { + return this.bottomItemHandlerExtern; + } else { + return this.sideItemHandlerExtern; + } + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.upgrades.getInstalledUpgrades(u); + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + } + + public long getClientStart() { + return this.clientStart; + } + + private void setClientStart(final long clientStart) { + this.clientStart = clientStart; + } + + public boolean isSmash() { + return this.smash; + } + + public void setSmash(final boolean smash) { + this.smash = smash; + } + + public int getMaxProcessingTime() { + return this.maxProcessingTime; + } + + public int getProcessingTime() { + return this.processingTime; + } + + private void setProcessingTime(final int processingTime) { + this.processingTime = processingTime; + } + + private IInscriberRecipe makeNamePressRecipe(ItemStack input, ItemStack plateA, ItemStack plateB) { + String name = ""; + + if (!plateA.isEmpty()) { + final NBTTagCompound tag = Platform.openNbtData(plateA); + name += tag.getString("InscribeName"); + } + + if (!plateB.isEmpty()) { + final NBTTagCompound tag = Platform.openNbtData(plateB); + name += " " + tag.getString("InscribeName"); + } + + final ItemStack startingItem = input.copy(); + final ItemStack renamedItem = input.copy(); + final NBTTagCompound tag = Platform.openNbtData(renamedItem); + + final NBTTagCompound display = tag.getCompoundTag("display"); + tag.setTag("display", display); + + if (name.length() > 0) { + display.setString("Name", name); + } else { + display.removeTag("Name"); + } + + final List inputs = Lists.newArrayList(startingItem); + final InscriberProcessType type = InscriberProcessType.INSCRIBE; + + final IInscriberRecipeBuilder builder = AEApi.instance().registries().inscriber().builder(); + builder.withInputs(inputs).withOutput(renamedItem).withProcessType(type); + + if (!plateA.isEmpty()) { + builder.withTopOptional(plateA); + } + + if (!plateB.isEmpty()) { + builder.withBottomOptional(plateB); + } + + return builder.build(); + } + + /** + * This is an item handler that exposes the inscribers inventory while providing simulation capabilities that do not + * reset the progress if there's already an item in a slot. Previously, the progress of the inscriber was reset when + * another mod attempted insertion of items when there were already items in the slot. + */ + private class ItemHandlerFilter implements IAEItemFilter { + @Override + public boolean allowExtract(IItemHandler inv, int slot, int amount) { + if (TileInscriber.this.isSmash()) { + return false; + } + + return inv == TileInscriber.this.topItemHandler || inv == TileInscriber.this.bottomItemHandler || slot == 1; + } + + @Override + public boolean allowInsert(IItemHandler inv, int slot, ItemStack stack) { + // output slot + if (slot == 1) { + return false; + } + + if (TileInscriber.this.isSmash()) { + return false; + } + + if (inv == TileInscriber.this.topItemHandler || inv == TileInscriber.this.bottomItemHandler) { + if (AEApi.instance().definitions().materials().namePress().isSameAs(stack)) { + return true; + } + for (final ItemStack optionals : AEApi.instance().registries().inscriber().getOptionals()) { + if (Platform.itemComparisons().isSameItem(stack, optionals)) { + return true; + } + } + return false; + } + return true; + } + } } diff --git a/src/main/java/appeng/tile/misc/TileInterface.java b/src/main/java/appeng/tile/misc/TileInterface.java index fcf587082..d699032a2 100644 --- a/src/main/java/appeng/tile/misc/TileInterface.java +++ b/src/main/java/appeng/tile/misc/TileInterface.java @@ -19,26 +19,6 @@ package appeng.tile.misc; -import java.io.IOException; -import java.util.EnumSet; -import java.util.List; - -import javax.annotation.Nullable; - -import com.google.common.collect.ImmutableSet; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.Upgrades; @@ -65,306 +45,267 @@ import appeng.tile.grid.AENetworkInvTile; import appeng.util.Platform; import appeng.util.inv.IInventoryDestination; import appeng.util.inv.InvOperation; +import com.google.common.collect.ImmutableSet; +import io.netty.buffer.ByteBuf; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.items.IItemHandler; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.util.EnumSet; +import java.util.List; -public class TileInterface extends AENetworkInvTile implements IGridTickable, IInventoryDestination, IInterfaceHost, IPriorityHost -{ +public class TileInterface extends AENetworkInvTile implements IGridTickable, IInventoryDestination, IInterfaceHost, IPriorityHost { - private final DualityInterface duality = new DualityInterface( this.getProxy(), this ); + private final DualityInterface duality = new DualityInterface(this.getProxy(), this); - // Indicates that this interface has no specific direction set - private boolean omniDirectional = true; + // Indicates that this interface has no specific direction set + private boolean omniDirectional = true; - @MENetworkEventSubscribe - public void stateChange( final MENetworkChannelsChanged c ) - { - this.duality.notifyNeighbors(); - } + @MENetworkEventSubscribe + public void stateChange(final MENetworkChannelsChanged c) { + this.duality.notifyNeighbors(); + } - @MENetworkEventSubscribe - public void stateChange( final MENetworkPowerStatusChange c ) - { - this.duality.notifyNeighbors(); - } + @MENetworkEventSubscribe + public void stateChange(final MENetworkPowerStatusChange c) { + this.duality.notifyNeighbors(); + } - public void setSide( final EnumFacing facing ) - { - if( Platform.isClient() ) - { - return; - } + public void setSide(final EnumFacing facing) { + if (Platform.isClient()) { + return; + } - EnumFacing newForward = facing; + EnumFacing newForward = facing; - if( !this.omniDirectional && this.getForward() == facing.getOpposite() ) - { - newForward = facing; - } - else if( !this.omniDirectional && ( this.getForward() == facing || this.getForward() == facing.getOpposite() ) ) - { - this.omniDirectional = true; - } - else if( this.omniDirectional ) - { - newForward = facing.getOpposite(); - this.omniDirectional = false; - } - else - { - newForward = Platform.rotateAround( this.getForward(), facing ); - } + if (!this.omniDirectional && this.getForward() == facing.getOpposite()) { + newForward = facing; + } else if (!this.omniDirectional && (this.getForward() == facing || this.getForward() == facing.getOpposite())) { + this.omniDirectional = true; + } else if (this.omniDirectional) { + newForward = facing.getOpposite(); + this.omniDirectional = false; + } else { + newForward = Platform.rotateAround(this.getForward(), facing); + } - if( this.omniDirectional ) - { - this.setOrientation( EnumFacing.NORTH, EnumFacing.UP ); - } - else - { - EnumFacing newUp = EnumFacing.UP; - if( newForward == EnumFacing.UP || newForward == EnumFacing.DOWN ) - { - newUp = EnumFacing.NORTH; - } - this.setOrientation( newForward, newUp ); - } + if (this.omniDirectional) { + this.setOrientation(EnumFacing.NORTH, EnumFacing.UP); + } else { + EnumFacing newUp = EnumFacing.UP; + if (newForward == EnumFacing.UP || newForward == EnumFacing.DOWN) { + newUp = EnumFacing.NORTH; + } + this.setOrientation(newForward, newUp); + } - this.configureNodeSides(); - this.markForUpdate(); - this.saveChanges(); - } + this.configureNodeSides(); + this.markForUpdate(); + this.saveChanges(); + } - private void configureNodeSides() - { - if( this.omniDirectional ) - { - this.getProxy().setValidSides( EnumSet.allOf( EnumFacing.class ) ); - } - else - { - this.getProxy().setValidSides( EnumSet.complementOf( EnumSet.of( this.getForward() ) ) ); - } - } + private void configureNodeSides() { + if (this.omniDirectional) { + this.getProxy().setValidSides(EnumSet.allOf(EnumFacing.class)); + } else { + this.getProxy().setValidSides(EnumSet.complementOf(EnumSet.of(this.getForward()))); + } + } - @Override - public void getDrops( final World w, final BlockPos pos, final List drops ) - { - this.duality.addDrops( drops ); - } + @Override + public void getDrops(final World w, final BlockPos pos, final List drops) { + this.duality.addDrops(drops); + } - @Override - public void gridChanged() - { - this.duality.gridChanged(); - } + @Override + public void gridChanged() { + this.duality.gridChanged(); + } - @Override - public void onReady() - { - this.configureNodeSides(); + @Override + public void onReady() { + this.configureNodeSides(); - super.onReady(); - this.duality.initialize(); - this.getProxy().setIdlePowerUsage( Math.pow( 4, ( this.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION ) ) ) ); - } + super.onReady(); + this.duality.initialize(); + this.getProxy().setIdlePowerUsage(Math.pow(4, (this.getInstalledUpgrades(Upgrades.PATTERN_EXPANSION)))); + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setBoolean( "omniDirectional", this.omniDirectional ); - this.duality.writeToNBT( data ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setBoolean("omniDirectional", this.omniDirectional); + this.duality.writeToNBT(data); + return data; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.omniDirectional = data.getBoolean( "omniDirectional" ); + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.omniDirectional = data.getBoolean("omniDirectional"); - this.duality.readFromNBT( data ); - } + this.duality.readFromNBT(data); + } - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - boolean oldOmniDirectional = this.omniDirectional; - this.omniDirectional = data.readBoolean(); - return oldOmniDirectional != this.omniDirectional || c; - } + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + boolean oldOmniDirectional = this.omniDirectional; + this.omniDirectional = data.readBoolean(); + return oldOmniDirectional != this.omniDirectional || c; + } - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - data.writeBoolean( this.omniDirectional ); - } + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeBoolean(this.omniDirectional); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return this.duality.getCableConnectionType( dir ); - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return this.duality.getCableConnectionType(dir); + } - @Override - public DimensionalCoord getLocation() - { - return this.duality.getLocation(); - } + @Override + public DimensionalCoord getLocation() { + return this.duality.getLocation(); + } - @Override - public boolean canInsert( final ItemStack stack ) - { - return this.duality.canInsert( stack ); - } + @Override + public boolean canInsert(final ItemStack stack) { + return this.duality.canInsert(stack); + } - @Override - public IItemHandler getInventoryByName( final String name ) - { - return this.duality.getInventoryByName( name ); - } + @Override + public IItemHandler getInventoryByName(final String name) { + return this.duality.getInventoryByName(name); + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return this.duality.getTickingRequest( node ); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return this.duality.getTickingRequest(node); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.duality.tickingRequest( node, ticksSinceLastCall ); - } + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.duality.tickingRequest(node, ticksSinceLastCall); + } - @Override - public IItemHandler getInternalInventory() - { - return this.duality.getInternalInventory(); - } + @Override + public IItemHandler getInternalInventory() { + return this.duality.getInternalInventory(); + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - this.duality.onChangeInventory( inv, slot, mc, removed, added ); - } + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { + this.duality.onChangeInventory(inv, slot, mc, removed, added); + } - @Override - public DualityInterface getInterfaceDuality() - { - return this.duality; - } + @Override + public DualityInterface getInterfaceDuality() { + return this.duality; + } - @Override - public EnumSet getTargets() - { - if( this.omniDirectional ) - { - return EnumSet.allOf( EnumFacing.class ); - } - return EnumSet.of( this.getForward() ); - } + @Override + public EnumSet getTargets() { + if (this.omniDirectional) { + return EnumSet.allOf(EnumFacing.class); + } + return EnumSet.of(this.getForward()); + } - @Override - public TileEntity getTileEntity() - { - return this; - } + @Override + public TileEntity getTileEntity() { + return this; + } - @Override - public IConfigManager getConfigManager() - { - return this.duality.getConfigManager(); - } + @Override + public IConfigManager getConfigManager() { + return this.duality.getConfigManager(); + } - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) - { - return this.duality.pushPattern( patternDetails, table ); - } + @Override + public boolean pushPattern(final ICraftingPatternDetails patternDetails, final InventoryCrafting table) { + return this.duality.pushPattern(patternDetails, table); + } - @Override - public boolean isBusy() - { - return this.duality.isBusy(); - } + @Override + public boolean isBusy() { + return this.duality.isBusy(); + } - @Override - public void provideCrafting( final ICraftingProviderHelper craftingTracker ) - { - this.duality.provideCrafting( craftingTracker ); - } + @Override + public void provideCrafting(final ICraftingProviderHelper craftingTracker) { + this.duality.provideCrafting(craftingTracker); + } - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.duality.getInstalledUpgrades( u ); - } + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.duality.getInstalledUpgrades(u); + } - @Override - public ImmutableSet getRequestedJobs() - { - return this.duality.getRequestedJobs(); - } + @Override + public ImmutableSet getRequestedJobs() { + return this.duality.getRequestedJobs(); + } - @Override - public IAEItemStack injectCraftedItems( final ICraftingLink link, final IAEItemStack items, final Actionable mode ) - { - return this.duality.injectCraftedItems( link, items, mode ); - } + @Override + public IAEItemStack injectCraftedItems(final ICraftingLink link, final IAEItemStack items, final Actionable mode) { + return this.duality.injectCraftedItems(link, items, mode); + } - @Override - public void jobStateChange( final ICraftingLink link ) - { - this.duality.jobStateChange( link ); - } + @Override + public void jobStateChange(final ICraftingLink link) { + this.duality.jobStateChange(link); + } - @Override - public int getPriority() - { - return this.duality.getPriority(); - } + @Override + public int getPriority() { + return this.duality.getPriority(); + } - @Override - public void setPriority( final int newValue ) - { - this.duality.setPriority( newValue ); - } + @Override + public void setPriority(final int newValue) { + this.duality.setPriority(newValue); + } - /** - * @return True if this interface is omni-directional. - */ - public boolean isOmniDirectional() - { - return this.omniDirectional; - } + /** + * @return True if this interface is omni-directional. + */ + public boolean isOmniDirectional() { + return this.omniDirectional; + } - @Override - public boolean hasCapability( Capability capability, @Nullable EnumFacing facing ) - { - return this.duality.hasCapability( capability, facing ) || super.hasCapability( capability, facing ); - } + @Override + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { + return this.duality.hasCapability(capability, facing) || super.hasCapability(capability, facing); + } - @Override - public T getCapability( Capability capability, @Nullable EnumFacing facing ) - { - T result = this.duality.getCapability( capability, facing ); - if( result != null ) - { - return result; - } - return super.getCapability( capability, facing ); - } + @Override + public T getCapability(Capability capability, @Nullable EnumFacing facing) { + T result = this.duality.getCapability(capability, facing); + if (result != null) { + return result; + } + return super.getCapability(capability, facing); + } - @Override - public ItemStack getItemStackRepresentation() - { - return AEApi.instance().definitions().blocks().iface().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - } + @Override + public ItemStack getItemStackRepresentation() { + return AEApi.instance().definitions().blocks().iface().maybeStack(1).orElse(ItemStack.EMPTY); + } - @Override - public GuiBridge getGuiBridge() - { - return GuiBridge.GUI_INTERFACE; - } + @Override + public GuiBridge getGuiBridge() { + return GuiBridge.GUI_INTERFACE; + } } diff --git a/src/main/java/appeng/tile/misc/TileLightDetector.java b/src/main/java/appeng/tile/misc/TileLightDetector.java index a6ab84b2e..f31061b12 100644 --- a/src/main/java/appeng/tile/misc/TileLightDetector.java +++ b/src/main/java/appeng/tile/misc/TileLightDetector.java @@ -19,48 +19,40 @@ package appeng.tile.misc; -import net.minecraft.util.ITickable; - import appeng.tile.AEBaseTile; import appeng.util.Platform; +import net.minecraft.util.ITickable; -public class TileLightDetector extends AEBaseTile implements ITickable -{ +public class TileLightDetector extends AEBaseTile implements ITickable { - private int lastCheck = 30; - private int lastLight = 0; + private int lastCheck = 30; + private int lastLight = 0; - public boolean isReady() - { - return this.lastLight > 0; - } + public boolean isReady() { + return this.lastLight > 0; + } - @Override - public void update() - { - this.lastCheck++; - if( this.lastCheck > 30 ) - { - this.lastCheck = 0; - this.updateLight(); - } - } + @Override + public void update() { + this.lastCheck++; + if (this.lastCheck > 30) { + this.lastCheck = 0; + this.updateLight(); + } + } - public void updateLight() - { - final int val = this.world.getLight( this.pos ); + public void updateLight() { + final int val = this.world.getLight(this.pos); - if( this.lastLight != val ) - { - this.lastLight = val; - Platform.notifyBlocksOfNeighbors( this.world, this.pos ); - } - } + if (this.lastLight != val) { + this.lastLight = val; + Platform.notifyBlocksOfNeighbors(this.world, this.pos); + } + } - @Override - public boolean canBeRotated() - { - return false; - } + @Override + public boolean canBeRotated() { + return false; + } } diff --git a/src/main/java/appeng/tile/misc/TilePaint.java b/src/main/java/appeng/tile/misc/TilePaint.java index 3ea68a889..ca228a11e 100644 --- a/src/main/java/appeng/tile/misc/TilePaint.java +++ b/src/main/java/appeng/tile/misc/TilePaint.java @@ -19,16 +19,12 @@ package appeng.tile.misc; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - +import appeng.api.util.AEColor; +import appeng.helpers.Splotch; +import appeng.items.misc.ItemPaintBall; +import appeng.tile.AEBaseTile; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; - import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -37,245 +33,201 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.EnumSkyBlock; -import appeng.api.util.AEColor; -import appeng.helpers.Splotch; -import appeng.items.misc.ItemPaintBall; -import appeng.tile.AEBaseTile; +import java.io.IOException; +import java.util.*; -public class TilePaint extends AEBaseTile -{ +public class TilePaint extends AEBaseTile { - private static final int LIGHT_PER_DOT = 12; + private static final int LIGHT_PER_DOT = 12; - private int isLit = 0; - private List dots = null; + private int isLit = 0; + private List dots = null; - @Override - public boolean canBeRotated() - { - return false; - } + @Override + public boolean canBeRotated() { + return false; + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - final ByteBuf myDat = Unpooled.buffer(); - this.writeBuffer( myDat ); - if( myDat.hasArray() ) - { - data.setByteArray( "dots", myDat.array() ); - } - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + final ByteBuf myDat = Unpooled.buffer(); + this.writeBuffer(myDat); + if (myDat.hasArray()) { + data.setByteArray("dots", myDat.array()); + } + return data; + } - private void writeBuffer( final ByteBuf out ) - { - if( this.dots == null ) - { - out.writeByte( 0 ); - return; - } + private void writeBuffer(final ByteBuf out) { + if (this.dots == null) { + out.writeByte(0); + return; + } - out.writeByte( this.dots.size() ); + out.writeByte(this.dots.size()); - for( final Splotch s : this.dots ) - { - s.writeToStream( out ); - } - } + for (final Splotch s : this.dots) { + s.writeToStream(out); + } + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - if( data.hasKey( "dots" ) ) - { - this.readBuffer( Unpooled.copiedBuffer( data.getByteArray( "dots" ) ) ); - } - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + if (data.hasKey("dots")) { + this.readBuffer(Unpooled.copiedBuffer(data.getByteArray("dots"))); + } + } - private void readBuffer( final ByteBuf in ) - { - final byte howMany = in.readByte(); + private void readBuffer(final ByteBuf in) { + final byte howMany = in.readByte(); - if( howMany == 0 ) - { - this.isLit = 0; - this.dots = null; - return; - } + if (howMany == 0) { + this.isLit = 0; + this.dots = null; + return; + } - this.dots = new ArrayList( howMany ); - for( int x = 0; x < howMany; x++ ) - { - this.dots.add( new Splotch( in ) ); - } + this.dots = new ArrayList(howMany); + for (int x = 0; x < howMany; x++) { + this.dots.add(new Splotch(in)); + } - this.isLit = 0; - for( final Splotch s : this.dots ) - { - if( s.isLumen() ) - { - this.isLit += LIGHT_PER_DOT; - } - } + this.isLit = 0; + for (final Splotch s : this.dots) { + if (s.isLumen()) { + this.isLit += LIGHT_PER_DOT; + } + } - this.maxLit(); - } + this.maxLit(); + } - private void maxLit() - { - if( this.isLit > 14 ) - { - this.isLit = 14; - } + private void maxLit() { + if (this.isLit > 14) { + this.isLit = 14; + } - if( this.world != null ) - { - this.world.getLightFor( EnumSkyBlock.BLOCK, this.pos ); - } - } + if (this.world != null) { + this.world.getLightFor(EnumSkyBlock.BLOCK, this.pos); + } + } - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - this.writeBuffer( data ); - } + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + this.writeBuffer(data); + } - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - super.readFromStream( data ); - this.readBuffer( data ); - return true; - } + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + super.readFromStream(data); + this.readBuffer(data); + return true; + } - public void neighborChanged() - { - if( this.dots == null ) - { - return; - } + public void neighborChanged() { + if (this.dots == null) { + return; + } - for( final EnumFacing side : EnumFacing.VALUES ) - { - if( !this.isSideValid( side ) ) - { - this.removeSide( side ); - } - } + for (final EnumFacing side : EnumFacing.VALUES) { + if (!this.isSideValid(side)) { + this.removeSide(side); + } + } - this.updateData(); - } + this.updateData(); + } - public boolean isSideValid( final EnumFacing side ) - { - final BlockPos p = this.pos.offset( side ); - final IBlockState blk = this.world.getBlockState( p ); - return blk.getBlock().isSideSolid( this.world.getBlockState( p ), this.world, p, side.getOpposite() ); - } + public boolean isSideValid(final EnumFacing side) { + final BlockPos p = this.pos.offset(side); + final IBlockState blk = this.world.getBlockState(p); + return blk.getBlock().isSideSolid(this.world.getBlockState(p), this.world, p, side.getOpposite()); + } - private void removeSide( final EnumFacing side ) - { - final Iterator i = this.dots.iterator(); - while( i.hasNext() ) - { - final Splotch s = i.next(); - if( s.getSide() == side ) - { - i.remove(); - } - } + private void removeSide(final EnumFacing side) { + final Iterator i = this.dots.iterator(); + while (i.hasNext()) { + final Splotch s = i.next(); + if (s.getSide() == side) { + i.remove(); + } + } - this.markForUpdate(); - this.saveChanges(); - } + this.markForUpdate(); + this.saveChanges(); + } - private void updateData() - { - this.isLit = 0; - for( final Splotch s : this.dots ) - { - if( s.isLumen() ) - { - this.isLit += LIGHT_PER_DOT; - } - } + private void updateData() { + this.isLit = 0; + for (final Splotch s : this.dots) { + if (s.isLumen()) { + this.isLit += LIGHT_PER_DOT; + } + } - this.maxLit(); + this.maxLit(); - if( this.dots.isEmpty() ) - { - this.dots = null; - } + if (this.dots.isEmpty()) { + this.dots = null; + } - if( this.dots == null ) - { - this.world.setBlockToAir( this.pos ); - } - } + if (this.dots == null) { + this.world.setBlockToAir(this.pos); + } + } - public void cleanSide( final EnumFacing side ) - { - if( this.dots == null ) - { - return; - } + public void cleanSide(final EnumFacing side) { + if (this.dots == null) { + return; + } - this.removeSide( side ); + this.removeSide(side); - this.updateData(); - } + this.updateData(); + } - public int getLightLevel() - { - return this.isLit; - } + public int getLightLevel() { + return this.isLit; + } - public void addBlot( final ItemStack type, final EnumFacing side, final Vec3d hitVec ) - { - final BlockPos p = this.pos.offset( side ); + public void addBlot(final ItemStack type, final EnumFacing side, final Vec3d hitVec) { + final BlockPos p = this.pos.offset(side); - final IBlockState blk = this.world.getBlockState( p ); - if( blk.getBlock().isSideSolid( this.world.getBlockState( p ), this.world, p, side.getOpposite() ) ) - { - final ItemPaintBall ipb = (ItemPaintBall) type.getItem(); + final IBlockState blk = this.world.getBlockState(p); + if (blk.getBlock().isSideSolid(this.world.getBlockState(p), this.world, p, side.getOpposite())) { + final ItemPaintBall ipb = (ItemPaintBall) type.getItem(); - final AEColor col = ipb.getColor( type ); - final boolean lit = ipb.isLumen( type ); + final AEColor col = ipb.getColor(type); + final boolean lit = ItemPaintBall.isLumen(type); - if( this.dots == null ) - { - this.dots = new ArrayList<>(); - } + if (this.dots == null) { + this.dots = new ArrayList<>(); + } - if( this.dots.size() > 20 ) - { - this.dots.remove( 0 ); - } + if (this.dots.size() > 20) { + this.dots.remove(0); + } - this.dots.add( new Splotch( col, lit, side, hitVec ) ); - if( lit ) - { - this.isLit += LIGHT_PER_DOT; - } + this.dots.add(new Splotch(col, lit, side, hitVec)); + if (lit) { + this.isLit += LIGHT_PER_DOT; + } - this.maxLit(); - this.markForUpdate(); - this.saveChanges(); - } - } + this.maxLit(); + this.markForUpdate(); + this.saveChanges(); + } + } - public Collection getDots() - { - if( this.dots == null ) - { - return Collections.emptyList(); - } + public Collection getDots() { + if (this.dots == null) { + return Collections.emptyList(); + } - return this.dots; - } + return this.dots; + } } diff --git a/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java b/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java index 0837b573a..0c5c93a12 100644 --- a/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java +++ b/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java @@ -19,13 +19,6 @@ package appeng.tile.misc; -import java.io.IOException; -import java.util.EnumSet; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.util.EnumFacing; - import appeng.api.implementations.IPowerChannelState; import appeng.api.implementations.tiles.ICrystalGrowthAccelerator; import appeng.api.networking.events.MENetworkEventSubscribe; @@ -35,88 +28,76 @@ import appeng.api.util.AEPartLocation; import appeng.me.GridAccessException; import appeng.tile.grid.AENetworkTile; import appeng.util.Platform; +import io.netty.buffer.ByteBuf; +import net.minecraft.util.EnumFacing; + +import java.io.IOException; +import java.util.EnumSet; -public class TileQuartzGrowthAccelerator extends AENetworkTile implements IPowerChannelState, ICrystalGrowthAccelerator -{ +public class TileQuartzGrowthAccelerator extends AENetworkTile implements IPowerChannelState, ICrystalGrowthAccelerator { - private boolean hasPower = false; + private boolean hasPower = false; - public TileQuartzGrowthAccelerator() - { - this.getProxy().setValidSides( EnumSet.noneOf( EnumFacing.class ) ); - this.getProxy().setFlags(); - this.getProxy().setIdlePowerUsage( 8 ); - } + public TileQuartzGrowthAccelerator() { + this.getProxy().setValidSides(EnumSet.noneOf(EnumFacing.class)); + this.getProxy().setFlags(); + this.getProxy().setIdlePowerUsage(8); + } - @MENetworkEventSubscribe - public void onPower( final MENetworkPowerStatusChange ch ) - { - this.markForUpdate(); - } + @MENetworkEventSubscribe + public void onPower(final MENetworkPowerStatusChange ch) { + this.markForUpdate(); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.COVERED; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.COVERED; + } - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - final boolean hadPower = this.isPowered(); - this.setPowered( data.readBoolean() ); - return this.isPowered() != hadPower || c; - } + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + final boolean hadPower = this.isPowered(); + this.setPowered(data.readBoolean()); + return this.isPowered() != hadPower || c; + } - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - try - { - data.writeBoolean( this.getProxy().getEnergy().isNetworkPowered() ); - } - catch( final GridAccessException e ) - { - data.writeBoolean( false ); - } - } + @Override + public void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + try { + data.writeBoolean(this.getProxy().getEnergy().isNetworkPowered()); + } catch (final GridAccessException e) { + data.writeBoolean(false); + } + } - @Override - public void setOrientation( final EnumFacing inForward, final EnumFacing inUp ) - { - super.setOrientation( inForward, inUp ); - this.getProxy().setValidSides( EnumSet.of( this.getUp(), this.getUp().getOpposite() ) ); - } + @Override + public void setOrientation(final EnumFacing inForward, final EnumFacing inUp) { + super.setOrientation(inForward, inUp); + this.getProxy().setValidSides(EnumSet.of(this.getUp(), this.getUp().getOpposite())); + } - @Override - public boolean isPowered() - { - if( Platform.isServer() ) - { - try - { - return this.getProxy().getEnergy().isNetworkPowered(); - } - catch( final GridAccessException e ) - { - return false; - } - } + @Override + public boolean isPowered() { + if (Platform.isServer()) { + try { + return this.getProxy().getEnergy().isNetworkPowered(); + } catch (final GridAccessException e) { + return false; + } + } - return this.hasPower; - } + return this.hasPower; + } - @Override - public boolean isActive() - { - return this.isPowered(); - } + @Override + public boolean isActive() { + return this.isPowered(); + } - private void setPowered( final boolean hasPower ) - { - this.hasPower = hasPower; - } + private void setPowered(final boolean hasPower) { + this.hasPower = hasPower; + } } diff --git a/src/main/java/appeng/tile/misc/TileSecurityStation.java b/src/main/java/appeng/tile/misc/TileSecurityStation.java index eac5479c1..072b9b01c 100644 --- a/src/main/java/appeng/tile/misc/TileSecurityStation.java +++ b/src/main/java/appeng/tile/misc/TileSecurityStation.java @@ -19,30 +19,8 @@ package appeng.tile.misc; -import java.io.IOException; -import java.util.EnumSet; -import java.util.List; -import java.util.Map; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; -import appeng.api.config.SecurityPermissions; -import appeng.api.config.Settings; -import appeng.api.config.SortDir; -import appeng.api.config.SortOrder; -import appeng.api.config.ViewItems; +import appeng.api.config.*; import appeng.api.events.LocatableEventAnnounce; import appeng.api.events.LocatableEventAnnounce.LocatableEvent; import appeng.api.features.ILocatable; @@ -62,11 +40,7 @@ import appeng.api.storage.ITerminalHost; import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEStack; -import appeng.api.util.AECableType; -import appeng.api.util.AEColor; -import appeng.api.util.AEPartLocation; -import appeng.api.util.DimensionalCoord; -import appeng.api.util.IConfigManager; +import appeng.api.util.*; import appeng.helpers.PlayerSecurityWrapper; import appeng.me.GridAccessException; import appeng.me.helpers.MEMonitorHandler; @@ -80,296 +54,267 @@ import appeng.util.helpers.ItemHandlerUtil; import appeng.util.inv.IAEAppEngInventory; import appeng.util.inv.InvOperation; import appeng.util.item.AEItemStack; +import io.netty.buffer.ByteBuf; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.items.IItemHandler; + +import java.io.IOException; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; -public class TileSecurityStation extends AENetworkTile implements ITerminalHost, IAEAppEngInventory, ILocatable, IConfigManagerHost, ISecurityProvider, IColorableTile -{ +public class TileSecurityStation extends AENetworkTile implements ITerminalHost, IAEAppEngInventory, ILocatable, IConfigManagerHost, ISecurityProvider, IColorableTile { - private static int difference = 0; - private final AppEngInternalInventory configSlot = new AppEngInternalInventory( this, 1 ); - private final IConfigManager cm = new ConfigManager( this ); - private final SecurityStationInventory inventory = new SecurityStationInventory( this ); - private final MEMonitorHandler securityMonitor = new MEMonitorHandler<>( this.inventory ); - private long securityKey; - private AEColor paintedColor = AEColor.TRANSPARENT; - private boolean isActive = false; + private static int difference = 0; + private final AppEngInternalInventory configSlot = new AppEngInternalInventory(this, 1); + private final IConfigManager cm = new ConfigManager(this); + private final SecurityStationInventory inventory = new SecurityStationInventory(this); + private final MEMonitorHandler securityMonitor = new MEMonitorHandler<>(this.inventory); + private long securityKey; + private AEColor paintedColor = AEColor.TRANSPARENT; + private boolean isActive = false; - public TileSecurityStation() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.getProxy().setIdlePowerUsage( 2.0 ); - difference++; + public TileSecurityStation() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.getProxy().setIdlePowerUsage(2.0); + difference++; - this.securityKey = System.currentTimeMillis() * 10 + difference; - if( difference > 10 ) - { - difference = 0; - } + this.securityKey = System.currentTimeMillis() * 10 + difference; + if (difference > 10) { + difference = 0; + } - this.cm.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - this.cm.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - this.cm.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - } + this.cm.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.cm.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + this.cm.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack) { - } + } - @Override - public void getDrops( final World w, final BlockPos pos, final List drops ) - { - if( !ItemHandlerUtil.isEmpty( this.getConfigSlot() ) ) - { - drops.add( this.getConfigSlot().getStackInSlot( 0 ) ); - } + @Override + public void getDrops(final World w, final BlockPos pos, final List drops) { + if (!ItemHandlerUtil.isEmpty(this.getConfigSlot())) { + drops.add(this.getConfigSlot().getStackInSlot(0)); + } - for( final IAEItemStack ais : this.inventory.getStoredItems() ) - { - drops.add( ais.createItemStack() ); - } - } + for (final IAEItemStack ais : this.inventory.getStoredItems()) { + drops.add(ais.createItemStack()); + } + } - IMEInventoryHandler getSecurityInventory() - { - return this.inventory; - } + IMEInventoryHandler getSecurityInventory() { + return this.inventory; + } - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - final boolean wasActive = this.isActive; - this.isActive = data.readBoolean(); + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + final boolean wasActive = this.isActive; + this.isActive = data.readBoolean(); - final AEColor oldPaintedColor = this.paintedColor; - this.paintedColor = AEColor.values()[data.readByte()]; + final AEColor oldPaintedColor = this.paintedColor; + this.paintedColor = AEColor.values()[data.readByte()]; - return oldPaintedColor != this.paintedColor || wasActive != this.isActive || c; - } + return oldPaintedColor != this.paintedColor || wasActive != this.isActive || c; + } - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - data.writeBoolean( this.getProxy().isActive() ); - data.writeByte( this.paintedColor.ordinal() ); - } + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeBoolean(this.getProxy().isActive()); + data.writeByte(this.paintedColor.ordinal()); + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.cm.writeToNBT( data ); - data.setByte( "paintedColor", (byte) this.paintedColor.ordinal() ); + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.cm.writeToNBT(data); + data.setByte("paintedColor", (byte) this.paintedColor.ordinal()); - data.setLong( "securityKey", this.securityKey ); - this.getConfigSlot().writeToNBT( data, "config" ); + data.setLong("securityKey", this.securityKey); + this.getConfigSlot().writeToNBT(data, "config"); - final NBTTagCompound storedItems = new NBTTagCompound(); + final NBTTagCompound storedItems = new NBTTagCompound(); - int offset = 0; - for( final IAEItemStack ais : this.inventory.getStoredItems() ) - { - final NBTTagCompound it = new NBTTagCompound(); - ais.createItemStack().writeToNBT( it ); - storedItems.setTag( String.valueOf( offset ), it ); - offset++; - } + int offset = 0; + for (final IAEItemStack ais : this.inventory.getStoredItems()) { + final NBTTagCompound it = new NBTTagCompound(); + ais.createItemStack().writeToNBT(it); + storedItems.setTag(String.valueOf(offset), it); + offset++; + } - data.setTag( "storedItems", storedItems ); - return data; - } + data.setTag("storedItems", storedItems); + return data; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.cm.readFromNBT( data ); - if( data.hasKey( "paintedColor" ) ) - { - this.paintedColor = AEColor.values()[data.getByte( "paintedColor" )]; - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.cm.readFromNBT(data); + if (data.hasKey("paintedColor")) { + this.paintedColor = AEColor.values()[data.getByte("paintedColor")]; + } - this.securityKey = data.getLong( "securityKey" ); - this.getConfigSlot().readFromNBT( data, "config" ); + this.securityKey = data.getLong("securityKey"); + this.getConfigSlot().readFromNBT(data, "config"); - final NBTTagCompound storedItems = data.getCompoundTag( "storedItems" ); - for( final Object key : storedItems.getKeySet() ) - { - final NBTBase obj = storedItems.getTag( (String) key ); - if( obj instanceof NBTTagCompound ) - { - this.inventory.getStoredItems().add( AEItemStack.fromItemStack( new ItemStack( (NBTTagCompound) obj ) ) ); - } - } - } + final NBTTagCompound storedItems = data.getCompoundTag("storedItems"); + for (final Object key : storedItems.getKeySet()) { + final NBTBase obj = storedItems.getTag((String) key); + if (obj instanceof NBTTagCompound) { + this.inventory.getStoredItems().add(AEItemStack.fromItemStack(new ItemStack((NBTTagCompound) obj))); + } + } + } - public void inventoryChanged() - { - try - { - this.saveChanges(); - this.getProxy().getGrid().postEvent( new MENetworkSecurityChange() ); - } - catch( final GridAccessException e ) - { - // :P - } - } + public void inventoryChanged() { + try { + this.saveChanges(); + this.getProxy().getGrid().postEvent(new MENetworkSecurityChange()); + } catch (final GridAccessException e) { + // :P + } + } - @MENetworkEventSubscribe - public void bootUpdate( final MENetworkChannelsChanged changed ) - { - this.markForUpdate(); - } + @MENetworkEventSubscribe + public void bootUpdate(final MENetworkChannelsChanged changed) { + this.markForUpdate(); + } - @MENetworkEventSubscribe - public void powerUpdate( final MENetworkPowerStatusChange changed ) - { - this.markForUpdate(); - } + @MENetworkEventSubscribe + public void powerUpdate(final MENetworkPowerStatusChange changed) { + this.markForUpdate(); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.SMART; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.SMART; + } - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.UNREGISTER ) ); - this.isActive = false; - } + @Override + public void onChunkUnload() { + super.onChunkUnload(); + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.UNREGISTER)); + this.isActive = false; + } - @Override - public void onReady() - { - super.onReady(); - if( Platform.isServer() ) - { - this.isActive = true; - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.REGISTER ) ); - } - } + @Override + public void onReady() { + super.onReady(); + if (Platform.isServer()) { + this.isActive = true; + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.REGISTER)); + } + } - @Override - public void invalidate() - { - super.invalidate(); - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.UNREGISTER ) ); - this.isActive = false; - } + @Override + public void invalidate() { + super.invalidate(); + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.UNREGISTER)); + this.isActive = false; + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - public boolean isActive() - { - return this.isActive; - } + public boolean isActive() { + return this.isActive; + } - @Override - public > IMEMonitor getInventory( IStorageChannel channel ) - { - if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - return (IMEMonitor) this.securityMonitor; - } - return null; + @Override + public > IMEMonitor getInventory(IStorageChannel channel) { + if (channel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + return (IMEMonitor) this.securityMonitor; + } + return null; - } + } - @Override - public long getLocatableSerial() - { - return this.securityKey; - } + @Override + public long getLocatableSerial() { + return this.securityKey; + } - public boolean isPowered() - { - return this.getProxy().isActive(); - } + public boolean isPowered() { + return this.getProxy().isActive(); + } - @Override - public IConfigManager getConfigManager() - { - return this.cm; - } + @Override + public IConfigManager getConfigManager() { + return this.cm; + } - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { - } + } - @Override - public long getSecurityKey() - { - return this.securityKey; - } + @Override + public long getSecurityKey() { + return this.securityKey; + } - @Override - public void readPermissions( final Map> playerPerms ) - { - final IPlayerRegistry pr = AEApi.instance().registries().players(); + @Override + public void readPermissions(final Map> playerPerms) { + final IPlayerRegistry pr = AEApi.instance().registries().players(); - // read permissions - for( final IAEItemStack ais : this.inventory.getStoredItems() ) - { - final ItemStack is = ais.createItemStack(); - final Item i = is.getItem(); - if( i instanceof IBiometricCard ) - { - final IBiometricCard bc = (IBiometricCard) i; - bc.registerPermissions( new PlayerSecurityWrapper( playerPerms ), pr, is ); - } - } + // read permissions + for (final IAEItemStack ais : this.inventory.getStoredItems()) { + final ItemStack is = ais.createItemStack(); + final Item i = is.getItem(); + if (i instanceof IBiometricCard) { + final IBiometricCard bc = (IBiometricCard) i; + bc.registerPermissions(new PlayerSecurityWrapper(playerPerms), pr, is); + } + } - // make sure thea admin is Boss. - playerPerms.put( this.getProxy().getNode().getPlayerID(), EnumSet.allOf( SecurityPermissions.class ) ); - } + // make sure thea admin is Boss. + playerPerms.put(this.getProxy().getNode().getPlayerID(), EnumSet.allOf(SecurityPermissions.class)); + } - @Override - public boolean isSecurityEnabled() - { - return this.isActive && this.getProxy().isActive(); - } + @Override + public boolean isSecurityEnabled() { + return this.isActive && this.getProxy().isActive(); + } - @Override - public int getOwner() - { - return this.getProxy().getNode().getPlayerID(); - } + @Override + public int getOwner() { + return this.getProxy().getNode().getPlayerID(); + } - @Override - public AEColor getColor() - { - return this.paintedColor; - } + @Override + public AEColor getColor() { + return this.paintedColor; + } - @Override - public boolean recolourBlock( final EnumFacing side, final AEColor newPaintedColor, final EntityPlayer who ) - { - if( this.paintedColor == newPaintedColor ) - { - return false; - } + @Override + public boolean recolourBlock(final EnumFacing side, final AEColor newPaintedColor, final EntityPlayer who) { + if (this.paintedColor == newPaintedColor) { + return false; + } - this.paintedColor = newPaintedColor; - this.saveChanges(); - this.markForUpdate(); - return true; - } + this.paintedColor = newPaintedColor; + this.saveChanges(); + this.markForUpdate(); + return true; + } - public AppEngInternalInventory getConfigSlot() - { - return this.configSlot; - } + public AppEngInternalInventory getConfigSlot() { + return this.configSlot; + } } diff --git a/src/main/java/appeng/tile/misc/TileSkyCompass.java b/src/main/java/appeng/tile/misc/TileSkyCompass.java index 20e31b97d..4c05e88cc 100644 --- a/src/main/java/appeng/tile/misc/TileSkyCompass.java +++ b/src/main/java/appeng/tile/misc/TileSkyCompass.java @@ -22,19 +22,16 @@ package appeng.tile.misc; import appeng.tile.AEBaseTile; -public class TileSkyCompass extends AEBaseTile -{ +public class TileSkyCompass extends AEBaseTile { - @Override - public boolean requiresTESR() - { - return true; - } + @Override + public boolean requiresTESR() { + return true; + } - @Override - public boolean hasFastRenderer() - { - return true; - } + @Override + public boolean hasFastRenderer() { + return true; + } } diff --git a/src/main/java/appeng/tile/misc/TileVibrationChamber.java b/src/main/java/appeng/tile/misc/TileVibrationChamber.java index e8284c8c7..1517ea031 100644 --- a/src/main/java/appeng/tile/misc/TileVibrationChamber.java +++ b/src/main/java/appeng/tile/misc/TileVibrationChamber.java @@ -19,19 +19,6 @@ package appeng.tile.misc; -import java.io.IOException; - -import javax.annotation.Nonnull; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntityFurnace; -import net.minecraft.util.EnumFacing; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.Actionable; import appeng.api.networking.IGridNode; import appeng.api.networking.energy.IEnergyGrid; @@ -49,284 +36,240 @@ import appeng.util.Platform; import appeng.util.inv.InvOperation; import appeng.util.inv.WrapperFilteredItemHandler; import appeng.util.inv.filter.IAEItemFilter; +import io.netty.buffer.ByteBuf; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntityFurnace; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.items.IItemHandler; + +import javax.annotation.Nonnull; +import java.io.IOException; -public class TileVibrationChamber extends AENetworkInvTile implements IGridTickable -{ - public static final double POWER_PER_TICK = 5; - public static final int MIN_BURN_SPEED = 20; - public static final int MAX_BURN_SPEED = 200; - public static final double DILATION_SCALING = 25.0; // x4 ~ 40 AE/t at max - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 1 ); - private final IItemHandler invExt = new WrapperFilteredItemHandler( this.inv, new FuelSlotFilter() ); +public class TileVibrationChamber extends AENetworkInvTile implements IGridTickable { + public static final double POWER_PER_TICK = 5; + public static final int MIN_BURN_SPEED = 20; + public static final int MAX_BURN_SPEED = 200; + public static final double DILATION_SCALING = 25.0; // x4 ~ 40 AE/t at max + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 1); + private final IItemHandler invExt = new WrapperFilteredItemHandler(this.inv, new FuelSlotFilter()); - private int burnSpeed = 100; - private double burnTime = 0; - private double maxBurnTime = 0; + private int burnSpeed = 100; + private double burnTime = 0; + private double maxBurnTime = 0; - // client side.. - public boolean isOn; + // client side.. + public boolean isOn; - public TileVibrationChamber() - { - this.getProxy().setIdlePowerUsage( 0 ); - this.getProxy().setFlags(); - } + public TileVibrationChamber() { + this.getProxy().setIdlePowerUsage(0); + this.getProxy().setFlags(); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.COVERED; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.COVERED; + } - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - final boolean wasOn = this.isOn; + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + final boolean wasOn = this.isOn; - this.isOn = data.readBoolean(); + this.isOn = data.readBoolean(); - return wasOn != this.isOn || c; // TESR doesn't need updates! - } + return wasOn != this.isOn || c; // TESR doesn't need updates! + } - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - data.writeBoolean( this.getBurnTime() > 0 ); - } + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeBoolean(this.getBurnTime() > 0); + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setDouble( "burnTime", this.getBurnTime() ); - data.setDouble( "maxBurnTime", this.getMaxBurnTime() ); - data.setInteger( "burnSpeed", this.getBurnSpeed() ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setDouble("burnTime", this.getBurnTime()); + data.setDouble("maxBurnTime", this.getMaxBurnTime()); + data.setInteger("burnSpeed", this.getBurnSpeed()); + return data; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.setBurnTime( data.getDouble( "burnTime" ) ); - this.setMaxBurnTime( data.getDouble( "maxBurnTime" ) ); - this.setBurnSpeed( data.getInteger( "burnSpeed" ) ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.setBurnTime(data.getDouble("burnTime")); + this.setMaxBurnTime(data.getDouble("maxBurnTime")); + this.setBurnSpeed(data.getInteger("burnSpeed")); + } - @Override - protected IItemHandler getItemHandlerForSide( @Nonnull EnumFacing facing ) - { - return this.invExt; - } + @Override + protected IItemHandler getItemHandlerForSide(@Nonnull EnumFacing facing) { + return this.invExt; + } - @Override - public IItemHandler getInternalInventory() - { - return this.inv; - } + @Override + public IItemHandler getInternalInventory() { + return this.inv; + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( this.getBurnTime() <= 0 ) - { - if( this.canEatFuel() ) - { - try - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // wake up! - } - } - } - } + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { + if (this.getBurnTime() <= 0) { + if (this.canEatFuel()) { + try { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // wake up! + } + } + } + } - private boolean canEatFuel() - { - final ItemStack is = this.inv.getStackInSlot( 0 ); - if( !is.isEmpty() ) - { - final int newBurnTime = TileEntityFurnace.getItemBurnTime( is ); - if( newBurnTime > 0 && is.getCount() > 0 ) - { - return true; - } - } - return false; - } + private boolean canEatFuel() { + final ItemStack is = this.inv.getStackInSlot(0); + if (!is.isEmpty()) { + final int newBurnTime = TileEntityFurnace.getItemBurnTime(is); + return newBurnTime > 0 && is.getCount() > 0; + } + return false; + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - if( this.getBurnTime() <= 0 ) - { - this.eatFuel(); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + if (this.getBurnTime() <= 0) { + this.eatFuel(); + } - return new TickingRequest( TickRates.VibrationChamber.getMin(), TickRates.VibrationChamber.getMax(), this.getBurnTime() <= 0, false ); - } + return new TickingRequest(TickRates.VibrationChamber.getMin(), TickRates.VibrationChamber.getMax(), this.getBurnTime() <= 0, false); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( this.getBurnTime() <= 0 ) - { - this.eatFuel(); + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (this.getBurnTime() <= 0) { + this.eatFuel(); - if( this.getBurnTime() > 0 ) - { - return TickRateModulation.URGENT; - } + if (this.getBurnTime() > 0) { + return TickRateModulation.URGENT; + } - this.setBurnSpeed( 100 ); - return TickRateModulation.SLEEP; - } + this.setBurnSpeed(100); + return TickRateModulation.SLEEP; + } - this.setBurnSpeed( Math.max( MIN_BURN_SPEED, Math.min( this.getBurnSpeed(), MAX_BURN_SPEED ) ) ); - final double dilation = this.getBurnSpeed() / DILATION_SCALING; + this.setBurnSpeed(Math.max(MIN_BURN_SPEED, Math.min(this.getBurnSpeed(), MAX_BURN_SPEED))); + final double dilation = this.getBurnSpeed() / DILATION_SCALING; - double timePassed = ticksSinceLastCall * dilation; - this.setBurnTime( this.getBurnTime() - timePassed ); - if( this.getBurnTime() < 0 ) - { - timePassed += this.getBurnTime(); - this.setBurnTime( 0 ); - } + double timePassed = ticksSinceLastCall * dilation; + this.setBurnTime(this.getBurnTime() - timePassed); + if (this.getBurnTime() < 0) { + timePassed += this.getBurnTime(); + this.setBurnTime(0); + } - try - { - final IEnergyGrid grid = this.getProxy().getEnergy(); - final double newPower = timePassed * POWER_PER_TICK; - final double overFlow = grid.injectPower( newPower, Actionable.SIMULATE ); + try { + final IEnergyGrid grid = this.getProxy().getEnergy(); + final double newPower = timePassed * POWER_PER_TICK; + final double overFlow = grid.injectPower(newPower, Actionable.SIMULATE); - // burn the over flow. - grid.injectPower( Math.max( 0.0, newPower - overFlow ), Actionable.MODULATE ); + // burn the over flow. + grid.injectPower(Math.max(0.0, newPower - overFlow), Actionable.MODULATE); - if( overFlow > 0 ) - { - this.setBurnSpeed( this.getBurnSpeed() - ticksSinceLastCall ); - } - else - { - this.setBurnSpeed( this.getBurnSpeed() + ticksSinceLastCall ); - } + if (overFlow > 0) { + this.setBurnSpeed(this.getBurnSpeed() - ticksSinceLastCall); + } else { + this.setBurnSpeed(this.getBurnSpeed() + ticksSinceLastCall); + } - this.setBurnSpeed( Math.max( MIN_BURN_SPEED, Math.min( this.getBurnSpeed(), MAX_BURN_SPEED ) ) ); - return overFlow > 0 ? TickRateModulation.SLOWER : TickRateModulation.FASTER; - } - catch( final GridAccessException e ) - { - this.setBurnSpeed( this.getBurnSpeed() - ticksSinceLastCall ); - this.setBurnSpeed( Math.max( MIN_BURN_SPEED, Math.min( this.getBurnSpeed(), MAX_BURN_SPEED ) ) ); - return TickRateModulation.SLOWER; - } - } + this.setBurnSpeed(Math.max(MIN_BURN_SPEED, Math.min(this.getBurnSpeed(), MAX_BURN_SPEED))); + return overFlow > 0 ? TickRateModulation.SLOWER : TickRateModulation.FASTER; + } catch (final GridAccessException e) { + this.setBurnSpeed(this.getBurnSpeed() - ticksSinceLastCall); + this.setBurnSpeed(Math.max(MIN_BURN_SPEED, Math.min(this.getBurnSpeed(), MAX_BURN_SPEED))); + return TickRateModulation.SLOWER; + } + } - private void eatFuel() - { - final ItemStack is = this.inv.getStackInSlot( 0 ); - if( !is.isEmpty() ) - { - final int newBurnTime = TileEntityFurnace.getItemBurnTime( is ); - if( newBurnTime > 0 && is.getCount() > 0 ) - { - this.setBurnTime( this.getBurnTime() + newBurnTime ); - this.setMaxBurnTime( this.getBurnTime() ); + private void eatFuel() { + final ItemStack is = this.inv.getStackInSlot(0); + if (!is.isEmpty()) { + final int newBurnTime = TileEntityFurnace.getItemBurnTime(is); + if (newBurnTime > 0 && is.getCount() > 0) { + this.setBurnTime(this.getBurnTime() + newBurnTime); + this.setMaxBurnTime(this.getBurnTime()); - final Item fuelItem = is.getItem(); - is.shrink( 1 ); + final Item fuelItem = is.getItem(); + is.shrink(1); - if( is.isEmpty() ) - { - this.inv.setStackInSlot( 0, fuelItem.getContainerItem( is ) ); - } - else - { - this.inv.setStackInSlot( 0, is ); - } - this.saveChanges(); - } - } + if (is.isEmpty()) { + this.inv.setStackInSlot(0, fuelItem.getContainerItem(is)); + } else { + this.inv.setStackInSlot(0, is); + } + this.saveChanges(); + } + } - if( this.getBurnTime() > 0 ) - { - try - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // gah! - } - } + if (this.getBurnTime() > 0) { + try { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // gah! + } + } - // state change - if( ( !this.isOn && this.getBurnTime() > 0 ) || ( this.isOn && this.getBurnTime() <= 0 ) ) - { - this.isOn = this.getBurnTime() > 0; - this.markForUpdate(); + // state change + if ((!this.isOn && this.getBurnTime() > 0) || (this.isOn && this.getBurnTime() <= 0)) { + this.isOn = this.getBurnTime() > 0; + this.markForUpdate(); - if( this.hasWorld() ) - { - Platform.notifyBlocksOfNeighbors( this.world, this.pos ); - } - } - } + if (this.hasWorld()) { + Platform.notifyBlocksOfNeighbors(this.world, this.pos); + } + } + } - public int getBurnSpeed() - { - return this.burnSpeed; - } + public int getBurnSpeed() { + return this.burnSpeed; + } - private void setBurnSpeed( final int burnSpeed ) - { - this.burnSpeed = burnSpeed; - } + private void setBurnSpeed(final int burnSpeed) { + this.burnSpeed = burnSpeed; + } - public double getMaxBurnTime() - { - return this.maxBurnTime; - } + public double getMaxBurnTime() { + return this.maxBurnTime; + } - private void setMaxBurnTime( final double maxBurnTime ) - { - this.maxBurnTime = maxBurnTime; - } + private void setMaxBurnTime(final double maxBurnTime) { + this.maxBurnTime = maxBurnTime; + } - public double getBurnTime() - { - return this.burnTime; - } + public double getBurnTime() { + return this.burnTime; + } - private void setBurnTime( final double burnTime ) - { - this.burnTime = burnTime; - } + private void setBurnTime(final double burnTime) { + this.burnTime = burnTime; + } - private class FuelSlotFilter implements IAEItemFilter - { - @Override - public boolean allowExtract( IItemHandler inv, int slot, int amount ) - { - return !TileEntityFurnace.isItemFuel( inv.getStackInSlot( slot ) ); - } + private class FuelSlotFilter implements IAEItemFilter { + @Override + public boolean allowExtract(IItemHandler inv, int slot, int amount) { + return !TileEntityFurnace.isItemFuel(inv.getStackInSlot(slot)); + } - @Override - public boolean allowInsert( IItemHandler inv, int slot, ItemStack stack ) - { - return TileEntityFurnace.isItemFuel( stack ); - } - } + @Override + public boolean allowInsert(IItemHandler inv, int slot, ItemStack stack) { + return TileEntityFurnace.isItemFuel(stack); + } + } } diff --git a/src/main/java/appeng/tile/networking/CableBusTESR.java b/src/main/java/appeng/tile/networking/CableBusTESR.java index b2bf0e71c..1d10b4b57 100644 --- a/src/main/java/appeng/tile/networking/CableBusTESR.java +++ b/src/main/java/appeng/tile/networking/CableBusTESR.java @@ -19,34 +19,28 @@ package appeng.tile.networking; +import appeng.api.parts.IPart; +import appeng.tile.AEBaseTile; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.util.EnumFacing; -import appeng.api.parts.IPart; -import appeng.tile.AEBaseTile; +public class CableBusTESR extends TileEntitySpecialRenderer { -public class CableBusTESR extends TileEntitySpecialRenderer -{ + @Override + public void render(AEBaseTile te, double x, double y, double z, float partialTicks, int destroyStage, float p_render_10_) { - @Override - public void render( AEBaseTile te, double x, double y, double z, float partialTicks, int destroyStage, float p_render_10_ ) - { + if (!(te instanceof TileCableBusTESR)) { + return; + } - if( !( te instanceof TileCableBusTESR ) ) - { - return; - } + TileCableBusTESR realTe = (TileCableBusTESR) te; - TileCableBusTESR realTe = (TileCableBusTESR) te; - - for( EnumFacing facing : EnumFacing.values() ) - { - IPart part = realTe.getPart( facing ); - if( part != null && part.requireDynamicRender() ) - { - part.renderDynamic( x, y, z, partialTicks, destroyStage ); - } - } - } + for (EnumFacing facing : EnumFacing.values()) { + IPart part = realTe.getPart(facing); + if (part != null && part.requireDynamicRender()) { + part.renderDynamic(x, y, z, partialTicks, destroyStage); + } + } + } } diff --git a/src/main/java/appeng/tile/networking/TileCableBus.java b/src/main/java/appeng/tile/networking/TileCableBus.java index 0f53291cd..ca93af3a4 100644 --- a/src/main/java/appeng/tile/networking/TileCableBus.java +++ b/src/main/java/appeng/tile/networking/TileCableBus.java @@ -19,26 +19,6 @@ package appeng.tile.networking; -import java.io.IOException; -import java.util.List; -import java.util.Set; - -import javax.annotation.Nullable; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; -import net.minecraftforge.common.capabilities.Capability; - import appeng.api.networking.IGridNode; import appeng.api.parts.IFacadeContainer; import appeng.api.parts.IPart; @@ -55,363 +35,320 @@ import appeng.hooks.TickHandler; import appeng.parts.CableBusContainer; import appeng.tile.AEBaseTile; import appeng.util.Platform; +import io.netty.buffer.ByteBuf; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; +import net.minecraft.world.World; +import net.minecraftforge.common.capabilities.Capability; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.util.List; +import java.util.Set; -public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomCollision -{ +public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomCollision { - private CableBusContainer cb = new CableBusContainer( this ); + private CableBusContainer cb = new CableBusContainer(this); - private int oldLV = -1; // on re-calculate light when it changes + private int oldLV = -1; // on re-calculate light when it changes - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.getCableBus().readFromNBT( data ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.getCableBus().readFromNBT(data); + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.getCableBus().writeToNBT( data ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.getCableBus().writeToNBT(data); + return data; + } - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - boolean ret = this.getCableBus().readFromStream( data ); + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + boolean ret = this.getCableBus().readFromStream(data); - final int newLV = this.getCableBus().getLightValue(); - if( newLV != this.oldLV ) - { - this.oldLV = newLV; - this.world.checkLight( this.pos ); - ret = true; - } + final int newLV = this.getCableBus().getLightValue(); + if (newLV != this.oldLV) { + this.oldLV = newLV; + this.world.checkLight(this.pos); + ret = true; + } - this.updateTileSetting(); - return ret || c; - } + this.updateTileSetting(); + return ret || c; + } - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - this.getCableBus().writeToStream( data ); - } + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + this.getCableBus().writeToStream(data); + } - /** - * Changes this tile to the TESR version if any of the parts require dynamic rendering. - */ - protected void updateTileSetting() - { - if( this.getCableBus().isRequiresDynamicRender() ) - { - try - { - final TileCableBus tcb = (TileCableBus) BlockCableBus.getTesrTile().newInstance(); - tcb.copyFrom( this ); - this.getWorld().setTileEntity( this.pos, tcb ); - } - catch( final Throwable ignored ) - { + /** + * Changes this tile to the TESR version if any of the parts require dynamic rendering. + */ + protected void updateTileSetting() { + if (this.getCableBus().isRequiresDynamicRender()) { + try { + final TileCableBus tcb = (TileCableBus) BlockCableBus.getTesrTile().newInstance(); + tcb.copyFrom(this); + this.getWorld().setTileEntity(this.pos, tcb); + } catch (final Throwable ignored) { - } - } - } + } + } + } - protected void copyFrom( final TileCableBus oldTile ) - { - final CableBusContainer tmpCB = this.getCableBus(); - this.setCableBus( oldTile.getCableBus() ); - this.oldLV = oldTile.oldLV; - oldTile.setCableBus( tmpCB ); - } + protected void copyFrom(final TileCableBus oldTile) { + final CableBusContainer tmpCB = this.getCableBus(); + this.setCableBus(oldTile.getCableBus()); + this.oldLV = oldTile.oldLV; + oldTile.setCableBus(tmpCB); + } - @Override - public double getMaxRenderDistanceSquared() - { - return 900.0; - } + @Override + public double getMaxRenderDistanceSquared() { + return 900.0; + } - @Override - public void invalidate() - { - super.invalidate(); - this.getCableBus().removeFromWorld(); - } + @Override + public void invalidate() { + super.invalidate(); + this.getCableBus().removeFromWorld(); + } - @Override - public void validate() - { - super.validate(); - TickHandler.INSTANCE.addInit( this ); - } + @Override + public void validate() { + super.validate(); + TickHandler.INSTANCE.addInit(this); + } - @Override - public IGridNode getGridNode( final AEPartLocation dir ) - { - return this.getCableBus().getGridNode( dir ); - } + @Override + public IGridNode getGridNode(final AEPartLocation dir) { + return this.getCableBus().getGridNode(dir); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation side ) - { - return this.getCableBus().getCableConnectionType( side ); - } + @Override + public AECableType getCableConnectionType(final AEPartLocation side) { + return this.getCableBus().getCableConnectionType(side); + } - @Override - public float getCableConnectionLength( AECableType cable ) - { - return this.getCableBus().getCableConnectionLength( cable ); - } + @Override + public float getCableConnectionLength(AECableType cable) { + return this.getCableBus().getCableConnectionLength(cable); + } - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.getCableBus().removeFromWorld(); - } + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.getCableBus().removeFromWorld(); + } - @Override - public void markForUpdate() - { - if( this.world == null ) - { - return; - } + @Override + public void markForUpdate() { + if (this.world == null) { + return; + } - final int newLV = this.getCableBus().getLightValue(); - if( newLV != this.oldLV ) - { - this.oldLV = newLV; - this.world.checkLight( this.pos ); - } + final int newLV = this.getCableBus().getLightValue(); + if (newLV != this.oldLV) { + this.oldLV = newLV; + this.world.checkLight(this.pos); + } - super.markForUpdate(); - } + super.markForUpdate(); + } - @Override - public boolean canBeRotated() - { - return false; - } + @Override + public boolean canBeRotated() { + return false; + } - @Override - public void getDrops( final World w, final BlockPos pos, final List drops ) - { - this.getCableBus().getDrops( drops ); - } + @Override + public void getDrops(final World w, final BlockPos pos, final List drops) { + this.getCableBus().getDrops(drops); + } - @Override - public void getNoDrops( final World w, final BlockPos pos, final List drops ) - { - this.getCableBus().getNoDrops( drops ); - } + @Override + public void getNoDrops(final World w, final BlockPos pos, final List drops) { + this.getCableBus().getNoDrops(drops); + } - @Override - public void onReady() - { - super.onReady(); - if( this.getCableBus().isEmpty() ) - { - if( this.world.getTileEntity( this.pos ) == this ) - { - this.world.destroyBlock( this.pos, true ); - } - } - else - { - this.getCableBus().addToWorld(); - } - } + @Override + public void onReady() { + super.onReady(); + if (this.getCableBus().isEmpty()) { + if (this.world.getTileEntity(this.pos) == this) { + this.world.destroyBlock(this.pos, true); + } + } else { + this.getCableBus().addToWorld(); + } + } - @Override - public boolean requiresTESR() - { - return this.getCableBus().isRequiresDynamicRender(); - } + @Override + public boolean requiresTESR() { + return this.getCableBus().isRequiresDynamicRender(); + } - @Override - public IFacadeContainer getFacadeContainer() - { - return this.getCableBus().getFacadeContainer(); - } + @Override + public IFacadeContainer getFacadeContainer() { + return this.getCableBus().getFacadeContainer(); + } - @Override - public boolean canAddPart( final ItemStack is, final AEPartLocation side ) - { - return this.getCableBus().canAddPart( is, side ); - } + @Override + public boolean canAddPart(final ItemStack is, final AEPartLocation side) { + return this.getCableBus().canAddPart(is, side); + } - @Override - public AEPartLocation addPart( final ItemStack is, final AEPartLocation side, final EntityPlayer player, final EnumHand hand ) - { - return this.getCableBus().addPart( is, side, player, hand ); - } + @Override + public AEPartLocation addPart(final ItemStack is, final AEPartLocation side, final EntityPlayer player, final EnumHand hand) { + return this.getCableBus().addPart(is, side, player, hand); + } - @Override - public IPart getPart( final AEPartLocation side ) - { - return this.cb.getPart( side ); - } + @Override + public IPart getPart(final AEPartLocation side) { + return this.cb.getPart(side); + } - @Override - public IPart getPart( final EnumFacing side ) - { - return this.getCableBus().getPart( side ); - } + @Override + public IPart getPart(final EnumFacing side) { + return this.getCableBus().getPart(side); + } - @Override - public void removePart( final AEPartLocation side, final boolean suppressUpdate ) - { - this.getCableBus().removePart( side, suppressUpdate ); - } + @Override + public void removePart(final AEPartLocation side, final boolean suppressUpdate) { + this.getCableBus().removePart(side, suppressUpdate); + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - public AEColor getColor() - { - return this.getCableBus().getColor(); - } + @Override + public AEColor getColor() { + return this.getCableBus().getColor(); + } - @Override - public void clearContainer() - { - this.setCableBus( new CableBusContainer( this ) ); - } + @Override + public void clearContainer() { + this.setCableBus(new CableBusContainer(this)); + } - @Override - public boolean isBlocked( final EnumFacing side ) - { - // TODO 1.10.2-R - Stuff. - return false; - } + @Override + public boolean isBlocked(final EnumFacing side) { + // TODO 1.10.2-R - Stuff. + return false; + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final BlockPos pos, final Entity e, final boolean visual ) - { - return this.getCableBus().getSelectedBoundingBoxesFromPool( false, true, e, visual ); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool(final World w, final BlockPos pos, final Entity e, final boolean visual) { + return this.getCableBus().getSelectedBoundingBoxesFromPool(false, true, e, visual); + } - @Override - public SelectedPart selectPart( final Vec3d pos ) - { - return this.getCableBus().selectPart( pos ); - } + @Override + public SelectedPart selectPart(final Vec3d pos) { + return this.getCableBus().selectPart(pos); + } - @Override - public void markForSave() - { - this.saveChanges(); - } + @Override + public void markForSave() { + this.saveChanges(); + } - @Override - public void partChanged() - { - this.notifyNeighbors(); - } + @Override + public void partChanged() { + this.notifyNeighbors(); + } - @Override - public boolean hasRedstone( final AEPartLocation side ) - { - return this.getCableBus().hasRedstone( side ); - } + @Override + public boolean hasRedstone(final AEPartLocation side) { + return this.getCableBus().hasRedstone(side); + } - @Override - public boolean isEmpty() - { - return this.getCableBus().isEmpty(); - } + @Override + public boolean isEmpty() { + return this.getCableBus().isEmpty(); + } - @Override - public Set getLayerFlags() - { - return this.getCableBus().getLayerFlags(); - } + @Override + public Set getLayerFlags() { + return this.getCableBus().getLayerFlags(); + } - @Override - public void cleanup() - { - this.getWorld().setBlockToAir( this.pos ); - } + @Override + public void cleanup() { + this.getWorld().setBlockToAir(this.pos); + } - @Override - public void addCollidingBlockToList( final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e ) - { - for( final AxisAlignedBB bx : this.getSelectedBoundingBoxesFromPool( w, pos, e, false ) ) - { - out.add( new AxisAlignedBB( bx.minX, bx.minY, bx.minZ, bx.maxX, bx.maxY, bx.maxZ ) ); - } - } + @Override + public void addCollidingBlockToList(final World w, final BlockPos pos, final AxisAlignedBB bb, final List out, final Entity e) { + for (final AxisAlignedBB bx : this.getSelectedBoundingBoxesFromPool(w, pos, e, false)) { + out.add(new AxisAlignedBB(bx.minX, bx.minY, bx.minZ, bx.maxX, bx.maxY, bx.maxZ)); + } + } - @Override - public void notifyNeighbors() - { - if( this.world != null && this.world.isBlockLoaded( this.pos ) && !CableBusContainer.isLoading() ) - { - Platform.notifyBlocksOfNeighbors( this.world, this.pos ); - } - } + @Override + public void notifyNeighbors() { + if (this.world != null && this.world.isBlockLoaded(this.pos) && !CableBusContainer.isLoading()) { + Platform.notifyBlocksOfNeighbors(this.world, this.pos); + } + } - @Override - public boolean isInWorld() - { - return this.getCableBus().isInWorld(); - } + @Override + public boolean isInWorld() { + return this.getCableBus().isInWorld(); + } - @Override - public boolean recolourBlock( final EnumFacing side, final AEColor colour, final EntityPlayer who ) - { - return this.getCableBus().recolourBlock( side, colour, who ); - } + @Override + public boolean recolourBlock(final EnumFacing side, final AEColor colour, final EntityPlayer who) { + return this.getCableBus().recolourBlock(side, colour, who); + } - public CableBusContainer getCableBus() - { - return this.cb; - } + public CableBusContainer getCableBus() { + return this.cb; + } - private void setCableBus( final CableBusContainer cb ) - { - this.cb = cb; - } + private void setCableBus(final CableBusContainer cb) { + this.cb = cb; + } - @Override - public boolean hasCapability( Capability capabilityClass, @Nullable EnumFacing fromSide ) - { - // Note that null will be translated to INTERNAL here - AEPartLocation partLocation = AEPartLocation.fromFacing( fromSide ); + @Override + public boolean hasCapability(Capability capabilityClass, @Nullable EnumFacing fromSide) { + // Note that null will be translated to INTERNAL here + AEPartLocation partLocation = AEPartLocation.fromFacing(fromSide); - IPart part = this.getPart( partLocation ); - boolean result = part != null && part.hasCapability( capabilityClass ); + IPart part = this.getPart(partLocation); + boolean result = part != null && part.hasCapability(capabilityClass); - return result || super.hasCapability( capabilityClass, fromSide ); - } + return result || super.hasCapability(capabilityClass, fromSide); + } - @Override - public T getCapability( Capability capabilityClass, @Nullable EnumFacing fromSide ) - { - // Note that null will be translated to INTERNAL here - AEPartLocation partLocation = AEPartLocation.fromFacing( fromSide ); + @Override + public T getCapability(Capability capabilityClass, @Nullable EnumFacing fromSide) { + // Note that null will be translated to INTERNAL here + AEPartLocation partLocation = AEPartLocation.fromFacing(fromSide); - IPart part = this.getPart( partLocation ); - T result = part == null ? null : part.getCapability( capabilityClass ); + IPart part = this.getPart(partLocation); + T result = part == null ? null : part.getCapability(capabilityClass); - if( result != null ) - { - return result; - } + if (result != null) { + return result; + } - return super.getCapability( capabilityClass, fromSide ); - } + return super.getCapability(capabilityClass, fromSide); + } } diff --git a/src/main/java/appeng/tile/networking/TileCableBusTESR.java b/src/main/java/appeng/tile/networking/TileCableBusTESR.java index b775765ec..3c4cd91e6 100644 --- a/src/main/java/appeng/tile/networking/TileCableBusTESR.java +++ b/src/main/java/appeng/tile/networking/TileCableBusTESR.java @@ -22,27 +22,21 @@ package appeng.tile.networking; import appeng.block.networking.BlockCableBus; -public class TileCableBusTESR extends TileCableBus -{ +public class TileCableBusTESR extends TileCableBus { - /** - * Changes this tile to the non-TESR version, if none of the parts require dynamic rendering. - */ - @Override - protected void updateTileSetting() - { - if( !this.getCableBus().isRequiresDynamicRender() ) - { - try - { - final TileCableBus tcb = (TileCableBus) BlockCableBus.getNoTesrTile().newInstance(); - tcb.copyFrom( this ); - this.getWorld().setTileEntity( this.pos, tcb ); - } - catch( final Throwable ignored ) - { + /** + * Changes this tile to the non-TESR version, if none of the parts require dynamic rendering. + */ + @Override + protected void updateTileSetting() { + if (!this.getCableBus().isRequiresDynamicRender()) { + try { + final TileCableBus tcb = (TileCableBus) BlockCableBus.getNoTesrTile().newInstance(); + tcb.copyFrom(this); + this.getWorld().setTileEntity(this.pos, tcb); + } catch (final Throwable ignored) { - } - } - } + } + } + } } diff --git a/src/main/java/appeng/tile/networking/TileController.java b/src/main/java/appeng/tile/networking/TileController.java index ec9bf8907..e30cfea87 100644 --- a/src/main/java/appeng/tile/networking/TileController.java +++ b/src/main/java/appeng/tile/networking/TileController.java @@ -19,14 +19,6 @@ package appeng.tile.networking; -import java.util.EnumSet; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.wrapper.EmptyHandler; - import appeng.api.config.Actionable; import appeng.api.networking.GridFlags; import appeng.api.networking.energy.IEnergyGrid; @@ -43,177 +35,149 @@ import appeng.block.networking.BlockController.ControllerBlockState; import appeng.me.GridAccessException; import appeng.tile.grid.AENetworkPowerTile; import appeng.util.inv.InvOperation; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.wrapper.EmptyHandler; + +import java.util.EnumSet; -public class TileController extends AENetworkPowerTile -{ - private boolean isValid = false; +public class TileController extends AENetworkPowerTile { + private boolean isValid = false; - public TileController() - { - this.setInternalMaxPower( 8000 ); - this.setInternalPublicPowerStorage( true ); - this.getProxy().setIdlePowerUsage( 3 ); - this.getProxy().setFlags( GridFlags.CANNOT_CARRY, GridFlags.DENSE_CAPACITY ); - } + public TileController() { + this.setInternalMaxPower(8000); + this.setInternalPublicPowerStorage(true); + this.getProxy().setIdlePowerUsage(3); + this.getProxy().setFlags(GridFlags.CANNOT_CARRY, GridFlags.DENSE_CAPACITY); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.DENSE_SMART; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.DENSE_SMART; + } - @Override - public void onReady() - { - this.onNeighborChange( true ); - super.onReady(); - } + @Override + public void onReady() { + this.onNeighborChange(true); + super.onReady(); + } - public void onNeighborChange( final boolean force ) - { - final boolean xx = this.checkController( this.pos.offset( EnumFacing.EAST ) ) && this.checkController( this.pos.offset( EnumFacing.WEST ) ); - final boolean yy = this.checkController( this.pos.offset( EnumFacing.UP ) ) && this.checkController( this.pos.offset( EnumFacing.DOWN ) ); - final boolean zz = this.checkController( this.pos.offset( EnumFacing.NORTH ) ) && this.checkController( this.pos.offset( EnumFacing.SOUTH ) ); + public void onNeighborChange(final boolean force) { + final boolean xx = this.checkController(this.pos.offset(EnumFacing.EAST)) && this.checkController(this.pos.offset(EnumFacing.WEST)); + final boolean yy = this.checkController(this.pos.offset(EnumFacing.UP)) && this.checkController(this.pos.offset(EnumFacing.DOWN)); + final boolean zz = this.checkController(this.pos.offset(EnumFacing.NORTH)) && this.checkController(this.pos.offset(EnumFacing.SOUTH)); - // int meta = world.getBlockMetadata( xCoord, yCoord, zCoord ); - // boolean hasPower = meta > 0; - // boolean isConflict = meta == 2; + // int meta = world.getBlockMetadata( xCoord, yCoord, zCoord ); + // boolean hasPower = meta > 0; + // boolean isConflict = meta == 2; - final boolean oldValid = this.isValid; + final boolean oldValid = this.isValid; - this.isValid = ( xx && !yy && !zz ) || ( !xx && yy && !zz ) || ( !xx && !yy && zz ) || ( ( xx ? 1 : 0 ) + ( yy ? 1 : 0 ) + ( zz ? 1 : 0 ) <= 1 ); + this.isValid = (xx && !yy && !zz) || (!xx && yy && !zz) || (!xx && !yy && zz) || ((xx ? 1 : 0) + (yy ? 1 : 0) + (zz ? 1 : 0) <= 1); - if( oldValid != this.isValid || force ) - { - if( this.isValid ) - { - this.getProxy().setValidSides( EnumSet.allOf( EnumFacing.class ) ); - } - else - { - this.getProxy().setValidSides( EnumSet.noneOf( EnumFacing.class ) ); - } + if (oldValid != this.isValid || force) { + if (this.isValid) { + this.getProxy().setValidSides(EnumSet.allOf(EnumFacing.class)); + } else { + this.getProxy().setValidSides(EnumSet.noneOf(EnumFacing.class)); + } - this.updateMeta(); - } + this.updateMeta(); + } - } + } - private void updateMeta() - { - if( !this.getProxy().isReady() ) - { - return; - } + private void updateMeta() { + if (!this.getProxy().isReady()) { + return; + } - ControllerBlockState metaState = ControllerBlockState.offline; + ControllerBlockState metaState = ControllerBlockState.offline; - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - metaState = ControllerBlockState.online; + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + metaState = ControllerBlockState.online; - if( this.getProxy().getPath().getControllerState() == ControllerState.CONTROLLER_CONFLICT ) - { - metaState = ControllerBlockState.conflicted; - } - } - } - catch( final GridAccessException e ) - { - metaState = ControllerBlockState.offline; - } + if (this.getProxy().getPath().getControllerState() == ControllerState.CONTROLLER_CONFLICT) { + metaState = ControllerBlockState.conflicted; + } + } + } catch (final GridAccessException e) { + metaState = ControllerBlockState.offline; + } - if( this.checkController( this.pos ) && this.world.getBlockState( this.pos ).getValue( BlockController.CONTROLLER_STATE ) != metaState ) - { - this.world.setBlockState( this.pos, this.world.getBlockState( this.pos ).withProperty( BlockController.CONTROLLER_STATE, metaState ) ); - } + if (this.checkController(this.pos) && this.world.getBlockState(this.pos).getValue(BlockController.CONTROLLER_STATE) != metaState) { + this.world.setBlockState(this.pos, this.world.getBlockState(this.pos).withProperty(BlockController.CONTROLLER_STATE, metaState)); + } - } + } - @Override - protected double getFunnelPowerDemand( final double maxReceived ) - { - try - { - final IEnergyGrid grid = this.getProxy().getEnergy(); + @Override + protected double getFunnelPowerDemand(final double maxReceived) { + try { + final IEnergyGrid grid = this.getProxy().getEnergy(); - return grid.getEnergyDemand( maxReceived ); - } - catch( final GridAccessException e ) - { - // no grid? use local... - return super.getFunnelPowerDemand( maxReceived ); - } - } + return grid.getEnergyDemand(maxReceived); + } catch (final GridAccessException e) { + // no grid? use local... + return super.getFunnelPowerDemand(maxReceived); + } + } - @Override - protected double funnelPowerIntoStorage( final double power, final Actionable mode ) - { - try - { - final IEnergyGrid grid = this.getProxy().getEnergy(); - final double leftOver = grid.injectPower( power, mode ); + @Override + protected double funnelPowerIntoStorage(final double power, final Actionable mode) { + try { + final IEnergyGrid grid = this.getProxy().getEnergy(); + final double leftOver = grid.injectPower(power, mode); - return leftOver; - } - catch( final GridAccessException e ) - { - // no grid? use local... - return super.funnelPowerIntoStorage( power, mode ); - } - } + return leftOver; + } catch (final GridAccessException e) { + // no grid? use local... + return super.funnelPowerIntoStorage(power, mode); + } + } - @Override - protected void PowerEvent( final PowerEventType x ) - { - try - { - this.getProxy().getGrid().postEvent( new MENetworkPowerStorage( this, x ) ); - } - catch( final GridAccessException e ) - { - // not ready! - } - } + @Override + protected void PowerEvent(final PowerEventType x) { + try { + this.getProxy().getGrid().postEvent(new MENetworkPowerStorage(this, x)); + } catch (final GridAccessException e) { + // not ready! + } + } - @MENetworkEventSubscribe - public void onControllerChange( final MENetworkControllerChange status ) - { - this.updateMeta(); - } + @MENetworkEventSubscribe + public void onControllerChange(final MENetworkControllerChange status) { + this.updateMeta(); + } - @MENetworkEventSubscribe - public void onPowerChange( final MENetworkPowerStatusChange status ) - { - this.updateMeta(); - } + @MENetworkEventSubscribe + public void onPowerChange(final MENetworkPowerStatusChange status) { + this.updateMeta(); + } - @Override - public IItemHandler getInternalInventory() - { - return EmptyHandler.INSTANCE; - } + @Override + public IItemHandler getInternalInventory() { + return EmptyHandler.INSTANCE; + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - } + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { + } - /** - * Check for a controller at this coordinates as well as is it loaded. - * - * @return true if there is a loaded controller - */ - private boolean checkController( final BlockPos pos ) - { - if( this.world.getChunkProvider().getLoadedChunk( pos.getX() >> 4, pos.getZ() >> 4 ) != null ) - { - return this.world.getTileEntity( pos ) instanceof TileController; - } + /** + * Check for a controller at this coordinates as well as is it loaded. + * + * @return true if there is a loaded controller + */ + private boolean checkController(final BlockPos pos) { + if (this.world.getChunkProvider().getLoadedChunk(pos.getX() >> 4, pos.getZ() >> 4) != null) { + return this.world.getTileEntity(pos) instanceof TileController; + } - return false; - } + return false; + } } diff --git a/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java b/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java index 8d6618f6d..08b88db23 100644 --- a/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java +++ b/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java @@ -28,53 +28,44 @@ import appeng.api.util.AEPartLocation; import appeng.tile.grid.AENetworkTile; -public class TileCreativeEnergyCell extends AENetworkTile implements IAEPowerStorage -{ +public class TileCreativeEnergyCell extends AENetworkTile implements IAEPowerStorage { - public TileCreativeEnergyCell() - { - this.getProxy().setIdlePowerUsage( 0 ); - } + public TileCreativeEnergyCell() { + this.getProxy().setIdlePowerUsage(0); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.COVERED; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.COVERED; + } - @Override - public double injectAEPower( final double amt, final Actionable mode ) - { - return 0; - } + @Override + public double injectAEPower(final double amt, final Actionable mode) { + return 0; + } - @Override - public double getAEMaxPower() - { - return Long.MAX_VALUE / 10000; - } + @Override + public double getAEMaxPower() { + return Long.MAX_VALUE / 10000; + } - @Override - public double getAECurrentPower() - { - return Long.MAX_VALUE / 10000; - } + @Override + public double getAECurrentPower() { + return Long.MAX_VALUE / 10000; + } - @Override - public boolean isAEPublicPowerStorage() - { - return true; - } + @Override + public boolean isAEPublicPowerStorage() { + return true; + } - @Override - public AccessRestriction getPowerFlow() - { - return AccessRestriction.READ_WRITE; - } + @Override + public AccessRestriction getPowerFlow() { + return AccessRestriction.READ_WRITE; + } - @Override - public double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier pm ) - { - return amt; - } + @Override + public double extractAEPower(final double amt, final Actionable mode, final PowerMultiplier pm) { + return amt; + } } diff --git a/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java b/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java index 7c2a8deef..df2c8fdc0 100644 --- a/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java +++ b/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java @@ -19,11 +19,9 @@ package appeng.tile.networking; -public class TileDenseEnergyCell extends TileEnergyCell -{ +public class TileDenseEnergyCell extends TileEnergyCell { - public TileDenseEnergyCell() - { - this.setInternalMaxPower( 200000 * 8 ); - } + public TileDenseEnergyCell() { + this.setInternalMaxPower(200000 * 8); + } } diff --git a/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java b/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java index 1efc00e2c..a095fcd29 100644 --- a/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java +++ b/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java @@ -19,10 +19,6 @@ package appeng.tile.networking; -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.wrapper.EmptyHandler; - import appeng.api.config.Actionable; import appeng.api.networking.energy.IEnergyGrid; import appeng.api.util.AECableType; @@ -30,68 +26,57 @@ import appeng.api.util.AEPartLocation; import appeng.me.GridAccessException; import appeng.tile.grid.AENetworkPowerTile; import appeng.util.inv.InvOperation; +import net.minecraft.item.ItemStack; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.wrapper.EmptyHandler; -public class TileEnergyAcceptor extends AENetworkPowerTile -{ - public TileEnergyAcceptor() - { - this.getProxy().setIdlePowerUsage( 0.0 ); - this.setInternalMaxPower( 0 ); - } +public class TileEnergyAcceptor extends AENetworkPowerTile { + public TileEnergyAcceptor() { + this.getProxy().setIdlePowerUsage(0.0); + this.setInternalMaxPower(0); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.COVERED; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.COVERED; + } - @Override - protected double getFunnelPowerDemand( final double maxRequired ) - { - try - { - final IEnergyGrid grid = this.getProxy().getEnergy(); + @Override + protected double getFunnelPowerDemand(final double maxRequired) { + try { + final IEnergyGrid grid = this.getProxy().getEnergy(); - return grid.getEnergyDemand( maxRequired ); - } - catch( final GridAccessException e ) - { - return 0; - } - } + return grid.getEnergyDemand(maxRequired); + } catch (final GridAccessException e) { + return 0; + } + } - @Override - public double getInternalMaxPower() - { - return getFunnelPowerDemand( Long.MAX_VALUE ); - } + @Override + public double getInternalMaxPower() { + return getFunnelPowerDemand(Long.MAX_VALUE); + } - @Override - protected double funnelPowerIntoStorage( final double power, final Actionable mode ) - { - try - { - final IEnergyGrid grid = this.getProxy().getEnergy(); - final double leftOver = grid.injectPower( power, mode ); + @Override + protected double funnelPowerIntoStorage(final double power, final Actionable mode) { + try { + final IEnergyGrid grid = this.getProxy().getEnergy(); + final double leftOver = grid.injectPower(power, mode); - return leftOver; - } - catch( final GridAccessException e ) - { - return super.funnelPowerIntoStorage( power, mode ); - } - } + return leftOver; + } catch (final GridAccessException e) { + return super.funnelPowerIntoStorage(power, mode); + } + } - @Override - public IItemHandler getInternalInventory() - { - return EmptyHandler.INSTANCE; - } + @Override + public IItemHandler getInternalInventory() { + return EmptyHandler.INSTANCE; + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { - } + } } diff --git a/src/main/java/appeng/tile/networking/TileEnergyCell.java b/src/main/java/appeng/tile/networking/TileEnergyCell.java index ac18962a4..7d486dd66 100644 --- a/src/main/java/appeng/tile/networking/TileEnergyCell.java +++ b/src/main/java/appeng/tile/networking/TileEnergyCell.java @@ -19,8 +19,6 @@ package appeng.tile.networking; -import net.minecraft.nbt.NBTTagCompound; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -33,224 +31,188 @@ import appeng.block.networking.BlockEnergyCell; import appeng.me.GridAccessException; import appeng.tile.grid.AENetworkTile; import appeng.util.SettingsFrom; +import net.minecraft.nbt.NBTTagCompound; -public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage -{ +public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage { - private double internalCurrentPower = 0.0; - private double internalMaxPower = 200000.0; + private double internalCurrentPower = 0.0; + private double internalMaxPower = 200000.0; - private byte currentMeta = -1; + private byte currentMeta = -1; - public TileEnergyCell() - { - this.getProxy().setIdlePowerUsage( 0 ); - } + public TileEnergyCell() { + this.getProxy().setIdlePowerUsage(0); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.COVERED; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.COVERED; + } - @Override - public void onReady() - { - super.onReady(); - final int value = this.world.getBlockState( this.pos ).getValue( BlockEnergyCell.ENERGY_STORAGE ); - this.currentMeta = (byte) value; - this.changePowerLevel(); - } + @Override + public void onReady() { + super.onReady(); + final int value = this.world.getBlockState(this.pos).getValue(BlockEnergyCell.ENERGY_STORAGE); + this.currentMeta = (byte) value; + this.changePowerLevel(); + } - /** - * Given a fill factor, return the storage level (0-7) used for the state of the block. - * This is also used for determining the item model. - */ - public static int getStorageLevelFromFillFactor( double fillFactor ) - { - byte boundMetadata = (byte) ( 8.0 * ( fillFactor ) ); + /** + * Given a fill factor, return the storage level (0-7) used for the state of the block. + * This is also used for determining the item model. + */ + public static int getStorageLevelFromFillFactor(double fillFactor) { + byte boundMetadata = (byte) (8.0 * (fillFactor)); - if( boundMetadata > 7 ) - { - boundMetadata = 7; - } - if( boundMetadata < 0 ) - { - boundMetadata = 0; - } - return boundMetadata; - } + if (boundMetadata > 7) { + boundMetadata = 7; + } + if (boundMetadata < 0) { + boundMetadata = 0; + } + return boundMetadata; + } - private void changePowerLevel() - { - if( this.notLoaded() || this.isInvalid() ) - { - return; - } + private void changePowerLevel() { + if (this.notLoaded() || this.isInvalid()) { + return; + } - int storageLevel = getStorageLevelFromFillFactor( this.internalCurrentPower / this.getInternalMaxPower() ); + int storageLevel = getStorageLevelFromFillFactor(this.internalCurrentPower / this.getInternalMaxPower()); - if( this.currentMeta != storageLevel ) - { - this.currentMeta = (byte) storageLevel; - this.world.setBlockState( this.pos, this.world.getBlockState( this.pos ).withProperty( BlockEnergyCell.ENERGY_STORAGE, storageLevel ) ); - } - } + if (this.currentMeta != storageLevel) { + this.currentMeta = (byte) storageLevel; + this.world.setBlockState(this.pos, this.world.getBlockState(this.pos).withProperty(BlockEnergyCell.ENERGY_STORAGE, storageLevel)); + } + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setDouble( "internalCurrentPower", this.internalCurrentPower ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setDouble("internalCurrentPower", this.internalCurrentPower); + return data; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.internalCurrentPower = data.getDouble( "internalCurrentPower" ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.internalCurrentPower = data.getDouble("internalCurrentPower"); + } - @Override - public boolean canBeRotated() - { - return false; - } + @Override + public boolean canBeRotated() { + return false; + } - @Override - public void uploadSettings( final SettingsFrom from, final NBTTagCompound compound ) - { - if( from == SettingsFrom.DISMANTLE_ITEM ) - { - this.internalCurrentPower = compound.getDouble( "internalCurrentPower" ); - } - } + @Override + public void uploadSettings(final SettingsFrom from, final NBTTagCompound compound) { + if (from == SettingsFrom.DISMANTLE_ITEM) { + this.internalCurrentPower = compound.getDouble("internalCurrentPower"); + } + } - @Override - public NBTTagCompound downloadSettings( final SettingsFrom from ) - { - if( from == SettingsFrom.DISMANTLE_ITEM ) - { - final NBTTagCompound tag = new NBTTagCompound(); - tag.setDouble( "internalCurrentPower", this.internalCurrentPower ); - tag.setDouble( "internalMaxPower", this.getInternalMaxPower() ); // used for tool tip. - return tag; - } - return null; - } + @Override + public NBTTagCompound downloadSettings(final SettingsFrom from) { + if (from == SettingsFrom.DISMANTLE_ITEM) { + final NBTTagCompound tag = new NBTTagCompound(); + tag.setDouble("internalCurrentPower", this.internalCurrentPower); + tag.setDouble("internalMaxPower", this.getInternalMaxPower()); // used for tool tip. + return tag; + } + return null; + } - @Override - public final double injectAEPower( double amt, final Actionable mode ) - { - if( mode == Actionable.SIMULATE ) - { - final double fakeBattery = this.internalCurrentPower + amt; - if( fakeBattery > this.getInternalMaxPower() ) - { - return fakeBattery - this.getInternalMaxPower(); - } + @Override + public final double injectAEPower(double amt, final Actionable mode) { + if (mode == Actionable.SIMULATE) { + final double fakeBattery = this.internalCurrentPower + amt; + if (fakeBattery > this.getInternalMaxPower()) { + return fakeBattery - this.getInternalMaxPower(); + } - return 0; - } + return 0; + } - if( this.internalCurrentPower < 0.01 && amt > 0 ) - { - this.getProxy().getNode().getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.PROVIDE_POWER ) ); - } + if (this.internalCurrentPower < 0.01 && amt > 0) { + this.getProxy().getNode().getGrid().postEvent(new MENetworkPowerStorage(this, PowerEventType.PROVIDE_POWER)); + } - this.internalCurrentPower += amt; - if( this.internalCurrentPower > this.getInternalMaxPower() ) - { - amt = this.internalCurrentPower - this.getInternalMaxPower(); - this.internalCurrentPower = this.getInternalMaxPower(); + this.internalCurrentPower += amt; + if (this.internalCurrentPower > this.getInternalMaxPower()) { + amt = this.internalCurrentPower - this.getInternalMaxPower(); + this.internalCurrentPower = this.getInternalMaxPower(); - this.changePowerLevel(); - return amt; - } + this.changePowerLevel(); + return amt; + } - this.changePowerLevel(); - return 0; - } + this.changePowerLevel(); + return 0; + } - @Override - public double getAEMaxPower() - { - return this.getInternalMaxPower(); - } + @Override + public double getAEMaxPower() { + return this.getInternalMaxPower(); + } - @Override - public double getAECurrentPower() - { - return this.internalCurrentPower; - } + @Override + public double getAECurrentPower() { + return this.internalCurrentPower; + } - @Override - public boolean isAEPublicPowerStorage() - { - return true; - } + @Override + public boolean isAEPublicPowerStorage() { + return true; + } - @Override - public AccessRestriction getPowerFlow() - { - return AccessRestriction.READ_WRITE; - } + @Override + public AccessRestriction getPowerFlow() { + return AccessRestriction.READ_WRITE; + } - @Override - public final double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier pm ) - { - return pm.divide( this.extractAEPower( pm.multiply( amt ), mode ) ); - } + @Override + public final double extractAEPower(final double amt, final Actionable mode, final PowerMultiplier pm) { + return pm.divide(this.extractAEPower(pm.multiply(amt), mode)); + } - private double extractAEPower( double amt, final Actionable mode ) - { - if( mode == Actionable.SIMULATE ) - { - if( this.internalCurrentPower > amt ) - { - return amt; - } - return this.internalCurrentPower; - } + private double extractAEPower(double amt, final Actionable mode) { + if (mode == Actionable.SIMULATE) { + if (this.internalCurrentPower > amt) { + return amt; + } + return this.internalCurrentPower; + } - final boolean wasFull = this.internalCurrentPower >= this.getInternalMaxPower() - 0.001; + final boolean wasFull = this.internalCurrentPower >= this.getInternalMaxPower() - 0.001; - if( wasFull && amt > 0 ) - { - try - { - this.getProxy().getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.REQUEST_POWER ) ); - } - catch( final GridAccessException ignored ) - { + if (wasFull && amt > 0) { + try { + this.getProxy().getGrid().postEvent(new MENetworkPowerStorage(this, PowerEventType.REQUEST_POWER)); + } catch (final GridAccessException ignored) { - } - } + } + } - if( this.internalCurrentPower > amt ) - { - this.internalCurrentPower -= amt; + if (this.internalCurrentPower > amt) { + this.internalCurrentPower -= amt; - this.changePowerLevel(); - return amt; - } + this.changePowerLevel(); + return amt; + } - amt = this.internalCurrentPower; - this.internalCurrentPower = 0; + amt = this.internalCurrentPower; + this.internalCurrentPower = 0; - this.changePowerLevel(); - return amt; - } + this.changePowerLevel(); + return amt; + } - private double getInternalMaxPower() - { - return this.internalMaxPower; - } + private double getInternalMaxPower() { + return this.internalMaxPower; + } - void setInternalMaxPower( final double internalMaxPower ) - { - this.internalMaxPower = internalMaxPower; - } + void setInternalMaxPower(final double internalMaxPower) { + this.internalMaxPower = internalMaxPower; + } } diff --git a/src/main/java/appeng/tile/networking/TileWireless.java b/src/main/java/appeng/tile/networking/TileWireless.java index 3c9d401c9..fa87b6f3a 100644 --- a/src/main/java/appeng/tile/networking/TileWireless.java +++ b/src/main/java/appeng/tile/networking/TileWireless.java @@ -19,15 +19,6 @@ package appeng.tile.networking; -import java.io.IOException; -import java.util.EnumSet; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.implementations.IPowerChannelState; import appeng.api.implementations.tiles.IWirelessAccessPoint; @@ -46,172 +37,149 @@ import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.Platform; import appeng.util.inv.InvOperation; import appeng.util.inv.filter.AEItemDefinitionFilter; +import io.netty.buffer.ByteBuf; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.items.IItemHandler; + +import java.io.IOException; +import java.util.EnumSet; -public class TileWireless extends AENetworkInvTile implements IWirelessAccessPoint, IPowerChannelState -{ +public class TileWireless extends AENetworkInvTile implements IWirelessAccessPoint, IPowerChannelState { - public static final int POWERED_FLAG = 1; - public static final int CHANNEL_FLAG = 2; + public static final int POWERED_FLAG = 1; + public static final int CHANNEL_FLAG = 2; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 1 ); + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 1); - private int clientFlags = 0; + private int clientFlags = 0; - public TileWireless() - { - this.inv.setFilter( new AEItemDefinitionFilter( AEApi.instance().definitions().materials().wirelessBooster() ) ); - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.getProxy().setValidSides( EnumSet.noneOf( EnumFacing.class ) ); - } + public TileWireless() { + this.inv.setFilter(new AEItemDefinitionFilter(AEApi.instance().definitions().materials().wirelessBooster())); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.getProxy().setValidSides(EnumSet.noneOf(EnumFacing.class)); + } - @Override - public void setOrientation( final EnumFacing inForward, final EnumFacing inUp ) - { - super.setOrientation( inForward, inUp ); - this.getProxy().setValidSides( EnumSet.of( this.getForward().getOpposite() ) ); - } + @Override + public void setOrientation(final EnumFacing inForward, final EnumFacing inUp) { + super.setOrientation(inForward, inUp); + this.getProxy().setValidSides(EnumSet.of(this.getForward().getOpposite())); + } - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - this.markForUpdate(); - } + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + this.markForUpdate(); + } - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.markForUpdate(); - } + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.markForUpdate(); + } - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - final int old = this.getClientFlags(); - this.setClientFlags( data.readByte() ); + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + final int old = this.getClientFlags(); + this.setClientFlags(data.readByte()); - return old != this.getClientFlags() || c; - } + return old != this.getClientFlags() || c; + } - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - this.setClientFlags( 0 ); + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + this.setClientFlags(0); - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - this.setClientFlags( this.getClientFlags() | POWERED_FLAG ); - } + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + this.setClientFlags(this.getClientFlags() | POWERED_FLAG); + } - if( this.getProxy().getNode().meetsChannelRequirements() ) - { - this.setClientFlags( this.getClientFlags() | CHANNEL_FLAG ); - } - } - catch( final GridAccessException e ) - { - // meh - } + if (this.getProxy().getNode().meetsChannelRequirements()) { + this.setClientFlags(this.getClientFlags() | CHANNEL_FLAG); + } + } catch (final GridAccessException e) { + // meh + } - data.writeByte( (byte) this.getClientFlags() ); - } + data.writeByte((byte) this.getClientFlags()); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.SMART; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.SMART; + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - public IItemHandler getInternalInventory() - { - return this.inv; - } + @Override + public IItemHandler getInternalInventory() { + return this.inv; + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - // :P - } + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { + // :P + } - @Override - public void onReady() - { - this.updatePower(); - super.onReady(); - } + @Override + public void onReady() { + this.updatePower(); + super.onReady(); + } - private void updatePower() - { - this.getProxy().setIdlePowerUsage( AEConfig.instance().wireless_getPowerDrain( this.getBoosters() ) ); - } + private void updatePower() { + this.getProxy().setIdlePowerUsage(AEConfig.instance().wireless_getPowerDrain(this.getBoosters())); + } - private int getBoosters() - { - final ItemStack boosters = this.inv.getStackInSlot( 0 ); - return boosters == null ? 0 : boosters.getCount(); - } + private int getBoosters() { + final ItemStack boosters = this.inv.getStackInSlot(0); + return boosters == null ? 0 : boosters.getCount(); + } - @Override - public void saveChanges() - { - this.updatePower(); - super.saveChanges(); - } + @Override + public void saveChanges() { + this.updatePower(); + super.saveChanges(); + } - @Override - public double getRange() - { - return AEConfig.instance().wireless_getMaxRange( this.getBoosters() ); - } + @Override + public double getRange() { + return AEConfig.instance().wireless_getMaxRange(this.getBoosters()); + } - @Override - public boolean isActive() - { - if( Platform.isClient() ) - { - return this.isPowered() && ( CHANNEL_FLAG == ( this.getClientFlags() & CHANNEL_FLAG ) ); - } + @Override + public boolean isActive() { + if (Platform.isClient()) { + return this.isPowered() && (CHANNEL_FLAG == (this.getClientFlags() & CHANNEL_FLAG)); + } - return this.getProxy().isActive(); - } + return this.getProxy().isActive(); + } - @Override - public IGrid getGrid() - { - try - { - return this.getProxy().getGrid(); - } - catch( final GridAccessException e ) - { - return null; - } - } + @Override + public IGrid getGrid() { + try { + return this.getProxy().getGrid(); + } catch (final GridAccessException e) { + return null; + } + } - @Override - public boolean isPowered() - { - return POWERED_FLAG == ( this.getClientFlags() & POWERED_FLAG ); - } + @Override + public boolean isPowered() { + return POWERED_FLAG == (this.getClientFlags() & POWERED_FLAG); + } - public int getClientFlags() - { - return this.clientFlags; - } + public int getClientFlags() { + return this.clientFlags; + } - private void setClientFlags( final int clientFlags ) - { - this.clientFlags = clientFlags; - } + private void setClientFlags(final int clientFlags) { + this.clientFlags = clientFlags; + } } diff --git a/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java b/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java index d5d4403dc..8223b5703 100644 --- a/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java +++ b/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java @@ -19,15 +19,6 @@ package appeng.tile.powersink; -import java.util.EnumSet; - -import javax.annotation.Nullable; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.energy.IEnergyStorage; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -38,295 +29,246 @@ import appeng.capabilities.Capabilities; import appeng.integration.Integrations; import appeng.integration.abstraction.IC2PowerSink; import appeng.tile.AEBaseInvTile; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.energy.IEnergyStorage; + +import javax.annotation.Nullable; +import java.util.EnumSet; -public abstract class AEBasePoweredTile extends AEBaseInvTile implements IAEPowerStorage, IExternalPowerSink -{ +public abstract class AEBasePoweredTile extends AEBaseInvTile implements IAEPowerStorage, IExternalPowerSink { - // values that determine general function, are set by inheriting classes if - // needed. These should generally remain static. - private double internalMaxPower = 10000; - private boolean internalPublicPowerStorage = false; - private AccessRestriction internalPowerFlow = AccessRestriction.READ_WRITE; - // the current power buffer. - private double internalCurrentPower = 0; - private EnumSet internalPowerSides = EnumSet.allOf( EnumFacing.class ); - private final IEnergyStorage forgeEnergyAdapter; - private Object teslaEnergyAdapter; - private GTCEEnergyAdapter gtceEnergyAdapter = null; - private IC2PowerSink ic2Sink; + // values that determine general function, are set by inheriting classes if + // needed. These should generally remain static. + private double internalMaxPower = 10000; + private boolean internalPublicPowerStorage = false; + private AccessRestriction internalPowerFlow = AccessRestriction.READ_WRITE; + // the current power buffer. + private double internalCurrentPower = 0; + private EnumSet internalPowerSides = EnumSet.allOf(EnumFacing.class); + private final IEnergyStorage forgeEnergyAdapter; + private Object teslaEnergyAdapter; + private GTCEEnergyAdapter gtceEnergyAdapter = null; + private final IC2PowerSink ic2Sink; - public AEBasePoweredTile() - { - this.forgeEnergyAdapter = new ForgeEnergyAdapter( this ); - if( Capabilities.TESLA_CONSUMER != null ) - { - this.teslaEnergyAdapter = new TeslaEnergyAdapter( this ); - } - if( Capabilities.GTCE_ENERGY != null ) - { - this.gtceEnergyAdapter = new GTCEEnergyAdapter( this ); - } + public AEBasePoweredTile() { + this.forgeEnergyAdapter = new ForgeEnergyAdapter(this); + if (Capabilities.TESLA_CONSUMER != null) { + this.teslaEnergyAdapter = new TeslaEnergyAdapter(this); + } + if (Capabilities.GTCE_ENERGY != null) { + this.gtceEnergyAdapter = new GTCEEnergyAdapter(this); + } - this.ic2Sink = Integrations.ic2().createPowerSink( this, this ); - this.ic2Sink.setValidFaces( this.internalPowerSides ); - } + this.ic2Sink = Integrations.ic2().createPowerSink(this, this); + this.ic2Sink.setValidFaces(this.internalPowerSides); + } - protected EnumSet getPowerSides() - { - return this.internalPowerSides.clone(); - } + protected EnumSet getPowerSides() { + return this.internalPowerSides.clone(); + } - protected void setPowerSides( final EnumSet sides ) - { - this.internalPowerSides = sides; - this.ic2Sink.setValidFaces( sides ); - // trigger re-calc! - } + protected void setPowerSides(final EnumSet sides) { + this.internalPowerSides = sides; + this.ic2Sink.setValidFaces(sides); + // trigger re-calc! + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setDouble( "internalCurrentPower", this.getInternalCurrentPower() ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setDouble("internalCurrentPower", this.getInternalCurrentPower()); + return data; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.setInternalCurrentPower( data.getDouble( "internalCurrentPower" ) ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.setInternalCurrentPower(data.getDouble("internalCurrentPower")); + } - @Override - public final double getExternalPowerDemand( final PowerUnits externalUnit, final double maxPowerRequired ) - { - return PowerUnits.AE.convertTo( externalUnit, Math.max( 0.0, this.getFunnelPowerDemand( externalUnit.convertTo( PowerUnits.AE, maxPowerRequired ) ) ) ); - } + @Override + public final double getExternalPowerDemand(final PowerUnits externalUnit, final double maxPowerRequired) { + return PowerUnits.AE.convertTo(externalUnit, Math.max(0.0, this.getFunnelPowerDemand(externalUnit.convertTo(PowerUnits.AE, maxPowerRequired)))); + } - protected double getFunnelPowerDemand( final double maxRequired ) - { - return this.getInternalMaxPower() - this.getInternalCurrentPower(); - } + protected double getFunnelPowerDemand(final double maxRequired) { + return this.getInternalMaxPower() - this.getInternalCurrentPower(); + } - @Override - public final double injectExternalPower( final PowerUnits input, final double amt, Actionable mode ) - { - return PowerUnits.AE.convertTo( input, this.funnelPowerIntoStorage( input.convertTo( PowerUnits.AE, amt ), mode ) ); - } + @Override + public final double injectExternalPower(final PowerUnits input, final double amt, Actionable mode) { + return PowerUnits.AE.convertTo(input, this.funnelPowerIntoStorage(input.convertTo(PowerUnits.AE, amt), mode)); + } - protected double funnelPowerIntoStorage( final double power, final Actionable mode ) - { - return this.injectAEPower( power, mode ); - } + protected double funnelPowerIntoStorage(final double power, final Actionable mode) { + return this.injectAEPower(power, mode); + } - @Override - public final double injectAEPower( double amt, final Actionable mode ) - { - if( amt < 0.000001 ) - { - return 0; - } + @Override + public final double injectAEPower(double amt, final Actionable mode) { + if (amt < 0.000001) { + return 0; + } - final double required = this.getAEMaxPower() - this.getAECurrentPower(); - final double insertable = Math.min( required, amt ); + final double required = this.getAEMaxPower() - this.getAECurrentPower(); + final double insertable = Math.min(required, amt); - if( mode == Actionable.MODULATE ) - { - if( this.getInternalCurrentPower() < 0.01 && insertable > 0.01 ) - { - this.PowerEvent( PowerEventType.PROVIDE_POWER ); - } + if (mode == Actionable.MODULATE) { + if (this.getInternalCurrentPower() < 0.01 && insertable > 0.01) { + this.PowerEvent(PowerEventType.PROVIDE_POWER); + } - this.setInternalCurrentPower( this.getInternalCurrentPower() + insertable ); - } + this.setInternalCurrentPower(this.getInternalCurrentPower() + insertable); + } - return amt - insertable; - } + return amt - insertable; + } - protected void PowerEvent( final PowerEventType x ) - { - // nothing. - } + protected void PowerEvent(final PowerEventType x) { + // nothing. + } - @Override - public final double getAEMaxPower() - { - return this.getInternalMaxPower(); - } + @Override + public final double getAEMaxPower() { + return this.getInternalMaxPower(); + } - @Override - public final double getAECurrentPower() - { - return this.getInternalCurrentPower(); - } + @Override + public final double getAECurrentPower() { + return this.getInternalCurrentPower(); + } - @Override - public final boolean isAEPublicPowerStorage() - { - return this.isInternalPublicPowerStorage(); - } + @Override + public final boolean isAEPublicPowerStorage() { + return this.isInternalPublicPowerStorage(); + } - @Override - public final AccessRestriction getPowerFlow() - { - return this.getInternalPowerFlow(); - } + @Override + public final AccessRestriction getPowerFlow() { + return this.getInternalPowerFlow(); + } - @Override - public final double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier multiplier ) - { - return multiplier.divide( this.extractAEPower( multiplier.multiply( amt ), mode ) ); - } + @Override + public final double extractAEPower(final double amt, final Actionable mode, final PowerMultiplier multiplier) { + return multiplier.divide(this.extractAEPower(multiplier.multiply(amt), mode)); + } - protected double extractAEPower( double amt, final Actionable mode ) - { - if( mode == Actionable.SIMULATE ) - { - if( this.getInternalCurrentPower() > amt ) - { - return amt; - } - return this.getInternalCurrentPower(); - } + protected double extractAEPower(double amt, final Actionable mode) { + if (mode == Actionable.SIMULATE) { + if (this.getInternalCurrentPower() > amt) { + return amt; + } + return this.getInternalCurrentPower(); + } - final boolean wasFull = this.getInternalCurrentPower() >= this.getInternalMaxPower() - 0.001; - if( wasFull && amt > 0.001 ) - { - this.PowerEvent( PowerEventType.REQUEST_POWER ); - } + final boolean wasFull = this.getInternalCurrentPower() >= this.getInternalMaxPower() - 0.001; + if (wasFull && amt > 0.001) { + this.PowerEvent(PowerEventType.REQUEST_POWER); + } - if( this.getInternalCurrentPower() > amt ) - { - this.setInternalCurrentPower( this.getInternalCurrentPower() - amt ); - return amt; - } + if (this.getInternalCurrentPower() > amt) { + this.setInternalCurrentPower(this.getInternalCurrentPower() - amt); + return amt; + } - amt = this.getInternalCurrentPower(); - this.setInternalCurrentPower( 0 ); - return amt; - } + amt = this.getInternalCurrentPower(); + this.setInternalCurrentPower(0); + return amt; + } - public double getInternalCurrentPower() - { - return this.internalCurrentPower; - } + public double getInternalCurrentPower() { + return this.internalCurrentPower; + } - public void setInternalCurrentPower( final double internalCurrentPower ) - { - this.internalCurrentPower = internalCurrentPower; - } + public void setInternalCurrentPower(final double internalCurrentPower) { + this.internalCurrentPower = internalCurrentPower; + } - public double getInternalMaxPower() - { - return this.internalMaxPower; - } + public double getInternalMaxPower() { + return this.internalMaxPower; + } - public void setInternalMaxPower( final double internalMaxPower ) - { - this.internalMaxPower = internalMaxPower; - } + public void setInternalMaxPower(final double internalMaxPower) { + this.internalMaxPower = internalMaxPower; + } - private boolean isInternalPublicPowerStorage() - { - return this.internalPublicPowerStorage; - } + private boolean isInternalPublicPowerStorage() { + return this.internalPublicPowerStorage; + } - public void setInternalPublicPowerStorage( final boolean internalPublicPowerStorage ) - { - this.internalPublicPowerStorage = internalPublicPowerStorage; - } + public void setInternalPublicPowerStorage(final boolean internalPublicPowerStorage) { + this.internalPublicPowerStorage = internalPublicPowerStorage; + } - private AccessRestriction getInternalPowerFlow() - { - return this.internalPowerFlow; - } + private AccessRestriction getInternalPowerFlow() { + return this.internalPowerFlow; + } - public void setInternalPowerFlow( final AccessRestriction internalPowerFlow ) - { - this.internalPowerFlow = internalPowerFlow; - } + public void setInternalPowerFlow(final AccessRestriction internalPowerFlow) { + this.internalPowerFlow = internalPowerFlow; + } - @Override - public void onReady() - { - super.onReady(); + @Override + public void onReady() { + super.onReady(); - this.ic2Sink.onLoad(); - } + this.ic2Sink.onLoad(); + } - @Override - public void onChunkUnload() - { - super.onChunkUnload(); + @Override + public void onChunkUnload() { + super.onChunkUnload(); - this.ic2Sink.onChunkUnload(); - } + this.ic2Sink.onChunkUnload(); + } - @Override - public void invalidate() - { - super.invalidate(); + @Override + public void invalidate() { + super.invalidate(); - this.ic2Sink.invalidate(); - } + this.ic2Sink.invalidate(); + } - @Override - public boolean hasCapability( Capability capability, EnumFacing facing ) - { - if( capability == Capabilities.FORGE_ENERGY ) - { - if( this.getPowerSides().contains( facing ) ) - { - return true; - } - } - else if( capability == Capabilities.TESLA_CONSUMER ) - { - if( this.getPowerSides().contains( facing ) ) - { - return true; - } - } - else if( capability == Capabilities.GTCE_ENERGY ) - { - if( this.getPowerSides().contains( facing ) ) - { - return true; - } - } + @Override + public boolean hasCapability(Capability capability, EnumFacing facing) { + if (capability == Capabilities.FORGE_ENERGY) { + if (this.getPowerSides().contains(facing)) { + return true; + } + } else if (capability == Capabilities.TESLA_CONSUMER) { + if (this.getPowerSides().contains(facing)) { + return true; + } + } else if (capability == Capabilities.GTCE_ENERGY) { + if (this.getPowerSides().contains(facing)) { + return true; + } + } - return super.hasCapability( capability, facing ); - } + return super.hasCapability(capability, facing); + } - @SuppressWarnings( "unchecked" ) - @Override - public T getCapability( Capability capability, @Nullable EnumFacing facing ) - { - if( capability == Capabilities.FORGE_ENERGY ) - { - if( this.getPowerSides().contains( facing ) ) - { - return (T) this.forgeEnergyAdapter; - } - } - else if( capability == Capabilities.TESLA_CONSUMER ) - { - if( this.getPowerSides().contains( facing ) ) - { - return (T) this.teslaEnergyAdapter; - } - } - else if( capability == Capabilities.GTCE_ENERGY ) - { - if( this.getPowerSides().contains( facing ) ) - { - return (T) this.gtceEnergyAdapter; - } - } - - return super.getCapability( capability, facing ); - } + @SuppressWarnings("unchecked") + @Override + public T getCapability(Capability capability, @Nullable EnumFacing facing) { + if (capability == Capabilities.FORGE_ENERGY) { + if (this.getPowerSides().contains(facing)) { + return (T) this.forgeEnergyAdapter; + } + } else if (capability == Capabilities.TESLA_CONSUMER) { + if (this.getPowerSides().contains(facing)) { + return (T) this.teslaEnergyAdapter; + } + } else if (capability == Capabilities.GTCE_ENERGY) { + if (this.getPowerSides().contains(facing)) { + return (T) this.gtceEnergyAdapter; + } + } + + return super.getCapability(capability, facing); + } } diff --git a/src/main/java/appeng/tile/powersink/ForgeEnergyAdapter.java b/src/main/java/appeng/tile/powersink/ForgeEnergyAdapter.java index 2ffed9fb4..90ab95ee9 100644 --- a/src/main/java/appeng/tile/powersink/ForgeEnergyAdapter.java +++ b/src/main/java/appeng/tile/powersink/ForgeEnergyAdapter.java @@ -1,63 +1,53 @@ - package appeng.tile.powersink; -import net.minecraftforge.energy.IEnergyStorage; - import appeng.api.config.Actionable; import appeng.api.config.PowerUnits; +import net.minecraftforge.energy.IEnergyStorage; /** * Adapts an {@link IExternalPowerSink} to Forges {@link IEnergyStorage}. */ -class ForgeEnergyAdapter implements IEnergyStorage -{ +class ForgeEnergyAdapter implements IEnergyStorage { - private final IExternalPowerSink sink; + private final IExternalPowerSink sink; - ForgeEnergyAdapter( IExternalPowerSink sink ) - { - this.sink = sink; - } + ForgeEnergyAdapter(IExternalPowerSink sink) { + this.sink = sink; + } - @Override - public final int receiveEnergy( int maxReceive, boolean simulate ) - { - final double offered = maxReceive; - final double overflow = this.sink.injectExternalPower( PowerUnits.RF, offered, simulate ? Actionable.SIMULATE : Actionable.MODULATE ); + @Override + public final int receiveEnergy(int maxReceive, boolean simulate) { + final double offered = maxReceive; + final double overflow = this.sink.injectExternalPower(PowerUnits.RF, offered, simulate ? Actionable.SIMULATE : Actionable.MODULATE); - return (int) ( maxReceive - overflow ); - } + return (int) (maxReceive - overflow); + } - @Override - public final int getEnergyStored() - { - return (int) Math.floor( PowerUnits.AE.convertTo( PowerUnits.RF, this.sink.getAECurrentPower() ) ); - } + @Override + public final int getEnergyStored() { + return (int) Math.floor(PowerUnits.AE.convertTo(PowerUnits.RF, this.sink.getAECurrentPower())); + } - @Override - public final int getMaxEnergyStored() - { - return (int) Math.floor( PowerUnits.AE.convertTo( PowerUnits.RF, this.sink.getAEMaxPower() ) ); - } + @Override + public final int getMaxEnergyStored() { + return (int) Math.floor(PowerUnits.AE.convertTo(PowerUnits.RF, this.sink.getAEMaxPower())); + } - @Override - public int extractEnergy( int maxExtract, boolean simulate ) - { - return 0; - } + @Override + public int extractEnergy(int maxExtract, boolean simulate) { + return 0; + } - @Override - public boolean canExtract() - { - return false; - } + @Override + public boolean canExtract() { + return false; + } - @Override - public boolean canReceive() - { - return true; - } + @Override + public boolean canReceive() { + return true; + } } diff --git a/src/main/java/appeng/tile/powersink/GTCEEnergyAdapter.java b/src/main/java/appeng/tile/powersink/GTCEEnergyAdapter.java index 8c55c9c95..bdded6bfe 100644 --- a/src/main/java/appeng/tile/powersink/GTCEEnergyAdapter.java +++ b/src/main/java/appeng/tile/powersink/GTCEEnergyAdapter.java @@ -6,84 +6,72 @@ import gregtech.api.capability.IEnergyContainer; import net.minecraft.util.EnumFacing; -public class GTCEEnergyAdapter implements IEnergyContainer -{ - private final IExternalPowerSink sink; +public class GTCEEnergyAdapter implements IEnergyContainer { + private final IExternalPowerSink sink; - double EUBuffer; + double EUBuffer; - GTCEEnergyAdapter( IExternalPowerSink sink ) - { - this.sink = sink; - } + GTCEEnergyAdapter(IExternalPowerSink sink) { + this.sink = sink; + } - @Override - public long acceptEnergyFromNetwork( EnumFacing enumFacing, long voltage, long amperage ) - { - final double power = voltage * amperage; - final double oldBuffer = EUBuffer; + @Override + public long acceptEnergyFromNetwork(EnumFacing enumFacing, long voltage, long amperage) { + final double power = voltage * amperage; + final double oldBuffer = EUBuffer; - EUBuffer = this.sink.injectExternalPower( PowerUnits.GTEU, power + EUBuffer, Actionable.MODULATE ); + EUBuffer = this.sink.injectExternalPower(PowerUnits.GTEU, power + EUBuffer, Actionable.MODULATE); - // if the overflow went down, all inputs were consumed - if( EUBuffer <= oldBuffer ) - { - return amperage; - } - // if overflow is greater than the inputs, nothing was consumed - if( EUBuffer >= power ) - { - EUBuffer -= power; - return 0; - } - // determine how many amps are being used - final double usedEU = power + oldBuffer - EUBuffer; - final long ampsUsed = (long) Math.ceil( usedEU / ( (double) voltage ) ); - // adjust the overflow - EUBuffer += usedEU % voltage; + // if the overflow went down, all inputs were consumed + if (EUBuffer <= oldBuffer) { + return amperage; + } + // if overflow is greater than the inputs, nothing was consumed + if (EUBuffer >= power) { + EUBuffer -= power; + return 0; + } + // determine how many amps are being used + final double usedEU = power + oldBuffer - EUBuffer; + final long ampsUsed = (long) Math.ceil(usedEU / ((double) voltage)); + // adjust the overflow + EUBuffer += usedEU % voltage; - return ampsUsed; - } + return ampsUsed; + } - @Override - public boolean inputsEnergy( EnumFacing enumFacing ) - { - return true; - } + @Override + public boolean inputsEnergy(EnumFacing enumFacing) { + return true; + } - @Override - public long changeEnergy( long l ) - { - return 0; - } + @Override + public long changeEnergy(long l) { + return 0; + } - @Override - public long getEnergyStored() - { - return (long) Math.floor( PowerUnits.AE.convertTo( PowerUnits.GTEU, this.sink.getAECurrentPower() ) ); - } + @Override + public long getEnergyStored() { + return (long) Math.floor(PowerUnits.AE.convertTo(PowerUnits.GTEU, this.sink.getAECurrentPower())); + } - @Override - public long getEnergyCapacity() - { - return (long) Math.floor( PowerUnits.AE.convertTo( PowerUnits.GTEU, this.sink.getAEMaxPower() ) ); - } + @Override + public long getEnergyCapacity() { + return (long) Math.floor(PowerUnits.AE.convertTo(PowerUnits.GTEU, this.sink.getAEMaxPower())); + } - @Override - public long getInputAmperage() - { - return 0; - } + @Override + public long getInputAmperage() { + return 0; + } - @Override - public long getInputVoltage() - { - return 0; - } + @Override + public long getInputVoltage() { + return 0; + } - @Override - public long getEnergyCanBeInserted() - { - return this.getEnergyCapacity() - this.getEnergyStored(); - } + @Override + public long getEnergyCanBeInserted() { + return this.getEnergyCapacity() - this.getEnergyStored(); + } } diff --git a/src/main/java/appeng/tile/powersink/IExternalPowerSink.java b/src/main/java/appeng/tile/powersink/IExternalPowerSink.java index 568bc6961..249129e9b 100644 --- a/src/main/java/appeng/tile/powersink/IExternalPowerSink.java +++ b/src/main/java/appeng/tile/powersink/IExternalPowerSink.java @@ -24,25 +24,23 @@ import appeng.api.config.PowerUnits; import appeng.api.networking.energy.IAEPowerStorage; -public interface IExternalPowerSink extends IAEPowerStorage -{ +public interface IExternalPowerSink extends IAEPowerStorage { - /** - * Inject power into the network - * - * @param externalUnit The {@link PowerUnits} used by the input - * @param amount The amount offered to the sink. - * @param mode Modulate or simulate the operation. - * @return The unused amount, which could not be inserted into the sink. - */ - double injectExternalPower( PowerUnits externalUnit, double amount, Actionable mode ); + /** + * Inject power into the network + * + * @param externalUnit The {@link PowerUnits} used by the input + * @param amount The amount offered to the sink. + * @param mode Modulate or simulate the operation. + * @return The unused amount, which could not be inserted into the sink. + */ + double injectExternalPower(PowerUnits externalUnit, double amount, Actionable mode); - /** - * - * @param externalUnit The {@link PowerUnits} used by the input - * @param maxPowerRequired Limit the demand to this upper bound. - * @return The amount of power demanded by the sink. - */ - double getExternalPowerDemand( PowerUnits externalUnit, double maxPowerRequired ); + /** + * @param externalUnit The {@link PowerUnits} used by the input + * @param maxPowerRequired Limit the demand to this upper bound. + * @return The amount of power demanded by the sink. + */ + double getExternalPowerDemand(PowerUnits externalUnit, double maxPowerRequired); } diff --git a/src/main/java/appeng/tile/powersink/TeslaEnergyAdapter.java b/src/main/java/appeng/tile/powersink/TeslaEnergyAdapter.java index 02b63239a..cf4da5ddf 100644 --- a/src/main/java/appeng/tile/powersink/TeslaEnergyAdapter.java +++ b/src/main/java/appeng/tile/powersink/TeslaEnergyAdapter.java @@ -19,33 +19,29 @@ package appeng.tile.powersink; -import net.darkhax.tesla.api.ITeslaConsumer; - import appeng.api.config.Actionable; import appeng.api.config.PowerUnits; +import net.darkhax.tesla.api.ITeslaConsumer; /** * Adapts an {@link IExternalPowerSink} to Forges {@link net.darkhax.tesla.api.ITeslaConsumer}. */ -class TeslaEnergyAdapter implements ITeslaConsumer -{ +class TeslaEnergyAdapter implements ITeslaConsumer { - private final IExternalPowerSink sink; + private final IExternalPowerSink sink; - TeslaEnergyAdapter( IExternalPowerSink sink ) - { - this.sink = sink; - } + TeslaEnergyAdapter(IExternalPowerSink sink) { + this.sink = sink; + } - @Override - public long givePower( long power, boolean simulated ) - { - // Cut it down to what we can represent in a double - double offeredPower = power; + @Override + public long givePower(long power, boolean simulated) { + // Cut it down to what we can represent in a double + double offeredPower = power; - final double overflow = this.sink.injectExternalPower( PowerUnits.RF, offeredPower, simulated ? Actionable.SIMULATE : Actionable.MODULATE ); + final double overflow = this.sink.injectExternalPower(PowerUnits.RF, offeredPower, simulated ? Actionable.SIMULATE : Actionable.MODULATE); - return (long) ( power - overflow ); - } + return (long) (power - overflow); + } } diff --git a/src/main/java/appeng/tile/qnb/TileQuantumBridge.java b/src/main/java/appeng/tile/qnb/TileQuantumBridge.java index e4d95c1fd..24e308371 100644 --- a/src/main/java/appeng/tile/qnb/TileQuantumBridge.java +++ b/src/main/java/appeng/tile/qnb/TileQuantumBridge.java @@ -19,21 +19,6 @@ package appeng.tile.qnb; -import java.io.IOException; -import java.util.EnumSet; -import java.util.Optional; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.ITickable; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.wrapper.EmptyHandler; - import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; import appeng.api.networking.GridFlags; @@ -51,301 +36,260 @@ import appeng.tile.grid.AENetworkInvTile; import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.Platform; import appeng.util.inv.InvOperation; +import io.netty.buffer.ByteBuf; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.ITickable; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.wrapper.EmptyHandler; + +import java.io.IOException; +import java.util.EnumSet; +import java.util.Optional; -public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock, ITickable -{ - private final byte corner = 16; - private final AppEngInternalInventory internalInventory = new AppEngInternalInventory( this, 1, 1 ); - private final byte hasSingularity = 32; - private final byte powered = 64; +public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock, ITickable { + private final byte corner = 16; + private final AppEngInternalInventory internalInventory = new AppEngInternalInventory(this, 1, 1); + private final byte hasSingularity = 32; + private final byte powered = 64; - private final QuantumCalculator calc = new QuantumCalculator( this ); - private byte constructed = -1; - private QuantumCluster cluster; - private boolean updateStatus = false; + private final QuantumCalculator calc = new QuantumCalculator(this); + private byte constructed = -1; + private QuantumCluster cluster; + private boolean updateStatus = false; - public TileQuantumBridge() - { - this.getProxy().setValidSides( EnumSet.noneOf( EnumFacing.class ) ); - this.getProxy().setFlags( GridFlags.DENSE_CAPACITY ); - this.getProxy().setIdlePowerUsage( 22 ); - } + public TileQuantumBridge() { + this.getProxy().setValidSides(EnumSet.noneOf(EnumFacing.class)); + this.getProxy().setFlags(GridFlags.DENSE_CAPACITY); + this.getProxy().setIdlePowerUsage(22); + } - @Override - public void update() - { - if( this.updateStatus ) - { - this.updateStatus = false; - if( this.cluster != null ) - { - this.cluster.updateStatus( true ); - } - this.markForUpdate(); - } - } + @Override + public void update() { + if (this.updateStatus) { + this.updateStatus = false; + if (this.cluster != null) { + this.cluster.updateStatus(true); + } + this.markForUpdate(); + } + } - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - int out = this.constructed; + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + int out = this.constructed; - if( !this.internalInventory.getStackInSlot( 0 ).isEmpty() && this.constructed != -1 ) - { - out |= this.hasSingularity; - } + if (!this.internalInventory.getStackInSlot(0).isEmpty() && this.constructed != -1) { + out |= this.hasSingularity; + } - if( this.getProxy().isActive() && this.constructed != -1 ) - { - out |= this.powered; - } + if (this.getProxy().isActive() && this.constructed != -1) { + out |= this.powered; + } - data.writeByte( (byte) out ); - } + data.writeByte((byte) out); + } - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - final int oldValue = this.constructed; - this.constructed = data.readByte(); - return this.constructed != oldValue || c; - } + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + final int oldValue = this.constructed; + this.constructed = data.readByte(); + return this.constructed != oldValue || c; + } - @Override - public IItemHandler getInternalInventory() - { - return this.internalInventory; - } + @Override + public IItemHandler getInternalInventory() { + return this.internalInventory; + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( this.cluster != null ) - { - this.cluster.updateStatus( true ); - } - } + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { + if (this.cluster != null) { + this.cluster.updateStatus(true); + } + } - @Override - protected IItemHandler getItemHandlerForSide( EnumFacing side ) - { - if( this.isCenter() ) - { - return this.internalInventory; - } - return EmptyHandler.INSTANCE; - } + @Override + protected IItemHandler getItemHandlerForSide(EnumFacing side) { + if (this.isCenter()) { + return this.internalInventory; + } + return EmptyHandler.INSTANCE; + } - private boolean isCenter() - { - return AEApi.instance() - .definitions() - .blocks() - .quantumLink() - .maybeBlock() - .map( link -> this.getBlockType() == link ) - .orElse( false ); - } + private boolean isCenter() { + return AEApi.instance() + .definitions() + .blocks() + .quantumLink() + .maybeBlock() + .map(link -> this.getBlockType() == link) + .orElse(false); + } - @MENetworkEventSubscribe - public void onPowerStatusChange( final MENetworkPowerStatusChange c ) - { - this.updateStatus = true; - } + @MENetworkEventSubscribe + public void onPowerStatusChange(final MENetworkPowerStatusChange c) { + this.updateStatus = true; + } - @Override - public void onChunkUnload() - { - this.disconnect( false ); - super.onChunkUnload(); - } + @Override + public void onChunkUnload() { + this.disconnect(false); + super.onChunkUnload(); + } - @Override - public void onReady() - { - super.onReady(); + @Override + public void onReady() { + super.onReady(); - final IBlockDefinition quantumRing = AEApi.instance().definitions().blocks().quantumRing(); - final Optional maybeLinkBlock = quantumRing.maybeBlock(); - final Optional maybeLinkStack = quantumRing.maybeStack( 1 ); + final IBlockDefinition quantumRing = AEApi.instance().definitions().blocks().quantumRing(); + final Optional maybeLinkBlock = quantumRing.maybeBlock(); + final Optional maybeLinkStack = quantumRing.maybeStack(1); - final boolean isPresent = maybeLinkBlock.isPresent() && maybeLinkStack.isPresent(); + final boolean isPresent = maybeLinkBlock.isPresent() && maybeLinkStack.isPresent(); - if( isPresent && this.getBlockType() == maybeLinkBlock.get() ) - { - final ItemStack linkStack = maybeLinkStack.get(); + if (isPresent && this.getBlockType() == maybeLinkBlock.get()) { + final ItemStack linkStack = maybeLinkStack.get(); - this.getProxy().setVisualRepresentation( linkStack ); - } - } + this.getProxy().setVisualRepresentation(linkStack); + } + } - @Override - public void invalidate() - { - this.disconnect( false ); - super.invalidate(); - } + @Override + public void invalidate() { + this.disconnect(false); + super.invalidate(); + } - @Override - public void disconnect( final boolean affectWorld ) - { - if( this.cluster != null ) - { - if( !affectWorld ) - { - this.cluster.setUpdateStatus( false ); - } + @Override + public void disconnect(final boolean affectWorld) { + if (this.cluster != null) { + if (!affectWorld) { + this.cluster.setUpdateStatus(false); + } - this.cluster.destroy(); - } + this.cluster.destroy(); + } - this.cluster = null; + this.cluster = null; - if( affectWorld ) - { - this.getProxy().setValidSides( EnumSet.noneOf( EnumFacing.class ) ); - } - } + if (affectWorld) { + this.getProxy().setValidSides(EnumSet.noneOf(EnumFacing.class)); + } + } - @Override - public IAECluster getCluster() - { - return this.cluster; - } + @Override + public IAECluster getCluster() { + return this.cluster; + } - @Override - public boolean isValid() - { - return !this.isInvalid(); - } + @Override + public boolean isValid() { + return !this.isInvalid(); + } - public void updateStatus( final QuantumCluster c, final byte flags, final boolean affectWorld ) - { - this.cluster = c; + public void updateStatus(final QuantumCluster c, final byte flags, final boolean affectWorld) { + this.cluster = c; - if( affectWorld ) - { - if( this.constructed != flags ) - { - this.constructed = flags; - this.markForUpdate(); - } + if (affectWorld) { + if (this.constructed != flags) { + this.constructed = flags; + this.markForUpdate(); + } - if( this.isCorner() || this.isCenter() ) - { - final EnumSet sides = EnumSet.noneOf( EnumFacing.class ); - for( final EnumFacing dir : this.getAdjacentQuantumBridges() ) - { - sides.add( dir ); - } + if (this.isCorner() || this.isCenter()) { + final EnumSet sides = EnumSet.noneOf(EnumFacing.class); + for (final EnumFacing dir : this.getAdjacentQuantumBridges()) { + sides.add(dir); + } - this.getProxy().setValidSides( sides ); - } - else - { - this.getProxy().setValidSides( EnumSet.allOf( EnumFacing.class ) ); - } - } - } + this.getProxy().setValidSides(sides); + } else { + this.getProxy().setValidSides(EnumSet.allOf(EnumFacing.class)); + } + } + } - public boolean isCorner() - { - return ( this.constructed & this.getCorner() ) == this.getCorner() && this.constructed != -1; - } + public boolean isCorner() { + return (this.constructed & this.getCorner()) == this.getCorner() && this.constructed != -1; + } - public EnumSet getAdjacentQuantumBridges() - { - final EnumSet set = EnumSet.noneOf( EnumFacing.class ); + public EnumSet getAdjacentQuantumBridges() { + final EnumSet set = EnumSet.noneOf(EnumFacing.class); - for( final EnumFacing d : EnumFacing.values() ) - { - final TileEntity te = this.world.getTileEntity( this.pos.offset( d ) ); - if( te instanceof TileQuantumBridge ) - { - set.add( d ); - } - } + for (final EnumFacing d : EnumFacing.values()) { + final TileEntity te = this.world.getTileEntity(this.pos.offset(d)); + if (te instanceof TileQuantumBridge) { + set.add(d); + } + } - return set; - } + return set; + } - public long getQEFrequency() - { - final ItemStack is = this.internalInventory.getStackInSlot( 0 ); - if( !is.isEmpty() ) - { - final NBTTagCompound c = is.getTagCompound(); - if( c != null ) - { - return c.getLong( "freq" ); - } - } - return 0; - } + public long getQEFrequency() { + final ItemStack is = this.internalInventory.getStackInSlot(0); + if (!is.isEmpty()) { + final NBTTagCompound c = is.getTagCompound(); + if (c != null) { + return c.getLong("freq"); + } + } + return 0; + } - public boolean isPowered() - { - if( Platform.isClient() ) - { - return ( this.constructed & this.powered ) == this.powered && this.constructed != -1; - } + public boolean isPowered() { + if (Platform.isClient()) { + return (this.constructed & this.powered) == this.powered && this.constructed != -1; + } - try - { - return this.getProxy().getEnergy().isNetworkPowered(); - } - catch( final GridAccessException e ) - { - // :P - } + try { + return this.getProxy().getEnergy().isNetworkPowered(); + } catch (final GridAccessException e) { + // :P + } - return false; - } + return false; + } - public boolean isFormed() - { - return this.constructed != -1; - } + public boolean isFormed() { + return this.constructed != -1; + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.DENSE_SMART; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.DENSE_SMART; + } - public void neighborUpdate() - { - this.calc.calculateMultiblock( this.world, this.getLocation() ); - } + public void neighborUpdate() { + this.calc.calculateMultiblock(this.world, this.getLocation()); + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - public boolean hasQES() - { - if( this.constructed == -1 ) - { - return false; - } - return ( this.constructed & this.hasSingularity ) == this.hasSingularity; - } + public boolean hasQES() { + if (this.constructed == -1) { + return false; + } + return (this.constructed & this.hasSingularity) == this.hasSingularity; + } - public void breakCluster() - { - if( this.cluster != null ) - { - this.cluster.destroy(); - } - } + public void breakCluster() { + if (this.cluster != null) { + this.cluster.destroy(); + } + } - public byte getCorner() - { - return this.corner; - } + public byte getCorner() { + return this.corner; + } } diff --git a/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java b/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java index f61d1ffb4..a902c42b9 100644 --- a/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java +++ b/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java @@ -19,14 +19,6 @@ package appeng.tile.spatial; -import javax.annotation.Nonnull; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; -import net.minecraft.world.World; -import net.minecraftforge.items.IItemHandler; - import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.config.YesNo; @@ -50,168 +42,146 @@ import appeng.util.Platform; import appeng.util.inv.InvOperation; import appeng.util.inv.WrapperFilteredItemHandler; import appeng.util.inv.filter.IAEItemFilter; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraft.world.World; +import net.minecraftforge.items.IItemHandler; + +import javax.annotation.Nonnull; -public class TileSpatialIOPort extends AENetworkInvTile implements IWorldCallable -{ +public class TileSpatialIOPort extends AENetworkInvTile implements IWorldCallable { - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 2 ); - private final IItemHandler invExt = new WrapperFilteredItemHandler( this.inv, new SpatialIOFilter() ); - private YesNo lastRedstoneState = YesNo.UNDECIDED; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 2); + private final IItemHandler invExt = new WrapperFilteredItemHandler(this.inv, new SpatialIOFilter()); + private YesNo lastRedstoneState = YesNo.UNDECIDED; - public TileSpatialIOPort() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - } + public TileSpatialIOPort() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setInteger( "lastRedstoneState", this.lastRedstoneState.ordinal() ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setInteger("lastRedstoneState", this.lastRedstoneState.ordinal()); + return data; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - if( data.hasKey( "lastRedstoneState" ) ) - { - this.lastRedstoneState = YesNo.values()[data.getInteger( "lastRedstoneState" )]; - } - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + if (data.hasKey("lastRedstoneState")) { + this.lastRedstoneState = YesNo.values()[data.getInteger("lastRedstoneState")]; + } + } - public boolean getRedstoneState() - { - if( this.lastRedstoneState == YesNo.UNDECIDED ) - { - this.updateRedstoneState(); - } + public boolean getRedstoneState() { + if (this.lastRedstoneState == YesNo.UNDECIDED) { + this.updateRedstoneState(); + } - return this.lastRedstoneState == YesNo.YES; - } + return this.lastRedstoneState == YesNo.YES; + } - public void updateRedstoneState() - { - final YesNo currentState = this.world.isBlockIndirectlyGettingPowered( this.pos ) != 0 ? YesNo.YES : YesNo.NO; - if( this.lastRedstoneState != currentState ) - { - this.lastRedstoneState = currentState; - if( this.lastRedstoneState == YesNo.YES ) - { - this.triggerTransition(); - } - } - } + public void updateRedstoneState() { + final YesNo currentState = this.world.isBlockIndirectlyGettingPowered(this.pos) != 0 ? YesNo.YES : YesNo.NO; + if (this.lastRedstoneState != currentState) { + this.lastRedstoneState = currentState; + if (this.lastRedstoneState == YesNo.YES) { + this.triggerTransition(); + } + } + } - private void triggerTransition() - { - if( Platform.isServer() ) - { - final ItemStack cell = this.inv.getStackInSlot( 0 ); - if( this.isSpatialCell( cell ) ) - { - TickHandler.INSTANCE.addCallable( null, this );// this needs to be cross world synced. - } - } - } + private void triggerTransition() { + if (Platform.isServer()) { + final ItemStack cell = this.inv.getStackInSlot(0); + if (this.isSpatialCell(cell)) { + TickHandler.INSTANCE.addCallable(null, this);// this needs to be cross world synced. + } + } + } - private boolean isSpatialCell( final ItemStack cell ) - { - if( !cell.isEmpty() && cell.getItem() instanceof ISpatialStorageCell ) - { - final ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); - return sc != null && sc.isSpatialStorage( cell ); - } - return false; - } + private boolean isSpatialCell(final ItemStack cell) { + if (!cell.isEmpty() && cell.getItem() instanceof ISpatialStorageCell) { + final ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); + return sc != null && sc.isSpatialStorage(cell); + } + return false; + } - @Override - public Void call( final World world ) throws Exception - { - final ItemStack cell = this.inv.getStackInSlot( 0 ); - if( this.isSpatialCell( cell ) && this.inv.getStackInSlot( 1 ).isEmpty() ) - { - final IGrid gi = this.getProxy().getGrid(); - final IEnergyGrid energy = this.getProxy().getEnergy(); + @Override + public Void call(final World world) throws Exception { + final ItemStack cell = this.inv.getStackInSlot(0); + if (this.isSpatialCell(cell) && this.inv.getStackInSlot(1).isEmpty()) { + final IGrid gi = this.getProxy().getGrid(); + final IEnergyGrid energy = this.getProxy().getEnergy(); - final ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); + final ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); - final SpatialPylonCache spc = gi.getCache( ISpatialCache.class ); - if( spc.hasRegion() && spc.isValidRegion() ) - { - final double req = spc.requiredPower(); - final double pr = energy.extractAEPower( req, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - if( Math.abs( pr - req ) < req * 0.001 ) - { - final MENetworkEvent res = gi.postEvent( new MENetworkSpatialEvent( this, req ) ); - if( !res.isCanceled() ) - { - int playerId = -1; - if( this.getProxy().getSecurity().isAvailable() ) - { - playerId = this.getProxy().getSecurity().getOwner(); - } + final SpatialPylonCache spc = gi.getCache(ISpatialCache.class); + if (spc.hasRegion() && spc.isValidRegion()) { + final double req = spc.requiredPower(); + final double pr = energy.extractAEPower(req, Actionable.SIMULATE, PowerMultiplier.CONFIG); + if (Math.abs(pr - req) < req * 0.001) { + final MENetworkEvent res = gi.postEvent(new MENetworkSpatialEvent(this, req)); + if (!res.isCanceled()) { + int playerId = -1; + if (this.getProxy().getSecurity().isAvailable()) { + playerId = this.getProxy().getSecurity().getOwner(); + } - final TransitionResult tr = sc.doSpatialTransition( cell, this.world, spc.getMin(), spc.getMax(), playerId ); - if( tr.success ) - { - energy.extractAEPower( req, Actionable.MODULATE, PowerMultiplier.CONFIG ); - this.inv.setStackInSlot( 0, ItemStack.EMPTY ); - this.inv.setStackInSlot( 1, cell ); - } - } - } - } - } + final TransitionResult tr = sc.doSpatialTransition(cell, this.world, spc.getMin(), spc.getMax(), playerId); + if (tr.success) { + energy.extractAEPower(req, Actionable.MODULATE, PowerMultiplier.CONFIG); + this.inv.setStackInSlot(0, ItemStack.EMPTY); + this.inv.setStackInSlot(1, cell); + } + } + } + } + } - return null; - } + return null; + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.SMART; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.SMART; + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - protected @Nonnull IItemHandler getItemHandlerForSide( @Nonnull EnumFacing side ) - { - return this.invExt; - } + @Override + protected @Nonnull + IItemHandler getItemHandlerForSide(@Nonnull EnumFacing side) { + return this.invExt; + } - @Override - public IItemHandler getInternalInventory() - { - return this.inv; - } + @Override + public IItemHandler getInternalInventory() { + return this.inv; + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { - } + } - private class SpatialIOFilter implements IAEItemFilter - { - @Override - public boolean allowExtract( IItemHandler inv, int slot, int amount ) - { - return slot == 1; - } + private class SpatialIOFilter implements IAEItemFilter { + @Override + public boolean allowExtract(IItemHandler inv, int slot, int amount) { + return slot == 1; + } - @Override - public boolean allowInsert( IItemHandler inv, int slot, ItemStack stack ) - { - return( slot == 0 && TileSpatialIOPort.this.isSpatialCell( stack ) ); - } + @Override + public boolean allowInsert(IItemHandler inv, int slot, ItemStack stack) { + return (slot == 0 && TileSpatialIOPort.this.isSpatialCell(stack)); + } - } + } } diff --git a/src/main/java/appeng/tile/spatial/TileSpatialPylon.java b/src/main/java/appeng/tile/spatial/TileSpatialPylon.java index d3bf6101f..6e32303a5 100644 --- a/src/main/java/appeng/tile/spatial/TileSpatialPylon.java +++ b/src/main/java/appeng/tile/spatial/TileSpatialPylon.java @@ -19,13 +19,6 @@ package appeng.tile.spatial; -import java.io.IOException; -import java.util.EnumSet; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.util.EnumFacing; - import appeng.api.networking.GridFlags; import appeng.api.networking.events.MENetworkChannelsChanged; import appeng.api.networking.events.MENetworkEventSubscribe; @@ -37,215 +30,184 @@ import appeng.me.cluster.implementations.SpatialPylonCluster; import appeng.me.helpers.AENetworkProxy; import appeng.me.helpers.AENetworkProxyMultiblock; import appeng.tile.grid.AENetworkTile; +import io.netty.buffer.ByteBuf; +import net.minecraft.util.EnumFacing; + +import java.io.IOException; +import java.util.EnumSet; -public class TileSpatialPylon extends AENetworkTile implements IAEMultiBlock -{ +public class TileSpatialPylon extends AENetworkTile implements IAEMultiBlock { - public static final int DISPLAY_END_MIN = 0x01; - public static final int DISPLAY_END_MAX = 0x02; - public static final int DISPLAY_MIDDLE = 0x01 + 0x02; - public static final int DISPLAY_X = 0x04; - public static final int DISPLAY_Y = 0x08; - public static final int DISPLAY_Z = 0x04 + 0x08; - public static final int MB_STATUS = 0x01 + 0x02 + 0x04 + 0x08; + public static final int DISPLAY_END_MIN = 0x01; + public static final int DISPLAY_END_MAX = 0x02; + public static final int DISPLAY_MIDDLE = 0x01 + 0x02; + public static final int DISPLAY_X = 0x04; + public static final int DISPLAY_Y = 0x08; + public static final int DISPLAY_Z = 0x04 + 0x08; + public static final int MB_STATUS = 0x01 + 0x02 + 0x04 + 0x08; - public static final int DISPLAY_ENABLED = 0x10; - public static final int DISPLAY_POWERED_ENABLED = 0x20; - public static final int NET_STATUS = 0x10 + 0x20; + public static final int DISPLAY_ENABLED = 0x10; + public static final int DISPLAY_POWERED_ENABLED = 0x20; + public static final int NET_STATUS = 0x10 + 0x20; - private final SpatialPylonCalculator calc = new SpatialPylonCalculator( this ); - private int displayBits = 0; - private SpatialPylonCluster cluster; - private boolean didHaveLight = false; + private final SpatialPylonCalculator calc = new SpatialPylonCalculator(this); + private int displayBits = 0; + private SpatialPylonCluster cluster; + private boolean didHaveLight = false; - public TileSpatialPylon() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL, GridFlags.MULTIBLOCK ); - this.getProxy().setIdlePowerUsage( 0.5 ); - this.getProxy().setValidSides( EnumSet.noneOf( EnumFacing.class ) ); - } + public TileSpatialPylon() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL, GridFlags.MULTIBLOCK); + this.getProxy().setIdlePowerUsage(0.5); + this.getProxy().setValidSides(EnumSet.noneOf(EnumFacing.class)); + } - @Override - protected AENetworkProxy createProxy() - { - return new AENetworkProxyMultiblock( this, "proxy", this.getItemFromTile( this ), true ); - } + @Override + protected AENetworkProxy createProxy() { + return new AENetworkProxyMultiblock(this, "proxy", this.getItemFromTile(this), true); + } - @Override - public void onChunkUnload() - { - this.disconnect( false ); - super.onChunkUnload(); - } + @Override + public void onChunkUnload() { + this.disconnect(false); + super.onChunkUnload(); + } - @Override - public void onReady() - { - super.onReady(); - this.neighborChanged(); - } + @Override + public void onReady() { + super.onReady(); + this.neighborChanged(); + } - @Override - public void invalidate() - { - this.disconnect( false ); - super.invalidate(); - } + @Override + public void invalidate() { + this.disconnect(false); + super.invalidate(); + } - public void neighborChanged() - { - this.calc.calculateMultiblock( this.world, this.getLocation() ); - } + public void neighborChanged() { + this.calc.calculateMultiblock(this.world, this.getLocation()); + } - @Override - public void disconnect( final boolean b ) - { - if( this.cluster != null ) - { - this.cluster.destroy(); - this.updateStatus( null ); - } - } + @Override + public void disconnect(final boolean b) { + if (this.cluster != null) { + this.cluster.destroy(); + this.updateStatus(null); + } + } - @Override - public SpatialPylonCluster getCluster() - { - return this.cluster; - } + @Override + public SpatialPylonCluster getCluster() { + return this.cluster; + } - @Override - public boolean isValid() - { - return true; - } + @Override + public boolean isValid() { + return true; + } - public void updateStatus( final SpatialPylonCluster c ) - { - this.cluster = c; - this.getProxy().setValidSides( c == null ? EnumSet.noneOf( EnumFacing.class ) : EnumSet.allOf( EnumFacing.class ) ); - this.recalculateDisplay(); - } + public void updateStatus(final SpatialPylonCluster c) { + this.cluster = c; + this.getProxy().setValidSides(c == null ? EnumSet.noneOf(EnumFacing.class) : EnumSet.allOf(EnumFacing.class)); + this.recalculateDisplay(); + } - public void recalculateDisplay() - { - final int oldBits = this.displayBits; + public void recalculateDisplay() { + final int oldBits = this.displayBits; - this.displayBits = 0; + this.displayBits = 0; - if( this.cluster != null ) - { - if( this.cluster.getMin().equals( this.getLocation() ) ) - { - this.displayBits = DISPLAY_END_MIN; - } - else if( this.cluster.getMax().equals( this.getLocation() ) ) - { - this.displayBits = DISPLAY_END_MAX; - } - else - { - this.displayBits = DISPLAY_MIDDLE; - } + if (this.cluster != null) { + if (this.cluster.getMin().equals(this.getLocation())) { + this.displayBits = DISPLAY_END_MIN; + } else if (this.cluster.getMax().equals(this.getLocation())) { + this.displayBits = DISPLAY_END_MAX; + } else { + this.displayBits = DISPLAY_MIDDLE; + } - switch( this.cluster.getCurrentAxis() ) - { - case X: - this.displayBits |= DISPLAY_X; - break; - case Y: - this.displayBits |= DISPLAY_Y; - break; - case Z: - this.displayBits |= DISPLAY_Z; - break; - default: - this.displayBits = 0; - break; - } + switch (this.cluster.getCurrentAxis()) { + case X: + this.displayBits |= DISPLAY_X; + break; + case Y: + this.displayBits |= DISPLAY_Y; + break; + case Z: + this.displayBits |= DISPLAY_Z; + break; + default: + this.displayBits = 0; + break; + } - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - this.displayBits |= DISPLAY_POWERED_ENABLED; - } + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + this.displayBits |= DISPLAY_POWERED_ENABLED; + } - if( this.cluster.isValid() && this.getProxy().isActive() ) - { - this.displayBits |= DISPLAY_ENABLED; - } - } - catch( final GridAccessException e ) - { - // nothing? - } - } + if (this.cluster.isValid() && this.getProxy().isActive()) { + this.displayBits |= DISPLAY_ENABLED; + } + } catch (final GridAccessException e) { + // nothing? + } + } - if( oldBits != this.displayBits ) - { - this.markForUpdate(); - } - } + if (oldBits != this.displayBits) { + this.markForUpdate(); + } + } - @Override - public void markForUpdate() - { - super.markForUpdate(); - final boolean hasLight = this.getLightValue() > 0; - if( hasLight != this.didHaveLight ) - { - this.didHaveLight = hasLight; - this.world.checkLight( this.pos ); - // world.updateAllLightTypes( xCoord, yCoord, zCoord ); - } - } + @Override + public void markForUpdate() { + super.markForUpdate(); + final boolean hasLight = this.getLightValue() > 0; + if (hasLight != this.didHaveLight) { + this.didHaveLight = hasLight; + this.world.checkLight(this.pos); + // world.updateAllLightTypes( xCoord, yCoord, zCoord ); + } + } - @Override - public boolean canBeRotated() - { - return false; - } + @Override + public boolean canBeRotated() { + return false; + } - public int getLightValue() - { - if( ( this.displayBits & DISPLAY_POWERED_ENABLED ) == DISPLAY_POWERED_ENABLED ) - { - return 8; - } - return 0; - } + public int getLightValue() { + if ((this.displayBits & DISPLAY_POWERED_ENABLED) == DISPLAY_POWERED_ENABLED) { + return 8; + } + return 0; + } - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - final int old = this.displayBits; - this.displayBits = data.readByte(); - return old != this.displayBits || c; - } + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + final int old = this.displayBits; + this.displayBits = data.readByte(); + return old != this.displayBits || c; + } - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - data.writeByte( this.displayBits ); - } + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeByte(this.displayBits); + } - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.recalculateDisplay(); - } + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.recalculateDisplay(); + } - @MENetworkEventSubscribe - public void activeRender( final MENetworkChannelsChanged c ) - { - this.recalculateDisplay(); - } + @MENetworkEventSubscribe + public void activeRender(final MENetworkChannelsChanged c) { + this.recalculateDisplay(); + } - public int getDisplayBits() - { - return this.displayBits; - } + public int getDisplayBits() { + return this.displayBits; + } } diff --git a/src/main/java/appeng/tile/storage/TileChest.java b/src/main/java/appeng/tile/storage/TileChest.java index bb4bd0bb7..5a550325a 100644 --- a/src/main/java/appeng/tile/storage/TileChest.java +++ b/src/main/java/appeng/tile/storage/TileChest.java @@ -19,68 +19,22 @@ package appeng.tile.storage; -import java.io.IOException; -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import appeng.me.storage.BasicCellInventoryHandler; -import appeng.me.storage.CreativeCellInventory; -import io.netty.buffer.ByteBuf; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.ITickable; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; -import net.minecraftforge.fluids.capability.FluidTankProperties; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidTankProperties; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; -import appeng.api.config.AccessRestriction; -import appeng.api.config.Actionable; -import appeng.api.config.PowerMultiplier; -import appeng.api.config.SecurityPermissions; -import appeng.api.config.Settings; -import appeng.api.config.SortDir; -import appeng.api.config.SortOrder; -import appeng.api.config.ViewItems; +import appeng.api.config.*; import appeng.api.implementations.tiles.IColorableTile; import appeng.api.implementations.tiles.IMEChest; import appeng.api.networking.GridFlags; import appeng.api.networking.IGrid; import appeng.api.networking.IGridNode; import appeng.api.networking.energy.IEnergyGrid; -import appeng.api.networking.events.MENetworkCellArrayUpdate; -import appeng.api.networking.events.MENetworkChannelsChanged; -import appeng.api.networking.events.MENetworkEventSubscribe; -import appeng.api.networking.events.MENetworkPowerStatusChange; -import appeng.api.networking.events.MENetworkPowerStorage; +import appeng.api.networking.events.*; import appeng.api.networking.events.MENetworkPowerStorage.PowerEventType; import appeng.api.networking.security.IActionHost; import appeng.api.networking.security.IActionSource; import appeng.api.networking.security.ISecurityGrid; import appeng.api.networking.storage.IBaseMonitor; import appeng.api.networking.storage.IStorageGrid; -import appeng.api.storage.ICellGuiHandler; -import appeng.api.storage.ICellHandler; -import appeng.api.storage.ICellInventory; -import appeng.api.storage.ICellInventoryHandler; -import appeng.api.storage.IMEInventoryHandler; -import appeng.api.storage.IMEMonitor; -import appeng.api.storage.IMEMonitorHandlerReceiver; -import appeng.api.storage.IStorageChannel; -import appeng.api.storage.IStorageMonitorable; -import appeng.api.storage.IStorageMonitorableAccessor; -import appeng.api.storage.ITerminalHost; +import appeng.api.storage.*; import appeng.api.storage.channels.IFluidStorageChannel; import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEFluidStack; @@ -106,856 +60,706 @@ import appeng.util.inv.InvOperation; import appeng.util.inv.WrapperChainedItemHandler; import appeng.util.inv.filter.IAEItemFilter; import appeng.util.item.AEItemStack; - - -public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminalHost, IPriorityHost, IConfigManagerHost, IColorableTile, ITickable -{ - private final AppEngInternalInventory inputInventory = new AppEngInternalInventory( this, 1 ); - private final AppEngInternalInventory cellInventory = new AppEngInternalInventory( this, 1 ); - private final IItemHandler internalInventory = new WrapperChainedItemHandler( this.inputInventory, this.cellInventory ); - - private final IActionSource mySrc = new MachineSource( this ); - private final IConfigManager config = new ConfigManager( this ); - private long lastStateChange = 0; - private int priority = 0; - private int state = 0; - private boolean wasActive = false; - private AEColor paintedColor = AEColor.TRANSPARENT; - private boolean isCached = false; - private ChestMonitorHandler cellHandler; - private Accessor accessor; - private IFluidHandler fluidHandler; - - public TileChest() - { - this.setInternalMaxPower( PowerMultiplier.CONFIG.multiply( 128 ) ); - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.config.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - this.config.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - this.config.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - - this.setInternalPublicPowerStorage( true ); - this.setInternalPowerFlow( AccessRestriction.WRITE ); - - this.inputInventory.setFilter( new InputInventoryFilter() ); - this.cellInventory.setFilter( new CellInventoryFilter() ); - } - - public ItemStack getCell() - { - return this.cellInventory.getStackInSlot( 0 ); - } - - @Override - protected void PowerEvent( final PowerEventType x ) - { - if( x == PowerEventType.REQUEST_POWER ) - { - try - { - this.getProxy().getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.REQUEST_POWER ) ); - } - catch( final GridAccessException e ) - { - // :( - } - } - else - { - this.recalculateDisplay(); - } - } - - private void recalculateDisplay() - { - final int oldState = this.state; - - for( int x = 0; x < this.getCellCount(); x++ ) - { - this.state |= ( this.getCellStatus( x ) << ( 3 * x ) ); - } - - if( this.isPowered() ) - { - this.state |= 0x40; - } - else - { - this.state &= ~0x40; - } - - final boolean currentActive = this.getProxy().isActive(); - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - if( oldState != this.state ) - { - this.markForUpdate(); - } - } - - @Override - public int getCellCount() - { - return 1; - } - - @SuppressWarnings( "unchecked" ) - private void updateHandler() - { - if( !this.isCached ) - { - this.cellHandler = null; - this.accessor = null; - this.fluidHandler = null; - - final ItemStack is = this.getCell(); - if( !is.isEmpty() ) - { - this.isCached = true; - ICellHandler cellHandler = AEApi.instance().registries().cell().getHandler( is ); - if( cellHandler != null ) - { - double power = 1.0; - - for( IStorageChannel channel : AEApi.instance().storage().storageChannels() ) - { - final ICellInventoryHandler newCell = cellHandler.getCellInventory( is, this, channel ); - if( newCell != null ) - { - power += cellHandler.cellIdleDrain( is, newCell ); - this.cellHandler = this.wrap( newCell ); - break; - } - } - - this.getProxy().setIdlePowerUsage( power ); - this.accessor = new Accessor(); - - if( this.cellHandler != null && this.cellHandler - .getChannel() == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) - { - this.fluidHandler = new FluidHandler(); - } - } - } - } - } - - private > ChestMonitorHandler wrap( final IMEInventoryHandler h ) - { - if( h == null ) - { - return null; - } - - final MEInventoryHandler ih = new MEInventoryHandler( h, h.getChannel() ); - ih.setPriority( this.priority ); - - final ChestMonitorHandler g = new ChestMonitorHandler( ih ); - g.addListener( new ChestNetNotifier( h.getChannel() ), g ); - - return g; - } - - @Override - public int getCellStatus( final int slot ) - { - if( Platform.isClient() ) - { - return ( this.state >> ( slot * 3 ) ) & 3; - } - - this.updateHandler(); - - final ItemStack cell = this.getCell(); - final ICellHandler ch = AEApi.instance().registries().cell().getHandler( cell ); - - if( this.cellHandler != null && ch != null ) - { - return ch.getStatusForCell( cell, this.cellHandler.getInternalHandler() ); - } - - return 0; - } - - @Override - public boolean isPowered() - { - if( Platform.isClient() ) - { - return ( this.state & 0x40 ) == 0x40; - } - - boolean gridPowered = this.getAECurrentPower() > 64; - - if( !gridPowered ) - { - try - { - gridPowered = this.getProxy().getEnergy().isNetworkPowered(); - } - catch( final GridAccessException ignored ) - { - } - } - - return super.getAECurrentPower() > 1 || gridPowered; - } - - @Override - public boolean isCellBlinking( final int slot ) - { - final long now = this.world.getTotalWorldTime(); - if( now - this.lastStateChange > 8 ) - { - return false; - } - - return ( ( this.state >> ( slot * 3 + 2 ) ) & 0x01 ) == 0x01; - } - - @Override - protected double extractAEPower( final double amt, final Actionable mode ) - { - double stash = 0.0; - - try - { - final IEnergyGrid eg = this.getProxy().getEnergy(); - stash = eg.extractAEPower( amt, mode, PowerMultiplier.ONE ); - if( stash >= amt ) - { - return stash; - } - } - catch( final GridAccessException e ) - { - // no grid :( - } - - // local battery! - return super.extractAEPower( amt - stash, mode ) + stash; - } - - @Override - public void update() - { - if( this.world.isRemote ) - { - return; - } - - final double idleUsage = this.getProxy().getIdlePowerUsage(); - - try - { - if( !this.getProxy().getEnergy().isNetworkPowered() ) - { - final double powerUsed = this.extractAEPower( idleUsage, Actionable.MODULATE, PowerMultiplier.CONFIG ); // drain - if( powerUsed + 0.1 >= idleUsage != ( this.state & 0x40 ) > 0 ) - { - this.recalculateDisplay(); - } - } - } - catch( final GridAccessException e ) - { - final double powerUsed = this.extractAEPower( this.getProxy().getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG ); // drain - if( powerUsed + 0.1 >= idleUsage != ( this.state & 0x40 ) > 0 ) - { - this.recalculateDisplay(); - } - } - - if( !ItemHandlerUtil.isEmpty( this.inputInventory ) ) - { - this.tryToStoreContents(); - } - } - - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - - if( this.world.getTotalWorldTime() - this.lastStateChange > 8 ) - { - this.state = 0; - } - else - { - this.state &= 0x24924924; // just keep the blinks... - } - - for( int x = 0; x < this.getCellCount(); x++ ) - { - this.state |= ( this.getCellStatus( x ) << ( 3 * x ) ); - } - - if( this.isPowered() ) - { - this.state |= 0x40; - } - else - { - this.state &= ~0x40; - } - - data.writeByte( this.state ); - data.writeByte( this.paintedColor.ordinal() ); - } - - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - - final int oldState = this.state; - - this.state = data.readByte(); - final AEColor oldPaintedColor = this.paintedColor; - this.paintedColor = AEColor.values()[data.readByte()]; - - this.lastStateChange = this.world.getTotalWorldTime(); - - return oldPaintedColor != this.paintedColor || ( this.state & 0xDB6DB6DB ) != ( oldState & 0xDB6DB6DB ) || c; - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.config.readFromNBT( data ); - this.priority = data.getInteger( "priority" ); - if( data.hasKey( "paintedColor" ) ) - { - this.paintedColor = AEColor.values()[data.getByte( "paintedColor" )]; - } - } - - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.config.writeToNBT( data ); - data.setInteger( "priority", this.priority ); - data.setByte( "paintedColor", (byte) this.paintedColor.ordinal() ); - return data; - } - - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.recalculateDisplay(); - } - - @MENetworkEventSubscribe - public void channelRender( final MENetworkChannelsChanged c ) - { - this.recalculateDisplay(); - } - - @SuppressWarnings( "unchecked" ) - @Override - public > IMEMonitor getInventory( IStorageChannel channel ) - { - this.updateHandler(); - - if( this.cellHandler != null && this.cellHandler.getChannel() == channel ) - { - return this.cellHandler; - } - return null; - } - - @Override - public IItemHandler getInternalInventory() - { - return this.internalInventory; - } - - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( inv == this.cellInventory ) - { - this.cellHandler = null; - this.isCached = false; // recalculate the storage cell. - - try - { - if( this.getProxy().isActive() ) - { - final IStorageGrid gs = this.getProxy().getStorage(); - Platform.postChanges( gs, removed, added, this.mySrc ); - } - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException ignored ) - { - } - - // update the neighbors - if( this.world != null ) - { - Platform.notifyBlocksOfNeighbors( this.world, this.pos ); - this.markForUpdate(); - } - } - if( inv == this.inputInventory && mc == InvOperation.INSERT ) - { - this.tryToStoreContents(); - } - } - - @Override - protected IItemHandler getItemHandlerForSide( @Nonnull EnumFacing side ) - { - if( side == this.getForward() ) - { - return this.cellInventory; - } - else - { - return this.inputInventory; - } - } - - private void tryToStoreContents() - { - if( !ItemHandlerUtil.isEmpty( this.inputInventory ) ) - { - this.updateHandler(); - - if( this.cellHandler != null && this.cellHandler.getChannel() == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - final IAEItemStack returns = Platform.poweredInsert( this, this.cellHandler, - AEItemStack.fromItemStack( this.inputInventory.getStackInSlot( 0 ) ), this.mySrc ); - - if( returns == null ) - { - this.inputInventory.setStackInSlot( 0, ItemStack.EMPTY ); - } - else - { - this.inputInventory.setStackInSlot( 0, returns.createItemStack() ); - } - } - } - } - - @Override - public List getCellArray( final IStorageChannel channel ) - { - this.updateHandler(); - if( this.cellHandler != null && this.cellHandler.getChannel() == channel ) - { - return Collections.singletonList( this.cellHandler ); - } - return Collections.emptyList(); - } - - @Override - public int getPriority() - { - return this.priority; - } - - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - this.cellHandler = null; - this.isCached = false; // recalculate the storage cell. - - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - public void blinkCell( final int slot ) - { - final long now = this.world.getTotalWorldTime(); - if( now - this.lastStateChange > 8 ) - { - this.state = 0; - } - this.lastStateChange = now; - - this.state |= 1 << ( slot * 3 + 2 ); - - this.recalculateDisplay(); - } - - @Override - public IConfigManager getConfigManager() - { - return this.config; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - - } - - public boolean openGui( final EntityPlayer p ) - { - this.updateHandler(); - if( this.cellHandler != null ) - { - final ICellHandler ch = AEApi.instance().registries().cell().getHandler( this.getCell() ); - - if( ch != null ) - { - final ICellGuiHandler chg = AEApi.instance().registries().cell().getGuiHandler( this.cellHandler.getChannel(), this.getCell() ); - if( chg != null ) - { - chg.openChestGui( p, this, ch, this.cellHandler, this.getCell(), this.cellHandler.getChannel() ); - return true; - } - } - - } - - return false; - } - - @Override - public AEColor getColor() - { - return this.paintedColor; - } - - @Override - public boolean recolourBlock( final EnumFacing side, final AEColor newPaintedColor, final EntityPlayer who ) - { - if( this.paintedColor == newPaintedColor ) - { - return false; - } - - this.paintedColor = newPaintedColor; - this.saveChanges(); - this.markForUpdate(); - return true; - } - - @Override - public void saveChanges( final ICellInventory cellInventory ) - { - if( cellInventory != null ) - { - cellInventory.persist(); - } - this.world.markChunkDirty( this.pos, this ); - } - - private class ChestNetNotifier> implements IMEMonitorHandlerReceiver - { - - private final IStorageChannel chan; - - public ChestNetNotifier( final IStorageChannel chan ) - { - this.chan = chan; - } - - @Override - public boolean isValid( final Object verificationToken ) - { - TileChest.this.updateHandler(); - if( TileChest.this.cellHandler != null && this.chan == TileChest.this.cellHandler.getChannel() ) - { - return verificationToken == TileChest.this.cellHandler; - } - return false; - } - - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final IActionSource source ) - { - try - { - if( TileChest.this.getProxy().isActive() ) - { - TileChest.this.getProxy().getStorage().postAlterationOfStoredItems( this.chan, change, TileChest.this.mySrc ); - } - } - catch( final GridAccessException e ) - { - // :( - } - TileChest.this.blinkCell( 0 ); - } - - @Override - public void onListUpdate() - { - // not used here - } - } - - private class ChestMonitorHandler> extends MEMonitorHandler - { - - public ChestMonitorHandler( final IMEInventoryHandler t ) - { - super( t ); - } - - private ICellInventoryHandler getInternalHandler() - { - final IMEInventoryHandler h = this.getHandler(); - if( h instanceof MEInventoryHandler ) - { - return (ICellInventoryHandler) ( (MEInventoryHandler) h ).getInternal(); - } - return (ICellInventoryHandler) this.getHandler(); - } - - @Override - public T injectItems( final T input, final Actionable mode, final IActionSource src ) - { - if( src.player().map( player -> !this.securityCheck( player, SecurityPermissions.INJECT ) ).orElse( false ) ) - { - return input; - } - T injected = super.injectItems( input, mode, src ); - if( mode == Actionable.MODULATE && ( injected == null || injected.getStackSize() != input.getStackSize() ) ) - { - if( TileChest.this.isPowered() && this.getInternalHandler().getCellInv() != null ) - { - TileChest.this.cellHandler.postChangesToListeners( Collections.singletonList( input.copy().setStackSize( input.getStackSize() - ( injected == null ? 0 : injected.getStackSize() ) ) ), TileChest.this.mySrc ); - } - } - return injected; - } - - private boolean securityCheck( final EntityPlayer player, final SecurityPermissions requiredPermission ) - { - if( TileChest.this.getTile() instanceof IActionHost && requiredPermission != null ) - { - - final IGridNode gn = ( (IActionHost) TileChest.this.getTile() ).getActionableNode(); - if( gn != null ) - { - final IGrid g = gn.getGrid(); - if( g != null ) - { - final boolean requirePower = false; - if( requirePower ) - { - final IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - if( !eg.isNetworkPowered() ) - { - return false; - } - } - - final ISecurityGrid sg = g.getCache( ISecurityGrid.class ); - if( sg.hasPermission( player, requiredPermission ) ) - { - return true; - } - } - } - - return false; - } - return true; - } - - @Override - public T extractItems( final T request, final Actionable mode, final IActionSource src ) - { - if( src.player().map( player -> !this.securityCheck( player, SecurityPermissions.EXTRACT ) ).orElse( false ) ) - { - return null; - } - T extracted = super.extractItems( request, mode, src ); - if( mode == Actionable.MODULATE && extracted != null ) - { - if( TileChest.this.isPowered() && this.getInternalHandler().getCellInv() != null ) - { - TileChest.this.cellHandler.postChangesToListeners( Collections.singletonList( request.copy().setStackSize( -extracted.getStackSize() ) ), TileChest.this.mySrc ); - } - } - return extracted; - } - } - - @Override - public boolean hasCapability( Capability capability, EnumFacing facing ) - { - this.updateHandler(); - if( capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY && this.fluidHandler != null && facing != this.getForward() ) - { - return true; - } - if( capability == Capabilities.STORAGE_MONITORABLE_ACCESSOR && this.accessor != null && facing != this.getForward() ) - { - return true; - } - return super.hasCapability( capability, facing ); - } - - @SuppressWarnings( "unchecked" ) - @Override - public T getCapability( Capability capability, @Nullable EnumFacing facing ) - { - this.updateHandler(); - if( capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY && this.fluidHandler != null && facing != this.getForward() ) - { - return (T) this.fluidHandler; - } - if( capability == Capabilities.STORAGE_MONITORABLE_ACCESSOR && this.accessor != null && facing != this.getForward() ) - { - return (T) this.accessor; - } - return super.getCapability( capability, facing ); - } - - private class Accessor implements IStorageMonitorableAccessor - { - @Nullable - @Override - public IStorageMonitorable getInventory( IActionSource src ) - { - if( Platform.canAccess( TileChest.this.getProxy(), src ) ) - { - return TileChest.this; - } - return null; - } - } - - private class FluidHandler implements IFluidHandler - { - private final IFluidTankProperties[] TANK_PROPS = new IFluidTankProperties[]{new FluidTankProperties( null, Fluid.BUCKET_VOLUME )}; - - @Override - public int fill( final FluidStack resource, final boolean doFill ) - { - TileChest.this.updateHandler(); - if( TileChest.this.cellHandler != null && TileChest.this.cellHandler - .getChannel() == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) - { - final IAEFluidStack results = Platform.poweredInsert( TileChest.this, TileChest.this.cellHandler, AEFluidStack.fromFluidStack( resource ), - TileChest.this.mySrc, doFill ? Actionable.MODULATE : Actionable.SIMULATE ); - - if( results == null ) - { - return resource.amount; - } - return resource.amount - (int) results.getStackSize(); - } - return 0; - } - - @Override - public FluidStack drain( final FluidStack resource, final boolean doDrain ) - { - return null; - } - - @Override - public FluidStack drain( final int maxDrain, final boolean doDrain ) - { - return null; - } - - @Override - public IFluidTankProperties[] getTankProperties() - { - TileChest.this.updateHandler(); - - if( TileChest.this.cellHandler != null && TileChest.this.cellHandler - .getChannel() == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) - { - return this.TANK_PROPS; - } - return null; - } - } - - private class InputInventoryFilter implements IAEItemFilter - { - @Override - public boolean allowExtract( IItemHandler inv, int slot, int amount ) - { - return false; - } - - @Override - public boolean allowInsert( IItemHandler inv, int slot, ItemStack stack ) - { - if( TileChest.this.isPowered() ) - { - TileChest.this.updateHandler(); - return TileChest.this.cellHandler != null && TileChest.this.cellHandler - .getChannel() == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); - } - return false; - } - } - - private class CellInventoryFilter implements IAEItemFilter - { - - @Override - public boolean allowExtract( IItemHandler inv, int slot, int amount ) - { - return true; - } - - @Override - public boolean allowInsert( IItemHandler inv, int slot, ItemStack stack ) - { - return AEApi.instance().registries().cell().getHandler( stack ) != null; - } - - } - - @Override - public ItemStack getItemStackRepresentation() - { - return AEApi.instance().definitions().blocks().chest().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - } - - @Override - public GuiBridge getGuiBridge() - { - this.updateHandler(); - if( this.cellHandler != null ) - { - if( this.cellHandler.getChannel() == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) - { - return GuiBridge.GUI_ME; - } - if( this.cellHandler.getChannel() == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) - { - return GuiBridge.GUI_FLUID_TERMINAL; - } - } - return null; - } +import io.netty.buffer.ByteBuf; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.ITickable; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; +import net.minecraftforge.fluids.capability.FluidTankProperties; +import net.minecraftforge.fluids.capability.IFluidHandler; +import net.minecraftforge.fluids.capability.IFluidTankProperties; +import net.minecraftforge.items.IItemHandler; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.IOException; +import java.util.Collections; +import java.util.List; + + +public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminalHost, IPriorityHost, IConfigManagerHost, IColorableTile, ITickable { + private final AppEngInternalInventory inputInventory = new AppEngInternalInventory(this, 1); + private final AppEngInternalInventory cellInventory = new AppEngInternalInventory(this, 1); + private final IItemHandler internalInventory = new WrapperChainedItemHandler(this.inputInventory, this.cellInventory); + + private final IActionSource mySrc = new MachineSource(this); + private final IConfigManager config = new ConfigManager(this); + private long lastStateChange = 0; + private int priority = 0; + private int state = 0; + private boolean wasActive = false; + private AEColor paintedColor = AEColor.TRANSPARENT; + private boolean isCached = false; + private ChestMonitorHandler cellHandler; + private Accessor accessor; + private IFluidHandler fluidHandler; + + public TileChest() { + this.setInternalMaxPower(PowerMultiplier.CONFIG.multiply(128)); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.config.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.config.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + this.config.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + + this.setInternalPublicPowerStorage(true); + this.setInternalPowerFlow(AccessRestriction.WRITE); + + this.inputInventory.setFilter(new InputInventoryFilter()); + this.cellInventory.setFilter(new CellInventoryFilter()); + } + + public ItemStack getCell() { + return this.cellInventory.getStackInSlot(0); + } + + @Override + protected void PowerEvent(final PowerEventType x) { + if (x == PowerEventType.REQUEST_POWER) { + try { + this.getProxy().getGrid().postEvent(new MENetworkPowerStorage(this, PowerEventType.REQUEST_POWER)); + } catch (final GridAccessException e) { + // :( + } + } else { + this.recalculateDisplay(); + } + } + + private void recalculateDisplay() { + final int oldState = this.state; + + for (int x = 0; x < this.getCellCount(); x++) { + this.state |= (this.getCellStatus(x) << (3 * x)); + } + + if (this.isPowered()) { + this.state |= 0x40; + } else { + this.state &= ~0x40; + } + + final boolean currentActive = this.getProxy().isActive(); + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } + + if (oldState != this.state) { + this.markForUpdate(); + } + } + + @Override + public int getCellCount() { + return 1; + } + + @SuppressWarnings("unchecked") + private void updateHandler() { + if (!this.isCached) { + this.cellHandler = null; + this.accessor = null; + this.fluidHandler = null; + + final ItemStack is = this.getCell(); + if (!is.isEmpty()) { + this.isCached = true; + ICellHandler cellHandler = AEApi.instance().registries().cell().getHandler(is); + if (cellHandler != null) { + double power = 1.0; + + for (IStorageChannel channel : AEApi.instance().storage().storageChannels()) { + final ICellInventoryHandler newCell = cellHandler.getCellInventory(is, this, channel); + if (newCell != null) { + power += cellHandler.cellIdleDrain(is, newCell); + this.cellHandler = this.wrap(newCell); + break; + } + } + + this.getProxy().setIdlePowerUsage(power); + this.accessor = new Accessor(); + + if (this.cellHandler != null && this.cellHandler + .getChannel() == AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)) { + this.fluidHandler = new FluidHandler(); + } + } + } + } + } + + private > ChestMonitorHandler wrap(final IMEInventoryHandler h) { + if (h == null) { + return null; + } + + final MEInventoryHandler ih = new MEInventoryHandler(h, h.getChannel()); + ih.setPriority(this.priority); + + final ChestMonitorHandler g = new ChestMonitorHandler(ih); + g.addListener(new ChestNetNotifier(h.getChannel()), g); + + return g; + } + + @Override + public int getCellStatus(final int slot) { + if (Platform.isClient()) { + return (this.state >> (slot * 3)) & 3; + } + + this.updateHandler(); + + final ItemStack cell = this.getCell(); + final ICellHandler ch = AEApi.instance().registries().cell().getHandler(cell); + + if (this.cellHandler != null && ch != null) { + return ch.getStatusForCell(cell, this.cellHandler.getInternalHandler()); + } + + return 0; + } + + @Override + public boolean isPowered() { + if (Platform.isClient()) { + return (this.state & 0x40) == 0x40; + } + + boolean gridPowered = this.getAECurrentPower() > 64; + + if (!gridPowered) { + try { + gridPowered = this.getProxy().getEnergy().isNetworkPowered(); + } catch (final GridAccessException ignored) { + } + } + + return super.getAECurrentPower() > 1 || gridPowered; + } + + @Override + public boolean isCellBlinking(final int slot) { + final long now = this.world.getTotalWorldTime(); + if (now - this.lastStateChange > 8) { + return false; + } + + return ((this.state >> (slot * 3 + 2)) & 0x01) == 0x01; + } + + @Override + protected double extractAEPower(final double amt, final Actionable mode) { + double stash = 0.0; + + try { + final IEnergyGrid eg = this.getProxy().getEnergy(); + stash = eg.extractAEPower(amt, mode, PowerMultiplier.ONE); + if (stash >= amt) { + return stash; + } + } catch (final GridAccessException e) { + // no grid :( + } + + // local battery! + return super.extractAEPower(amt - stash, mode) + stash; + } + + @Override + public void update() { + if (this.world.isRemote) { + return; + } + + final double idleUsage = this.getProxy().getIdlePowerUsage(); + + try { + if (!this.getProxy().getEnergy().isNetworkPowered()) { + final double powerUsed = this.extractAEPower(idleUsage, Actionable.MODULATE, PowerMultiplier.CONFIG); // drain + if (powerUsed + 0.1 >= idleUsage != (this.state & 0x40) > 0) { + this.recalculateDisplay(); + } + } + } catch (final GridAccessException e) { + final double powerUsed = this.extractAEPower(this.getProxy().getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG); // drain + if (powerUsed + 0.1 >= idleUsage != (this.state & 0x40) > 0) { + this.recalculateDisplay(); + } + } + + if (!ItemHandlerUtil.isEmpty(this.inputInventory)) { + this.tryToStoreContents(); + } + } + + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + + if (this.world.getTotalWorldTime() - this.lastStateChange > 8) { + this.state = 0; + } else { + this.state &= 0x24924924; // just keep the blinks... + } + + for (int x = 0; x < this.getCellCount(); x++) { + this.state |= (this.getCellStatus(x) << (3 * x)); + } + + if (this.isPowered()) { + this.state |= 0x40; + } else { + this.state &= ~0x40; + } + + data.writeByte(this.state); + data.writeByte(this.paintedColor.ordinal()); + } + + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + + final int oldState = this.state; + + this.state = data.readByte(); + final AEColor oldPaintedColor = this.paintedColor; + this.paintedColor = AEColor.values()[data.readByte()]; + + this.lastStateChange = this.world.getTotalWorldTime(); + + return oldPaintedColor != this.paintedColor || (this.state & 0xDB6DB6DB) != (oldState & 0xDB6DB6DB) || c; + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.config.readFromNBT(data); + this.priority = data.getInteger("priority"); + if (data.hasKey("paintedColor")) { + this.paintedColor = AEColor.values()[data.getByte("paintedColor")]; + } + } + + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.config.writeToNBT(data); + data.setInteger("priority", this.priority); + data.setByte("paintedColor", (byte) this.paintedColor.ordinal()); + return data; + } + + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.recalculateDisplay(); + } + + @MENetworkEventSubscribe + public void channelRender(final MENetworkChannelsChanged c) { + this.recalculateDisplay(); + } + + @SuppressWarnings("unchecked") + @Override + public > IMEMonitor getInventory(IStorageChannel channel) { + this.updateHandler(); + + if (this.cellHandler != null && this.cellHandler.getChannel() == channel) { + return this.cellHandler; + } + return null; + } + + @Override + public IItemHandler getInternalInventory() { + return this.internalInventory; + } + + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { + if (inv == this.cellInventory) { + this.cellHandler = null; + this.isCached = false; // recalculate the storage cell. + + try { + if (this.getProxy().isActive()) { + final IStorageGrid gs = this.getProxy().getStorage(); + Platform.postChanges(gs, removed, added, this.mySrc); + } + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException ignored) { + } + + // update the neighbors + if (this.world != null) { + Platform.notifyBlocksOfNeighbors(this.world, this.pos); + this.markForUpdate(); + } + } + if (inv == this.inputInventory && mc == InvOperation.INSERT) { + this.tryToStoreContents(); + } + } + + @Override + protected IItemHandler getItemHandlerForSide(@Nonnull EnumFacing side) { + if (side == this.getForward()) { + return this.cellInventory; + } else { + return this.inputInventory; + } + } + + private void tryToStoreContents() { + if (!ItemHandlerUtil.isEmpty(this.inputInventory)) { + this.updateHandler(); + + if (this.cellHandler != null && this.cellHandler.getChannel() == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + final IAEItemStack returns = Platform.poweredInsert(this, this.cellHandler, + AEItemStack.fromItemStack(this.inputInventory.getStackInSlot(0)), this.mySrc); + + if (returns == null) { + this.inputInventory.setStackInSlot(0, ItemStack.EMPTY); + } else { + this.inputInventory.setStackInSlot(0, returns.createItemStack()); + } + } + } + } + + @Override + public List getCellArray(final IStorageChannel channel) { + this.updateHandler(); + if (this.cellHandler != null && this.cellHandler.getChannel() == channel) { + return Collections.singletonList(this.cellHandler); + } + return Collections.emptyList(); + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + this.cellHandler = null; + this.isCached = false; // recalculate the storage cell. + + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } + + @Override + public void blinkCell(final int slot) { + final long now = this.world.getTotalWorldTime(); + if (now - this.lastStateChange > 8) { + this.state = 0; + } + this.lastStateChange = now; + + this.state |= 1 << (slot * 3 + 2); + + this.recalculateDisplay(); + } + + @Override + public IConfigManager getConfigManager() { + return this.config; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + + } + + public boolean openGui(final EntityPlayer p) { + this.updateHandler(); + if (this.cellHandler != null) { + final ICellHandler ch = AEApi.instance().registries().cell().getHandler(this.getCell()); + + if (ch != null) { + final ICellGuiHandler chg = AEApi.instance().registries().cell().getGuiHandler(this.cellHandler.getChannel(), this.getCell()); + if (chg != null) { + chg.openChestGui(p, this, ch, this.cellHandler, this.getCell(), this.cellHandler.getChannel()); + return true; + } + } + + } + + return false; + } + + @Override + public AEColor getColor() { + return this.paintedColor; + } + + @Override + public boolean recolourBlock(final EnumFacing side, final AEColor newPaintedColor, final EntityPlayer who) { + if (this.paintedColor == newPaintedColor) { + return false; + } + + this.paintedColor = newPaintedColor; + this.saveChanges(); + this.markForUpdate(); + return true; + } + + @Override + public void saveChanges(final ICellInventory cellInventory) { + if (cellInventory != null) { + cellInventory.persist(); + } + this.world.markChunkDirty(this.pos, this); + } + + private class ChestNetNotifier> implements IMEMonitorHandlerReceiver { + + private final IStorageChannel chan; + + public ChestNetNotifier(final IStorageChannel chan) { + this.chan = chan; + } + + @Override + public boolean isValid(final Object verificationToken) { + TileChest.this.updateHandler(); + if (TileChest.this.cellHandler != null && this.chan == TileChest.this.cellHandler.getChannel()) { + return verificationToken == TileChest.this.cellHandler; + } + return false; + } + + @Override + public void postChange(final IBaseMonitor monitor, final Iterable change, final IActionSource source) { + try { + if (TileChest.this.getProxy().isActive()) { + TileChest.this.getProxy().getStorage().postAlterationOfStoredItems(this.chan, change, TileChest.this.mySrc); + } + } catch (final GridAccessException e) { + // :( + } + TileChest.this.blinkCell(0); + } + + @Override + public void onListUpdate() { + // not used here + } + } + + private class ChestMonitorHandler> extends MEMonitorHandler { + + public ChestMonitorHandler(final IMEInventoryHandler t) { + super(t); + } + + private ICellInventoryHandler getInternalHandler() { + final IMEInventoryHandler h = this.getHandler(); + if (h instanceof MEInventoryHandler) { + return (ICellInventoryHandler) ((MEInventoryHandler) h).getInternal(); + } + return (ICellInventoryHandler) this.getHandler(); + } + + @Override + public T injectItems(final T input, final Actionable mode, final IActionSource src) { + if (src.player().map(player -> !this.securityCheck(player, SecurityPermissions.INJECT)).orElse(false)) { + return input; + } + T injected = super.injectItems(input, mode, src); + if (mode == Actionable.MODULATE && (injected == null || injected.getStackSize() != input.getStackSize())) { + if (TileChest.this.isPowered() && this.getInternalHandler().getCellInv() != null) { + TileChest.this.cellHandler.postChangesToListeners(Collections.singletonList(input.copy().setStackSize(input.getStackSize() - (injected == null ? 0 : injected.getStackSize()))), TileChest.this.mySrc); + } + } + return injected; + } + + private boolean securityCheck(final EntityPlayer player, final SecurityPermissions requiredPermission) { + if (TileChest.this.getTile() instanceof IActionHost && requiredPermission != null) { + + final IGridNode gn = ((IActionHost) TileChest.this.getTile()).getActionableNode(); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + final boolean requirePower = false; + if (requirePower) { + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + if (!eg.isNetworkPowered()) { + return false; + } + } + + final ISecurityGrid sg = g.getCache(ISecurityGrid.class); + return sg.hasPermission(player, requiredPermission); + } + } + + return false; + } + return true; + } + + @Override + public T extractItems(final T request, final Actionable mode, final IActionSource src) { + if (src.player().map(player -> !this.securityCheck(player, SecurityPermissions.EXTRACT)).orElse(false)) { + return null; + } + T extracted = super.extractItems(request, mode, src); + if (mode == Actionable.MODULATE && extracted != null) { + if (TileChest.this.isPowered() && this.getInternalHandler().getCellInv() != null) { + TileChest.this.cellHandler.postChangesToListeners(Collections.singletonList(request.copy().setStackSize(-extracted.getStackSize())), TileChest.this.mySrc); + } + } + return extracted; + } + } + + @Override + public boolean hasCapability(Capability capability, EnumFacing facing) { + this.updateHandler(); + if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY && this.fluidHandler != null && facing != this.getForward()) { + return true; + } + if (capability == Capabilities.STORAGE_MONITORABLE_ACCESSOR && this.accessor != null && facing != this.getForward()) { + return true; + } + return super.hasCapability(capability, facing); + } + + @SuppressWarnings("unchecked") + @Override + public T getCapability(Capability capability, @Nullable EnumFacing facing) { + this.updateHandler(); + if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY && this.fluidHandler != null && facing != this.getForward()) { + return (T) this.fluidHandler; + } + if (capability == Capabilities.STORAGE_MONITORABLE_ACCESSOR && this.accessor != null && facing != this.getForward()) { + return (T) this.accessor; + } + return super.getCapability(capability, facing); + } + + private class Accessor implements IStorageMonitorableAccessor { + @Nullable + @Override + public IStorageMonitorable getInventory(IActionSource src) { + if (Platform.canAccess(TileChest.this.getProxy(), src)) { + return TileChest.this; + } + return null; + } + } + + private class FluidHandler implements IFluidHandler { + private final IFluidTankProperties[] TANK_PROPS = new IFluidTankProperties[]{new FluidTankProperties(null, Fluid.BUCKET_VOLUME)}; + + @Override + public int fill(final FluidStack resource, final boolean doFill) { + TileChest.this.updateHandler(); + if (TileChest.this.cellHandler != null && TileChest.this.cellHandler + .getChannel() == AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)) { + final IAEFluidStack results = Platform.poweredInsert(TileChest.this, TileChest.this.cellHandler, AEFluidStack.fromFluidStack(resource), + TileChest.this.mySrc, doFill ? Actionable.MODULATE : Actionable.SIMULATE); + + if (results == null) { + return resource.amount; + } + return resource.amount - (int) results.getStackSize(); + } + return 0; + } + + @Override + public FluidStack drain(final FluidStack resource, final boolean doDrain) { + return null; + } + + @Override + public FluidStack drain(final int maxDrain, final boolean doDrain) { + return null; + } + + @Override + public IFluidTankProperties[] getTankProperties() { + TileChest.this.updateHandler(); + + if (TileChest.this.cellHandler != null && TileChest.this.cellHandler + .getChannel() == AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)) { + return this.TANK_PROPS; + } + return null; + } + } + + private class InputInventoryFilter implements IAEItemFilter { + @Override + public boolean allowExtract(IItemHandler inv, int slot, int amount) { + return false; + } + + @Override + public boolean allowInsert(IItemHandler inv, int slot, ItemStack stack) { + if (TileChest.this.isPowered()) { + TileChest.this.updateHandler(); + return TileChest.this.cellHandler != null && TileChest.this.cellHandler + .getChannel() == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class); + } + return false; + } + } + + private class CellInventoryFilter implements IAEItemFilter { + + @Override + public boolean allowExtract(IItemHandler inv, int slot, int amount) { + return true; + } + + @Override + public boolean allowInsert(IItemHandler inv, int slot, ItemStack stack) { + return AEApi.instance().registries().cell().getHandler(stack) != null; + } + + } + + @Override + public ItemStack getItemStackRepresentation() { + return AEApi.instance().definitions().blocks().chest().maybeStack(1).orElse(ItemStack.EMPTY); + } + + @Override + public GuiBridge getGuiBridge() { + this.updateHandler(); + if (this.cellHandler != null) { + if (this.cellHandler.getChannel() == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) { + return GuiBridge.GUI_ME; + } + if (this.cellHandler.getChannel() == AEApi.instance().storage().getStorageChannel(IFluidStorageChannel.class)) { + return GuiBridge.GUI_FLUID_TERMINAL; + } + } + return null; + } } diff --git a/src/main/java/appeng/tile/storage/TileDrive.java b/src/main/java/appeng/tile/storage/TileDrive.java index afa5a5008..32628500c 100644 --- a/src/main/java/appeng/tile/storage/TileDrive.java +++ b/src/main/java/appeng/tile/storage/TileDrive.java @@ -19,20 +19,6 @@ package appeng.tile.storage; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; - -import io.netty.buffer.ByteBuf; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; import appeng.api.implementations.tiles.IChestOrDrive; import appeng.api.networking.GridFlags; @@ -42,11 +28,7 @@ import appeng.api.networking.events.MENetworkEventSubscribe; import appeng.api.networking.events.MENetworkPowerStatusChange; import appeng.api.networking.security.IActionSource; import appeng.api.networking.storage.IStorageGrid; -import appeng.api.storage.ICellHandler; -import appeng.api.storage.ICellInventory; -import appeng.api.storage.ICellInventoryHandler; -import appeng.api.storage.IMEInventoryHandler; -import appeng.api.storage.IStorageChannel; +import appeng.api.storage.*; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEStack; import appeng.api.util.AECableType; @@ -62,349 +44,299 @@ import appeng.tile.inventory.AppEngCellInventory; import appeng.util.Platform; import appeng.util.inv.InvOperation; import appeng.util.inv.filter.IAEItemFilter; +import io.netty.buffer.ByteBuf; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.items.IItemHandler; + +import java.io.IOException; +import java.util.*; -public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPriorityHost -{ +public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPriorityHost { - private static final int BIT_POWER_MASK = 0x80000000; - private static final int BIT_BLINK_MASK = 0x24924924; - private static final int BIT_STATE_MASK = 0xDB6DB6DB; + private static final int BIT_POWER_MASK = 0x80000000; + private static final int BIT_BLINK_MASK = 0x24924924; + private static final int BIT_STATE_MASK = 0xDB6DB6DB; - private final AppEngCellInventory inv = new AppEngCellInventory( this, 10 ); - private final ICellHandler[] handlersBySlot = new ICellHandler[10]; - private final DriveWatcher[] invBySlot = new DriveWatcher[10]; - private final IActionSource mySrc; - private boolean isCached = false; - private Map>, List> inventoryHandlers; - private int priority = 0; - private boolean wasActive = false; + private final AppEngCellInventory inv = new AppEngCellInventory(this, 10); + private final ICellHandler[] handlersBySlot = new ICellHandler[10]; + private final DriveWatcher[] invBySlot = new DriveWatcher[10]; + private final IActionSource mySrc; + private boolean isCached = false; + private final Map>, List> inventoryHandlers; + private int priority = 0; + private boolean wasActive = false; - /** - * The state of all cells inside a drive as bitset, using the following format. - * - * Bit 31: power state. 0 = off, 1 = on. - * Bit 30: undefined - * Bit 29-0: 3 bits as state of each cell with the cell in slot 0 located in the 3 least significant bits. - * - * Cell states: - * Bit 2: blink. 0 = off, 1 = on. - * Bit 1-0: cell status - * - * - */ - private int state = 0; + /** + * The state of all cells inside a drive as bitset, using the following format. + *

+ * Bit 31: power state. 0 = off, 1 = on. + * Bit 30: undefined + * Bit 29-0: 3 bits as state of each cell with the cell in slot 0 located in the 3 least significant bits. + *

+ * Cell states: + * Bit 2: blink. 0 = off, 1 = on. + * Bit 1-0: cell status + */ + private int state = 0; - public TileDrive() - { - this.mySrc = new MachineSource( this ); - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.inv.setFilter( new CellValidInventoryFilter() ); - this.inventoryHandlers = new IdentityHashMap<>(); - } + public TileDrive() { + this.mySrc = new MachineSource(this); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.inv.setFilter(new CellValidInventoryFilter()); + this.inventoryHandlers = new IdentityHashMap<>(); + } - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - int newState = 0; + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + int newState = 0; - if( this.getProxy().isActive() ) - { - newState |= BIT_POWER_MASK; - } + if (this.getProxy().isActive()) { + newState |= BIT_POWER_MASK; + } - for( int x = 0; x < this.getCellCount(); x++ ) - { - newState |= ( this.getCellStatus( x ) << ( 3 * x ) ); - } + for (int x = 0; x < this.getCellCount(); x++) { + newState |= (this.getCellStatus(x) << (3 * x)); + } - data.writeInt( newState ); - } + data.writeInt(newState); + } - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - final int oldState = this.state; - this.state = data.readInt(); - return ( this.state & BIT_STATE_MASK ) != ( oldState & BIT_STATE_MASK ) || c; - } + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + final int oldState = this.state; + this.state = data.readInt(); + return (this.state & BIT_STATE_MASK) != (oldState & BIT_STATE_MASK) || c; + } - @Override - public int getCellCount() - { - return 10; - } + @Override + public int getCellCount() { + return 10; + } - @Override - public int getCellStatus( final int slot ) - { - if( Platform.isClient() ) - { - return ( this.state >> ( slot * 3 ) ) & 3; - } + @Override + public int getCellStatus(final int slot) { + if (Platform.isClient()) { + return (this.state >> (slot * 3)) & 3; + } - final DriveWatcher handler = this.invBySlot[slot]; - if( handler == null ) - { - return 0; - } + final DriveWatcher handler = this.invBySlot[slot]; + if (handler == null) { + return 0; + } - return handler.getStatus(); - } + return handler.getStatus(); + } - @Override - public boolean isPowered() - { - if( Platform.isClient() ) - { - return ( this.state & BIT_POWER_MASK ) == BIT_POWER_MASK; - } + @Override + public boolean isPowered() { + if (Platform.isClient()) { + return (this.state & BIT_POWER_MASK) == BIT_POWER_MASK; + } - return this.getProxy().isActive(); - } + return this.getProxy().isActive(); + } - @Override - public boolean isCellBlinking( final int slot ) - { - return ( ( this.state >> ( slot * 3 + 2 ) ) & 0x01 ) == 0x01; - } + @Override + public boolean isCellBlinking(final int slot) { + return ((this.state >> (slot * 3 + 2)) & 0x01) == 0x01; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.isCached = false; - this.priority = data.getInteger( "priority" ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.isCached = false; + this.priority = data.getInteger("priority"); + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setInteger( "priority", this.priority ); - return data; - } + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setInteger("priority", this.priority); + return data; + } - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.recalculateDisplay(); - } + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.recalculateDisplay(); + } - private void recalculateDisplay() - { - final boolean currentActive = this.getProxy().isActive(); - int newState = 0; + private void recalculateDisplay() { + final boolean currentActive = this.getProxy().isActive(); + int newState = 0; - if( currentActive ) - { - newState |= BIT_POWER_MASK; - } + if (currentActive) { + newState |= BIT_POWER_MASK; + } - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } - for( int x = 0; x < this.getCellCount(); x++ ) - { - newState |= ( this.getCellStatus( x ) << ( 3 * x ) ); - } + for (int x = 0; x < this.getCellCount(); x++) { + newState |= (this.getCellStatus(x) << (3 * x)); + } - if( newState != this.state ) - { - this.state = newState; - this.markForUpdate(); - } - } + if (newState != this.state) { + this.state = newState; + this.markForUpdate(); + } + } - @MENetworkEventSubscribe - public void channelRender( final MENetworkChannelsChanged c ) - { - this.recalculateDisplay(); - } + @MENetworkEventSubscribe + public void channelRender(final MENetworkChannelsChanged c) { + this.recalculateDisplay(); + } - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.SMART; - } + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.SMART; + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - public IItemHandler getInternalInventory() - { - return this.inv; - } + @Override + public IItemHandler getInternalInventory() { + return this.inv; + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( this.isCached ) - { - this.isCached = false; // recalculate the storage cell. - this.updateState(); - } + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { + if (this.isCached) { + this.isCached = false; // recalculate the storage cell. + this.updateState(); + } - try - { - if( this.getProxy().isActive() ) - { - final IStorageGrid gs = this.getProxy().getStorage(); - Platform.postChanges( gs, removed, added, this.mySrc ); - } - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException ignored ) - { - } + try { + if (this.getProxy().isActive()) { + final IStorageGrid gs = this.getProxy().getStorage(); + Platform.postChanges(gs, removed, added, this.mySrc); + } + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException ignored) { + } - this.markForUpdate(); - } + this.markForUpdate(); + } - private void updateState() - { - if( !this.isCached ) - { - final Collection>> storageChannels = AEApi.instance().storage().storageChannels(); - storageChannels.forEach( channel -> this.inventoryHandlers.put( channel, new ArrayList<>( 10 ) ) ); + private void updateState() { + if (!this.isCached) { + final Collection>> storageChannels = AEApi.instance().storage().storageChannels(); + storageChannels.forEach(channel -> this.inventoryHandlers.put(channel, new ArrayList<>(10))); - double power = 2.0; + double power = 2.0; - for( int x = 0; x < this.inv.getSlots(); x++ ) - { - final ItemStack is = this.inv.getStackInSlot( x ); - this.invBySlot[x] = null; - this.handlersBySlot[x] = null; + for (int x = 0; x < this.inv.getSlots(); x++) { + final ItemStack is = this.inv.getStackInSlot(x); + this.invBySlot[x] = null; + this.handlersBySlot[x] = null; - if( !is.isEmpty() ) - { - this.handlersBySlot[x] = AEApi.instance().registries().cell().getHandler( is ); + if (!is.isEmpty()) { + this.handlersBySlot[x] = AEApi.instance().registries().cell().getHandler(is); - if( this.handlersBySlot[x] != null ) - { - for( IStorageChannel> channel : storageChannels ) - { + if (this.handlersBySlot[x] != null) { + for (IStorageChannel> channel : storageChannels) { - ICellInventoryHandler cell = this.handlersBySlot[x].getCellInventory( is, this, channel ); + ICellInventoryHandler cell = this.handlersBySlot[x].getCellInventory(is, this, channel); - if( cell != null ) - { - this.inv.setHandler( x, cell ); - power += this.handlersBySlot[x].cellIdleDrain( is, cell ); + if (cell != null) { + this.inv.setHandler(x, cell); + power += this.handlersBySlot[x].cellIdleDrain(is, cell); - final DriveWatcher ih = new DriveWatcher( cell, is, this.handlersBySlot[x], this ); - ih.setPriority( this.priority ); - this.invBySlot[x] = ih; - this.inventoryHandlers.get( channel ).add( ih ); + final DriveWatcher ih = new DriveWatcher(cell, is, this.handlersBySlot[x], this); + ih.setPriority(this.priority); + this.invBySlot[x] = ih; + this.inventoryHandlers.get(channel).add(ih); - break; - } - } - } - } - } + break; + } + } + } + } + } - this.getProxy().setIdlePowerUsage( power ); + this.getProxy().setIdlePowerUsage(power); - this.isCached = true; - } - } + this.isCached = true; + } + } - @Override - public void onReady() - { - super.onReady(); - this.updateState(); - } + @Override + public void onReady() { + super.onReady(); + this.updateState(); + } - @Override - public List getCellArray( final IStorageChannel channel ) - { - this.updateState(); - return this.inventoryHandlers.get( channel ); - } + @Override + public List getCellArray(final IStorageChannel channel) { + this.updateState(); + return this.inventoryHandlers.get(channel); + } - @Override - public int getPriority() - { - return this.priority; - } + @Override + public int getPriority() { + return this.priority; + } - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - this.saveChanges(); + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + this.saveChanges(); - this.isCached = false; // recalculate the storage cell. - this.updateState(); + this.isCached = false; // recalculate the storage cell. + this.updateState(); - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } - @Override - public void blinkCell( final int slot ) - { - this.state |= 1 << ( slot * 3 + 2 ); + @Override + public void blinkCell(final int slot) { + this.state |= 1 << (slot * 3 + 2); - this.recalculateDisplay(); - } + this.recalculateDisplay(); + } - @Override - public void saveChanges( final ICellInventory cellInventory ) - { - this.world.markChunkDirty( this.pos, this ); - } + @Override + public void saveChanges(final ICellInventory cellInventory) { + this.world.markChunkDirty(this.pos, this); + } - private class CellValidInventoryFilter implements IAEItemFilter - { + private class CellValidInventoryFilter implements IAEItemFilter { - @Override - public boolean allowExtract( IItemHandler inv, int slot, int amount ) - { - return true; - } + @Override + public boolean allowExtract(IItemHandler inv, int slot, int amount) { + return true; + } - @Override - public boolean allowInsert( IItemHandler inv, int slot, ItemStack stack ) - { - return !stack.isEmpty() && AEApi.instance().registries().cell().isCellHandled( stack ); - } + @Override + public boolean allowInsert(IItemHandler inv, int slot, ItemStack stack) { + return !stack.isEmpty() && AEApi.instance().registries().cell().isCellHandled(stack); + } - } + } - @Override - public ItemStack getItemStackRepresentation() - { - return AEApi.instance().definitions().blocks().drive().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - } + @Override + public ItemStack getItemStackRepresentation() { + return AEApi.instance().definitions().blocks().drive().maybeStack(1).orElse(ItemStack.EMPTY); + } - @Override - public GuiBridge getGuiBridge() - { - return GuiBridge.GUI_DRIVE; - } + @Override + public GuiBridge getGuiBridge() { + return GuiBridge.GUI_DRIVE; + } } diff --git a/src/main/java/appeng/tile/storage/TileIOPort.java b/src/main/java/appeng/tile/storage/TileIOPort.java index 249be6859..73bdd9c10 100644 --- a/src/main/java/appeng/tile/storage/TileIOPort.java +++ b/src/main/java/appeng/tile/storage/TileIOPort.java @@ -19,26 +19,8 @@ package appeng.tile.storage; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; - -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.items.IItemHandler; - import appeng.api.AEApi; -import appeng.api.config.Actionable; -import appeng.api.config.FullnessMode; -import appeng.api.config.OperationMode; -import appeng.api.config.RedstoneMode; -import appeng.api.config.Settings; -import appeng.api.config.Upgrades; -import appeng.api.config.YesNo; +import appeng.api.config.*; import appeng.api.implementations.IUpgradeableHost; import appeng.api.networking.GridFlags; import appeng.api.networking.IGridNode; @@ -73,464 +55,387 @@ import appeng.util.inv.InvOperation; import appeng.util.inv.WrapperChainedItemHandler; import appeng.util.inv.WrapperFilteredItemHandler; import appeng.util.inv.filter.AEItemFilters; - - -public class TileIOPort extends AENetworkInvTile implements IUpgradeableHost, IConfigManagerHost, IGridTickable -{ - private static final int NUMBER_OF_CELL_SLOTS = 6; - private static final int NUMBER_OF_UPGRADE_SLOTS = 3; - - private final ConfigManager manager; - - private final AppEngInternalInventory inputCells = new AppEngInternalInventory( this, NUMBER_OF_CELL_SLOTS ); - private final AppEngInternalInventory outputCells = new AppEngInternalInventory( this, NUMBER_OF_CELL_SLOTS ); - private final IItemHandler combinedInventory = new WrapperChainedItemHandler( this.inputCells, this.outputCells ); - - private final IItemHandler inputCellsExt = new WrapperFilteredItemHandler( this.inputCells, AEItemFilters.INSERT_ONLY ); - private final IItemHandler outputCellsExt = new WrapperFilteredItemHandler( this.outputCells, AEItemFilters.EXTRACT_ONLY ); - - private final UpgradeInventory upgrades; - private final IActionSource mySrc; - private YesNo lastRedstoneState; - private ItemStack currentCell; - private Map, IMEInventory> cachedInventories; - - public TileIOPort() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.manager = new ConfigManager( this ); - this.manager.registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.manager.registerSetting( Settings.FULLNESS_MODE, FullnessMode.EMPTY ); - this.manager.registerSetting( Settings.OPERATION_MODE, OperationMode.EMPTY ); - this.mySrc = new MachineSource( this ); - this.lastRedstoneState = YesNo.UNDECIDED; - - final Block ioPortBlock = AEApi.instance().definitions().blocks().iOPort().maybeBlock().get(); - this.upgrades = new BlockUpgradeInventory( ioPortBlock, this, NUMBER_OF_UPGRADE_SLOTS ); - } - - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.manager.writeToNBT( data ); - this.upgrades.writeToNBT( data, "upgrades" ); - data.setInteger( "lastRedstoneState", this.lastRedstoneState.ordinal() ); - return data; - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.manager.readFromNBT( data ); - this.upgrades.readFromNBT( data, "upgrades" ); - if( data.hasKey( "lastRedstoneState" ) ) - { - this.lastRedstoneState = YesNo.values()[data.getInteger( "lastRedstoneState" )]; - } - } - - @Override - public AECableType getCableConnectionType( final AEPartLocation dir ) - { - return AECableType.SMART; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - private void updateTask() - { - try - { - if( this.hasWork() ) - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - else - { - this.getProxy().getTick().sleepDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - - public void updateRedstoneState() - { - final YesNo currentState = this.world.isBlockIndirectlyGettingPowered( this.pos ) != 0 ? YesNo.YES : YesNo.NO; - if( this.lastRedstoneState != currentState ) - { - this.lastRedstoneState = currentState; - this.updateTask(); - } - } - - private boolean getRedstoneState() - { - if( this.lastRedstoneState == YesNo.UNDECIDED ) - { - this.updateRedstoneState(); - } - - return this.lastRedstoneState == YesNo.YES; - } - - private boolean isEnabled() - { - if( this.getInstalledUpgrades( Upgrades.REDSTONE ) == 0 ) - { - return true; - } - - final RedstoneMode rs = (RedstoneMode) this.manager.getSetting( Settings.REDSTONE_CONTROLLED ); - if( rs == RedstoneMode.HIGH_SIGNAL ) - { - return this.getRedstoneState(); - } - return !this.getRedstoneState(); - } - - @Override - public IConfigManager getConfigManager() - { - return this.manager; - } - - @Override - public IItemHandler getInventoryByName( final String name ) - { - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - if( name.equals( "cells" ) ) - { - return this.combinedInventory; - } - - return null; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.updateTask(); - } - - private boolean hasWork() - { - if( this.isEnabled() ) - { - return !ItemHandlerUtil.isEmpty( this.inputCells ); - } - - return false; - } - - @Override - public IItemHandler getInternalInventory() - { - return this.combinedInventory; - } - - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( this.inputCells == inv ) - { - this.updateTask(); - } - } - - @Override - protected IItemHandler getItemHandlerForSide( final EnumFacing facing ) - { - if( facing == this.getUp() || facing == this.getUp().getOpposite() ) - { - return this.inputCellsExt; - } - else - { - return this.outputCellsExt; - } - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.IOPort.getMin(), TickRates.IOPort.getMax(), !this.hasWork(), false ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( !this.getProxy().isActive() ) - { - return TickRateModulation.IDLE; - } - - TickRateModulation ret = TickRateModulation.SLEEP; - long itemsToMove = 256; - - switch( this.getInstalledUpgrades( Upgrades.SPEED ) ) - { - case 1: - itemsToMove *= 2; - break; - case 2: - itemsToMove *= 4; - break; - case 3: - itemsToMove *= 8; - break; - } - - try - { - final IEnergySource energy = this.getProxy().getEnergy(); - for( int x = 0; x < NUMBER_OF_CELL_SLOTS; x++ ) - { - final ItemStack is = this.inputCells.getStackInSlot( x ); - if( !is.isEmpty() ) - { - boolean shouldMove = true; - - for( IStorageChannel> c : AEApi.instance().storage().storageChannels() ) - { - if( itemsToMove > 0 ) - { - final IMEMonitor> network = this.getProxy().getStorage().getInventory( c ); - final IMEInventory inv = this.getInv( is, c ); - - if( inv == null ) - { - continue; - } - - if( this.manager.getSetting( Settings.OPERATION_MODE ) == OperationMode.EMPTY ) - { - itemsToMove = this.transferContents( energy, inv, network, itemsToMove, c ); - } - else - { - itemsToMove = this.transferContents( energy, network, inv, itemsToMove, c ); - } - - shouldMove &= this.shouldMove( inv ); - - if( itemsToMove > 0 ) - { - ret = TickRateModulation.IDLE; - } - else - { - ret = TickRateModulation.URGENT; - } - } - } - - if( itemsToMove > 0 && shouldMove && this.moveSlot( x ) ) - { - ret = TickRateModulation.URGENT; - } - else - { - ret = TickRateModulation.URGENT; - } - - } - } - } - catch( final GridAccessException e ) - { - ret = TickRateModulation.IDLE; - } - - return ret; - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.upgrades.getInstalledUpgrades( u ); - } - - private IMEInventory getInv( final ItemStack is, final IStorageChannel chan ) - { - if( this.currentCell != is ) - { - this.currentCell = is; - this.cachedInventories = new IdentityHashMap<>(); - - for( IStorageChannel> c : AEApi.instance().storage().storageChannels() ) - { - this.cachedInventories.put( c, AEApi.instance().registries().cell().getCellInventory( is, null, c ) ); - } - } - - return this.cachedInventories.get( chan ); - } - - private long transferContents( final IEnergySource energy, final IMEInventory src, final IMEInventory destination, long itemsToMove, final IStorageChannel chan ) - { - final IItemList myList; - if( src instanceof IMEMonitor ) - { - myList = ( (IMEMonitor) src ).getStorageList(); - } - else - { - myList = src.getAvailableItems( src.getChannel().createList() ); - } - - itemsToMove *= chan.transferFactor(); - - boolean didStuff; - - do - { - didStuff = false; - - for( final IAEStack s : myList ) - { - final long totalStackSize = s.getStackSize(); - if( totalStackSize > 0 ) - { - final IAEStack stack = destination.injectItems( s, Actionable.SIMULATE, this.mySrc ); - - long possible = 0; - if( stack == null ) - { - possible = totalStackSize; - } - else - { - possible = totalStackSize - stack.getStackSize(); - } - - if( possible > 0 ) - { - IAEStack injectable = s.copy(); - - possible = Math.min( possible, itemsToMove ); - injectable.setStackSize( possible ); - - final IAEStack extracted = src.extractItems( injectable, Actionable.MODULATE, this.mySrc ); - if( extracted != null ) - { - possible = extracted.getStackSize(); - extracted.setCraftable( false ); - final IAEStack failed = Platform.poweredInsert( energy, destination, extracted, this.mySrc ); - - if( failed != null ) - { - possible -= failed.getStackSize(); - src.injectItems( failed, Actionable.MODULATE, this.mySrc ); - } - - if( possible > 0 ) - { - itemsToMove -= possible; - didStuff = true; - } - - break; - } - } - } - } - } - while( itemsToMove > 0 && didStuff ); - - return itemsToMove / chan.transferFactor(); - } - - private boolean shouldMove( final IMEInventory inv ) - { - final FullnessMode fm = (FullnessMode) this.manager.getSetting( Settings.FULLNESS_MODE ); - - if( inv != null ) - { - return this.matches( fm, inv ); - } - - return true; - } - - private boolean moveSlot( final int x ) - { - final InventoryAdaptor ad = new AdaptorItemHandler( this.outputCells ); - if( ad.addItems( this.inputCells.getStackInSlot( x ) ).isEmpty() ) - { - this.inputCells.setStackInSlot( x, ItemStack.EMPTY ); - return true; - } - return false; - } - - private boolean matches( final FullnessMode fm, final IMEInventory src ) - { - if( fm == FullnessMode.HALF ) - { - return true; - } - - final IItemList myList; - - if( src instanceof IMEMonitor ) - { - myList = ( (IMEMonitor) src ).getStorageList(); - } - else - { - myList = src.getAvailableItems( src.getChannel().createList() ); - } - - if( fm == FullnessMode.EMPTY ) - { - return myList.isEmpty(); - } - - final IAEStack test = myList.getFirstItem(); - if( test != null ) - { - IAEStack testCopy = test.copy(); - testCopy.setStackSize( 1 ); - return src.injectItems( testCopy, Actionable.SIMULATE, this.mySrc ) != null; - } - return false; - } - - /** - * Adds the items in the upgrade slots to the drop list. - * - * @param w world - * @param x x pos of tile entity - * @param y y pos of tile entity - * @param z z pos of tile entity - * @param drops drops of tile entity - */ - @Override - public void getDrops( final World w, final BlockPos pos, final List drops ) - { - super.getDrops( w, pos, drops ); - - for( int upgradeIndex = 0; upgradeIndex < this.upgrades.getSlots(); upgradeIndex++ ) - { - final ItemStack stackInSlot = this.upgrades.getStackInSlot( upgradeIndex ); - - if( !stackInSlot.isEmpty() ) - { - drops.add( stackInSlot ); - } - } - } +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.items.IItemHandler; + +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; + + +public class TileIOPort extends AENetworkInvTile implements IUpgradeableHost, IConfigManagerHost, IGridTickable { + private static final int NUMBER_OF_CELL_SLOTS = 6; + private static final int NUMBER_OF_UPGRADE_SLOTS = 3; + + private final ConfigManager manager; + + private final AppEngInternalInventory inputCells = new AppEngInternalInventory(this, NUMBER_OF_CELL_SLOTS); + private final AppEngInternalInventory outputCells = new AppEngInternalInventory(this, NUMBER_OF_CELL_SLOTS); + private final IItemHandler combinedInventory = new WrapperChainedItemHandler(this.inputCells, this.outputCells); + + private final IItemHandler inputCellsExt = new WrapperFilteredItemHandler(this.inputCells, AEItemFilters.INSERT_ONLY); + private final IItemHandler outputCellsExt = new WrapperFilteredItemHandler(this.outputCells, AEItemFilters.EXTRACT_ONLY); + + private final UpgradeInventory upgrades; + private final IActionSource mySrc; + private YesNo lastRedstoneState; + private ItemStack currentCell; + private Map, IMEInventory> cachedInventories; + + public TileIOPort() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.manager = new ConfigManager(this); + this.manager.registerSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.manager.registerSetting(Settings.FULLNESS_MODE, FullnessMode.EMPTY); + this.manager.registerSetting(Settings.OPERATION_MODE, OperationMode.EMPTY); + this.mySrc = new MachineSource(this); + this.lastRedstoneState = YesNo.UNDECIDED; + + final Block ioPortBlock = AEApi.instance().definitions().blocks().iOPort().maybeBlock().get(); + this.upgrades = new BlockUpgradeInventory(ioPortBlock, this, NUMBER_OF_UPGRADE_SLOTS); + } + + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.manager.writeToNBT(data); + this.upgrades.writeToNBT(data, "upgrades"); + data.setInteger("lastRedstoneState", this.lastRedstoneState.ordinal()); + return data; + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.manager.readFromNBT(data); + this.upgrades.readFromNBT(data, "upgrades"); + if (data.hasKey("lastRedstoneState")) { + this.lastRedstoneState = YesNo.values()[data.getInteger("lastRedstoneState")]; + } + } + + @Override + public AECableType getCableConnectionType(final AEPartLocation dir) { + return AECableType.SMART; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + private void updateTask() { + try { + if (this.hasWork()) { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } else { + this.getProxy().getTick().sleepDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + + public void updateRedstoneState() { + final YesNo currentState = this.world.isBlockIndirectlyGettingPowered(this.pos) != 0 ? YesNo.YES : YesNo.NO; + if (this.lastRedstoneState != currentState) { + this.lastRedstoneState = currentState; + this.updateTask(); + } + } + + private boolean getRedstoneState() { + if (this.lastRedstoneState == YesNo.UNDECIDED) { + this.updateRedstoneState(); + } + + return this.lastRedstoneState == YesNo.YES; + } + + private boolean isEnabled() { + if (this.getInstalledUpgrades(Upgrades.REDSTONE) == 0) { + return true; + } + + final RedstoneMode rs = (RedstoneMode) this.manager.getSetting(Settings.REDSTONE_CONTROLLED); + if (rs == RedstoneMode.HIGH_SIGNAL) { + return this.getRedstoneState(); + } + return !this.getRedstoneState(); + } + + @Override + public IConfigManager getConfigManager() { + return this.manager; + } + + @Override + public IItemHandler getInventoryByName(final String name) { + if (name.equals("upgrades")) { + return this.upgrades; + } + + if (name.equals("cells")) { + return this.combinedInventory; + } + + return null; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + this.updateTask(); + } + + private boolean hasWork() { + if (this.isEnabled()) { + return !ItemHandlerUtil.isEmpty(this.inputCells); + } + + return false; + } + + @Override + public IItemHandler getInternalInventory() { + return this.combinedInventory; + } + + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { + if (this.inputCells == inv) { + this.updateTask(); + } + } + + @Override + protected IItemHandler getItemHandlerForSide(final EnumFacing facing) { + if (facing == this.getUp() || facing == this.getUp().getOpposite()) { + return this.inputCellsExt; + } else { + return this.outputCellsExt; + } + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.IOPort.getMin(), TickRates.IOPort.getMax(), !this.hasWork(), false); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (!this.getProxy().isActive()) { + return TickRateModulation.IDLE; + } + + TickRateModulation ret = TickRateModulation.SLEEP; + long itemsToMove = 256; + + switch (this.getInstalledUpgrades(Upgrades.SPEED)) { + case 1: + itemsToMove *= 2; + break; + case 2: + itemsToMove *= 4; + break; + case 3: + itemsToMove *= 8; + break; + } + + try { + final IEnergySource energy = this.getProxy().getEnergy(); + for (int x = 0; x < NUMBER_OF_CELL_SLOTS; x++) { + final ItemStack is = this.inputCells.getStackInSlot(x); + if (!is.isEmpty()) { + boolean shouldMove = true; + + for (IStorageChannel> c : AEApi.instance().storage().storageChannels()) { + if (itemsToMove > 0) { + final IMEMonitor> network = this.getProxy().getStorage().getInventory(c); + final IMEInventory inv = this.getInv(is, c); + + if (inv == null) { + continue; + } + + if (this.manager.getSetting(Settings.OPERATION_MODE) == OperationMode.EMPTY) { + itemsToMove = this.transferContents(energy, inv, network, itemsToMove, c); + } else { + itemsToMove = this.transferContents(energy, network, inv, itemsToMove, c); + } + + shouldMove &= this.shouldMove(inv); + + if (itemsToMove > 0) { + ret = TickRateModulation.IDLE; + } else { + ret = TickRateModulation.URGENT; + } + } + } + + if (itemsToMove > 0 && shouldMove && this.moveSlot(x)) { + ret = TickRateModulation.URGENT; + } else { + ret = TickRateModulation.URGENT; + } + + } + } + } catch (final GridAccessException e) { + ret = TickRateModulation.IDLE; + } + + return ret; + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.upgrades.getInstalledUpgrades(u); + } + + private IMEInventory getInv(final ItemStack is, final IStorageChannel chan) { + if (this.currentCell != is) { + this.currentCell = is; + this.cachedInventories = new IdentityHashMap<>(); + + for (IStorageChannel> c : AEApi.instance().storage().storageChannels()) { + this.cachedInventories.put(c, AEApi.instance().registries().cell().getCellInventory(is, null, c)); + } + } + + return this.cachedInventories.get(chan); + } + + private long transferContents(final IEnergySource energy, final IMEInventory src, final IMEInventory destination, long itemsToMove, final IStorageChannel chan) { + final IItemList myList; + if (src instanceof IMEMonitor) { + myList = ((IMEMonitor) src).getStorageList(); + } else { + myList = src.getAvailableItems(src.getChannel().createList()); + } + + itemsToMove *= chan.transferFactor(); + + boolean didStuff; + + do { + didStuff = false; + + for (final IAEStack s : myList) { + final long totalStackSize = s.getStackSize(); + if (totalStackSize > 0) { + final IAEStack stack = destination.injectItems(s, Actionable.SIMULATE, this.mySrc); + + long possible = 0; + if (stack == null) { + possible = totalStackSize; + } else { + possible = totalStackSize - stack.getStackSize(); + } + + if (possible > 0) { + IAEStack injectable = s.copy(); + + possible = Math.min(possible, itemsToMove); + injectable.setStackSize(possible); + + final IAEStack extracted = src.extractItems(injectable, Actionable.MODULATE, this.mySrc); + if (extracted != null) { + possible = extracted.getStackSize(); + extracted.setCraftable(false); + final IAEStack failed = Platform.poweredInsert(energy, destination, extracted, this.mySrc); + + if (failed != null) { + possible -= failed.getStackSize(); + src.injectItems(failed, Actionable.MODULATE, this.mySrc); + } + + if (possible > 0) { + itemsToMove -= possible; + didStuff = true; + } + + break; + } + } + } + } + } + while (itemsToMove > 0 && didStuff); + + return itemsToMove / chan.transferFactor(); + } + + private boolean shouldMove(final IMEInventory inv) { + final FullnessMode fm = (FullnessMode) this.manager.getSetting(Settings.FULLNESS_MODE); + + if (inv != null) { + return this.matches(fm, inv); + } + + return true; + } + + private boolean moveSlot(final int x) { + final InventoryAdaptor ad = new AdaptorItemHandler(this.outputCells); + if (ad.addItems(this.inputCells.getStackInSlot(x)).isEmpty()) { + this.inputCells.setStackInSlot(x, ItemStack.EMPTY); + return true; + } + return false; + } + + private boolean matches(final FullnessMode fm, final IMEInventory src) { + if (fm == FullnessMode.HALF) { + return true; + } + + final IItemList myList; + + if (src instanceof IMEMonitor) { + myList = ((IMEMonitor) src).getStorageList(); + } else { + myList = src.getAvailableItems(src.getChannel().createList()); + } + + if (fm == FullnessMode.EMPTY) { + return myList.isEmpty(); + } + + final IAEStack test = myList.getFirstItem(); + if (test != null) { + IAEStack testCopy = test.copy(); + testCopy.setStackSize(1); + return src.injectItems(testCopy, Actionable.SIMULATE, this.mySrc) != null; + } + return false; + } + + /** + * Adds the items in the upgrade slots to the drop list. + * + * @param w world + * @param x x pos of tile entity + * @param y y pos of tile entity + * @param z z pos of tile entity + * @param drops drops of tile entity + */ + @Override + public void getDrops(final World w, final BlockPos pos, final List drops) { + super.getDrops(w, pos, drops); + + for (int upgradeIndex = 0; upgradeIndex < this.upgrades.getSlots(); upgradeIndex++) { + final ItemStack stackInSlot = this.upgrades.getStackInSlot(upgradeIndex); + + if (!stackInSlot.isEmpty()) { + drops.add(stackInSlot); + } + } + } } diff --git a/src/main/java/appeng/tile/storage/TileSkyChest.java b/src/main/java/appeng/tile/storage/TileSkyChest.java index 2ea8923f5..b6617437e 100644 --- a/src/main/java/appeng/tile/storage/TileSkyChest.java +++ b/src/main/java/appeng/tile/storage/TileSkyChest.java @@ -19,10 +19,10 @@ package appeng.tile.storage; -import java.io.IOException; - +import appeng.tile.AEBaseInvTile; +import appeng.tile.inventory.AppEngInternalInventory; +import appeng.util.inv.InvOperation; import io.netty.buffer.ByteBuf; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemStack; @@ -30,185 +30,153 @@ import net.minecraft.util.ITickable; import net.minecraft.util.SoundCategory; import net.minecraftforge.items.IItemHandler; -import appeng.tile.AEBaseInvTile; -import appeng.tile.inventory.AppEngInternalInventory; -import appeng.util.inv.InvOperation; +import java.io.IOException; -public class TileSkyChest extends AEBaseInvTile implements ITickable -{ +public class TileSkyChest extends AEBaseInvTile implements ITickable { - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 9 * 4 ); - // server - private int numPlayersUsing; - // client.. - private long lastEvent; - private float lidAngle; - private float prevLidAngle; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 9 * 4); + // server + private int numPlayersUsing; + // client.. + private long lastEvent; + private float lidAngle; + private float prevLidAngle; - @Override - protected void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - data.writeBoolean( this.getPlayerOpen() > 0 ); - } + @Override + protected void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeBoolean(this.getPlayerOpen() > 0); + } - @Override - protected boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean c = super.readFromStream( data ); - final int wasOpen = this.getPlayerOpen(); - this.setPlayerOpen( data.readBoolean() ? 1 : 0 ); + @Override + protected boolean readFromStream(final ByteBuf data) throws IOException { + final boolean c = super.readFromStream(data); + final int wasOpen = this.getPlayerOpen(); + this.setPlayerOpen(data.readBoolean() ? 1 : 0); - if( wasOpen != this.getPlayerOpen() ) - { - this.setLastEvent( System.currentTimeMillis() ); - } + if (wasOpen != this.getPlayerOpen()) { + this.setLastEvent(System.currentTimeMillis()); + } - return c; // TESR yo! - } + return c; // TESR yo! + } - @Override - public boolean requiresTESR() - { - return true; - } + @Override + public boolean requiresTESR() { + return true; + } - @Override - public boolean canRenderBreaking() - { - return true; - } + @Override + public boolean canRenderBreaking() { + return true; + } - @Override - public IItemHandler getInternalInventory() - { - return this.inv; - } + @Override + public IItemHandler getInternalInventory() { + return this.inv; + } - public void openInventory( final EntityPlayer player ) - { - if( !player.isSpectator() ) - { - this.setPlayerOpen( this.getPlayerOpen() + 1 ); - this.world.addBlockEvent( this.pos, this.getBlockType(), 1, this.numPlayersUsing ); - this.world.notifyNeighborsOfStateChange( this.pos, this.getBlockType(), true ); - this.world.notifyNeighborsOfStateChange( this.pos.down(), this.getBlockType(), true ); + public void openInventory(final EntityPlayer player) { + if (!player.isSpectator()) { + this.setPlayerOpen(this.getPlayerOpen() + 1); + this.world.addBlockEvent(this.pos, this.getBlockType(), 1, this.numPlayersUsing); + this.world.notifyNeighborsOfStateChange(this.pos, this.getBlockType(), true); + this.world.notifyNeighborsOfStateChange(this.pos.down(), this.getBlockType(), true); - if( this.getPlayerOpen() == 1 ) - { - this.getWorld() - .playSound( player, this.pos.getX() + 0.5D, this.pos.getY() + 0.5D, this.pos.getZ() + 0.5D, SoundEvents.BLOCK_CHEST_OPEN, - SoundCategory.BLOCKS, 0.5F, this.getWorld().rand.nextFloat() * 0.1F + 0.9F ); - this.markForUpdate(); - } - } - } + if (this.getPlayerOpen() == 1) { + this.getWorld() + .playSound(player, this.pos.getX() + 0.5D, this.pos.getY() + 0.5D, this.pos.getZ() + 0.5D, SoundEvents.BLOCK_CHEST_OPEN, + SoundCategory.BLOCKS, 0.5F, this.getWorld().rand.nextFloat() * 0.1F + 0.9F); + this.markForUpdate(); + } + } + } - public void closeInventory( final EntityPlayer player ) - { - if( !player.isSpectator() ) - { - this.setPlayerOpen( this.getPlayerOpen() - 1 ); - this.world.addBlockEvent( this.pos, this.getBlockType(), 1, this.numPlayersUsing ); - this.world.notifyNeighborsOfStateChange( this.pos, this.getBlockType(), true ); - this.world.notifyNeighborsOfStateChange( this.pos.down(), this.getBlockType(), true ); + public void closeInventory(final EntityPlayer player) { + if (!player.isSpectator()) { + this.setPlayerOpen(this.getPlayerOpen() - 1); + this.world.addBlockEvent(this.pos, this.getBlockType(), 1, this.numPlayersUsing); + this.world.notifyNeighborsOfStateChange(this.pos, this.getBlockType(), true); + this.world.notifyNeighborsOfStateChange(this.pos.down(), this.getBlockType(), true); - if( this.getPlayerOpen() < 0 ) - { - this.setPlayerOpen( 0 ); - } + if (this.getPlayerOpen() < 0) { + this.setPlayerOpen(0); + } - if( this.getPlayerOpen() == 0 ) - { - this.getWorld() - .playSound( player, this.pos.getX() + 0.5D, this.pos.getY() + 0.5D, this.pos.getZ() + 0.5D, SoundEvents.BLOCK_CHEST_CLOSE, - SoundCategory.BLOCKS, 0.5F, this.getWorld().rand.nextFloat() * 0.1F + 0.9F ); - this.markForUpdate(); - } - } - } + if (this.getPlayerOpen() == 0) { + this.getWorld() + .playSound(player, this.pos.getX() + 0.5D, this.pos.getY() + 0.5D, this.pos.getZ() + 0.5D, SoundEvents.BLOCK_CHEST_CLOSE, + SoundCategory.BLOCKS, 0.5F, this.getWorld().rand.nextFloat() * 0.1F + 0.9F); + this.markForUpdate(); + } + } + } - @Override - public void update() - { - int i = this.pos.getX(); - int j = this.pos.getY(); - int k = this.pos.getZ(); + @Override + public void update() { + int i = this.pos.getX(); + int j = this.pos.getY(); + int k = this.pos.getZ(); - this.prevLidAngle = this.lidAngle; - float f1 = 0.1F; + this.prevLidAngle = this.lidAngle; + float f1 = 0.1F; - if( this.numPlayersUsing == 0 && this.lidAngle > 0.0F || this.numPlayersUsing > 0 && this.lidAngle < 1.0F ) - { - float f2 = this.lidAngle; + if (this.numPlayersUsing == 0 && this.lidAngle > 0.0F || this.numPlayersUsing > 0 && this.lidAngle < 1.0F) { + float f2 = this.lidAngle; - if( this.numPlayersUsing > 0 ) - { - this.lidAngle += 0.1F; - } - else - { - this.lidAngle -= 0.1F; - } + if (this.numPlayersUsing > 0) { + this.lidAngle += 0.1F; + } else { + this.lidAngle -= 0.1F; + } - if( this.lidAngle > 1.0F ) - { - this.lidAngle = 1.0F; - } + if (this.lidAngle > 1.0F) { + this.lidAngle = 1.0F; + } - float f3 = 0.5F; + float f3 = 0.5F; - if( this.lidAngle < 0.0F ) - { - this.lidAngle = 0.0F; - } - } - } + if (this.lidAngle < 0.0F) { + this.lidAngle = 0.0F; + } + } + } - @Override - public void onChangeInventory( final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { + @Override + public void onChangeInventory(final IItemHandler inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added) { - } + } - public float getLidAngle() - { - return this.lidAngle; - } + public float getLidAngle() { + return this.lidAngle; + } - public void setLidAngle( final float lidAngle ) - { - this.lidAngle = lidAngle; - } + public void setLidAngle(final float lidAngle) { + this.lidAngle = lidAngle; + } - public float getPrevLidAngle() - { - return this.prevLidAngle; - } + public float getPrevLidAngle() { + return this.prevLidAngle; + } - public void setPrevLidAngle( float prevLidAngle ) - { - this.prevLidAngle = prevLidAngle; - } + public void setPrevLidAngle(float prevLidAngle) { + this.prevLidAngle = prevLidAngle; + } - public int getPlayerOpen() - { - return this.numPlayersUsing; - } + public int getPlayerOpen() { + return this.numPlayersUsing; + } - private void setPlayerOpen( final int playerOpen ) - { - this.numPlayersUsing = playerOpen; - } + private void setPlayerOpen(final int playerOpen) { + this.numPlayersUsing = playerOpen; + } - public long getLastEvent() - { - return this.lastEvent; - } + public long getLastEvent() { + return this.lastEvent; + } - private void setLastEvent( final long lastEvent ) - { - this.lastEvent = lastEvent; - } + private void setLastEvent(final long lastEvent) { + this.lastEvent = lastEvent; + } } diff --git a/src/main/java/appeng/util/BlockPosUtils.java b/src/main/java/appeng/util/BlockPosUtils.java index 37479ab3e..dbd822ce8 100644 --- a/src/main/java/appeng/util/BlockPosUtils.java +++ b/src/main/java/appeng/util/BlockPosUtils.java @@ -3,39 +3,28 @@ package appeng.util; import net.minecraft.util.math.BlockPos; -public class BlockPosUtils -{ - public static long getDistance( BlockPos blockPos, BlockPos blockPos2 ) - { +public class BlockPosUtils { + public static long getDistance(BlockPos blockPos, BlockPos blockPos2) { int x; - if( (blockPos.getX() > 0 && blockPos2.getX() > 0) || (blockPos.getX() < 0 && blockPos2.getX() < 0)) - { + if ((blockPos.getX() > 0 && blockPos2.getX() > 0) || (blockPos.getX() < 0 && blockPos2.getX() < 0)) { x = blockPos.getX() - blockPos2.getX(); - } - else - { + } else { x = blockPos.getX() + blockPos2.getX(); } int y; - if( (blockPos.getY() > 0 && blockPos2.getY() > 0) || (blockPos.getY() < 0 && blockPos2.getY() < 0) ) - { + if ((blockPos.getY() > 0 && blockPos2.getY() > 0) || (blockPos.getY() < 0 && blockPos2.getY() < 0)) { y = blockPos.getY() - blockPos2.getY(); - } - else - { + } else { y = blockPos.getY() + blockPos2.getY(); } int z; - if( (blockPos.getZ() > 0 && blockPos2.getZ() > 0) || (blockPos.getZ() < 0 && blockPos2.getZ() < 0) ) - { + if ((blockPos.getZ() > 0 && blockPos2.getZ() > 0) || (blockPos.getZ() < 0 && blockPos2.getZ() < 0)) { z = blockPos.getZ() - blockPos2.getZ(); - } - else - { + } else { z = blockPos.getZ() + blockPos2.getZ(); } - return Math.abs( x ) + Math.abs( y ) + Math.abs( z ); + return Math.abs(x) + Math.abs(y) + Math.abs(z); } } diff --git a/src/main/java/appeng/util/BlockUpdate.java b/src/main/java/appeng/util/BlockUpdate.java index 3efafc862..87ddce8ff 100644 --- a/src/main/java/appeng/util/BlockUpdate.java +++ b/src/main/java/appeng/util/BlockUpdate.java @@ -23,23 +23,19 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -public class BlockUpdate implements IWorldCallable -{ - private final BlockPos pos; +public class BlockUpdate implements IWorldCallable { + private final BlockPos pos; - BlockUpdate( final BlockPos pos ) - { - this.pos = pos; - } + BlockUpdate(final BlockPos pos) { + this.pos = pos; + } - @Override - public Boolean call( final World world ) throws Exception - { - if( world.isBlockLoaded( this.pos ) ) - { - world.notifyNeighborsOfStateChange( this.pos, Platform.AIR_BLOCK, true ); - } + @Override + public Boolean call(final World world) throws Exception { + if (world.isBlockLoaded(this.pos)) { + world.notifyNeighborsOfStateChange(this.pos, Platform.AIR_BLOCK, true); + } - return true; - } + return true; + } } diff --git a/src/main/java/appeng/util/ClassInstantiation.java b/src/main/java/appeng/util/ClassInstantiation.java index 0c5499a3a..51bb8bfc0 100644 --- a/src/main/java/appeng/util/ClassInstantiation.java +++ b/src/main/java/appeng/util/ClassInstantiation.java @@ -19,103 +19,78 @@ package appeng.util; +import appeng.core.AELog; + import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Optional; -import appeng.core.AELog; +public class ClassInstantiation { + private final Class template; + private final Object[] args; -public class ClassInstantiation -{ - private final Class template; - private final Object[] args; + public ClassInstantiation(final Class template, final Object... args) { + this.template = template; + this.args = args; + } - public ClassInstantiation( final Class template, final Object... args ) - { - this.template = template; - this.args = args; - } + public Optional get() { + @SuppressWarnings("unchecked") final Constructor[] constructors = (Constructor[]) this.template.getConstructors(); - public Optional get() - { - @SuppressWarnings( "unchecked" ) - final Constructor[] constructors = (Constructor[]) this.template.getConstructors(); + for (final Constructor constructor : constructors) { + final Class[] paramTypes = constructor.getParameterTypes(); + if (paramTypes.length == this.args.length) { + boolean valid = true; - for( final Constructor constructor : constructors ) - { - final Class[] paramTypes = constructor.getParameterTypes(); - if( paramTypes.length == this.args.length ) - { - boolean valid = true; + for (int idx = 0; idx < paramTypes.length; idx++) { + final Class cz = this.args[idx].getClass(); + if (!this.isClassMatch(paramTypes[idx], cz, this.args[idx])) { + valid = false; + } + } - for( int idx = 0; idx < paramTypes.length; idx++ ) - { - final Class cz = this.args[idx].getClass(); - if( !this.isClassMatch( paramTypes[idx], cz, this.args[idx] ) ) - { - valid = false; - } - } + if (valid) { + try { + return Optional.of(constructor.newInstance(this.args)); + } catch (final InstantiationException e) { + e.printStackTrace(); + } catch (final IllegalAccessException e) { + e.printStackTrace(); + } catch (final InvocationTargetException e) { + e.printStackTrace(); + } + break; + } + } + } - if( valid ) - { - try - { - return Optional.of( constructor.newInstance( this.args ) ); - } - catch( final InstantiationException e ) - { - e.printStackTrace(); - } - catch( final IllegalAccessException e ) - { - e.printStackTrace(); - } - catch( final InvocationTargetException e ) - { - e.printStackTrace(); - } - break; - } - } - } + return Optional.empty(); + } - return Optional.empty(); - } + private boolean isClassMatch(Class expected, Class got, final Object value) { + if (value == null && !expected.isPrimitive()) { + return true; + } - private boolean isClassMatch( Class expected, Class got, final Object value ) - { - if( value == null && !expected.isPrimitive() ) - { - return true; - } + expected = this.condense(expected, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class); + got = this.condense(got, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class); - expected = this.condense( expected, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class ); - got = this.condense( got, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class ); + return expected == got || expected.isAssignableFrom(got); + } - return expected == got || expected.isAssignableFrom( got ); - } - - private Class condense( final Class expected, final Class... wrappers ) - { - if( expected.isPrimitive() ) - { - for( final Class clz : wrappers ) - { - try - { - if( expected == clz.getField( "TYPE" ).get( null ) ) - { - return clz; - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } - } - return expected; - } + private Class condense(final Class expected, final Class... wrappers) { + if (expected.isPrimitive()) { + for (final Class clz : wrappers) { + try { + if (expected == clz.getField("TYPE").get(null)) { + return clz; + } + } catch (final Throwable t) { + AELog.debug(t); + } + } + } + return expected; + } } diff --git a/src/main/java/appeng/util/ConfigManager.java b/src/main/java/appeng/util/ConfigManager.java index bf25c269d..289f1f6c7 100644 --- a/src/main/java/appeng/util/ConfigManager.java +++ b/src/main/java/appeng/util/ConfigManager.java @@ -19,120 +19,101 @@ package appeng.util; -import java.util.EnumMap; -import java.util.Map; -import java.util.Set; - -import net.minecraft.nbt.NBTTagCompound; - import appeng.api.config.LevelEmitterMode; import appeng.api.config.Settings; import appeng.api.config.StorageFilter; import appeng.api.util.IConfigManager; import appeng.core.AELog; +import net.minecraft.nbt.NBTTagCompound; + +import java.util.EnumMap; +import java.util.Map; +import java.util.Set; -public final class ConfigManager implements IConfigManager -{ - private final Map> settings = new EnumMap<>( Settings.class ); - private final IConfigManagerHost target; - private Map> oldSettings = new EnumMap<>( Settings.class ); +public final class ConfigManager implements IConfigManager { + private final Map> settings = new EnumMap<>(Settings.class); + private final IConfigManagerHost target; + private final Map> oldSettings = new EnumMap<>(Settings.class); - public ConfigManager( final IConfigManagerHost tile ) - { - this.target = tile; - } + public ConfigManager(final IConfigManagerHost tile) { + this.target = tile; + } - @Override - public Set getSettings() - { - return this.settings.keySet(); - } + @Override + public Set getSettings() { + return this.settings.keySet(); + } - @Override - public void registerSetting( final Settings settingName, final Enum defaultValue ) - { - this.settings.put( settingName, defaultValue ); - } + @Override + public void registerSetting(final Settings settingName, final Enum defaultValue) { + this.settings.put(settingName, defaultValue); + } - @Override - public Enum getSetting( final Settings settingName ) - { - final Enum oldValue = this.settings.get( settingName ); + @Override + public Enum getSetting(final Settings settingName) { + final Enum oldValue = this.settings.get(settingName); - if( oldValue != null ) - { - return oldValue; - } + if (oldValue != null) { + return oldValue; + } - throw new IllegalStateException( "Invalid Config setting. Expected a non-null value for " + settingName ); - } + throw new IllegalStateException("Invalid Config setting. Expected a non-null value for " + settingName); + } - @Override - public Enum putSetting( final Settings settingName, final Enum newValue ) - { - final Enum oldValue = this.getSetting( settingName ); - this.settings.put( settingName, newValue ); - this.oldSettings.put( settingName, oldValue ); - this.target.updateSetting( this, settingName, newValue ); - return oldValue; - } + @Override + public Enum putSetting(final Settings settingName, final Enum newValue) { + final Enum oldValue = this.getSetting(settingName); + this.settings.put(settingName, newValue); + this.oldSettings.put(settingName, oldValue); + this.target.updateSetting(this, settingName, newValue); + return oldValue; + } - public Enum getOldSetting(final Settings settingName){ - return this.oldSettings.get( settingName ); - } + public Enum getOldSetting(final Settings settingName) { + return this.oldSettings.get(settingName); + } - /** - * save all settings using config manager. - * - * @param tagCompound to be written to compound - */ - @Override - public void writeToNBT( final NBTTagCompound tagCompound ) - { - for( final Map.Entry> entry : this.settings.entrySet() ) - { - tagCompound.setString( entry.getKey().name(), this.settings.get( entry.getKey() ).toString() ); - } - } + /** + * save all settings using config manager. + * + * @param tagCompound to be written to compound + */ + @Override + public void writeToNBT(final NBTTagCompound tagCompound) { + for (final Map.Entry> entry : this.settings.entrySet()) { + tagCompound.setString(entry.getKey().name(), this.settings.get(entry.getKey()).toString()); + } + } - /** - * read all settings using config manager. - * - * @param tagCompound to be read from compound - */ - @Override - public void readFromNBT( final NBTTagCompound tagCompound ) - { - for( final Map.Entry> entry : this.settings.entrySet() ) - { - try - { - if( tagCompound.hasKey( entry.getKey().name() ) ) - { - String value = tagCompound.getString( entry.getKey().name() ); + /** + * read all settings using config manager. + * + * @param tagCompound to be read from compound + */ + @Override + public void readFromNBT(final NBTTagCompound tagCompound) { + for (final Map.Entry> entry : this.settings.entrySet()) { + try { + if (tagCompound.hasKey(entry.getKey().name())) { + String value = tagCompound.getString(entry.getKey().name()); - // Provides an upgrade path for the rename of this value in the API between rv1 and rv2 - if( value.equals( "EXTACTABLE_ONLY" ) ) - { - value = StorageFilter.EXTRACTABLE_ONLY.toString(); - } - else if( value.equals( "STOREABLE_AMOUNT" ) ) - { - value = LevelEmitterMode.STORABLE_AMOUNT.toString(); - } + // Provides an upgrade path for the rename of this value in the API between rv1 and rv2 + if (value.equals("EXTACTABLE_ONLY")) { + value = StorageFilter.EXTRACTABLE_ONLY.toString(); + } else if (value.equals("STOREABLE_AMOUNT")) { + value = LevelEmitterMode.STORABLE_AMOUNT.toString(); + } - final Enum oldValue = this.settings.get( entry.getKey() ); + final Enum oldValue = this.settings.get(entry.getKey()); - final Enum newValue = Enum.valueOf( oldValue.getClass(), value ); + final Enum newValue = Enum.valueOf(oldValue.getClass(), value); - this.putSetting( entry.getKey(), newValue ); - } - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - } - } + this.putSetting(entry.getKey(), newValue); + } + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } + } + } } diff --git a/src/main/java/appeng/util/IConfigManagerHost.java b/src/main/java/appeng/util/IConfigManagerHost.java index 1323a7df5..8cfedcf27 100644 --- a/src/main/java/appeng/util/IConfigManagerHost.java +++ b/src/main/java/appeng/util/IConfigManagerHost.java @@ -22,8 +22,7 @@ package appeng.util; import appeng.api.util.IConfigManager; -public interface IConfigManagerHost -{ +public interface IConfigManagerHost { - void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ); + void updateSetting(IConfigManager manager, Enum settingName, Enum newValue); } diff --git a/src/main/java/appeng/util/ISlimReadableNumberConverter.java b/src/main/java/appeng/util/ISlimReadableNumberConverter.java index ea427f4e1..583cb2f82 100644 --- a/src/main/java/appeng/util/ISlimReadableNumberConverter.java +++ b/src/main/java/appeng/util/ISlimReadableNumberConverter.java @@ -30,20 +30,18 @@ import javax.annotation.Nonnegative; * @version rv2 * @since rv2 */ -public interface ISlimReadableNumberConverter -{ - /** - * Converts a number into a human readable form. It will not round the number, but down it. - * Will try to cut the number down 1 decimal later, but rarely because of the 3 width limitation. - * Can only handle non negative numbers - * - * Example: - * 10000L -> 10K - * 9999L -> 9K, not 9.9K cause 4 width - * - * @param number to be converted number - * - * @return String in SI format cut down as far as possible - */ - String toSlimReadableForm( @Nonnegative long number ); +public interface ISlimReadableNumberConverter { + /** + * Converts a number into a human readable form. It will not round the number, but down it. + * Will try to cut the number down 1 decimal later, but rarely because of the 3 width limitation. + * Can only handle non negative numbers + *

+ * Example: + * 10000L -> 10K + * 9999L -> 9K, not 9.9K cause 4 width + * + * @param number to be converted number + * @return String in SI format cut down as far as possible + */ + String toSlimReadableForm(@Nonnegative long number); } diff --git a/src/main/java/appeng/util/IWideReadableNumberConverter.java b/src/main/java/appeng/util/IWideReadableNumberConverter.java index 209e03ea4..c8679c166 100644 --- a/src/main/java/appeng/util/IWideReadableNumberConverter.java +++ b/src/main/java/appeng/util/IWideReadableNumberConverter.java @@ -29,20 +29,18 @@ import javax.annotation.Nonnegative; * @version rv2 * @since rv2 */ -public interface IWideReadableNumberConverter -{ - /** - * Converts a number into a human readable form. It will not round the number, but down it. - * Will try to cut the number down 1 decimal later if width can be below 4. - * Can only handle non negative numbers - * - * Example: - * 10000L -> 10K - * 9999L -> 9999 - * - * @param number to be converted number - * - * @return String in SI format cut down as far as possible - */ - String toWideReadableForm( @Nonnegative long number ); +public interface IWideReadableNumberConverter { + /** + * Converts a number into a human readable form. It will not round the number, but down it. + * Will try to cut the number down 1 decimal later if width can be below 4. + * Can only handle non negative numbers + *

+ * Example: + * 10000L -> 10K + * 9999L -> 9999 + * + * @param number to be converted number + * @return String in SI format cut down as far as possible + */ + String toWideReadableForm(@Nonnegative long number); } diff --git a/src/main/java/appeng/util/IWorldCallable.java b/src/main/java/appeng/util/IWorldCallable.java index 2e8057913..5d665fc96 100644 --- a/src/main/java/appeng/util/IWorldCallable.java +++ b/src/main/java/appeng/util/IWorldCallable.java @@ -19,11 +19,10 @@ package appeng.util; -import java.util.concurrent.Callable; +import net.minecraft.world.World; import javax.annotation.Nullable; - -import net.minecraft.world.World; +import java.util.concurrent.Callable; /** @@ -34,19 +33,16 @@ import net.minecraft.world.World; * @see Callable * @since rv3 */ -public interface IWorldCallable -{ - /** - * Similar to {@link Callable#call()} - * - * @param world this param is given to not hold a reference to the world but let the caller handle it. Do not expect - * a world here thus can be null. - * - * @return result of call on the world. Can be null. - * - * @throws Exception if the call fails - * @see Callable#call() - */ - @Nullable - T call( @Nullable World world ) throws Exception; +public interface IWorldCallable { + /** + * Similar to {@link Callable#call()} + * + * @param world this param is given to not hold a reference to the world but let the caller handle it. Do not expect + * a world here thus can be null. + * @return result of call on the world. Can be null. + * @throws Exception if the call fails + * @see Callable#call() + */ + @Nullable + T call(@Nullable World world) throws Exception; } diff --git a/src/main/java/appeng/util/InWorldToolOperationResult.java b/src/main/java/appeng/util/InWorldToolOperationResult.java index 6df11be61..ecb1048f0 100644 --- a/src/main/java/appeng/util/InWorldToolOperationResult.java +++ b/src/main/java/appeng/util/InWorldToolOperationResult.java @@ -19,70 +19,60 @@ package appeng.util; -import java.util.ArrayList; -import java.util.List; - import net.minecraft.block.Block; import net.minecraft.block.BlockAir; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; +import java.util.ArrayList; +import java.util.List; -public class InWorldToolOperationResult -{ - private final IBlockState blockState; - private final List drops; +public class InWorldToolOperationResult { - public InWorldToolOperationResult() - { - this.blockState = null; - this.drops = null; - } + private final IBlockState blockState; + private final List drops; - public InWorldToolOperationResult( final IBlockState block, final List drops ) - { - this.blockState = block; - this.drops = drops; - } + public InWorldToolOperationResult() { + this.blockState = null; + this.drops = null; + } - public InWorldToolOperationResult( final IBlockState block ) - { - this.blockState = block; - this.drops = null; - } + public InWorldToolOperationResult(final IBlockState block, final List drops) { + this.blockState = block; + this.drops = drops; + } - public static InWorldToolOperationResult getBlockOperationResult( final ItemStack[] items ) - { - final List temp = new ArrayList<>(); - IBlockState b = null; + public InWorldToolOperationResult(final IBlockState block) { + this.blockState = block; + this.drops = null; + } - for( final ItemStack l : items ) - { - if( b == null ) - { - final Block bl = Block.getBlockFromItem( l.getItem() ); + public static InWorldToolOperationResult getBlockOperationResult(final ItemStack[] items) { + final List temp = new ArrayList<>(); + IBlockState b = null; - if( bl != null && !( bl instanceof BlockAir ) ) - { - b = bl.getDefaultState(); - continue; - } - } + for (final ItemStack l : items) { + if (b == null) { + final Block bl = Block.getBlockFromItem(l.getItem()); - temp.add( l ); - } + if (bl != null && !(bl instanceof BlockAir)) { + b = bl.getDefaultState(); + continue; + } + } - return new InWorldToolOperationResult( b, temp ); - } + temp.add(l); + } - public IBlockState getBlockState() - { - return this.blockState; - } + return new InWorldToolOperationResult(b, temp); + } - public List getDrops() - { - return this.drops; - } + public IBlockState getBlockState() { + return this.blockState; + } + + public List getDrops() { + return this.drops; + } } diff --git a/src/main/java/appeng/util/InventoryAdaptor.java b/src/main/java/appeng/util/InventoryAdaptor.java index 21295f575..da953d571 100644 --- a/src/main/java/appeng/util/InventoryAdaptor.java +++ b/src/main/java/appeng/util/InventoryAdaptor.java @@ -19,6 +19,7 @@ package appeng.util; +import appeng.api.config.FuzzyMode; import appeng.util.inv.*; import com.jaquadro.minecraft.storagedrawers.api.capabilities.IItemRepository; import net.minecraft.entity.player.EntityPlayer; @@ -30,70 +31,59 @@ import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; -import appeng.api.config.FuzzyMode; - /** * Universal Facade for other inventories. Used to conveniently interact with various types of inventories. This is not * used for * actually monitoring an inventory. It is just for insertion and extraction, and is primarily used by import/export * buses. */ -public abstract class InventoryAdaptor implements Iterable -{ - @CapabilityInject( IItemRepository.class) - public static Capability ITEM_REPOSITORY_CAPABILITY = null; +public abstract class InventoryAdaptor implements Iterable { + @CapabilityInject(IItemRepository.class) + public static Capability ITEM_REPOSITORY_CAPABILITY = null; - public static InventoryAdaptor getAdaptor( final TileEntity te, final EnumFacing d ) - { - if( te != null ) - { - if( ITEM_REPOSITORY_CAPABILITY != null && te.hasCapability( ITEM_REPOSITORY_CAPABILITY, d ) ) - { - IItemRepository itemRepository = te.getCapability( ITEM_REPOSITORY_CAPABILITY, d ); - if (itemRepository != null){ - return new AdaptorItemRepository( itemRepository ); - } - } - else if( te.hasCapability( CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, d ) ) - { + public static InventoryAdaptor getAdaptor(final TileEntity te, final EnumFacing d) { + if (te != null) { + if (ITEM_REPOSITORY_CAPABILITY != null && te.hasCapability(ITEM_REPOSITORY_CAPABILITY, d)) { + IItemRepository itemRepository = te.getCapability(ITEM_REPOSITORY_CAPABILITY, d); + if (itemRepository != null) { + return new AdaptorItemRepository(itemRepository); + } + } else if (te.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, d)) { - // Attempt getting an IItemHandler for the given side via caps - IItemHandler itemHandler = te.getCapability( CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, d ); - if( itemHandler != null ) - { - return new AdaptorItemHandler( itemHandler ); - } - } - } - return null; - } + // Attempt getting an IItemHandler for the given side via caps + IItemHandler itemHandler = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, d); + if (itemHandler != null) { + return new AdaptorItemHandler(itemHandler); + } + } + } + return null; + } - public static InventoryAdaptor getAdaptor( final EntityPlayer te ) - { - if( te != null ) - { - return new AdaptorItemHandlerPlayerInv( te ); - } - return null; - } + public static InventoryAdaptor getAdaptor(final EntityPlayer te) { + if (te != null) { + return new AdaptorItemHandlerPlayerInv(te); + } + return null; + } - // return what was extracted. - public abstract ItemStack removeItems( int amount, ItemStack filter, IInventoryDestination destination ); + // return what was extracted. + public abstract ItemStack removeItems(int amount, ItemStack filter, IInventoryDestination destination); - public abstract ItemStack simulateRemove( int amount, ItemStack filter, IInventoryDestination destination ); + public abstract ItemStack simulateRemove(int amount, ItemStack filter, IInventoryDestination destination); - // return what was extracted. - public abstract ItemStack removeSimilarItems( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ); + // return what was extracted. + public abstract ItemStack removeSimilarItems(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination); - public abstract ItemStack simulateSimilarRemove( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ); + public abstract ItemStack simulateSimilarRemove(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination); - // return what isn't used... - public abstract ItemStack addItems( ItemStack toBeAdded ); + // return what isn't used... + public abstract ItemStack addItems(ItemStack toBeAdded); - public abstract ItemStack simulateAdd( ItemStack toBeSimulated ); + public abstract ItemStack simulateAdd(ItemStack toBeSimulated); - public abstract boolean containsItems(); + public abstract boolean containsItems(); - public abstract boolean hasSlots(); + public abstract boolean hasSlots(); } diff --git a/src/main/java/appeng/util/ItemSorters.java b/src/main/java/appeng/util/ItemSorters.java index 3ff5349d3..dc11d0d36 100644 --- a/src/main/java/appeng/util/ItemSorters.java +++ b/src/main/java/appeng/util/ItemSorters.java @@ -19,105 +19,90 @@ package appeng.util; -import java.util.Comparator; - import appeng.api.config.SortDir; import appeng.api.storage.data.IAEItemStack; import appeng.integration.Integrations; import appeng.integration.abstraction.IInvTweaks; import appeng.util.item.AEItemStack; +import java.util.Comparator; -public class ItemSorters -{ - private static SortDir Direction = SortDir.ASCENDING; +public class ItemSorters { - public static final Comparator CONFIG_BASED_SORT_BY_NAME = ( o1, o2 ) -> - { - final int cmp = Platform.getItemDisplayName( o1 ).compareToIgnoreCase( Platform.getItemDisplayName( o2 ) ); - return applyDirection( cmp ); - }; + private static SortDir Direction = SortDir.ASCENDING; - public static final Comparator CONFIG_BASED_SORT_BY_MOD = ( o1, o2 ) -> - { - final AEItemStack op1 = (AEItemStack) o1; - final AEItemStack op2 = (AEItemStack) o2; - int cmp = op1.getModID().compareToIgnoreCase( op2.getModID() ); + public static final Comparator CONFIG_BASED_SORT_BY_NAME = (o1, o2) -> + { + final int cmp = Platform.getItemDisplayName(o1).compareToIgnoreCase(Platform.getItemDisplayName(o2)); + return applyDirection(cmp); + }; - if( cmp == 0 ) - { - cmp = Platform.getItemDisplayName( o1 ).compareToIgnoreCase( Platform.getItemDisplayName( o2 ) ); - } + public static final Comparator CONFIG_BASED_SORT_BY_MOD = (o1, o2) -> + { + final AEItemStack op1 = (AEItemStack) o1; + final AEItemStack op2 = (AEItemStack) o2; + int cmp = op1.getModID().compareToIgnoreCase(op2.getModID()); - return applyDirection( cmp ); - }; + if (cmp == 0) { + cmp = Platform.getItemDisplayName(o1).compareToIgnoreCase(Platform.getItemDisplayName(o2)); + } - public static final Comparator CONFIG_BASED_SORT_BY_SIZE = ( o1, o2 ) -> - { - final int cmp = Long.compare( o2.getStackSize(), o1.getStackSize() ); - return applyDirection( cmp ); - }; + return applyDirection(cmp); + }; - private static IInvTweaks api; + public static final Comparator CONFIG_BASED_SORT_BY_SIZE = (o1, o2) -> + { + final int cmp = Long.compare(o2.getStackSize(), o1.getStackSize()); + return applyDirection(cmp); + }; - public static final Comparator CONFIG_BASED_SORT_BY_INV_TWEAKS = ( o1, o2 ) -> - { - if( api == null ) - { - return CONFIG_BASED_SORT_BY_NAME.compare( o1, o2 ); - } + private static IInvTweaks api; - final int cmp = api.compareItems( o1.createItemStack(), o2.createItemStack() ); - return applyDirection( cmp ); - }; + public static final Comparator CONFIG_BASED_SORT_BY_INV_TWEAKS = (o1, o2) -> + { + if (api == null) { + return CONFIG_BASED_SORT_BY_NAME.compare(o1, o2); + } - public static void init() - { - if( api != null ) - { - return; - } + final int cmp = api.compareItems(o1.createItemStack(), o2.createItemStack()); + return applyDirection(cmp); + }; - if( Integrations.invTweaks().isEnabled() ) - { - api = Integrations.invTweaks(); - } - else - { - api = null; - } - } + public static void init() { + if (api != null) { + return; + } - public static int compareLong( final long a, final long b ) - { - if( a == b ) - { - return 0; - } - if( a < b ) - { - return -1; - } - return 1; - } + if (Integrations.invTweaks().isEnabled()) { + api = Integrations.invTweaks(); + } else { + api = null; + } + } - private static SortDir getDirection() - { - return Direction; - } + public static int compareLong(final long a, final long b) { + if (a == b) { + return 0; + } + if (a < b) { + return -1; + } + return 1; + } - public static void setDirection( final SortDir direction ) - { - Direction = direction; - } + private static SortDir getDirection() { + return Direction; + } - private static int applyDirection( int cmp ) - { - if( getDirection() == SortDir.ASCENDING ) - { - return cmp; - } - return -cmp; - } + public static void setDirection(final SortDir direction) { + Direction = direction; + } + + private static int applyDirection(int cmp) { + if (getDirection() == SortDir.ASCENDING) { + return cmp; + } + return -cmp; + } } diff --git a/src/main/java/appeng/util/Lazy.java b/src/main/java/appeng/util/Lazy.java index 567f5182b..eb56d1565 100644 --- a/src/main/java/appeng/util/Lazy.java +++ b/src/main/java/appeng/util/Lazy.java @@ -22,23 +22,19 @@ package appeng.util; import java.util.function.Supplier; -public class Lazy implements Supplier -{ - private final Supplier supplier; - private T instance = null; +public class Lazy implements Supplier { + private final Supplier supplier; + private T instance = null; - public Lazy( final Supplier supplier ) - { - this.supplier = supplier; - } + public Lazy(final Supplier supplier) { + this.supplier = supplier; + } - @Override - public T get() - { - if( this.instance == null ) - { - this.instance = this.supplier.get(); - } - return this.instance; - } + @Override + public T get() { + if (this.instance == null) { + this.instance = this.supplier.get(); + } + return this.instance; + } } diff --git a/src/main/java/appeng/util/LookDirection.java b/src/main/java/appeng/util/LookDirection.java index 9d5507d3c..8c4e0a05a 100644 --- a/src/main/java/appeng/util/LookDirection.java +++ b/src/main/java/appeng/util/LookDirection.java @@ -22,25 +22,21 @@ package appeng.util; import net.minecraft.util.math.Vec3d; -public class LookDirection -{ +public class LookDirection { - private final Vec3d a; - private final Vec3d b; + private final Vec3d a; + private final Vec3d b; - public LookDirection( final Vec3d a, final Vec3d b ) - { - this.a = a; - this.b = b; - } + public LookDirection(final Vec3d a, final Vec3d b) { + this.a = a; + this.b = b; + } - public Vec3d getA() - { - return this.a; - } + public Vec3d getA() { + return this.a; + } - public Vec3d getB() - { - return this.b; - } + public Vec3d getB() { + return this.b; + } } diff --git a/src/main/java/appeng/util/Platform.java b/src/main/java/appeng/util/Platform.java index 0a01e9bb7..439244797 100644 --- a/src/main/java/appeng/util/Platform.java +++ b/src/main/java/appeng/util/Platform.java @@ -19,82 +19,8 @@ package appeng.util; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.security.InvalidParameterException; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; -import java.util.WeakHashMap; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -import gregtech.api.block.machines.BlockMachine; -import gregtech.api.items.IToolItem; -import gregtech.api.metatileentity.MetaTileEntity; -import gregtech.api.util.GTUtility; -import ic2.api.item.ICustomDamageItem; -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.Minecraft; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.entity.Entity; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.CraftingManager; -import net.minecraft.item.crafting.IRecipe; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.play.server.SPacketChunkData; -import net.minecraft.server.management.PlayerChunkMap; -import net.minecraft.server.management.PlayerChunkMapEntry; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.registry.RegistryNamespaced; -import net.minecraft.util.text.translation.I18n; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; -import net.minecraft.world.WorldServer; -import net.minecraft.world.chunk.Chunk; -import net.minecraftforge.common.util.FakePlayerFactory; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.ModContainer; -import net.minecraftforge.fml.common.Optional; -import net.minecraftforge.fml.relauncher.ReflectionHelper; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; -import net.minecraftforge.oredict.OreDictionary; - import appeng.api.AEApi; -import appeng.api.config.AccessRestriction; -import appeng.api.config.Actionable; -import appeng.api.config.PowerMultiplier; -import appeng.api.config.PowerUnits; -import appeng.api.config.SearchBoxMode; -import appeng.api.config.SecurityPermissions; -import appeng.api.config.SortOrder; +import appeng.api.config.*; import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.IMaterials; import appeng.api.definitions.IParts; @@ -137,6 +63,61 @@ import appeng.util.helpers.ItemComparisonHelper; import appeng.util.helpers.P2PHelper; import appeng.util.item.AEItemStack; import appeng.util.prioritylist.IPartitionList; +import com.google.common.base.Preconditions; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import gregtech.api.block.machines.BlockMachine; +import gregtech.api.items.IToolItem; +import gregtech.api.metatileentity.MetaTileEntity; +import gregtech.api.util.GTUtility; +import ic2.api.item.ICustomDamageItem; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.entity.Entity; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.play.server.SPacketChunkData; +import net.minecraft.server.management.PlayerChunkMap; +import net.minecraft.server.management.PlayerChunkMapEntry; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.*; +import net.minecraft.util.registry.RegistryNamespaced; +import net.minecraft.util.text.translation.I18n; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraft.world.WorldServer; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.common.util.FakePlayerFactory; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.common.ModContainer; +import net.minecraftforge.fml.common.Optional; +import net.minecraftforge.fml.relauncher.ReflectionHelper; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.oredict.OreDictionary; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.security.InvalidParameterException; +import java.text.DecimalFormat; +import java.util.*; /** @@ -145,1585 +126,1317 @@ import appeng.util.prioritylist.IPartitionList; * @version rv2 * @since rv0 */ -@Optional.Interface( iface = "gregtech.api.items.IToolItem", modid = "gregtech" ) -@Optional.Interface( iface = "ic2.api.item.ICustomDamageItem", modid = "IC2" ) -public class Platform -{ - - public static final Block AIR_BLOCK = Blocks.AIR; - - public static final int DEF_OFFSET = 16; - - private static final boolean CLIENT_INSTALL = FMLCommonHandler.instance().getSide().isClient(); - - /* - * random source, use it for item drop locations... - */ - private static final Random RANDOM_GENERATOR = new Random(); - private static final WeakHashMap FAKE_PLAYERS = new WeakHashMap<>(); - // private static Method getEntry; - - private static final ItemComparisonHelper ITEM_COMPARISON_HELPER = new ItemComparisonHelper(); - private static final P2PHelper P2P_HELPER = new P2PHelper(); - private static Method reflectGTgetMTE; - - public static ItemComparisonHelper itemComparisons() - { - return ITEM_COMPARISON_HELPER; - } - - public static P2PHelper p2p() - { - return P2P_HELPER; - } - - public static Random getRandom() - { - return RANDOM_GENERATOR; - } - - public static float getRandomFloat() - { - return RANDOM_GENERATOR.nextFloat(); - } - - /** - * This displays the value for encoded longs ( double *100 ) - * - * @param n to be formatted long value - * @param isRate if true it adds a /t to the formatted string - * @return formatted long value - */ - public static String formatPowerLong( final long n, final boolean isRate ) - { - double p = ( (double) n ) / 100; - - final PowerUnits displayUnits = AEConfig.instance().selectedPowerUnit(); - p = PowerUnits.AE.convertTo( displayUnits, p ); - - final String[] preFixes = { - "k", "M", "G", "T", "P", "T", "P", "E", "Z", "Y" - }; - String unitName = displayUnits.name(); - - String level = ""; - int offset = 0; - while ( p > 1000 && offset < preFixes.length ) - { - p /= 1000; - level = preFixes[offset]; - offset++; - } - - final DecimalFormat df = new DecimalFormat( "#.##" ); - return df.format( p ) + ' ' + level + unitName + ( isRate ? "/t" : "" ); - } - - public static AEPartLocation crossProduct( final AEPartLocation forward, final AEPartLocation up ) - { - final int west_x = forward.yOffset * up.zOffset - forward.zOffset * up.yOffset; - final int west_y = forward.zOffset * up.xOffset - forward.xOffset * up.zOffset; - final int west_z = forward.xOffset * up.yOffset - forward.yOffset * up.xOffset; - - switch ( west_x + west_y * 2 + west_z * 3 ) - { - case 1: - return AEPartLocation.EAST; - case -1: - return AEPartLocation.WEST; - - case 2: - return AEPartLocation.UP; - case -2: - return AEPartLocation.DOWN; - - case 3: - return AEPartLocation.SOUTH; - case -3: - return AEPartLocation.NORTH; - } - - return AEPartLocation.INTERNAL; - } - - public static EnumFacing crossProduct( final EnumFacing forward, final EnumFacing up ) - { - final int west_x = forward.getFrontOffsetY() * up.getFrontOffsetZ() - forward.getFrontOffsetZ() * up.getFrontOffsetY(); - final int west_y = forward.getFrontOffsetZ() * up.getFrontOffsetX() - forward.getFrontOffsetX() * up.getFrontOffsetZ(); - final int west_z = forward.getFrontOffsetX() * up.getFrontOffsetY() - forward.getFrontOffsetY() * up.getFrontOffsetX(); - - switch ( west_x + west_y * 2 + west_z * 3 ) - { - case 1: - return EnumFacing.EAST; - case -1: - return EnumFacing.WEST; - - case 2: - return EnumFacing.UP; - case -2: - return EnumFacing.DOWN; - - case 3: - return EnumFacing.SOUTH; - case -3: - return EnumFacing.NORTH; - } - - // something is better then nothing? - return EnumFacing.NORTH; - } - - public static T rotateEnum( T ce, final boolean backwards, final EnumSet validOptions ) - { - do - { - if( backwards ) - { - ce = prevEnum( ce ); - } - else - { - ce = nextEnum( ce ); - } - } while ( !validOptions.contains( ce ) || isNotValidSetting( ce ) ); - - return ce; - } - - /* - * Simple way to cycle an enum... - */ - private static T prevEnum( final T ce ) - { - final EnumSet valList = EnumSet.allOf( ce.getClass() ); - - int pLoc = ce.ordinal() - 1; - if( pLoc < 0 ) - { - pLoc = valList.size() - 1; - } - - if( pLoc < 0 || pLoc >= valList.size() ) - { - pLoc = 0; - } - - int pos = 0; - for( final Object g : valList ) - { - if( pos == pLoc ) - { - return (T) g; - } - pos++; - } - - return null; - } - - /* - * Simple way to cycle an enum... - */ - public static T nextEnum( final T ce ) - { - final EnumSet valList = EnumSet.allOf( ce.getClass() ); - - int pLoc = ce.ordinal() + 1; - if( pLoc >= valList.size() ) - { - pLoc = 0; - } - - if( pLoc < 0 || pLoc >= valList.size() ) - { - pLoc = 0; - } - - int pos = 0; - for( final Object g : valList ) - { - if( pos == pLoc ) - { - return (T) g; - } - pos++; - } - - return null; - } - - private static boolean isNotValidSetting( final Enum e ) - { - if( e == SortOrder.INVTWEAKS && !Integrations.invTweaks().isEnabled() && !InventoryBogoSortModule.isLoaded() ) - { - return true; - } - - final boolean isJEI = e == SearchBoxMode.JEI_AUTOSEARCH || e == SearchBoxMode.JEI_AUTOSEARCH_KEEP || e == SearchBoxMode.JEI_MANUAL_SEARCH || e == SearchBoxMode.JEI_MANUAL_SEARCH_KEEP; - if( isJEI && !Integrations.jei().isEnabled() ) - { - return true; - } - - return false; - } - - public static void openGUI( @Nonnull final EntityPlayer p, @Nullable final TileEntity tile, @Nullable final AEPartLocation side, @Nonnull final GuiBridge type ) - { - if( isClient() ) - { - return; - } - - int x = (int) p.posX; - int y = (int) p.posY; - int z = (int) p.posZ; - if( tile != null ) - { - x = tile.getPos().getX(); - y = tile.getPos().getY(); - z = tile.getPos().getZ(); - } - - if( ( type.getType().isItem() && tile == null ) || type.hasPermissions( tile, x, y, z, side, p ) ) - { - if( tile == null && type.getType() == GuiHostType.ITEM ) - { - p.openGui( AppEng.instance(), type.ordinal() << 4, p.getEntityWorld(), p.inventory.currentItem, 0, 0 ); - } - else if( tile == null || type.getType() == GuiHostType.ITEM ) - { - p.openGui( AppEng.instance(), type.ordinal() << 4 | ( 1 << 3 ), p.getEntityWorld(), x, y, z ); - } - else - { - p.openGui( AppEng.instance(), type.ordinal() << 4 | ( side.ordinal() ), tile.getWorld(), x, y, z ); - } - } - } - - /* - * returns true if the code is on the client. - */ - public static boolean isClient() - { - return FMLCommonHandler.instance().getEffectiveSide().isClient(); - } - - /* - * returns true if client classes are available. - */ - public static boolean isClientInstall() - { - return CLIENT_INSTALL; - } - - public static boolean hasPermissions( final DimensionalCoord dc, final EntityPlayer player ) - { - return dc.getWorld().canMineBlockBody( player, dc.getPos() ); - } - - /* - * Checks to see if a block is air? - */ - public static boolean isBlockAir( final World w, final BlockPos pos ) - { - try - { - return w.getBlockState( pos ).getBlock().isAir( w.getBlockState( pos ), w, pos ); - } - catch( final Throwable e ) - { - return false; - } - } - - public static ItemStack[] getBlockDrops( final World w, final BlockPos pos ) - { - List out = new ArrayList<>(); - final IBlockState state = w.getBlockState( pos ); - - if( state != null ) - { - out = state.getBlock().getDrops( w, pos, state, 0 ); - } - - if( out == null ) - { - return new ItemStack[0]; - } - return out.toArray( new ItemStack[out.size()] ); - } - - public static AEPartLocation cycleOrientations( final AEPartLocation dir, final boolean upAndDown ) - { - if( upAndDown ) - { - switch ( dir ) - { - case NORTH: - return AEPartLocation.SOUTH; - case SOUTH: - return AEPartLocation.EAST; - case EAST: - return AEPartLocation.WEST; - case WEST: - return AEPartLocation.NORTH; - case UP: - return AEPartLocation.UP; - case DOWN: - return AEPartLocation.DOWN; - case INTERNAL: - return AEPartLocation.INTERNAL; - } - } - else - { - switch ( dir ) - { - case UP: - return AEPartLocation.DOWN; - case DOWN: - return AEPartLocation.NORTH; - case NORTH: - return AEPartLocation.SOUTH; - case SOUTH: - return AEPartLocation.EAST; - case EAST: - return AEPartLocation.WEST; - case WEST: - return AEPartLocation.UP; - case INTERNAL: - return AEPartLocation.INTERNAL; - } - } - - return AEPartLocation.INTERNAL; - } - - /* - * Creates / or loads previous NBT Data on items, used for editing items owned by AE. - */ - public static NBTTagCompound openNbtData( final ItemStack i ) - { - NBTTagCompound compound = i.getTagCompound(); - - if( compound == null ) - { - i.setTagCompound( compound = new NBTTagCompound() ); - } - - return compound; - } - - /* - * Generates Item entities in the world similar to how items are generally dropped. - */ - public static void spawnDrops( final World w, final BlockPos pos, final List drops ) - { - if( isServer() ) - { - for( final ItemStack i : drops ) - { - if( !i.isEmpty() ) - { - if( i.getCount() > 0 ) - { - final double offset_x = ( getRandomInt() % 32 - 16 ) / 82; - final double offset_y = ( getRandomInt() % 32 - 16 ) / 82; - final double offset_z = ( getRandomInt() % 32 - 16 ) / 82; - final EntityItem ei = new EntityItem( w, 0.5 + offset_x + pos.getX(), 0.5 + offset_y + pos.getY(), 0.2 + offset_z + pos.getZ(), i.copy() ); - w.spawnEntity( ei ); - } - } - } - } - } - - /* - * returns true if the code is on the server. - */ - public static boolean isServer() - { - return FMLCommonHandler.instance().getEffectiveSide().isServer(); - } - - public static int getRandomInt() - { - return Math.abs( RANDOM_GENERATOR.nextInt() ); - } - - public static boolean isModLoaded( final String modid ) - { - try - { - // if this fails for some reason, try the other method. - return Loader.isModLoaded( modid ); - } - catch( final Throwable ignored ) - { - } - - for( final ModContainer f : Loader.instance().getActiveModList() ) - { - if( f.getModId().equals( modid ) ) - { - return true; - } - } - return false; - } - - public static ItemStack findMatchingRecipeOutput( final InventoryCrafting ic, final World world ) - { - return CraftingManager.findMatchingResult( ic, world ); - } - - @SideOnly( Side.CLIENT ) - public static List getTooltip( final Object o ) - { - if( o == null ) - { - return new ArrayList<>(); - } - - ItemStack itemStack = ItemStack.EMPTY; - if( o instanceof AEItemStack ) - { - final AEItemStack ais = (AEItemStack) o; - return ais.getToolTip(); - } - else if( o instanceof ItemStack ) - { - itemStack = (ItemStack) o; - } - else - { - return new ArrayList<>(); - } - - try - { - ITooltipFlag.TooltipFlags tooltipFlag = Minecraft.getMinecraft().gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL; - return itemStack.getTooltip( Minecraft.getMinecraft().player, tooltipFlag ); - } - catch( final Exception errB ) - { - return new ArrayList<>(); - } - } - - public static String getModId( final IAEItemStack is ) - { - if( is == null ) - { - return "** Null"; - } - - final String n = ( (AEItemStack) is ).getModID(); - return n == null ? "** Null" : n; - } - - public static String getModId( final IAEFluidStack fs ) - { - if( fs == null || fs.getFluidStack() == null ) - { - return "** Null"; - } - - final String n = FluidRegistry.getModId( fs.getFluidStack() ); - return n == null ? "** Null" : n; - } - - public static String getItemDisplayName( final Object o ) - { - if( o == null ) - { - return "** Null"; - } - - ItemStack itemStack = ItemStack.EMPTY; - if( o instanceof AEItemStack ) - { - final String n = ( (AEItemStack) o ).getDisplayName(); - return n == null ? "** Null" : n; - } - else if( o instanceof ItemStack ) - { - itemStack = (ItemStack) o; - } - else - { - return "**Invalid Object"; - } - - try - { - String name = itemStack.getDisplayName(); - if( name == null || name.isEmpty() ) - { - name = itemStack.getItem().getUnlocalizedName( itemStack ); - } - return name == null ? "** Null" : name; - } - catch( final Exception errA ) - { - try - { - final String n = itemStack.getUnlocalizedName(); - return n == null ? "** Null" : n; - } - catch( final Exception errB ) - { - return "** Exception"; - } - } - } - - public static String getFluidDisplayName( Object o ) - { - if( o == null ) - { - return "** Null"; - } - FluidStack fluidStack = null; - if( o instanceof AEFluidStack ) - { - fluidStack = ( (AEFluidStack) o ).getFluidStack(); - } - else if( o instanceof FluidStack ) - { - fluidStack = (FluidStack) o; - } - else - { - return "**Invalid Object"; - } - String n = fluidStack.getLocalizedName(); - if( n == null || "".equalsIgnoreCase( n ) ) - { - n = fluidStack.getUnlocalizedName(); - } - return n == null ? "** Null" : n; - } - - public static boolean isWrench( final EntityPlayer player, final ItemStack eq, final BlockPos pos ) - { - if( !eq.isEmpty() ) - { - try - { - // TODO: Build Craft Wrench? - /* - * if( eq.getItem() instanceof IToolWrench ) - * { - * IToolWrench wrench = (IToolWrench) eq.getItem(); - * return wrench.canWrench( player, x, y, z ); - * } - */ - - if( eq.getItem() instanceof cofh.api.item.IToolHammer ) - { - return ( (cofh.api.item.IToolHammer) eq.getItem() ).isUsable( eq, player, pos ); - } - } - catch( final Throwable ignore ) - { // explodes without BC - - } - - if( eq.getItem() instanceof IAEWrench ) - { - final IAEWrench wrench = (IAEWrench) eq.getItem(); - return wrench.canWrench( eq, player, pos ); - } - } - return false; - } - - public static boolean isChargeable( final ItemStack i ) - { - if( i.isEmpty() ) - { - return false; - } - final Item it = i.getItem(); - if( it instanceof IAEItemPowerStorage ) - { - return ( (IAEItemPowerStorage) it ).getPowerFlow( i ) != AccessRestriction.READ; - } - return false; - } - - public static EntityPlayer getPlayer( final WorldServer w ) - { - if( w == null ) - { - throw new InvalidParameterException( "World is null." ); - } - - final EntityPlayer wrp = FAKE_PLAYERS.get( w ); - if( wrp != null ) - { - return wrp; - } - - final EntityPlayer p = FakePlayerFactory.getMinecraft( w ); - FAKE_PLAYERS.put( w, p ); - return p; - } - - public static int MC2MEColor( final int color ) - { - switch ( color ) - { - case 4: // "blue" - return 0; - case 0: // "black" - return 1; - case 15: // "white" - return 2; - case 3: // "brown" - return 3; - case 1: // "red" - return 4; - case 11: // "yellow" - return 5; - case 2: // "green" - return 6; - - case 5: // "purple" - case 6: // "cyan" - case 7: // "silver" - case 8: // "gray" - case 9: // "pink" - case 10: // "lime" - case 12: // "lightBlue" - case 13: // "magenta" - case 14: // "orange" - } - return -1; - } - - public static int findEmpty( final RegistryNamespaced registry, final int minId, final int maxId ) - { - for( int x = minId; x < maxId; x++ ) - { - if( registry.getObjectById( x ) == null ) - { - return x; - } - } - return -1; - } - - public static int findEmpty( final Object[] l ) - { - for( int x = 0; x < l.length; x++ ) - { - if( l[x] == null ) - { - return x; - } - } - return -1; - } - - /** - * Returns a random element from the given collection. - * - * @return null if the collection is empty - */ - @Nullable - public static T pickRandom( final Collection outs ) - { - if( outs.isEmpty() ) - { - return null; - } - - int index = RANDOM_GENERATOR.nextInt( outs.size() ); - return Iterables.get( outs, index, null ); - } - - public static AEPartLocation rotateAround( final AEPartLocation forward, final AEPartLocation axis ) - { - if( axis == AEPartLocation.INTERNAL || forward == AEPartLocation.INTERNAL ) - { - return forward; - } - - switch ( forward ) - { - case DOWN: - switch ( axis ) - { - case DOWN: - return forward; - case UP: - return forward; - case NORTH: - return AEPartLocation.EAST; - case SOUTH: - return AEPartLocation.WEST; - case EAST: - return AEPartLocation.NORTH; - case WEST: - return AEPartLocation.SOUTH; - default: - break; - } - break; - case UP: - switch ( axis ) - { - case NORTH: - return AEPartLocation.WEST; - case SOUTH: - return AEPartLocation.EAST; - case EAST: - return AEPartLocation.SOUTH; - case WEST: - return AEPartLocation.NORTH; - default: - break; - } - break; - case NORTH: - switch ( axis ) - { - case UP: - return AEPartLocation.WEST; - case DOWN: - return AEPartLocation.EAST; - case EAST: - return AEPartLocation.UP; - case WEST: - return AEPartLocation.DOWN; - default: - break; - } - break; - case SOUTH: - switch ( axis ) - { - case UP: - return AEPartLocation.EAST; - case DOWN: - return AEPartLocation.WEST; - case EAST: - return AEPartLocation.DOWN; - case WEST: - return AEPartLocation.UP; - default: - break; - } - break; - case EAST: - switch ( axis ) - { - case UP: - return AEPartLocation.NORTH; - case DOWN: - return AEPartLocation.SOUTH; - case NORTH: - return AEPartLocation.UP; - case SOUTH: - return AEPartLocation.DOWN; - default: - break; - } - case WEST: - switch ( axis ) - { - case UP: - return AEPartLocation.SOUTH; - case DOWN: - return AEPartLocation.NORTH; - case NORTH: - return AEPartLocation.DOWN; - case SOUTH: - return AEPartLocation.UP; - default: - break; - } - default: - break; - } - return forward; - } - - public static EnumFacing rotateAround( final EnumFacing forward, final EnumFacing axis ) - { - switch ( forward ) - { - case DOWN: - switch ( axis ) - { - case DOWN: - return forward; - case UP: - return forward; - case NORTH: - return EnumFacing.EAST; - case SOUTH: - return EnumFacing.WEST; - case EAST: - return EnumFacing.NORTH; - case WEST: - return EnumFacing.SOUTH; - default: - break; - } - break; - case UP: - switch ( axis ) - { - case NORTH: - return EnumFacing.WEST; - case SOUTH: - return EnumFacing.EAST; - case EAST: - return EnumFacing.SOUTH; - case WEST: - return EnumFacing.NORTH; - default: - break; - } - break; - case NORTH: - switch ( axis ) - { - case UP: - return EnumFacing.WEST; - case DOWN: - return EnumFacing.EAST; - case EAST: - return EnumFacing.UP; - case WEST: - return EnumFacing.DOWN; - default: - break; - } - break; - case SOUTH: - switch ( axis ) - { - case UP: - return EnumFacing.EAST; - case DOWN: - return EnumFacing.WEST; - case EAST: - return EnumFacing.DOWN; - case WEST: - return EnumFacing.UP; - default: - break; - } - break; - case EAST: - switch ( axis ) - { - case UP: - return EnumFacing.NORTH; - case DOWN: - return EnumFacing.SOUTH; - case NORTH: - return EnumFacing.UP; - case SOUTH: - return EnumFacing.DOWN; - default: - break; - } - case WEST: - switch ( axis ) - { - case UP: - return EnumFacing.SOUTH; - case DOWN: - return EnumFacing.NORTH; - case NORTH: - return EnumFacing.DOWN; - case SOUTH: - return EnumFacing.UP; - default: - break; - } - default: - break; - } - return forward; - } - - @SideOnly( Side.CLIENT ) - public static String gui_localize( final String string ) - { - return I18n.translateToLocal( string ); - } - - public static LookDirection getPlayerRay( final EntityPlayer playerIn, final float eyeOffset ) - { - double reachDistance = 5.0d; - - final double x = playerIn.prevPosX + ( playerIn.posX - playerIn.prevPosX ); - final double y = playerIn.prevPosY + ( playerIn.posY - playerIn.prevPosY ) + playerIn.getEyeHeight(); - final double z = playerIn.prevPosZ + ( playerIn.posZ - playerIn.prevPosZ ); - - final float playerPitch = playerIn.prevRotationPitch + ( playerIn.rotationPitch - playerIn.prevRotationPitch ); - final float playerYaw = playerIn.prevRotationYaw + ( playerIn.rotationYaw - playerIn.prevRotationYaw ); - - final float yawRayX = MathHelper.sin( -playerYaw * 0.017453292f - (float) Math.PI ); - final float yawRayZ = MathHelper.cos( -playerYaw * 0.017453292f - (float) Math.PI ); - - final float pitchMultiplier = -MathHelper.cos( -playerPitch * 0.017453292F ); - final float eyeRayY = MathHelper.sin( -playerPitch * 0.017453292F ); - final float eyeRayX = yawRayX * pitchMultiplier; - final float eyeRayZ = yawRayZ * pitchMultiplier; - - if( playerIn instanceof EntityPlayerMP ) - { - reachDistance = ( (EntityPlayerMP) playerIn ).interactionManager.getBlockReachDistance(); - } - - final Vec3d from = new Vec3d( x, y, z ); - final Vec3d to = from.addVector( eyeRayX * reachDistance, eyeRayY * reachDistance, eyeRayZ * reachDistance ); - - return new LookDirection( from, to ); - } - - public static RayTraceResult rayTrace( final EntityPlayer p, final boolean hitBlocks, final boolean hitEntities ) - { - final World w = p.getEntityWorld(); - - final float f = 1.0F; - float f1 = p.prevRotationPitch + ( p.rotationPitch - p.prevRotationPitch ) * f; - final float f2 = p.prevRotationYaw + ( p.rotationYaw - p.prevRotationYaw ) * f; - final double d0 = p.prevPosX + ( p.posX - p.prevPosX ) * f; - final double d1 = p.prevPosY + ( p.posY - p.prevPosY ) * f + 1.62D - p.getYOffset(); - final double d2 = p.prevPosZ + ( p.posZ - p.prevPosZ ) * f; - final Vec3d vec3 = new Vec3d( d0, d1, d2 ); - final float f3 = MathHelper.cos( -f2 * 0.017453292F - (float) Math.PI ); - final float f4 = MathHelper.sin( -f2 * 0.017453292F - (float) Math.PI ); - final float f5 = -MathHelper.cos( -f1 * 0.017453292F ); - final float f6 = MathHelper.sin( -f1 * 0.017453292F ); - final float f7 = f4 * f5; - final float f8 = f3 * f5; - final double d3 = 32.0D; - - final Vec3d vec31 = vec3.addVector( f7 * d3, f6 * d3, f8 * d3 ); - - final AxisAlignedBB bb = new AxisAlignedBB( Math.min( vec3.x, vec31.x ), Math.min( vec3.y, vec31.y ), Math.min( vec3.z, vec31.z ), Math.max( vec3.x, vec31.x ), Math.max( vec3.y, vec31.y ), Math.max( vec3.z, vec31.z ) ).grow( 16, 16, 16 ); - - Entity entity = null; - double closest = 9999999.0D; - if( hitEntities ) - { - final List list = w.getEntitiesWithinAABBExcludingEntity( p, bb ); - - for( int l = 0; l < list.size(); ++l ) - { - final Entity entity1 = (Entity) list.get( l ); - - if( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) - { - if( entity1.isEntityAlive() ) - { - // prevent killing / flying of mounts. - if( entity1.isRidingOrBeingRiddenBy( p ) ) - { - continue; - } - - f1 = 0.3F; - final AxisAlignedBB boundingBox = entity1.getEntityBoundingBox().grow( f1, f1, f1 ); - final RayTraceResult RayTraceResult = boundingBox.calculateIntercept( vec3, vec31 ); - - if( RayTraceResult != null ) - { - final double nd = vec3.squareDistanceTo( RayTraceResult.hitVec ); - - if( nd < closest ) - { - entity = entity1; - closest = nd; - } - } - } - } - } - } - - RayTraceResult pos = null; - Vec3d vec = null; - - if( hitBlocks ) - { - vec = new Vec3d( d0, d1, d2 ); - pos = w.rayTraceBlocks( vec3, vec31, true ); - } - - if( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) - { - pos = new RayTraceResult( entity ); - } - else if( entity != null && pos == null ) - { - pos = new RayTraceResult( entity ); - } - - return pos; - } - - public static > T poweredExtraction( final IEnergySource energy, final IMEInventory cell, final T request, final IActionSource src ) - { - return poweredExtraction( energy, cell, request, src, Actionable.MODULATE ); - } - - public static > T poweredExtraction( final IEnergySource energy, final IMEInventory cell, final T request, final IActionSource src, final Actionable mode ) - { - Preconditions.checkNotNull( energy ); - Preconditions.checkNotNull( cell ); - Preconditions.checkNotNull( request ); - Preconditions.checkNotNull( src ); - Preconditions.checkNotNull( mode ); - - final T possible = cell.extractItems( request.copy(), Actionable.SIMULATE, src ); - - long retrieved = 0; - if( possible != null ) - { - retrieved = possible.getStackSize(); - } - - final double energyFactor = Math.max( 1.0, cell.getChannel().transferFactor() ); - final double availablePower = energy.extractAEPower( retrieved / energyFactor, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - final long itemToExtract = Math.min( (long) ( ( availablePower * energyFactor ) + 0.9 ), retrieved ); - - if( itemToExtract > 0 ) - { - if( mode == Actionable.MODULATE ) - { - energy.extractAEPower( retrieved / energyFactor, Actionable.MODULATE, PowerMultiplier.CONFIG ); - possible.setStackSize( itemToExtract ); - final T ret = cell.extractItems( possible, Actionable.MODULATE, src ); - - if( ret != null ) - { - src.player().ifPresent( player -> Stats.ItemsExtracted.addToPlayer( player, (int) ret.getStackSize() ) ); - } - return ret; - } - else - { - return possible.setStackSize( itemToExtract ); - } - } - - return null; - } - - public static > T poweredInsert( final IEnergySource energy, final IMEInventory cell, final T input, final IActionSource src ) - { - return poweredInsert( energy, cell, input, src, Actionable.MODULATE ); - } - - public static > T poweredInsert( final IEnergySource energy, final IMEInventory cell, final T input, final IActionSource src, final Actionable mode ) - { - Preconditions.checkNotNull( energy ); - Preconditions.checkNotNull( cell ); - Preconditions.checkNotNull( input ); - Preconditions.checkNotNull( src ); - Preconditions.checkNotNull( mode ); - - final T possible = cell.injectItems( input, Actionable.SIMULATE, src ); - - long stored = input.getStackSize(); - if( possible != null ) - { - stored -= possible.getStackSize(); - } - - final double energyFactor = Math.max( 1.0, cell.getChannel().transferFactor() ); - final double availablePower = energy.extractAEPower( stored / energyFactor, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - final long itemToAdd = Math.min( (long) ( ( availablePower * energyFactor ) + 0.9 ), stored ); - - if( itemToAdd > 0 ) - { - if( mode == Actionable.MODULATE ) - { - energy.extractAEPower( stored / energyFactor, Actionable.MODULATE, PowerMultiplier.CONFIG ); - if( itemToAdd < input.getStackSize() ) - { - final long original = input.getStackSize(); - final T leftover = input.copy(); - final T split = input.copy(); - - leftover.decStackSize( itemToAdd ); - split.setStackSize( itemToAdd ); - leftover.add( cell.injectItems( split, Actionable.MODULATE, src ) ); - - src.player().ifPresent( player -> - { - final long diff = original - leftover.getStackSize(); - Stats.ItemsInserted.addToPlayer( player, (int) diff ); - } ); - - return leftover; - } - - final T ret = cell.injectItems( input, Actionable.MODULATE, src ); - - src.player().ifPresent( player -> - { - final long diff = ret == null ? input.getStackSize() : input.getStackSize() - ret.getStackSize(); - Stats.ItemsInserted.addToPlayer( player, (int) diff ); - } ); - - return ret; - } - else - { - final T ret = input.copy().setStackSize( input.getStackSize() - itemToAdd ); - return ( ret != null && ret.getStackSize() > 0 ) ? ret : null; - } - } - - return input; - } - - @SuppressWarnings( {"rawtypes", "unchecked"} ) - public static void postChanges( final IStorageGrid gs, final ItemStack removed, final ItemStack added, final IActionSource src ) - { - for( final IStorageChannel chan : AEApi.instance().storage().storageChannels() ) - { - final IItemList myChanges = chan.createList(); - - if( !removed.isEmpty() ) - { - final IMEInventory myInv = AEApi.instance().registries().cell().getCellInventory( removed, null, chan ); - if( myInv != null ) - { - myInv.getAvailableItems( myChanges ); - for( final IAEStack is : myChanges ) - { - is.setStackSize( -is.getStackSize() ); - } - } - } - if( !added.isEmpty() ) - { - final IMEInventory myInv = AEApi.instance().registries().cell().getCellInventory( added, null, chan ); - if( myInv != null ) - { - myInv.getAvailableItems( myChanges ); - } - - } - gs.postAlterationOfStoredItems( chan, myChanges, src ); - } - } - - public static > void postListChanges( final IItemList before, final IItemList after, final IMEMonitorHandlerReceiver meMonitorPassthrough, final IActionSource source ) - { - final List changes = new ArrayList<>(); - - for( final T is : before ) - { - is.setStackSize( -is.getStackSize() ); - } - - for( final T is : after ) - { - before.add( is ); - } - - for( final T is : before ) - { - if( is.getStackSize() != 0 ) - { - changes.add( is ); - } - } - - if( !changes.isEmpty() ) - { - meMonitorPassthrough.postChange( null, changes, source ); - } - } - - public static boolean securityCheck( final GridNode a, final GridNode b ) - { - if( a.getLastSecurityKey() == -1 && b.getLastSecurityKey() == -1 ) - { - return true; - } - else if( a.getLastSecurityKey() == b.getLastSecurityKey() ) - { - return true; - } - - final boolean a_isSecure = isPowered( a.getGrid() ) && a.getLastSecurityKey() != -1; - final boolean b_isSecure = isPowered( b.getGrid() ) && b.getLastSecurityKey() != -1; - - if( AEConfig.instance().isFeatureEnabled( AEFeature.LOG_SECURITY_AUDITS ) ) - { - final String locationA = a.getGridBlock().isWorldAccessible() ? a.getGridBlock().getLocation().toString() : "notInWorld"; - final String locationB = b.getGridBlock().isWorldAccessible() ? b.getGridBlock().getLocation().toString() : "notInWorld"; - - AELog.info( "Audit: Node A [isSecure=%b, key=%d, playerID=%d, location={%s}] vs Node B[isSecure=%b, key=%d, playerID=%d, location={%s}]", a_isSecure, a.getLastSecurityKey(), a.getPlayerID(), locationA, b_isSecure, b.getLastSecurityKey(), b.getPlayerID(), locationB ); - } - - // can't do that son... - if( a_isSecure && b_isSecure ) - { - return false; - } - - if( !a_isSecure && b_isSecure ) - { - return checkPlayerPermissions( b.getGrid(), a.getPlayerID() ); - } - - if( a_isSecure && !b_isSecure ) - { - return checkPlayerPermissions( a.getGrid(), b.getPlayerID() ); - } - - return true; - } - - private static boolean isPowered( final IGrid grid ) - { - if( grid == null ) - { - return false; - } - - final IEnergyGrid eg = grid.getCache( IEnergyGrid.class ); - return eg.isNetworkPowered(); - } - - private static boolean checkPlayerPermissions( final IGrid grid, final int playerID ) - { - if( grid == null ) - { - return true; - } - - final ISecurityGrid gs = grid.getCache( ISecurityGrid.class ); - - if( gs == null ) - { - return true; - } - - if( !gs.isAvailable() ) - { - return true; - } - - return gs.hasPermission( playerID, SecurityPermissions.BUILD ); - } - - public static void configurePlayer( final EntityPlayer player, final AEPartLocation side, final TileEntity tile ) - { - float pitch = 0.0f; - float yaw = 0.0f; - // player.yOffset = 1.8f; - - switch ( side ) - { - case DOWN: - pitch = 90.0f; - // player.getYOffset() = -1.8f; - break; - case EAST: - yaw = -90.0f; - break; - case NORTH: - yaw = 180.0f; - break; - case SOUTH: - yaw = 0.0f; - break; - case INTERNAL: - break; - case UP: - pitch = 90.0f; - break; - case WEST: - yaw = 90.0f; - break; - } - - player.posX = tile.getPos().getX() + 0.5; - player.posY = tile.getPos().getY() + 0.5; - player.posZ = tile.getPos().getZ() + 0.5; - - player.rotationPitch = player.prevCameraPitch = player.cameraPitch = pitch; - player.rotationYaw = player.prevCameraYaw = player.cameraYaw = yaw; - } - - public static boolean canAccess( final AENetworkProxy gridProxy, final IActionSource src ) - { - try - { - if( src.player().isPresent() ) - { - return gridProxy.getSecurity().hasPermission( src.player().get(), SecurityPermissions.BUILD ); - } - else if( src.machine().isPresent() ) - { - final IActionHost te = src.machine().get(); - final IGridNode n = te.getActionableNode(); - if( n == null ) - { - return false; - } - - final int playerID = n.getPlayerID(); - return gridProxy.getSecurity().hasPermission( playerID, SecurityPermissions.BUILD ); - } - else - { - return false; - } - } - catch( final GridAccessException gae ) - { - return false; - } - } - - public static ItemStack extractItemsByRecipe( final IEnergySource energySrc, final IActionSource mySrc, final IMEMonitor src, final World w, final IRecipe r, final ItemStack output, final InventoryCrafting ci, final ItemStack providedTemplate, final int slot, final IItemList items, final Actionable realForFake, final IPartitionList filter ) - { - if( energySrc.extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.9 ) - { - if( providedTemplate == null ) - { - return ItemStack.EMPTY; - } - - final AEItemStack ae_req = AEItemStack.fromItemStack( providedTemplate ); - ae_req.setStackSize( 1 ); - - if( filter == null || filter.isListed( ae_req ) ) - { - final IAEItemStack ae_ext = src.extractItems( ae_req, realForFake, mySrc ); - if( ae_ext != null ) - { - final ItemStack extracted = ae_ext.createItemStack(); - if( !extracted.isEmpty() ) - { - energySrc.extractAEPower( 1, realForFake, PowerMultiplier.CONFIG ); - return extracted; - } - } - } - - final boolean checkFuzzy = ae_req.getOre().isPresent() || providedTemplate.getItemDamage() == OreDictionary.WILDCARD_VALUE || providedTemplate.hasTagCompound() || providedTemplate.isItemStackDamageable(); - - if( items != null && checkFuzzy ) - { - for( final IAEItemStack x : items ) - { - final ItemStack sh = x.getDefinition(); - if( ( Platform.itemComparisons().isEqualItemType( providedTemplate, sh ) || ae_req.sameOre( x ) ) && !ItemStack.areItemsEqual( sh, output ) ) - { // Platform.isSameItemType( sh, providedTemplate ) - final ItemStack cp = sh.copy(); - cp.setCount( 1 ); - ci.setInventorySlotContents( slot, cp ); - if( r.matches( ci, w ) && ItemStack.areItemsEqual( r.getCraftingResult( ci ), output ) ) - { - final IAEItemStack ax = x.copy(); - ax.setStackSize( 1 ); - if( filter == null || filter.isListed( ax ) ) - { - final IAEItemStack ex = src.extractItems( ax, realForFake, mySrc ); - if( ex != null ) - { - energySrc.extractAEPower( 1, realForFake, PowerMultiplier.CONFIG ); - return ex.createItemStack(); - } - } - } - ci.setInventorySlotContents( slot, providedTemplate ); - } - } - } - } - return ItemStack.EMPTY; - } - - // TODO wtf is this? - public static ItemStack getContainerItem( final ItemStack stackInSlot ) - { - if( stackInSlot == null ) - { - return ItemStack.EMPTY; - } - - final Item i = stackInSlot.getItem(); - if( i == null || !i.hasContainerItem( stackInSlot ) ) - { - if( stackInSlot.getCount() > 1 ) - { - stackInSlot.setCount( stackInSlot.getCount() - 1 ); - return stackInSlot; - } - return ItemStack.EMPTY; - } - - ItemStack ci = i.getContainerItem( stackInSlot.copy() ); - if( !ci.isEmpty() && ci.isItemStackDamageable() && ci.getItemDamage() == ci.getMaxDamage() ) - { - ci = ItemStack.EMPTY; - } - - return ci; - } - - public static void notifyBlocksOfNeighbors( final World world, final BlockPos pos ) - { - if( !world.isRemote ) - { - TickHandler.INSTANCE.addCallable( world, new BlockUpdate( pos ) ); - } - } - - public static boolean canRepair( final AEFeature type, final ItemStack a, final ItemStack b ) - { - if( b.isEmpty() || a.isEmpty() ) - { - return false; - } - - if( type == AEFeature.CERTUS_QUARTZ_TOOLS ) - { - final IItemDefinition certusQuartzCrystal = AEApi.instance().definitions().materials().certusQuartzCrystal(); - - return certusQuartzCrystal.isSameAs( b ); - } - - if( type == AEFeature.NETHER_QUARTZ_TOOLS ) - { - return Items.QUARTZ == b.getItem(); - } - - return false; - } - - public static List findPreferred( final ItemStack[] is ) - { - final IParts parts = AEApi.instance().definitions().parts(); - - for( final ItemStack stack : is ) - { - if( parts.cableGlass().sameAs( AEColor.TRANSPARENT, stack ) ) - { - return Collections.singletonList( stack ); - } - - if( parts.cableCovered().sameAs( AEColor.TRANSPARENT, stack ) ) - { - return Collections.singletonList( stack ); - } - - if( parts.cableSmart().sameAs( AEColor.TRANSPARENT, stack ) ) - { - return Collections.singletonList( stack ); - } - - if( parts.cableDenseSmart().sameAs( AEColor.TRANSPARENT, stack ) ) - { - return Collections.singletonList( stack ); - } - } - - return Lists.newArrayList( is ); - } - - public static void sendChunk( final Chunk c, final int verticalBits ) - { - try - { - final WorldServer ws = (WorldServer) c.getWorld(); - final PlayerChunkMap pm = ws.getPlayerChunkMap(); - final PlayerChunkMapEntry playerInstance = pm.getEntry( c.x, c.z ); - - if( playerInstance != null ) - { - playerInstance.sendPacket( new SPacketChunkData( c, verticalBits ) ); - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } - - public static float getEyeOffset( final EntityPlayer player ) - { - assert player.world.isRemote : "Valid only on client"; - return (float) ( player.posY + player.getEyeHeight() - player.getDefaultEyeHeight() ); - } - - // public static void addStat( final int playerID, final Achievement achievement ) - // { - // final EntityPlayer p = AEApi.instance().registries().players().findPlayer( playerID ); - // if( p != null ) - // { - // p.addStat( achievement, 1 ); - // } - // } - - public static boolean isRecipePrioritized( final ItemStack what ) - { - final IMaterials materials = AEApi.instance().definitions().materials(); - - boolean isPurified = materials.purifiedCertusQuartzCrystal().isSameAs( what ); - isPurified |= materials.purifiedFluixCrystal().isSameAs( what ); - isPurified |= materials.purifiedNetherQuartzCrystal().isSameAs( what ); - - return isPurified; - } - - //consider methods below moving to a compability class - public static boolean isGTDamageableItem( Item item ) - { - return ( isModLoaded( "gregtech" ) && item instanceof IToolItem ); - } - - public static MetaTileEntity getMetaTileEntity( IBlockAccess world, BlockPos pos ) - { - if( reflectGTgetMTE == null ) - { - try - { - reflectGTgetMTE = ReflectionHelper.findMethod( BlockMachine.class, "getMetaTileEntity", null, IBlockAccess.class, BlockPos.class ); - } - catch( ReflectionHelper.UnableToFindMethodException e ) - { - reflectGTgetMTE = ReflectionHelper.findMethod( GTUtility.class, "getMetaTileEntity", null, IBlockAccess.class, BlockPos.class ); - } - } - else - { - try - { - return (MetaTileEntity) reflectGTgetMTE.invoke( reflectGTgetMTE, world, pos ); - } - catch( IllegalAccessException | InvocationTargetException e ) - { - e.printStackTrace(); - } - } - return null; - } - - public static boolean isIC2DamageableItem( Item item ) - { - return ( isModLoaded( "IC2" ) && item instanceof ICustomDamageItem ); - } +@Optional.Interface(iface = "gregtech.api.items.IToolItem", modid = "gregtech") +@Optional.Interface(iface = "ic2.api.item.ICustomDamageItem", modid = "IC2") +public class Platform { + + public static final Block AIR_BLOCK = Blocks.AIR; + + public static final int DEF_OFFSET = 16; + + private static final boolean CLIENT_INSTALL = FMLCommonHandler.instance().getSide().isClient(); + + /* + * random source, use it for item drop locations... + */ + private static final Random RANDOM_GENERATOR = new Random(); + private static final WeakHashMap FAKE_PLAYERS = new WeakHashMap<>(); + // private static Method getEntry; + + private static final ItemComparisonHelper ITEM_COMPARISON_HELPER = new ItemComparisonHelper(); + private static final P2PHelper P2P_HELPER = new P2PHelper(); + private static Method reflectGTgetMTE; + + public static ItemComparisonHelper itemComparisons() { + return ITEM_COMPARISON_HELPER; + } + + public static P2PHelper p2p() { + return P2P_HELPER; + } + + public static Random getRandom() { + return RANDOM_GENERATOR; + } + + public static float getRandomFloat() { + return RANDOM_GENERATOR.nextFloat(); + } + + /** + * This displays the value for encoded longs ( double *100 ) + * + * @param n to be formatted long value + * @param isRate if true it adds a /t to the formatted string + * @return formatted long value + */ + public static String formatPowerLong(final long n, final boolean isRate) { + double p = ((double) n) / 100; + + final PowerUnits displayUnits = AEConfig.instance().selectedPowerUnit(); + p = PowerUnits.AE.convertTo(displayUnits, p); + + final String[] preFixes = { + "k", "M", "G", "T", "P", "T", "P", "E", "Z", "Y" + }; + String unitName = displayUnits.name(); + + String level = ""; + int offset = 0; + while (p > 1000 && offset < preFixes.length) { + p /= 1000; + level = preFixes[offset]; + offset++; + } + + final DecimalFormat df = new DecimalFormat("#.##"); + return df.format(p) + ' ' + level + unitName + (isRate ? "/t" : ""); + } + + public static AEPartLocation crossProduct(final AEPartLocation forward, final AEPartLocation up) { + final int west_x = forward.yOffset * up.zOffset - forward.zOffset * up.yOffset; + final int west_y = forward.zOffset * up.xOffset - forward.xOffset * up.zOffset; + final int west_z = forward.xOffset * up.yOffset - forward.yOffset * up.xOffset; + + switch (west_x + west_y * 2 + west_z * 3) { + case 1: + return AEPartLocation.EAST; + case -1: + return AEPartLocation.WEST; + + case 2: + return AEPartLocation.UP; + case -2: + return AEPartLocation.DOWN; + + case 3: + return AEPartLocation.SOUTH; + case -3: + return AEPartLocation.NORTH; + } + + return AEPartLocation.INTERNAL; + } + + public static EnumFacing crossProduct(final EnumFacing forward, final EnumFacing up) { + final int west_x = forward.getFrontOffsetY() * up.getFrontOffsetZ() - forward.getFrontOffsetZ() * up.getFrontOffsetY(); + final int west_y = forward.getFrontOffsetZ() * up.getFrontOffsetX() - forward.getFrontOffsetX() * up.getFrontOffsetZ(); + final int west_z = forward.getFrontOffsetX() * up.getFrontOffsetY() - forward.getFrontOffsetY() * up.getFrontOffsetX(); + + switch (west_x + west_y * 2 + west_z * 3) { + case 1: + return EnumFacing.EAST; + case -1: + return EnumFacing.WEST; + + case 2: + return EnumFacing.UP; + case -2: + return EnumFacing.DOWN; + + case 3: + return EnumFacing.SOUTH; + case -3: + return EnumFacing.NORTH; + } + + // something is better then nothing? + return EnumFacing.NORTH; + } + + public static T rotateEnum(T ce, final boolean backwards, final EnumSet validOptions) { + do { + if (backwards) { + ce = prevEnum(ce); + } else { + ce = nextEnum(ce); + } + } while (!validOptions.contains(ce) || isNotValidSetting(ce)); + + return ce; + } + + /* + * Simple way to cycle an enum... + */ + private static T prevEnum(final T ce) { + final EnumSet valList = EnumSet.allOf(ce.getClass()); + + int pLoc = ce.ordinal() - 1; + if (pLoc < 0) { + pLoc = valList.size() - 1; + } + + if (pLoc < 0 || pLoc >= valList.size()) { + pLoc = 0; + } + + int pos = 0; + for (final Object g : valList) { + if (pos == pLoc) { + return (T) g; + } + pos++; + } + + return null; + } + + /* + * Simple way to cycle an enum... + */ + public static T nextEnum(final T ce) { + final EnumSet valList = EnumSet.allOf(ce.getClass()); + + int pLoc = ce.ordinal() + 1; + if (pLoc >= valList.size()) { + pLoc = 0; + } + + if (pLoc < 0 || pLoc >= valList.size()) { + pLoc = 0; + } + + int pos = 0; + for (final Object g : valList) { + if (pos == pLoc) { + return (T) g; + } + pos++; + } + + return null; + } + + private static boolean isNotValidSetting(final Enum e) { + if (e == SortOrder.INVTWEAKS && !Integrations.invTweaks().isEnabled() && !InventoryBogoSortModule.isLoaded()) { + return true; + } + + final boolean isJEI = e == SearchBoxMode.JEI_AUTOSEARCH || e == SearchBoxMode.JEI_AUTOSEARCH_KEEP || e == SearchBoxMode.JEI_MANUAL_SEARCH || e == SearchBoxMode.JEI_MANUAL_SEARCH_KEEP; + return isJEI && !Integrations.jei().isEnabled(); + } + + public static void openGUI(@Nonnull final EntityPlayer p, @Nullable final TileEntity tile, @Nullable final AEPartLocation side, @Nonnull final GuiBridge type) { + if (isClient()) { + return; + } + + int x = (int) p.posX; + int y = (int) p.posY; + int z = (int) p.posZ; + if (tile != null) { + x = tile.getPos().getX(); + y = tile.getPos().getY(); + z = tile.getPos().getZ(); + } + + if ((type.getType().isItem() && tile == null) || type.hasPermissions(tile, x, y, z, side, p)) { + if (tile == null && type.getType() == GuiHostType.ITEM) { + p.openGui(AppEng.instance(), type.ordinal() << 4, p.getEntityWorld(), p.inventory.currentItem, 0, 0); + } else if (tile == null || type.getType() == GuiHostType.ITEM) { + p.openGui(AppEng.instance(), type.ordinal() << 4 | (1 << 3), p.getEntityWorld(), x, y, z); + } else { + p.openGui(AppEng.instance(), type.ordinal() << 4 | (side.ordinal()), tile.getWorld(), x, y, z); + } + } + } + + /* + * returns true if the code is on the client. + */ + public static boolean isClient() { + return FMLCommonHandler.instance().getEffectiveSide().isClient(); + } + + /* + * returns true if client classes are available. + */ + public static boolean isClientInstall() { + return CLIENT_INSTALL; + } + + public static boolean hasPermissions(final DimensionalCoord dc, final EntityPlayer player) { + return dc.getWorld().canMineBlockBody(player, dc.getPos()); + } + + /* + * Checks to see if a block is air? + */ + public static boolean isBlockAir(final World w, final BlockPos pos) { + try { + return w.getBlockState(pos).getBlock().isAir(w.getBlockState(pos), w, pos); + } catch (final Throwable e) { + return false; + } + } + + public static ItemStack[] getBlockDrops(final World w, final BlockPos pos) { + List out = new ArrayList<>(); + final IBlockState state = w.getBlockState(pos); + + if (state != null) { + out = state.getBlock().getDrops(w, pos, state, 0); + } + + if (out == null) { + return new ItemStack[0]; + } + return out.toArray(new ItemStack[out.size()]); + } + + public static AEPartLocation cycleOrientations(final AEPartLocation dir, final boolean upAndDown) { + if (upAndDown) { + switch (dir) { + case NORTH: + return AEPartLocation.SOUTH; + case SOUTH: + return AEPartLocation.EAST; + case EAST: + return AEPartLocation.WEST; + case WEST: + return AEPartLocation.NORTH; + case UP: + return AEPartLocation.UP; + case DOWN: + return AEPartLocation.DOWN; + case INTERNAL: + return AEPartLocation.INTERNAL; + } + } else { + switch (dir) { + case UP: + return AEPartLocation.DOWN; + case DOWN: + return AEPartLocation.NORTH; + case NORTH: + return AEPartLocation.SOUTH; + case SOUTH: + return AEPartLocation.EAST; + case EAST: + return AEPartLocation.WEST; + case WEST: + return AEPartLocation.UP; + case INTERNAL: + return AEPartLocation.INTERNAL; + } + } + + return AEPartLocation.INTERNAL; + } + + /* + * Creates / or loads previous NBT Data on items, used for editing items owned by AE. + */ + public static NBTTagCompound openNbtData(final ItemStack i) { + NBTTagCompound compound = i.getTagCompound(); + + if (compound == null) { + i.setTagCompound(compound = new NBTTagCompound()); + } + + return compound; + } + + /* + * Generates Item entities in the world similar to how items are generally dropped. + */ + public static void spawnDrops(final World w, final BlockPos pos, final List drops) { + if (isServer()) { + for (final ItemStack i : drops) { + if (!i.isEmpty()) { + if (i.getCount() > 0) { + final double offset_x = (getRandomInt() % 32 - 16) / 82; + final double offset_y = (getRandomInt() % 32 - 16) / 82; + final double offset_z = (getRandomInt() % 32 - 16) / 82; + final EntityItem ei = new EntityItem(w, 0.5 + offset_x + pos.getX(), 0.5 + offset_y + pos.getY(), 0.2 + offset_z + pos.getZ(), i.copy()); + w.spawnEntity(ei); + } + } + } + } + } + + /* + * returns true if the code is on the server. + */ + public static boolean isServer() { + return FMLCommonHandler.instance().getEffectiveSide().isServer(); + } + + public static int getRandomInt() { + return Math.abs(RANDOM_GENERATOR.nextInt()); + } + + public static boolean isModLoaded(final String modid) { + try { + // if this fails for some reason, try the other method. + return Loader.isModLoaded(modid); + } catch (final Throwable ignored) { + } + + for (final ModContainer f : Loader.instance().getActiveModList()) { + if (f.getModId().equals(modid)) { + return true; + } + } + return false; + } + + public static ItemStack findMatchingRecipeOutput(final InventoryCrafting ic, final World world) { + return CraftingManager.findMatchingResult(ic, world); + } + + @SideOnly(Side.CLIENT) + public static List getTooltip(final Object o) { + if (o == null) { + return new ArrayList<>(); + } + + ItemStack itemStack = ItemStack.EMPTY; + if (o instanceof AEItemStack) { + final AEItemStack ais = (AEItemStack) o; + return ais.getToolTip(); + } else if (o instanceof ItemStack) { + itemStack = (ItemStack) o; + } else { + return new ArrayList<>(); + } + + try { + ITooltipFlag.TooltipFlags tooltipFlag = Minecraft.getMinecraft().gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL; + return itemStack.getTooltip(Minecraft.getMinecraft().player, tooltipFlag); + } catch (final Exception errB) { + return new ArrayList<>(); + } + } + + public static String getModId(final IAEItemStack is) { + if (is == null) { + return "** Null"; + } + + final String n = ((AEItemStack) is).getModID(); + return n == null ? "** Null" : n; + } + + public static String getModId(final IAEFluidStack fs) { + if (fs == null || fs.getFluidStack() == null) { + return "** Null"; + } + + final String n = FluidRegistry.getModId(fs.getFluidStack()); + return n == null ? "** Null" : n; + } + + public static String getItemDisplayName(final Object o) { + if (o == null) { + return "** Null"; + } + + ItemStack itemStack = ItemStack.EMPTY; + if (o instanceof AEItemStack) { + final String n = ((AEItemStack) o).getDisplayName(); + return n == null ? "** Null" : n; + } else if (o instanceof ItemStack) { + itemStack = (ItemStack) o; + } else { + return "**Invalid Object"; + } + + try { + String name = itemStack.getDisplayName(); + if (name == null || name.isEmpty()) { + name = itemStack.getItem().getUnlocalizedName(itemStack); + } + return name == null ? "** Null" : name; + } catch (final Exception errA) { + try { + final String n = itemStack.getUnlocalizedName(); + return n == null ? "** Null" : n; + } catch (final Exception errB) { + return "** Exception"; + } + } + } + + public static String getFluidDisplayName(Object o) { + if (o == null) { + return "** Null"; + } + FluidStack fluidStack = null; + if (o instanceof AEFluidStack) { + fluidStack = ((AEFluidStack) o).getFluidStack(); + } else if (o instanceof FluidStack) { + fluidStack = (FluidStack) o; + } else { + return "**Invalid Object"; + } + String n = fluidStack.getLocalizedName(); + if (n == null || "".equalsIgnoreCase(n)) { + n = fluidStack.getUnlocalizedName(); + } + return n == null ? "** Null" : n; + } + + public static boolean isWrench(final EntityPlayer player, final ItemStack eq, final BlockPos pos) { + if (!eq.isEmpty()) { + try { + // TODO: Build Craft Wrench? + /* + * if( eq.getItem() instanceof IToolWrench ) + * { + * IToolWrench wrench = (IToolWrench) eq.getItem(); + * return wrench.canWrench( player, x, y, z ); + * } + */ + + if (eq.getItem() instanceof cofh.api.item.IToolHammer) { + return ((cofh.api.item.IToolHammer) eq.getItem()).isUsable(eq, player, pos); + } + } catch (final Throwable ignore) { // explodes without BC + + } + + if (eq.getItem() instanceof IAEWrench) { + final IAEWrench wrench = (IAEWrench) eq.getItem(); + return wrench.canWrench(eq, player, pos); + } + } + return false; + } + + public static boolean isChargeable(final ItemStack i) { + if (i.isEmpty()) { + return false; + } + final Item it = i.getItem(); + if (it instanceof IAEItemPowerStorage) { + return ((IAEItemPowerStorage) it).getPowerFlow(i) != AccessRestriction.READ; + } + return false; + } + + public static EntityPlayer getPlayer(final WorldServer w) { + if (w == null) { + throw new InvalidParameterException("World is null."); + } + + final EntityPlayer wrp = FAKE_PLAYERS.get(w); + if (wrp != null) { + return wrp; + } + + final EntityPlayer p = FakePlayerFactory.getMinecraft(w); + FAKE_PLAYERS.put(w, p); + return p; + } + + public static int MC2MEColor(final int color) { + switch (color) { + case 4: // "blue" + return 0; + case 0: // "black" + return 1; + case 15: // "white" + return 2; + case 3: // "brown" + return 3; + case 1: // "red" + return 4; + case 11: // "yellow" + return 5; + case 2: // "green" + return 6; + + case 5: // "purple" + case 6: // "cyan" + case 7: // "silver" + case 8: // "gray" + case 9: // "pink" + case 10: // "lime" + case 12: // "lightBlue" + case 13: // "magenta" + case 14: // "orange" + } + return -1; + } + + public static int findEmpty(final RegistryNamespaced registry, final int minId, final int maxId) { + for (int x = minId; x < maxId; x++) { + if (registry.getObjectById(x) == null) { + return x; + } + } + return -1; + } + + public static int findEmpty(final Object[] l) { + for (int x = 0; x < l.length; x++) { + if (l[x] == null) { + return x; + } + } + return -1; + } + + /** + * Returns a random element from the given collection. + * + * @return null if the collection is empty + */ + @Nullable + public static T pickRandom(final Collection outs) { + if (outs.isEmpty()) { + return null; + } + + int index = RANDOM_GENERATOR.nextInt(outs.size()); + return Iterables.get(outs, index, null); + } + + public static AEPartLocation rotateAround(final AEPartLocation forward, final AEPartLocation axis) { + if (axis == AEPartLocation.INTERNAL || forward == AEPartLocation.INTERNAL) { + return forward; + } + + switch (forward) { + case DOWN: + switch (axis) { + case DOWN: + return forward; + case UP: + return forward; + case NORTH: + return AEPartLocation.EAST; + case SOUTH: + return AEPartLocation.WEST; + case EAST: + return AEPartLocation.NORTH; + case WEST: + return AEPartLocation.SOUTH; + default: + break; + } + break; + case UP: + switch (axis) { + case NORTH: + return AEPartLocation.WEST; + case SOUTH: + return AEPartLocation.EAST; + case EAST: + return AEPartLocation.SOUTH; + case WEST: + return AEPartLocation.NORTH; + default: + break; + } + break; + case NORTH: + switch (axis) { + case UP: + return AEPartLocation.WEST; + case DOWN: + return AEPartLocation.EAST; + case EAST: + return AEPartLocation.UP; + case WEST: + return AEPartLocation.DOWN; + default: + break; + } + break; + case SOUTH: + switch (axis) { + case UP: + return AEPartLocation.EAST; + case DOWN: + return AEPartLocation.WEST; + case EAST: + return AEPartLocation.DOWN; + case WEST: + return AEPartLocation.UP; + default: + break; + } + break; + case EAST: + switch (axis) { + case UP: + return AEPartLocation.NORTH; + case DOWN: + return AEPartLocation.SOUTH; + case NORTH: + return AEPartLocation.UP; + case SOUTH: + return AEPartLocation.DOWN; + default: + break; + } + case WEST: + switch (axis) { + case UP: + return AEPartLocation.SOUTH; + case DOWN: + return AEPartLocation.NORTH; + case NORTH: + return AEPartLocation.DOWN; + case SOUTH: + return AEPartLocation.UP; + default: + break; + } + default: + break; + } + return forward; + } + + public static EnumFacing rotateAround(final EnumFacing forward, final EnumFacing axis) { + switch (forward) { + case DOWN: + switch (axis) { + case DOWN: + return forward; + case UP: + return forward; + case NORTH: + return EnumFacing.EAST; + case SOUTH: + return EnumFacing.WEST; + case EAST: + return EnumFacing.NORTH; + case WEST: + return EnumFacing.SOUTH; + default: + break; + } + break; + case UP: + switch (axis) { + case NORTH: + return EnumFacing.WEST; + case SOUTH: + return EnumFacing.EAST; + case EAST: + return EnumFacing.SOUTH; + case WEST: + return EnumFacing.NORTH; + default: + break; + } + break; + case NORTH: + switch (axis) { + case UP: + return EnumFacing.WEST; + case DOWN: + return EnumFacing.EAST; + case EAST: + return EnumFacing.UP; + case WEST: + return EnumFacing.DOWN; + default: + break; + } + break; + case SOUTH: + switch (axis) { + case UP: + return EnumFacing.EAST; + case DOWN: + return EnumFacing.WEST; + case EAST: + return EnumFacing.DOWN; + case WEST: + return EnumFacing.UP; + default: + break; + } + break; + case EAST: + switch (axis) { + case UP: + return EnumFacing.NORTH; + case DOWN: + return EnumFacing.SOUTH; + case NORTH: + return EnumFacing.UP; + case SOUTH: + return EnumFacing.DOWN; + default: + break; + } + case WEST: + switch (axis) { + case UP: + return EnumFacing.SOUTH; + case DOWN: + return EnumFacing.NORTH; + case NORTH: + return EnumFacing.DOWN; + case SOUTH: + return EnumFacing.UP; + default: + break; + } + default: + break; + } + return forward; + } + + @SideOnly(Side.CLIENT) + public static String gui_localize(final String string) { + return I18n.translateToLocal(string); + } + + public static LookDirection getPlayerRay(final EntityPlayer playerIn, final float eyeOffset) { + double reachDistance = 5.0d; + + final double x = playerIn.prevPosX + (playerIn.posX - playerIn.prevPosX); + final double y = playerIn.prevPosY + (playerIn.posY - playerIn.prevPosY) + playerIn.getEyeHeight(); + final double z = playerIn.prevPosZ + (playerIn.posZ - playerIn.prevPosZ); + + final float playerPitch = playerIn.prevRotationPitch + (playerIn.rotationPitch - playerIn.prevRotationPitch); + final float playerYaw = playerIn.prevRotationYaw + (playerIn.rotationYaw - playerIn.prevRotationYaw); + + final float yawRayX = MathHelper.sin(-playerYaw * 0.017453292f - (float) Math.PI); + final float yawRayZ = MathHelper.cos(-playerYaw * 0.017453292f - (float) Math.PI); + + final float pitchMultiplier = -MathHelper.cos(-playerPitch * 0.017453292F); + final float eyeRayY = MathHelper.sin(-playerPitch * 0.017453292F); + final float eyeRayX = yawRayX * pitchMultiplier; + final float eyeRayZ = yawRayZ * pitchMultiplier; + + if (playerIn instanceof EntityPlayerMP) { + reachDistance = ((EntityPlayerMP) playerIn).interactionManager.getBlockReachDistance(); + } + + final Vec3d from = new Vec3d(x, y, z); + final Vec3d to = from.addVector(eyeRayX * reachDistance, eyeRayY * reachDistance, eyeRayZ * reachDistance); + + return new LookDirection(from, to); + } + + public static RayTraceResult rayTrace(final EntityPlayer p, final boolean hitBlocks, final boolean hitEntities) { + final World w = p.getEntityWorld(); + + final float f = 1.0F; + float f1 = p.prevRotationPitch + (p.rotationPitch - p.prevRotationPitch) * f; + final float f2 = p.prevRotationYaw + (p.rotationYaw - p.prevRotationYaw) * f; + final double d0 = p.prevPosX + (p.posX - p.prevPosX) * f; + final double d1 = p.prevPosY + (p.posY - p.prevPosY) * f + 1.62D - p.getYOffset(); + final double d2 = p.prevPosZ + (p.posZ - p.prevPosZ) * f; + final Vec3d vec3 = new Vec3d(d0, d1, d2); + final float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); + final float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); + final float f5 = -MathHelper.cos(-f1 * 0.017453292F); + final float f6 = MathHelper.sin(-f1 * 0.017453292F); + final float f7 = f4 * f5; + final float f8 = f3 * f5; + final double d3 = 32.0D; + + final Vec3d vec31 = vec3.addVector(f7 * d3, f6 * d3, f8 * d3); + + final AxisAlignedBB bb = new AxisAlignedBB(Math.min(vec3.x, vec31.x), Math.min(vec3.y, vec31.y), Math.min(vec3.z, vec31.z), Math.max(vec3.x, vec31.x), Math.max(vec3.y, vec31.y), Math.max(vec3.z, vec31.z)).grow(16, 16, 16); + + Entity entity = null; + double closest = 9999999.0D; + if (hitEntities) { + final List list = w.getEntitiesWithinAABBExcludingEntity(p, bb); + + for (int l = 0; l < list.size(); ++l) { + final Entity entity1 = (Entity) list.get(l); + + if (!entity1.isDead && entity1 != p && !(entity1 instanceof EntityItem)) { + if (entity1.isEntityAlive()) { + // prevent killing / flying of mounts. + if (entity1.isRidingOrBeingRiddenBy(p)) { + continue; + } + + f1 = 0.3F; + final AxisAlignedBB boundingBox = entity1.getEntityBoundingBox().grow(f1, f1, f1); + final RayTraceResult RayTraceResult = boundingBox.calculateIntercept(vec3, vec31); + + if (RayTraceResult != null) { + final double nd = vec3.squareDistanceTo(RayTraceResult.hitVec); + + if (nd < closest) { + entity = entity1; + closest = nd; + } + } + } + } + } + } + + RayTraceResult pos = null; + Vec3d vec = null; + + if (hitBlocks) { + vec = new Vec3d(d0, d1, d2); + pos = w.rayTraceBlocks(vec3, vec31, true); + } + + if (entity != null && pos != null && pos.hitVec.squareDistanceTo(vec) > closest) { + pos = new RayTraceResult(entity); + } else if (entity != null && pos == null) { + pos = new RayTraceResult(entity); + } + + return pos; + } + + public static > T poweredExtraction(final IEnergySource energy, final IMEInventory cell, final T request, final IActionSource src) { + return poweredExtraction(energy, cell, request, src, Actionable.MODULATE); + } + + public static > T poweredExtraction(final IEnergySource energy, final IMEInventory cell, final T request, final IActionSource src, final Actionable mode) { + Preconditions.checkNotNull(energy); + Preconditions.checkNotNull(cell); + Preconditions.checkNotNull(request); + Preconditions.checkNotNull(src); + Preconditions.checkNotNull(mode); + + final T possible = cell.extractItems(request.copy(), Actionable.SIMULATE, src); + + long retrieved = 0; + if (possible != null) { + retrieved = possible.getStackSize(); + } + + final double energyFactor = Math.max(1.0, cell.getChannel().transferFactor()); + final double availablePower = energy.extractAEPower(retrieved / energyFactor, Actionable.SIMULATE, PowerMultiplier.CONFIG); + final long itemToExtract = Math.min((long) ((availablePower * energyFactor) + 0.9), retrieved); + + if (itemToExtract > 0) { + if (mode == Actionable.MODULATE) { + energy.extractAEPower(retrieved / energyFactor, Actionable.MODULATE, PowerMultiplier.CONFIG); + possible.setStackSize(itemToExtract); + final T ret = cell.extractItems(possible, Actionable.MODULATE, src); + + if (ret != null) { + src.player().ifPresent(player -> Stats.ItemsExtracted.addToPlayer(player, (int) ret.getStackSize())); + } + return ret; + } else { + return possible.setStackSize(itemToExtract); + } + } + + return null; + } + + public static > T poweredInsert(final IEnergySource energy, final IMEInventory cell, final T input, final IActionSource src) { + return poweredInsert(energy, cell, input, src, Actionable.MODULATE); + } + + public static > T poweredInsert(final IEnergySource energy, final IMEInventory cell, final T input, final IActionSource src, final Actionable mode) { + Preconditions.checkNotNull(energy); + Preconditions.checkNotNull(cell); + Preconditions.checkNotNull(input); + Preconditions.checkNotNull(src); + Preconditions.checkNotNull(mode); + + final T possible = cell.injectItems(input, Actionable.SIMULATE, src); + + long stored = input.getStackSize(); + if (possible != null) { + stored -= possible.getStackSize(); + } + + final double energyFactor = Math.max(1.0, cell.getChannel().transferFactor()); + final double availablePower = energy.extractAEPower(stored / energyFactor, Actionable.SIMULATE, PowerMultiplier.CONFIG); + final long itemToAdd = Math.min((long) ((availablePower * energyFactor) + 0.9), stored); + + if (itemToAdd > 0) { + if (mode == Actionable.MODULATE) { + energy.extractAEPower(stored / energyFactor, Actionable.MODULATE, PowerMultiplier.CONFIG); + if (itemToAdd < input.getStackSize()) { + final long original = input.getStackSize(); + final T leftover = input.copy(); + final T split = input.copy(); + + leftover.decStackSize(itemToAdd); + split.setStackSize(itemToAdd); + leftover.add(cell.injectItems(split, Actionable.MODULATE, src)); + + src.player().ifPresent(player -> + { + final long diff = original - leftover.getStackSize(); + Stats.ItemsInserted.addToPlayer(player, (int) diff); + }); + + return leftover; + } + + final T ret = cell.injectItems(input, Actionable.MODULATE, src); + + src.player().ifPresent(player -> + { + final long diff = ret == null ? input.getStackSize() : input.getStackSize() - ret.getStackSize(); + Stats.ItemsInserted.addToPlayer(player, (int) diff); + }); + + return ret; + } else { + final T ret = input.copy().setStackSize(input.getStackSize() - itemToAdd); + return (ret != null && ret.getStackSize() > 0) ? ret : null; + } + } + + return input; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static void postChanges(final IStorageGrid gs, final ItemStack removed, final ItemStack added, final IActionSource src) { + for (final IStorageChannel chan : AEApi.instance().storage().storageChannels()) { + final IItemList myChanges = chan.createList(); + + if (!removed.isEmpty()) { + final IMEInventory myInv = AEApi.instance().registries().cell().getCellInventory(removed, null, chan); + if (myInv != null) { + myInv.getAvailableItems(myChanges); + for (final IAEStack is : myChanges) { + is.setStackSize(-is.getStackSize()); + } + } + } + if (!added.isEmpty()) { + final IMEInventory myInv = AEApi.instance().registries().cell().getCellInventory(added, null, chan); + if (myInv != null) { + myInv.getAvailableItems(myChanges); + } + + } + gs.postAlterationOfStoredItems(chan, myChanges, src); + } + } + + public static > void postListChanges(final IItemList before, final IItemList after, final IMEMonitorHandlerReceiver meMonitorPassthrough, final IActionSource source) { + final List changes = new ArrayList<>(); + + for (final T is : before) { + is.setStackSize(-is.getStackSize()); + } + + for (final T is : after) { + before.add(is); + } + + for (final T is : before) { + if (is.getStackSize() != 0) { + changes.add(is); + } + } + + if (!changes.isEmpty()) { + meMonitorPassthrough.postChange(null, changes, source); + } + } + + public static boolean securityCheck(final GridNode a, final GridNode b) { + if (a.getLastSecurityKey() == -1 && b.getLastSecurityKey() == -1) { + return true; + } else if (a.getLastSecurityKey() == b.getLastSecurityKey()) { + return true; + } + + final boolean a_isSecure = isPowered(a.getGrid()) && a.getLastSecurityKey() != -1; + final boolean b_isSecure = isPowered(b.getGrid()) && b.getLastSecurityKey() != -1; + + if (AEConfig.instance().isFeatureEnabled(AEFeature.LOG_SECURITY_AUDITS)) { + final String locationA = a.getGridBlock().isWorldAccessible() ? a.getGridBlock().getLocation().toString() : "notInWorld"; + final String locationB = b.getGridBlock().isWorldAccessible() ? b.getGridBlock().getLocation().toString() : "notInWorld"; + + AELog.info("Audit: Node A [isSecure=%b, key=%d, playerID=%d, location={%s}] vs Node B[isSecure=%b, key=%d, playerID=%d, location={%s}]", a_isSecure, a.getLastSecurityKey(), a.getPlayerID(), locationA, b_isSecure, b.getLastSecurityKey(), b.getPlayerID(), locationB); + } + + // can't do that son... + if (a_isSecure && b_isSecure) { + return false; + } + + if (!a_isSecure && b_isSecure) { + return checkPlayerPermissions(b.getGrid(), a.getPlayerID()); + } + + if (a_isSecure && !b_isSecure) { + return checkPlayerPermissions(a.getGrid(), b.getPlayerID()); + } + + return true; + } + + private static boolean isPowered(final IGrid grid) { + if (grid == null) { + return false; + } + + final IEnergyGrid eg = grid.getCache(IEnergyGrid.class); + return eg.isNetworkPowered(); + } + + private static boolean checkPlayerPermissions(final IGrid grid, final int playerID) { + if (grid == null) { + return true; + } + + final ISecurityGrid gs = grid.getCache(ISecurityGrid.class); + + if (gs == null) { + return true; + } + + if (!gs.isAvailable()) { + return true; + } + + return gs.hasPermission(playerID, SecurityPermissions.BUILD); + } + + public static void configurePlayer(final EntityPlayer player, final AEPartLocation side, final TileEntity tile) { + float pitch = 0.0f; + float yaw = 0.0f; + // player.yOffset = 1.8f; + + switch (side) { + case DOWN: + pitch = 90.0f; + // player.getYOffset() = -1.8f; + break; + case EAST: + yaw = -90.0f; + break; + case NORTH: + yaw = 180.0f; + break; + case SOUTH: + yaw = 0.0f; + break; + case INTERNAL: + break; + case UP: + pitch = 90.0f; + break; + case WEST: + yaw = 90.0f; + break; + } + + player.posX = tile.getPos().getX() + 0.5; + player.posY = tile.getPos().getY() + 0.5; + player.posZ = tile.getPos().getZ() + 0.5; + + player.rotationPitch = player.prevCameraPitch = player.cameraPitch = pitch; + player.rotationYaw = player.prevCameraYaw = player.cameraYaw = yaw; + } + + public static boolean canAccess(final AENetworkProxy gridProxy, final IActionSource src) { + try { + if (src.player().isPresent()) { + return gridProxy.getSecurity().hasPermission(src.player().get(), SecurityPermissions.BUILD); + } else if (src.machine().isPresent()) { + final IActionHost te = src.machine().get(); + final IGridNode n = te.getActionableNode(); + if (n == null) { + return false; + } + + final int playerID = n.getPlayerID(); + return gridProxy.getSecurity().hasPermission(playerID, SecurityPermissions.BUILD); + } else { + return false; + } + } catch (final GridAccessException gae) { + return false; + } + } + + public static ItemStack extractItemsByRecipe(final IEnergySource energySrc, final IActionSource mySrc, final IMEMonitor src, final World w, final IRecipe r, final ItemStack output, final InventoryCrafting ci, final ItemStack providedTemplate, final int slot, final IItemList items, final Actionable realForFake, final IPartitionList filter) { + if (energySrc.extractAEPower(1, Actionable.SIMULATE, PowerMultiplier.CONFIG) > 0.9) { + if (providedTemplate == null) { + return ItemStack.EMPTY; + } + + final AEItemStack ae_req = AEItemStack.fromItemStack(providedTemplate); + ae_req.setStackSize(1); + + if (filter == null || filter.isListed(ae_req)) { + final IAEItemStack ae_ext = src.extractItems(ae_req, realForFake, mySrc); + if (ae_ext != null) { + final ItemStack extracted = ae_ext.createItemStack(); + if (!extracted.isEmpty()) { + energySrc.extractAEPower(1, realForFake, PowerMultiplier.CONFIG); + return extracted; + } + } + } + + final boolean checkFuzzy = ae_req.getOre().isPresent() || providedTemplate.getItemDamage() == OreDictionary.WILDCARD_VALUE || providedTemplate.hasTagCompound() || providedTemplate.isItemStackDamageable(); + + if (items != null && checkFuzzy) { + for (final IAEItemStack x : items) { + final ItemStack sh = x.getDefinition(); + if ((Platform.itemComparisons().isEqualItemType(providedTemplate, sh) || ae_req.sameOre(x)) && !ItemStack.areItemsEqual(sh, output)) { // Platform.isSameItemType( sh, providedTemplate ) + final ItemStack cp = sh.copy(); + cp.setCount(1); + ci.setInventorySlotContents(slot, cp); + if (r.matches(ci, w) && ItemStack.areItemsEqual(r.getCraftingResult(ci), output)) { + final IAEItemStack ax = x.copy(); + ax.setStackSize(1); + if (filter == null || filter.isListed(ax)) { + final IAEItemStack ex = src.extractItems(ax, realForFake, mySrc); + if (ex != null) { + energySrc.extractAEPower(1, realForFake, PowerMultiplier.CONFIG); + return ex.createItemStack(); + } + } + } + ci.setInventorySlotContents(slot, providedTemplate); + } + } + } + } + return ItemStack.EMPTY; + } + + // TODO wtf is this? + public static ItemStack getContainerItem(final ItemStack stackInSlot) { + if (stackInSlot == null) { + return ItemStack.EMPTY; + } + + final Item i = stackInSlot.getItem(); + if (i == null || !i.hasContainerItem(stackInSlot)) { + if (stackInSlot.getCount() > 1) { + stackInSlot.setCount(stackInSlot.getCount() - 1); + return stackInSlot; + } + return ItemStack.EMPTY; + } + + ItemStack ci = i.getContainerItem(stackInSlot.copy()); + if (!ci.isEmpty() && ci.isItemStackDamageable() && ci.getItemDamage() == ci.getMaxDamage()) { + ci = ItemStack.EMPTY; + } + + return ci; + } + + public static void notifyBlocksOfNeighbors(final World world, final BlockPos pos) { + if (!world.isRemote) { + TickHandler.INSTANCE.addCallable(world, new BlockUpdate(pos)); + } + } + + public static boolean canRepair(final AEFeature type, final ItemStack a, final ItemStack b) { + if (b.isEmpty() || a.isEmpty()) { + return false; + } + + if (type == AEFeature.CERTUS_QUARTZ_TOOLS) { + final IItemDefinition certusQuartzCrystal = AEApi.instance().definitions().materials().certusQuartzCrystal(); + + return certusQuartzCrystal.isSameAs(b); + } + + if (type == AEFeature.NETHER_QUARTZ_TOOLS) { + return Items.QUARTZ == b.getItem(); + } + + return false; + } + + public static List findPreferred(final ItemStack[] is) { + final IParts parts = AEApi.instance().definitions().parts(); + + for (final ItemStack stack : is) { + if (parts.cableGlass().sameAs(AEColor.TRANSPARENT, stack)) { + return Collections.singletonList(stack); + } + + if (parts.cableCovered().sameAs(AEColor.TRANSPARENT, stack)) { + return Collections.singletonList(stack); + } + + if (parts.cableSmart().sameAs(AEColor.TRANSPARENT, stack)) { + return Collections.singletonList(stack); + } + + if (parts.cableDenseSmart().sameAs(AEColor.TRANSPARENT, stack)) { + return Collections.singletonList(stack); + } + } + + return Lists.newArrayList(is); + } + + public static void sendChunk(final Chunk c, final int verticalBits) { + try { + final WorldServer ws = (WorldServer) c.getWorld(); + final PlayerChunkMap pm = ws.getPlayerChunkMap(); + final PlayerChunkMapEntry playerInstance = pm.getEntry(c.x, c.z); + + if (playerInstance != null) { + playerInstance.sendPacket(new SPacketChunkData(c, verticalBits)); + } + } catch (final Throwable t) { + AELog.debug(t); + } + } + + public static float getEyeOffset(final EntityPlayer player) { + assert player.world.isRemote : "Valid only on client"; + return (float) (player.posY + player.getEyeHeight() - player.getDefaultEyeHeight()); + } + + // public static void addStat( final int playerID, final Achievement achievement ) + // { + // final EntityPlayer p = AEApi.instance().registries().players().findPlayer( playerID ); + // if( p != null ) + // { + // p.addStat( achievement, 1 ); + // } + // } + + public static boolean isRecipePrioritized(final ItemStack what) { + final IMaterials materials = AEApi.instance().definitions().materials(); + + boolean isPurified = materials.purifiedCertusQuartzCrystal().isSameAs(what); + isPurified |= materials.purifiedFluixCrystal().isSameAs(what); + isPurified |= materials.purifiedNetherQuartzCrystal().isSameAs(what); + + return isPurified; + } + + //consider methods below moving to a compability class + public static boolean isGTDamageableItem(Item item) { + return (isModLoaded("gregtech") && item instanceof IToolItem); + } + + public static MetaTileEntity getMetaTileEntity(IBlockAccess world, BlockPos pos) { + if (reflectGTgetMTE == null) { + try { + reflectGTgetMTE = ReflectionHelper.findMethod(BlockMachine.class, "getMetaTileEntity", null, IBlockAccess.class, BlockPos.class); + } catch (ReflectionHelper.UnableToFindMethodException e) { + reflectGTgetMTE = ReflectionHelper.findMethod(GTUtility.class, "getMetaTileEntity", null, IBlockAccess.class, BlockPos.class); + } + } else { + try { + return (MetaTileEntity) reflectGTgetMTE.invoke(reflectGTgetMTE, world, pos); + } catch (IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + } + return null; + } + + public static boolean isIC2DamageableItem(Item item) { + return (isModLoaded("IC2") && item instanceof ICustomDamageItem); + } } diff --git a/src/main/java/appeng/util/ReadOnlyCollection.java b/src/main/java/appeng/util/ReadOnlyCollection.java index 5499a93a7..7340ef0ed 100644 --- a/src/main/java/appeng/util/ReadOnlyCollection.java +++ b/src/main/java/appeng/util/ReadOnlyCollection.java @@ -19,43 +19,37 @@ package appeng.util; +import appeng.api.util.IReadOnlyCollection; + import java.util.Collection; import java.util.Iterator; -import appeng.api.util.IReadOnlyCollection; +public class ReadOnlyCollection implements IReadOnlyCollection { -public class ReadOnlyCollection implements IReadOnlyCollection -{ + private final Collection c; - private final Collection c; + public ReadOnlyCollection(final Collection in) { + this.c = in; + } - public ReadOnlyCollection( final Collection in ) - { - this.c = in; - } + @Override + public Iterator iterator() { + return this.c.iterator(); + } - @Override - public Iterator iterator() - { - return this.c.iterator(); - } + @Override + public int size() { + return this.c.size(); + } - @Override - public int size() - { - return this.c.size(); - } + @Override + public boolean isEmpty() { + return this.c.isEmpty(); + } - @Override - public boolean isEmpty() - { - return this.c.isEmpty(); - } - - @Override - public boolean contains( final Object node ) - { - return this.c.contains( (T) node ); - } + @Override + public boolean contains(final Object node) { + return this.c.contains((T) node); + } } diff --git a/src/main/java/appeng/util/ReadableNumberConverter.java b/src/main/java/appeng/util/ReadableNumberConverter.java index 405910d4f..0bf663656 100644 --- a/src/main/java/appeng/util/ReadableNumberConverter.java +++ b/src/main/java/appeng/util/ReadableNumberConverter.java @@ -32,93 +32,85 @@ import java.text.Format; * @version rv2 * @since rv2 */ -public enum ReadableNumberConverter implements ISlimReadableNumberConverter, IWideReadableNumberConverter -{ - INSTANCE; +public enum ReadableNumberConverter implements ISlimReadableNumberConverter, IWideReadableNumberConverter { + INSTANCE; - /** - * Defines the base for a division, non-si standard could be 1024 for kilobytes - */ - private static final int DIVISION_BASE = 1000; + /** + * Defines the base for a division, non-si standard could be 1024 for kilobytes + */ + private static final int DIVISION_BASE = 1000; - /** - * String representation of the sorted postfixes - */ - private static final char[] ENCODED_POSTFIXES = "KMGTPE".toCharArray(); + /** + * String representation of the sorted postfixes + */ + private static final char[] ENCODED_POSTFIXES = "KMGTPE".toCharArray(); - private final Format format; + private final Format format; - /** - * Initializes the specific decimal format with special format for negative and positive numbers - */ - ReadableNumberConverter() - { - final DecimalFormatSymbols symbols = new DecimalFormatSymbols(); - symbols.setDecimalSeparator( '.' ); - final DecimalFormat format = new DecimalFormat( ".#;0.#" ); - format.setDecimalFormatSymbols( symbols ); - format.setRoundingMode( RoundingMode.DOWN ); + /** + * Initializes the specific decimal format with special format for negative and positive numbers + */ + ReadableNumberConverter() { + final DecimalFormatSymbols symbols = new DecimalFormatSymbols(); + symbols.setDecimalSeparator('.'); + final DecimalFormat format = new DecimalFormat(".#;0.#"); + format.setDecimalFormatSymbols(symbols); + format.setRoundingMode(RoundingMode.DOWN); - this.format = format; - } + this.format = format; + } - @Override - public String toSlimReadableForm( final long number ) - { - return this.toReadableFormRestrictedByWidth( number, 3 ); - } + @Override + public String toSlimReadableForm(final long number) { + return this.toReadableFormRestrictedByWidth(number, 3); + } - /** - * restricts a string representation of a number to a specific width - * - * @param number to be formatted number - * @param width width limitation of the resulting number - * - * @return formatted number restricted by the width limitation - */ - private String toReadableFormRestrictedByWidth( final long number, final int width ) - { - assert number >= 0; + /** + * restricts a string representation of a number to a specific width + * + * @param number to be formatted number + * @param width width limitation of the resulting number + * @return formatted number restricted by the width limitation + */ + private String toReadableFormRestrictedByWidth(final long number, final int width) { + assert number >= 0; - // handles low numbers more efficiently since no format is needed - final String numberString = Long.toString( number ); - int numberSize = numberString.length(); - if( numberSize <= width ) - { - return numberString; - } + // handles low numbers more efficiently since no format is needed + final String numberString = Long.toString(number); + int numberSize = numberString.length(); + if (numberSize <= width) { + return numberString; + } - long base = number; - double last = base * 1000; - int exponent = -1; - String postFix = ""; + long base = number; + double last = base * 1000; + int exponent = -1; + String postFix = ""; - while( numberSize > width ) - { - last = base; - base /= DIVISION_BASE; + while (numberSize > width) { + last = base; + base /= DIVISION_BASE; - exponent++; + exponent++; - // adds +1 due to the postfix - numberSize = Long.toString( base ).length() + 1; - postFix = String.valueOf( ENCODED_POSTFIXES[exponent] ); - } + // adds +1 due to the postfix + numberSize = Long.toString(base).length() + 1; + postFix = String.valueOf(ENCODED_POSTFIXES[exponent]); + } - final String withPrecision = this.format.format( last / DIVISION_BASE ) + postFix; - final String withoutPrecision = Long.toString( base ) + postFix; + final String withPrecision = this.format.format(last / DIVISION_BASE) + postFix; + final String withoutPrecision = base + postFix; - final String slimResult = ( withPrecision.length() <= width ) ? withPrecision : withoutPrecision; + final String slimResult = (withPrecision.length() <= width) ? withPrecision : withoutPrecision; - // post condition - assert slimResult.length() <= width; + // post condition + assert slimResult.length() <= width; - return slimResult; - } + return slimResult; + } - @Override - public String toWideReadableForm( final long number ) - { - return this.toReadableFormRestrictedByWidth( number, 4 ); - } + @Override + public String toWideReadableForm(final long number) { + return this.toReadableFormRestrictedByWidth(number, 4); + } } diff --git a/src/main/java/appeng/util/SettingsFrom.java b/src/main/java/appeng/util/SettingsFrom.java index f187f9948..4197c422f 100644 --- a/src/main/java/appeng/util/SettingsFrom.java +++ b/src/main/java/appeng/util/SettingsFrom.java @@ -19,11 +19,10 @@ package appeng.util; -public enum SettingsFrom -{ - // moved the item, and replaced it. - DISMANTLE_ITEM, +public enum SettingsFrom { + // moved the item, and replaced it. + DISMANTLE_ITEM, - // used memory card? - MEMORY_CARD + // used memory card? + MEMORY_CARD } diff --git a/src/main/java/appeng/util/UUIDMatcher.java b/src/main/java/appeng/util/UUIDMatcher.java index 2a6c92353..7513f545f 100644 --- a/src/main/java/appeng/util/UUIDMatcher.java +++ b/src/main/java/appeng/util/UUIDMatcher.java @@ -25,27 +25,24 @@ import java.util.regex.Pattern; /** * Regex wrapper for {@link java.util.UUID}s to not rely on try catch */ -public final class UUIDMatcher -{ - /** - * String which is the regular expression for {@link java.util.UUID}s - */ - private static final String UUID_REGEX = "[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"; +public final class UUIDMatcher { + /** + * String which is the regular expression for {@link java.util.UUID}s + */ + private static final String UUID_REGEX = "[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"; - /** - * Pattern which pre-compiles the {@link appeng.util.UUIDMatcher#UUID_REGEX} - */ - private static final Pattern PATTERN = Pattern.compile( UUID_REGEX ); + /** + * Pattern which pre-compiles the {@link appeng.util.UUIDMatcher#UUID_REGEX} + */ + private static final Pattern PATTERN = Pattern.compile(UUID_REGEX); - /** - * Checks if a potential {@link java.util.UUID} is an {@link java.util.UUID} by applying a regular expression on it. - * - * @param potential to be checked potential {@link java.util.UUID} - * - * @return true, if the potential {@link java.util.UUID} is indeed an {@link java.util.UUID} - */ - public boolean isUUID( final CharSequence potential ) - { - return PATTERN.matcher( potential ).matches(); - } + /** + * Checks if a potential {@link java.util.UUID} is an {@link java.util.UUID} by applying a regular expression on it. + * + * @param potential to be checked potential {@link java.util.UUID} + * @return true, if the potential {@link java.util.UUID} is indeed an {@link java.util.UUID} + */ + public boolean isUUID(final CharSequence potential) { + return PATTERN.matcher(potential).matches(); + } } diff --git a/src/main/java/appeng/util/helpers/ItemComparisonHelper.java b/src/main/java/appeng/util/helpers/ItemComparisonHelper.java index b65c50f03..e6094f202 100644 --- a/src/main/java/appeng/util/helpers/ItemComparisonHelper.java +++ b/src/main/java/appeng/util/helpers/ItemComparisonHelper.java @@ -19,142 +19,120 @@ package appeng.util.helpers; -import javax.annotation.Nonnull; - +import appeng.api.config.FuzzyMode; +import appeng.util.item.OreHelper; +import appeng.util.item.OreReference; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTBase; import net.minecraftforge.oredict.OreDictionary; -import appeng.api.config.FuzzyMode; -import appeng.util.item.OreHelper; -import appeng.util.item.OreReference; +import javax.annotation.Nonnull; /** * A helper class for comparing {@link Item}, {@link ItemStack} or NBT - * */ -public class ItemComparisonHelper -{ +public class ItemComparisonHelper { - /** - * Compare the two {@link ItemStack}s based on the same {@link Item} and damage value. - * - * In case of the item being damageable, only the {@link Item} will be considered. - * If not it will also compare both damage values. - * - * Ignores NBT. - * - * @return true, if both are equal. - */ - public boolean isEqualItemType( @Nonnull final ItemStack that, @Nonnull final ItemStack other ) - { - if( !that.isEmpty() && !other.isEmpty() && that.getItem() == other.getItem() ) - { - if( that.isItemStackDamageable() ) - { - return true; - } - return that.getItemDamage() == other.getItemDamage(); - } - return false; - } + /** + * Compare the two {@link ItemStack}s based on the same {@link Item} and damage value. + *

+ * In case of the item being damageable, only the {@link Item} will be considered. + * If not it will also compare both damage values. + *

+ * Ignores NBT. + * + * @return true, if both are equal. + */ + public boolean isEqualItemType(@Nonnull final ItemStack that, @Nonnull final ItemStack other) { + if (!that.isEmpty() && !other.isEmpty() && that.getItem() == other.getItem()) { + if (that.isItemStackDamageable()) { + return true; + } + return that.getItemDamage() == other.getItemDamage(); + } + return false; + } - /** - * Compares two {@link ItemStack} and their NBT tag for equality. - * - * Use this when a precise check is required and the same item is required. - * Not just something with different NBT tags. - * - * @return true, if both are identical. - */ - public boolean isSameItem( @Nonnull final ItemStack is, @Nonnull final ItemStack filter ) - { - return ItemStack.areItemsEqual( is, filter ) && this.isNbtTagEqual( is.getTagCompound(), filter.getTagCompound() ); - } + /** + * Compares two {@link ItemStack} and their NBT tag for equality. + *

+ * Use this when a precise check is required and the same item is required. + * Not just something with different NBT tags. + * + * @return true, if both are identical. + */ + public boolean isSameItem(@Nonnull final ItemStack is, @Nonnull final ItemStack filter) { + return ItemStack.areItemsEqual(is, filter) && this.isNbtTagEqual(is.getTagCompound(), filter.getTagCompound()); + } - /** - * Similar to {@link ItemComparisonHelper#isEqualItem(ItemStack, ItemStack)}, - * but it can further check, if both match the same {@link FuzzyMode} - * or are considered equal by the {@link OreDictionary} - * - * @param mode how to compare the two {@link ItemStack}s - * @return true, if both are matching the mode or considered equal by the {@link OreDictionary} - */ - public boolean isFuzzyEqualItem( final ItemStack a, final ItemStack b, final FuzzyMode mode ) - { - if( a.isEmpty() && b.isEmpty() ) - { - return true; - } + /** + * Similar to {@link ItemComparisonHelper#isEqualItem(ItemStack, ItemStack)}, + * but it can further check, if both match the same {@link FuzzyMode} + * or are considered equal by the {@link OreDictionary} + * + * @param mode how to compare the two {@link ItemStack}s + * @return true, if both are matching the mode or considered equal by the {@link OreDictionary} + */ + public boolean isFuzzyEqualItem(final ItemStack a, final ItemStack b, final FuzzyMode mode) { + if (a.isEmpty() && b.isEmpty()) { + return true; + } - if( a.isEmpty() || b.isEmpty() ) - { - return false; - } + if (a.isEmpty() || b.isEmpty()) { + return false; + } - // test damageable items.. - if( a.getItem() == b.getItem() && a.getItem().isDamageable() ) - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - return true; - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - return ( a.getItemDamage() > 1 ) == ( b.getItemDamage() > 1 ); - } - else - { - final float percentDamagedOfA = (float) a.getItemDamage() / (float) a.getMaxDamage(); - final float percentDamagedOfB = (float) b.getItemDamage() / (float) b.getMaxDamage(); + // test damageable items.. + if (a.getItem() == b.getItem() && a.getItem().isDamageable()) { + if (mode == FuzzyMode.IGNORE_ALL) { + return true; + } else if (mode == FuzzyMode.PERCENT_99) { + return (a.getItemDamage() > 1) == (b.getItemDamage() > 1); + } else { + final float percentDamagedOfA = (float) a.getItemDamage() / (float) a.getMaxDamage(); + final float percentDamagedOfB = (float) b.getItemDamage() / (float) b.getMaxDamage(); - return ( percentDamagedOfA > mode.breakPoint ) == ( percentDamagedOfB > mode.breakPoint ); - } - } + return (percentDamagedOfA > mode.breakPoint) == (percentDamagedOfB > mode.breakPoint); + } + } - final OreReference aOR = OreHelper.INSTANCE.getOre( a ).orElse( null ); - final OreReference bOR = OreHelper.INSTANCE.getOre( b ).orElse( null ); + final OreReference aOR = OreHelper.INSTANCE.getOre(a).orElse(null); + final OreReference bOR = OreHelper.INSTANCE.getOre(b).orElse(null); - if( OreHelper.INSTANCE.sameOre( aOR, bOR ) ) - { - return true; - } + if (OreHelper.INSTANCE.sameOre(aOR, bOR)) { + return true; + } - return a.isItemEqual( b ); - } + return a.isItemEqual(b); + } - /** - * recursive test for NBT Equality, this was faster then trying to compare / generate hashes, its also more reliable - * then the vanilla version which likes to fail when NBT Compound data changes order, it is pretty expensive - * performance wise, so try an use shared tag compounds as long as the system remains in AE. - */ - public boolean isNbtTagEqual( final NBTBase left, final NBTBase right ) - { - if( left == right ) - { - return true; - } + /** + * recursive test for NBT Equality, this was faster then trying to compare / generate hashes, its also more reliable + * then the vanilla version which likes to fail when NBT Compound data changes order, it is pretty expensive + * performance wise, so try an use shared tag compounds as long as the system remains in AE. + */ + public boolean isNbtTagEqual(final NBTBase left, final NBTBase right) { + if (left == right) { + return true; + } - final boolean isLeftEmpty = left == null || left.hasNoTags(); - final boolean isRightEmpty = right == null || right.hasNoTags(); + final boolean isLeftEmpty = left == null || left.hasNoTags(); + final boolean isRightEmpty = right == null || right.hasNoTags(); - if( isLeftEmpty && isRightEmpty ) - { - return true; - } + if (isLeftEmpty && isRightEmpty) { + return true; + } - if( isLeftEmpty != isRightEmpty ) - { - return false; - } + if (isLeftEmpty != isRightEmpty) { + return false; + } - if( left != null ) - { - return left.equals( right ); - } + if (left != null) { + return left.equals(right); + } - return false; - } + return false; + } } diff --git a/src/main/java/appeng/util/helpers/ItemHandlerUtil.java b/src/main/java/appeng/util/helpers/ItemHandlerUtil.java index 3dcffb3b0..9842cc872 100644 --- a/src/main/java/appeng/util/helpers/ItemHandlerUtil.java +++ b/src/main/java/appeng/util/helpers/ItemHandlerUtil.java @@ -25,58 +25,43 @@ import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; -public class ItemHandlerUtil -{ - private ItemHandlerUtil() - { - } +public class ItemHandlerUtil { + private ItemHandlerUtil() { + } - public static void setStackInSlot( final IItemHandler inv, final int slot, final ItemStack stack ) - { - if( inv instanceof IItemHandlerModifiable ) - { - ( (IItemHandlerModifiable) inv ).setStackInSlot( slot, stack ); - } - else - { - inv.extractItem( slot, Integer.MAX_VALUE, false ); - inv.insertItem( slot, stack, false ); - } - } + public static void setStackInSlot(final IItemHandler inv, final int slot, final ItemStack stack) { + if (inv instanceof IItemHandlerModifiable) { + ((IItemHandlerModifiable) inv).setStackInSlot(slot, stack); + } else { + inv.extractItem(slot, Integer.MAX_VALUE, false); + inv.insertItem(slot, stack, false); + } + } - public static void clear( final IItemHandler inv ) - { - for( int x = 0; x < inv.getSlots(); x++ ) - { - setStackInSlot( inv, x, ItemStack.EMPTY ); - } - } + public static void clear(final IItemHandler inv) { + for (int x = 0; x < inv.getSlots(); x++) { + setStackInSlot(inv, x, ItemStack.EMPTY); + } + } - public static boolean isEmpty( final IItemHandler inv ) - { - for( int x = 0; x < inv.getSlots(); x++ ) - { - if( !inv.getStackInSlot( x ).isEmpty() ) - { - return false; - } - } - return true; - } + public static boolean isEmpty(final IItemHandler inv) { + for (int x = 0; x < inv.getSlots(); x++) { + if (!inv.getStackInSlot(x).isEmpty()) { + return false; + } + } + return true; + } - public static void copy( final IItemHandler from, final IItemHandler to, boolean deepCopy ) - { - for( int i = 0; i < Math.min( from.getSlots(), to.getSlots() ); ++i ) - { - setStackInSlot( to, i, deepCopy ? from.getStackInSlot( i ).copy() : from.getStackInSlot( i ) ); - } - } + public static void copy(final IItemHandler from, final IItemHandler to, boolean deepCopy) { + for (int i = 0; i < Math.min(from.getSlots(), to.getSlots()); ++i) { + setStackInSlot(to, i, deepCopy ? from.getStackInSlot(i).copy() : from.getStackInSlot(i)); + } + } - public static void copy( final InventoryCrafting from, final IItemHandler to, boolean deepCopy ) - { - for( int i = 0; i < Math.min( from.getSizeInventory(), to.getSlots() ); ++i ) - { - setStackInSlot( to, i, deepCopy ? from.getStackInSlot( i ).copy() : from.getStackInSlot( i ) ); - } - } + public static void copy(final InventoryCrafting from, final IItemHandler to, boolean deepCopy) { + for (int i = 0; i < Math.min(from.getSizeInventory(), to.getSlots()); ++i) { + setStackInSlot(to, i, deepCopy ? from.getStackInSlot(i).copy() : from.getStackInSlot(i)); + } + } } diff --git a/src/main/java/appeng/util/helpers/P2PHelper.java b/src/main/java/appeng/util/helpers/P2PHelper.java index f4f2a6dca..f6284335b 100644 --- a/src/main/java/appeng/util/helpers/P2PHelper.java +++ b/src/main/java/appeng/util/helpers/P2PHelper.java @@ -19,52 +19,44 @@ package appeng.util.helpers; +import appeng.api.util.AEColor; import com.google.common.base.Preconditions; -import appeng.api.util.AEColor; +public class P2PHelper { -public class P2PHelper -{ + public AEColor[] toColors(short frequency) { + final AEColor[] colors = new AEColor[4]; - public AEColor[] toColors( short frequency ) - { - final AEColor[] colors = new AEColor[4]; + for (int i = 0; i < 4; i++) { + int nibble = (frequency >> 4 * (3 - i)) & 0xF; - for( int i = 0; i < 4; i++ ) - { - int nibble = ( frequency >> 4 * ( 3 - i ) ) & 0xF; + colors[i] = AEColor.values()[nibble]; + } - colors[i] = AEColor.values()[nibble]; - } + return colors; + } - return colors; - } + public short fromColors(AEColor[] colors) { + Preconditions.checkArgument(colors.length == 4); - public short fromColors( AEColor[] colors ) - { - Preconditions.checkArgument( colors.length == 4 ); + int t = 0; - int t = 0; + for (int i = 0; i < 4; i++) { + int code = colors[3 - i].ordinal() << 4 * i; - for( int i = 0; i < 4; i++ ) - { - int code = colors[3 - i].ordinal() << 4 * i; + t |= code; + } - t |= code; - } + return (short) (t & 0xFFFF); + } - return (short) ( t & 0xFFFF ); - } + public String toHexDigit(AEColor color) { + return String.format("%01X", color.ordinal()); + } - public String toHexDigit( AEColor color ) - { - return String.format( "%01X", color.ordinal() ); - } - - public String toHexString( short frequency ) - { - return String.format( "%04X", frequency ); - } + public String toHexString(short frequency) { + return String.format("%04X", frequency); + } } diff --git a/src/main/java/appeng/util/inv/AdaptorItemHandler.java b/src/main/java/appeng/util/inv/AdaptorItemHandler.java index c9cdc9eaf..c2debc404 100644 --- a/src/main/java/appeng/util/inv/AdaptorItemHandler.java +++ b/src/main/java/appeng/util/inv/AdaptorItemHandler.java @@ -28,246 +28,201 @@ import net.minecraftforge.items.IItemHandler; import java.util.Iterator; -public class AdaptorItemHandler extends InventoryAdaptor -{ - protected final IItemHandler itemHandler; +public class AdaptorItemHandler extends InventoryAdaptor { + protected final IItemHandler itemHandler; - public AdaptorItemHandler( IItemHandler itemHandler ) - { - this.itemHandler = itemHandler; - } + public AdaptorItemHandler(IItemHandler itemHandler) { + this.itemHandler = itemHandler; + } - @Override - public boolean hasSlots() - { - return this.itemHandler.getSlots() > 0; - } + @Override + public boolean hasSlots() { + return this.itemHandler.getSlots() > 0; + } - @Override - public ItemStack removeItems( int amount, ItemStack filter, IInventoryDestination destination ) - { - int slots = this.itemHandler.getSlots(); - ItemStack rv = ItemStack.EMPTY; + @Override + public ItemStack removeItems(int amount, ItemStack filter, IInventoryDestination destination) { + int slots = this.itemHandler.getSlots(); + ItemStack rv = ItemStack.EMPTY; - for( int slot = 0; slot < slots && amount > 0; slot++ ) - { - final ItemStack is = this.itemHandler.getStackInSlot( slot ); - if( is.isEmpty() || ( !filter.isEmpty() && !Platform.itemComparisons().isSameItem( is, filter ) ) ) - { - continue; - } + for (int slot = 0; slot < slots && amount > 0; slot++) { + final ItemStack is = this.itemHandler.getStackInSlot(slot); + if (is.isEmpty() || (!filter.isEmpty() && !Platform.itemComparisons().isSameItem(is, filter))) { + continue; + } - if( destination != null ) - { - if( !destination.canInsert( is ) ) - { - break; - } + if (destination != null) { + if (!destination.canInsert(is)) { + break; + } - ItemStack extracted = this.itemHandler.extractItem( slot, amount, true ); - if( extracted.isEmpty() ) - { - continue; - } - } + ItemStack extracted = this.itemHandler.extractItem(slot, amount, true); + if (extracted.isEmpty()) { + continue; + } + } - // Attempt extracting it - ItemStack extracted = this.itemHandler.extractItem( slot, amount, false ); + // Attempt extracting it + ItemStack extracted = this.itemHandler.extractItem(slot, amount, false); - if( extracted.isEmpty() ) - { - continue; - } + if (extracted.isEmpty()) { + continue; + } - if( rv.isEmpty() ) - { - // Use the first stack as a template for the result - rv = extracted; - filter = extracted; - amount -= extracted.getCount(); - } - else - { - // Subsequent stacks will just increase the extracted size - rv.grow( extracted.getCount() ); - amount -= extracted.getCount(); - } - } + if (rv.isEmpty()) { + // Use the first stack as a template for the result + rv = extracted; + filter = extracted; + amount -= extracted.getCount(); + } else { + // Subsequent stacks will just increase the extracted size + rv.grow(extracted.getCount()); + amount -= extracted.getCount(); + } + } - return rv; - } + return rv; + } - @Override - public ItemStack simulateRemove( int amount, ItemStack filter, IInventoryDestination destination ) - { - int slots = this.itemHandler.getSlots(); - ItemStack rv = ItemStack.EMPTY; + @Override + public ItemStack simulateRemove(int amount, ItemStack filter, IInventoryDestination destination) { + int slots = this.itemHandler.getSlots(); + ItemStack rv = ItemStack.EMPTY; - for( int slot = 0; slot < slots && amount > 0; slot++ ) - { - final ItemStack is = this.itemHandler.getStackInSlot( slot ); - if( !is.isEmpty() && ( filter.isEmpty() || Platform.itemComparisons().isSameItem( is, filter ) ) ) - { - if( destination != null ) - { - if( !destination.canInsert( is ) ) - { - break; - } - } + for (int slot = 0; slot < slots && amount > 0; slot++) { + final ItemStack is = this.itemHandler.getStackInSlot(slot); + if (!is.isEmpty() && (filter.isEmpty() || Platform.itemComparisons().isSameItem(is, filter))) { + if (destination != null) { + if (!destination.canInsert(is)) { + break; + } + } - ItemStack extracted = this.itemHandler.extractItem( slot, amount, true ); - if( extracted.isEmpty() ) - { - continue; - } + ItemStack extracted = this.itemHandler.extractItem(slot, amount, true); + if (extracted.isEmpty()) { + continue; + } - if( rv.isEmpty() ) - { - // Use the first stack as a template for the result - rv = extracted.copy(); - filter = extracted; - amount -= extracted.getCount(); - } - else - { - // Subsequent stacks will just increase the extracted size - rv.grow( extracted.getCount() ); - amount -= extracted.getCount(); - } - } - } + if (rv.isEmpty()) { + // Use the first stack as a template for the result + rv = extracted.copy(); + filter = extracted; + amount -= extracted.getCount(); + } else { + // Subsequent stacks will just increase the extracted size + rv.grow(extracted.getCount()); + amount -= extracted.getCount(); + } + } + } - return rv; - } + return rv; + } - /** - * For fuzzy extract, we will only ever extract one slot, since we're afraid of merging two item stacks with - * different damage values. - */ - @Override - public ItemStack removeSimilarItems( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) - { - int slots = this.itemHandler.getSlots(); - ItemStack extracted = ItemStack.EMPTY; + /** + * For fuzzy extract, we will only ever extract one slot, since we're afraid of merging two item stacks with + * different damage values. + */ + @Override + public ItemStack removeSimilarItems(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination) { + int slots = this.itemHandler.getSlots(); + ItemStack extracted = ItemStack.EMPTY; - for( int slot = 0; slot < slots && extracted.isEmpty(); slot++ ) - { - final ItemStack is = this.itemHandler.getStackInSlot( slot ); - if( is.isEmpty() || ( !filter.isEmpty() && !Platform.itemComparisons().isFuzzyEqualItem( is, filter, fuzzyMode ) ) ) - { - continue; - } + for (int slot = 0; slot < slots && extracted.isEmpty(); slot++) { + final ItemStack is = this.itemHandler.getStackInSlot(slot); + if (is.isEmpty() || (!filter.isEmpty() && !Platform.itemComparisons().isFuzzyEqualItem(is, filter, fuzzyMode))) { + continue; + } - if( destination != null ) - { - if( !destination.canInsert( is ) ) - { - continue; - } + if (destination != null) { + if (!destination.canInsert(is)) { + continue; + } - ItemStack simulated = this.itemHandler.extractItem( slot, amount, true ); - if( simulated.isEmpty() ) - { - continue; - } - } + ItemStack simulated = this.itemHandler.extractItem(slot, amount, true); + if (simulated.isEmpty()) { + continue; + } + } - // Attempt extracting it - extracted = this.itemHandler.extractItem( slot, amount, false ); - if( !extracted.isEmpty() ) - { - return extracted; - } - } + // Attempt extracting it + extracted = this.itemHandler.extractItem(slot, amount, false); + if (!extracted.isEmpty()) { + return extracted; + } + } - return extracted; - } + return extracted; + } - @Override - public ItemStack simulateSimilarRemove( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) - { - int slots = this.itemHandler.getSlots(); - ItemStack extracted = ItemStack.EMPTY; + @Override + public ItemStack simulateSimilarRemove(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination) { + int slots = this.itemHandler.getSlots(); + ItemStack extracted = ItemStack.EMPTY; - for( int slot = 0; slot < slots && extracted.isEmpty(); slot++ ) - { - final ItemStack is = this.itemHandler.getStackInSlot( slot ); - if( is.isEmpty() || ( !filter.isEmpty() && !Platform.itemComparisons().isFuzzyEqualItem( is, filter, fuzzyMode ) ) ) - { - continue; - } + for (int slot = 0; slot < slots && extracted.isEmpty(); slot++) { + final ItemStack is = this.itemHandler.getStackInSlot(slot); + if (is.isEmpty() || (!filter.isEmpty() && !Platform.itemComparisons().isFuzzyEqualItem(is, filter, fuzzyMode))) { + continue; + } - if( destination != null && !destination.canInsert( is ) ) - { - continue; - } + if (destination != null && !destination.canInsert(is)) { + continue; + } - // Attempt extracting it - extracted = this.itemHandler.extractItem( slot, amount, true ); - if( !extracted.isEmpty() ) - { - return extracted; - } - } + // Attempt extracting it + extracted = this.itemHandler.extractItem(slot, amount, true); + if (!extracted.isEmpty()) { + return extracted; + } + } - return extracted; - } + return extracted; + } - @Override - public ItemStack addItems( ItemStack toBeAdded ) - { - return this.addItems( toBeAdded, false ); - } + @Override + public ItemStack addItems(ItemStack toBeAdded) { + return this.addItems(toBeAdded, false); + } - @Override - public ItemStack simulateAdd( ItemStack toBeSimulated ) - { - return this.addItems( toBeSimulated, true ); - } + @Override + public ItemStack simulateAdd(ItemStack toBeSimulated) { + return this.addItems(toBeSimulated, true); + } - protected ItemStack addItems( ItemStack itemsToAdd, final boolean simulate ) - { - if( itemsToAdd.isEmpty() ) - { - return ItemStack.EMPTY; - } + protected ItemStack addItems(ItemStack itemsToAdd, final boolean simulate) { + if (itemsToAdd.isEmpty()) { + return ItemStack.EMPTY; + } - for( int slot = 0; slot < this.itemHandler.getSlots(); slot++ ) - { - if( !simulate ) - { - itemsToAdd = itemsToAdd.copy(); - } - itemsToAdd = this.itemHandler.insertItem( slot, itemsToAdd, simulate ); + for (int slot = 0; slot < this.itemHandler.getSlots(); slot++) { + if (!simulate) { + itemsToAdd = itemsToAdd.copy(); + } + itemsToAdd = this.itemHandler.insertItem(slot, itemsToAdd, simulate); - if( itemsToAdd.isEmpty() ) - { - return ItemStack.EMPTY; - } - } + if (itemsToAdd.isEmpty()) { + return ItemStack.EMPTY; + } + } - return itemsToAdd; - } + return itemsToAdd; + } - @Override - public boolean containsItems() - { - int slots = this.itemHandler.getSlots(); - for( int slot = 0; slot < slots; slot++ ) - { - if( !this.itemHandler.getStackInSlot( slot ).isEmpty() ) - { - return true; - } - } - return false; - } + @Override + public boolean containsItems() { + int slots = this.itemHandler.getSlots(); + for (int slot = 0; slot < slots; slot++) { + if (!this.itemHandler.getStackInSlot(slot).isEmpty()) { + return true; + } + } + return false; + } - @Override - public Iterator iterator() - { - return new ItemHandlerIterator( this.itemHandler ); - } + @Override + public Iterator iterator() { + return new ItemHandlerIterator(this.itemHandler); + } } diff --git a/src/main/java/appeng/util/inv/AdaptorItemHandlerPlayerInv.java b/src/main/java/appeng/util/inv/AdaptorItemHandlerPlayerInv.java index df8a5aacd..e13f36fa2 100644 --- a/src/main/java/appeng/util/inv/AdaptorItemHandlerPlayerInv.java +++ b/src/main/java/appeng/util/inv/AdaptorItemHandlerPlayerInv.java @@ -19,57 +19,47 @@ package appeng.util.inv; +import appeng.util.Platform; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraftforge.items.wrapper.PlayerMainInvWrapper; -import appeng.util.Platform; +public class AdaptorItemHandlerPlayerInv extends AdaptorItemHandler { + public AdaptorItemHandlerPlayerInv(final EntityPlayer playerInv) { + super(new PlayerMainInvWrapper(playerInv.inventory)); + } -public class AdaptorItemHandlerPlayerInv extends AdaptorItemHandler -{ - public AdaptorItemHandlerPlayerInv( final EntityPlayer playerInv ) - { - super( new PlayerMainInvWrapper( playerInv.inventory ) ); - } + /** + * Tries to fill existing stacks first + */ + @Override + protected ItemStack addItems(final ItemStack itemsToAdd, final boolean simulate) { + if (itemsToAdd.isEmpty()) { + return ItemStack.EMPTY; + } - /** - * Tries to fill existing stacks first - */ - @Override - protected ItemStack addItems( final ItemStack itemsToAdd, final boolean simulate ) - { - if( itemsToAdd.isEmpty() ) - { - return ItemStack.EMPTY; - } + ItemStack left = itemsToAdd.copy(); - ItemStack left = itemsToAdd.copy(); + for (int slot = 0; slot < this.itemHandler.getSlots(); slot++) { + ItemStack is = this.itemHandler.getStackInSlot(slot); - for( int slot = 0; slot < this.itemHandler.getSlots(); slot++ ) - { - ItemStack is = this.itemHandler.getStackInSlot( slot ); + if (Platform.itemComparisons().isSameItem(is, left)) { + left = this.itemHandler.insertItem(slot, left, simulate); + } + if (left.isEmpty()) { + return ItemStack.EMPTY; + } + } - if( Platform.itemComparisons().isSameItem( is, left ) ) - { - left = this.itemHandler.insertItem( slot, left, simulate ); - } - if( left.isEmpty() ) - { - return ItemStack.EMPTY; - } - } + for (int slot = 0; slot < this.itemHandler.getSlots(); slot++) { + left = this.itemHandler.insertItem(slot, left, simulate); + if (left.isEmpty()) { + return ItemStack.EMPTY; + } + } - for( int slot = 0; slot < this.itemHandler.getSlots(); slot++ ) - { - left = this.itemHandler.insertItem( slot, left, simulate ); - if( left.isEmpty() ) - { - return ItemStack.EMPTY; - } - } - - return left; - } + return left; + } } diff --git a/src/main/java/appeng/util/inv/AdaptorItemRepository.java b/src/main/java/appeng/util/inv/AdaptorItemRepository.java index de7e93b4b..5c5e29960 100644 --- a/src/main/java/appeng/util/inv/AdaptorItemRepository.java +++ b/src/main/java/appeng/util/inv/AdaptorItemRepository.java @@ -2,7 +2,6 @@ package appeng.util.inv; import appeng.api.config.FuzzyMode; import appeng.util.InventoryAdaptor; - import appeng.util.Platform; import com.jaquadro.minecraft.storagedrawers.api.capabilities.IItemRepository; import net.minecraft.item.ItemStack; @@ -10,203 +9,164 @@ import net.minecraft.item.ItemStack; import java.util.Iterator; -public class AdaptorItemRepository extends InventoryAdaptor -{ - protected final IItemRepository itemRepository; +public class AdaptorItemRepository extends InventoryAdaptor { + protected final IItemRepository itemRepository; - public AdaptorItemRepository( IItemRepository itemRepository ) - { - this.itemRepository = itemRepository; - } + public AdaptorItemRepository(IItemRepository itemRepository) { + this.itemRepository = itemRepository; + } - @Override - public ItemStack removeItems( int amount, ItemStack filter, IInventoryDestination destination ) - { - ItemStack rv = ItemStack.EMPTY; - ItemStack extracted = ItemStack.EMPTY; + @Override + public ItemStack removeItems(int amount, ItemStack filter, IInventoryDestination destination) { + ItemStack rv = ItemStack.EMPTY; + ItemStack extracted = ItemStack.EMPTY; - if( !filter.isEmpty() ) - { - extracted = this.itemRepository.extractItem( filter, amount, true ); - } - else - { - for( IItemRepository.ItemRecord record : this.itemRepository.getAllItems() ) - { - extracted = this.itemRepository.extractItem( record.itemPrototype, amount, true ); - if( !extracted.isEmpty() ) - { - break; - } - } - } + if (!filter.isEmpty()) { + extracted = this.itemRepository.extractItem(filter, amount, true); + } else { + for (IItemRepository.ItemRecord record : this.itemRepository.getAllItems()) { + extracted = this.itemRepository.extractItem(record.itemPrototype, amount, true); + if (!extracted.isEmpty()) { + break; + } + } + } - if( destination != null ) - { + if (destination != null) { - if( extracted.isEmpty() || !destination.canInsert( extracted ) ) - { - return rv; - } + if (extracted.isEmpty() || !destination.canInsert(extracted)) { + return rv; + } - } + } - extracted = this.itemRepository.extractItem( filter.isEmpty() ? extracted : filter, amount, false ); + extracted = this.itemRepository.extractItem(filter.isEmpty() ? extracted : filter, amount, false); - return extracted; - } + return extracted; + } - @Override - public ItemStack simulateRemove( int amount, ItemStack filter, IInventoryDestination destination ) - { - ItemStack rv = ItemStack.EMPTY; - ItemStack extracted = ItemStack.EMPTY; + @Override + public ItemStack simulateRemove(int amount, ItemStack filter, IInventoryDestination destination) { + ItemStack rv = ItemStack.EMPTY; + ItemStack extracted = ItemStack.EMPTY; - if( !filter.isEmpty() ) - { - extracted = this.itemRepository.extractItem( filter, amount, true ); - } - else - { - for( IItemRepository.ItemRecord record : this.itemRepository.getAllItems() ) - { - extracted = this.itemRepository.extractItem( record.itemPrototype, amount, true ); - if( !extracted.isEmpty() ) - { - break; - } - } - } + if (!filter.isEmpty()) { + extracted = this.itemRepository.extractItem(filter, amount, true); + } else { + for (IItemRepository.ItemRecord record : this.itemRepository.getAllItems()) { + extracted = this.itemRepository.extractItem(record.itemPrototype, amount, true); + if (!extracted.isEmpty()) { + break; + } + } + } - if( destination != null ) - { + if (destination != null) { - if( extracted.isEmpty() || !destination.canInsert( extracted ) ) - { - return rv; - } + if (extracted.isEmpty() || !destination.canInsert(extracted)) { + return rv; + } - } + } - return extracted; - } + return extracted; + } - @Override - public ItemStack removeSimilarItems( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) - { - ItemStack rv = ItemStack.EMPTY; - ItemStack extracted = ItemStack.EMPTY; + @Override + public ItemStack removeSimilarItems(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination) { + ItemStack rv = ItemStack.EMPTY; + ItemStack extracted = ItemStack.EMPTY; - for( IItemRepository.ItemRecord record : this.itemRepository.getAllItems() ) - { - if( Platform.itemComparisons().isFuzzyEqualItem( record.itemPrototype, filter, fuzzyMode ) ) - { - extracted = this.itemRepository.extractItem( record.itemPrototype, amount, true ); - } + for (IItemRepository.ItemRecord record : this.itemRepository.getAllItems()) { + if (Platform.itemComparisons().isFuzzyEqualItem(record.itemPrototype, filter, fuzzyMode)) { + extracted = this.itemRepository.extractItem(record.itemPrototype, amount, true); + } - if( !extracted.isEmpty() ) - { - break; - } - } + if (!extracted.isEmpty()) { + break; + } + } - if( destination != null ) - { + if (destination != null) { - if( extracted.isEmpty() || !destination.canInsert( extracted ) ) - { - return rv; - } + if (extracted.isEmpty() || !destination.canInsert(extracted)) { + return rv; + } - } + } - extracted = this.itemRepository.extractItem( extracted, amount, false ); + extracted = this.itemRepository.extractItem(extracted, amount, false); - return extracted; - } + return extracted; + } - @Override - public ItemStack simulateSimilarRemove( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) - { - ItemStack rv = ItemStack.EMPTY; - ItemStack extracted = ItemStack.EMPTY; + @Override + public ItemStack simulateSimilarRemove(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination) { + ItemStack rv = ItemStack.EMPTY; + ItemStack extracted = ItemStack.EMPTY; - for( IItemRepository.ItemRecord record : this.itemRepository.getAllItems() ) - { - if( Platform.itemComparisons().isFuzzyEqualItem( record.itemPrototype, filter, fuzzyMode ) ) - { - extracted = this.itemRepository.extractItem( record.itemPrototype, amount, true ); - } + for (IItemRepository.ItemRecord record : this.itemRepository.getAllItems()) { + if (Platform.itemComparisons().isFuzzyEqualItem(record.itemPrototype, filter, fuzzyMode)) { + extracted = this.itemRepository.extractItem(record.itemPrototype, amount, true); + } - if( !extracted.isEmpty() ) - { - break; - } - } + if (!extracted.isEmpty()) { + break; + } + } - if( destination != null ) - { + if (destination != null) { - if( extracted.isEmpty() || !destination.canInsert( extracted ) ) - { - return rv; - } + if (extracted.isEmpty() || !destination.canInsert(extracted)) { + return rv; + } - } + } - return extracted; - } + return extracted; + } - @Override - public ItemStack addItems( ItemStack toBeAdded ) - { - return this.addItems( toBeAdded, false ); - } + @Override + public ItemStack addItems(ItemStack toBeAdded) { + return this.addItems(toBeAdded, false); + } - protected ItemStack addItems( ItemStack itemsToAdd, final boolean simulate ) - { - if( itemsToAdd.isEmpty() ) - { - return ItemStack.EMPTY; - } + protected ItemStack addItems(ItemStack itemsToAdd, final boolean simulate) { + if (itemsToAdd.isEmpty()) { + return ItemStack.EMPTY; + } - if( !simulate ) - { - itemsToAdd = itemsToAdd.copy(); - } + if (!simulate) { + itemsToAdd = itemsToAdd.copy(); + } - itemsToAdd = this.itemRepository.insertItem( itemsToAdd, simulate ); + itemsToAdd = this.itemRepository.insertItem(itemsToAdd, simulate); - if( itemsToAdd.isEmpty() ) - { - return ItemStack.EMPTY; - } + if (itemsToAdd.isEmpty()) { + return ItemStack.EMPTY; + } - return itemsToAdd; - } + return itemsToAdd; + } - @Override - public ItemStack simulateAdd( ItemStack toBeSimulated ) - { - return this.addItems( toBeSimulated, true ); - } + @Override + public ItemStack simulateAdd(ItemStack toBeSimulated) { + return this.addItems(toBeSimulated, true); + } - @Override - public boolean containsItems() - { - return !this.itemRepository.getAllItems().isEmpty(); - } + @Override + public boolean containsItems() { + return !this.itemRepository.getAllItems().isEmpty(); + } - @Override - public boolean hasSlots() - { - return true; - } + @Override + public boolean hasSlots() { + return true; + } - @Override - public Iterator iterator() - { - return null; - } + @Override + public Iterator iterator() { + return null; + } } diff --git a/src/main/java/appeng/util/inv/AdaptorList.java b/src/main/java/appeng/util/inv/AdaptorList.java index cf6639eeb..c6334e667 100644 --- a/src/main/java/appeng/util/inv/AdaptorList.java +++ b/src/main/java/appeng/util/inv/AdaptorList.java @@ -19,211 +19,171 @@ package appeng.util.inv; -import java.util.Iterator; -import java.util.List; - -import net.minecraft.item.ItemStack; - import appeng.api.config.FuzzyMode; import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.iterators.StackToSlotIterator; +import net.minecraft.item.ItemStack; + +import java.util.Iterator; +import java.util.List; -public class AdaptorList extends InventoryAdaptor -{ +public class AdaptorList extends InventoryAdaptor { - private final List i; + private final List i; - public AdaptorList( final List s ) - { - this.i = s; - } + public AdaptorList(final List s) { + this.i = s; + } - @Override - public boolean hasSlots() - { - return !this.i.isEmpty(); - } + @Override + public boolean hasSlots() { + return !this.i.isEmpty(); + } - @Override - public ItemStack removeItems( int amount, final ItemStack filter, final IInventoryDestination destination ) - { - final int s = this.i.size(); - for( int x = 0; x < s; x++ ) - { - final ItemStack is = this.i.get( x ); - if( !is.isEmpty() && ( filter.isEmpty() || Platform.itemComparisons().isSameItem( is, filter ) ) ) - { - if( amount > is.getCount() ) - { - amount = is.getCount(); - } - if( destination != null && !destination.canInsert( is ) ) - { - amount = 0; - } + @Override + public ItemStack removeItems(int amount, final ItemStack filter, final IInventoryDestination destination) { + final int s = this.i.size(); + for (int x = 0; x < s; x++) { + final ItemStack is = this.i.get(x); + if (!is.isEmpty() && (filter.isEmpty() || Platform.itemComparisons().isSameItem(is, filter))) { + if (amount > is.getCount()) { + amount = is.getCount(); + } + if (destination != null && !destination.canInsert(is)) { + amount = 0; + } - if( amount > 0 ) - { - final ItemStack rv = is.copy(); - rv.setCount( amount ); - is.grow( -amount ); + if (amount > 0) { + final ItemStack rv = is.copy(); + rv.setCount(amount); + is.grow(-amount); - // remove it.. - if( is.getCount() <= 0 ) - { - this.i.remove( x ); - } + // remove it.. + if (is.getCount() <= 0) { + this.i.remove(x); + } - return rv; - } - } - } - return ItemStack.EMPTY; - } + return rv; + } + } + } + return ItemStack.EMPTY; + } - @Override - public ItemStack simulateRemove( int amount, final ItemStack filter, final IInventoryDestination destination ) - { - for( final ItemStack is : this.i ) - { - if( !is.isEmpty() && ( filter.isEmpty() || Platform.itemComparisons().isSameItem( is, filter ) ) ) - { - if( amount > is.getCount() ) - { - amount = is.getCount(); - } - if( destination != null && !destination.canInsert( is ) ) - { - amount = 0; - } + @Override + public ItemStack simulateRemove(int amount, final ItemStack filter, final IInventoryDestination destination) { + for (final ItemStack is : this.i) { + if (!is.isEmpty() && (filter.isEmpty() || Platform.itemComparisons().isSameItem(is, filter))) { + if (amount > is.getCount()) { + amount = is.getCount(); + } + if (destination != null && !destination.canInsert(is)) { + amount = 0; + } - if( amount > 0 ) - { - final ItemStack rv = is.copy(); - rv.setCount( amount ); - return rv; - } - } - } - return ItemStack.EMPTY; - } + if (amount > 0) { + final ItemStack rv = is.copy(); + rv.setCount(amount); + return rv; + } + } + } + return ItemStack.EMPTY; + } - @Override - public ItemStack removeSimilarItems( int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - final int s = this.i.size(); - for( int x = 0; x < s; x++ ) - { - final ItemStack is = this.i.get( x ); - if( !is.isEmpty() && ( filter.isEmpty() || Platform.itemComparisons().isFuzzyEqualItem( is, filter, fuzzyMode ) ) ) - { - if( amount > is.getCount() ) - { - amount = is.getCount(); - } - if( destination != null && !destination.canInsert( is ) ) - { - amount = 0; - } + @Override + public ItemStack removeSimilarItems(int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination) { + final int s = this.i.size(); + for (int x = 0; x < s; x++) { + final ItemStack is = this.i.get(x); + if (!is.isEmpty() && (filter.isEmpty() || Platform.itemComparisons().isFuzzyEqualItem(is, filter, fuzzyMode))) { + if (amount > is.getCount()) { + amount = is.getCount(); + } + if (destination != null && !destination.canInsert(is)) { + amount = 0; + } - if( amount > 0 ) - { - final ItemStack rv = is.copy(); - rv.setCount( amount ); - is.grow( -amount ); + if (amount > 0) { + final ItemStack rv = is.copy(); + rv.setCount(amount); + is.grow(-amount); - // remove it.. - if( is.getCount() <= 0 ) - { - this.i.remove( x ); - } + // remove it.. + if (is.getCount() <= 0) { + this.i.remove(x); + } - return rv; - } - } - } - return ItemStack.EMPTY; - } + return rv; + } + } + } + return ItemStack.EMPTY; + } - @Override - public ItemStack simulateSimilarRemove( int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - for( final ItemStack is : this.i ) - { - if( !is.isEmpty() && ( filter.isEmpty() || Platform.itemComparisons().isFuzzyEqualItem( is, filter, fuzzyMode ) ) ) - { - if( amount > is.getCount() ) - { - amount = is.getCount(); - } - if( destination != null && !destination.canInsert( is ) ) - { - amount = 0; - } + @Override + public ItemStack simulateSimilarRemove(int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination) { + for (final ItemStack is : this.i) { + if (!is.isEmpty() && (filter.isEmpty() || Platform.itemComparisons().isFuzzyEqualItem(is, filter, fuzzyMode))) { + if (amount > is.getCount()) { + amount = is.getCount(); + } + if (destination != null && !destination.canInsert(is)) { + amount = 0; + } - if( amount > 0 ) - { - final ItemStack rv = is.copy(); - rv.setCount( amount ); - return rv; - } - } - } - return ItemStack.EMPTY; - } + if (amount > 0) { + final ItemStack rv = is.copy(); + rv.setCount(amount); + return rv; + } + } + } + return ItemStack.EMPTY; + } - @Override - public ItemStack addItems( final ItemStack toBeAdded ) - { - if( toBeAdded.isEmpty() ) - { - return ItemStack.EMPTY; - } - if( toBeAdded.getCount() == 0 ) - { - return ItemStack.EMPTY; - } + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + if (toBeAdded.isEmpty()) { + return ItemStack.EMPTY; + } + if (toBeAdded.getCount() == 0) { + return ItemStack.EMPTY; + } - final ItemStack left = toBeAdded.copy(); + final ItemStack left = toBeAdded.copy(); - for( final ItemStack is : this.i ) - { - if( ItemStack.areItemsEqual( is, left ) ) - { - is.grow( left.getCount() ); - return ItemStack.EMPTY; - } - } + for (final ItemStack is : this.i) { + if (ItemStack.areItemsEqual(is, left)) { + is.grow(left.getCount()); + return ItemStack.EMPTY; + } + } - this.i.add( left ); - return ItemStack.EMPTY; - } + this.i.add(left); + return ItemStack.EMPTY; + } - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - return ItemStack.EMPTY; - } + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + return ItemStack.EMPTY; + } - @Override - public boolean containsItems() - { - for( final ItemStack is : this.i ) - { - if( !is.isEmpty() ) - { - return true; - } - } - return false; - } + @Override + public boolean containsItems() { + for (final ItemStack is : this.i) { + if (!is.isEmpty()) { + return true; + } + } + return false; + } - @Override - public Iterator iterator() - { - return new StackToSlotIterator( this.i.iterator() ); - } + @Override + public Iterator iterator() { + return new StackToSlotIterator(this.i.iterator()); + } } diff --git a/src/main/java/appeng/util/inv/BlockingInventoryAdaptor.java b/src/main/java/appeng/util/inv/BlockingInventoryAdaptor.java index 7400e0c68..aaa2e1701 100644 --- a/src/main/java/appeng/util/inv/BlockingInventoryAdaptor.java +++ b/src/main/java/appeng/util/inv/BlockingInventoryAdaptor.java @@ -6,21 +6,17 @@ import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; -public abstract class BlockingInventoryAdaptor implements Iterable -{ - public static BlockingInventoryAdaptor getAdaptor( final TileEntity te, final EnumFacing d ) - { - if( te != null && te.hasCapability( CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, d ) ) - { - // Attempt getting an IItemHandler for the given side via caps - IItemHandler itemHandler = te.getCapability( CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, d ); - if( itemHandler != null ) - { - return new BlockingItemHandler( itemHandler, te.getBlockType().getRegistryName().getResourceDomain() ); - } - } - return null; - } +public abstract class BlockingInventoryAdaptor implements Iterable { + public static BlockingInventoryAdaptor getAdaptor(final TileEntity te, final EnumFacing d) { + if (te != null && te.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, d)) { + // Attempt getting an IItemHandler for the given side via caps + IItemHandler itemHandler = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, d); + if (itemHandler != null) { + return new BlockingItemHandler(itemHandler, te.getBlockType().getRegistryName().getResourceDomain()); + } + } + return null; + } - public abstract boolean containsBlockingItems(); + public abstract boolean containsBlockingItems(); } \ No newline at end of file diff --git a/src/main/java/appeng/util/inv/BlockingItemHandler.java b/src/main/java/appeng/util/inv/BlockingItemHandler.java index 2e854f59a..3d02652cd 100644 --- a/src/main/java/appeng/util/inv/BlockingItemHandler.java +++ b/src/main/java/appeng/util/inv/BlockingItemHandler.java @@ -10,45 +10,37 @@ import net.minecraftforge.items.IItemHandler; import java.util.Iterator; -public class BlockingItemHandler extends BlockingInventoryAdaptor -{ - protected final IItemHandler itemHandler; - private final String domain; +public class BlockingItemHandler extends BlockingInventoryAdaptor { + protected final IItemHandler itemHandler; + private final String domain; - public BlockingItemHandler( IItemHandler itemHandler, String domain ) - { - this.itemHandler = itemHandler; - this.domain = domain; - } + public BlockingItemHandler(IItemHandler itemHandler, String domain) { + this.itemHandler = itemHandler; + this.domain = domain; + } - boolean isBlockableItem( ItemStack stack ) - { - Object2ObjectOpenHashMap map = NonBlockingItems.INSTANCE.getMap().get( domain ); - if( map.get( stack.getItem() ) != null ) - { - return !map.get( stack.getItem() ).contains( stack.getMetadata() ); - } - return true; - } + boolean isBlockableItem(ItemStack stack) { + Object2ObjectOpenHashMap map = NonBlockingItems.INSTANCE.getMap().get(domain); + if (map.get(stack.getItem()) != null) { + return !map.get(stack.getItem()).contains(stack.getMetadata()); + } + return true; + } - @Override - public boolean containsBlockingItems() - { - int slots = this.itemHandler.getSlots(); - for( int slot = 0; slot < slots; slot++ ) - { - ItemStack is = this.itemHandler.getStackInSlot( slot ); - if( !is.isEmpty() && isBlockableItem( is ) ) - { - return true; - } - } - return false; - } + @Override + public boolean containsBlockingItems() { + int slots = this.itemHandler.getSlots(); + for (int slot = 0; slot < slots; slot++) { + ItemStack is = this.itemHandler.getStackInSlot(slot); + if (!is.isEmpty() && isBlockableItem(is)) { + return true; + } + } + return false; + } - @Override - public Iterator iterator() - { - return new ItemHandlerIterator( this.itemHandler ); - } + @Override + public Iterator iterator() { + return new ItemHandlerIterator(this.itemHandler); + } } \ No newline at end of file diff --git a/src/main/java/appeng/util/inv/IAEAppEngInventory.java b/src/main/java/appeng/util/inv/IAEAppEngInventory.java index a811a980e..3e7a29e4b 100644 --- a/src/main/java/appeng/util/inv/IAEAppEngInventory.java +++ b/src/main/java/appeng/util/inv/IAEAppEngInventory.java @@ -23,9 +23,8 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; -public interface IAEAppEngInventory -{ - void saveChanges(); +public interface IAEAppEngInventory { + void saveChanges(); - void onChangeInventory( IItemHandler inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ); + void onChangeInventory(IItemHandler inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack); } diff --git a/src/main/java/appeng/util/inv/IInventoryDestination.java b/src/main/java/appeng/util/inv/IInventoryDestination.java index 61a3cf8b9..efb9d95f9 100644 --- a/src/main/java/appeng/util/inv/IInventoryDestination.java +++ b/src/main/java/appeng/util/inv/IInventoryDestination.java @@ -22,8 +22,7 @@ package appeng.util.inv; import net.minecraft.item.ItemStack; -public interface IInventoryDestination -{ +public interface IInventoryDestination { - boolean canInsert( ItemStack stack ); + boolean canInsert(ItemStack stack); } diff --git a/src/main/java/appeng/util/inv/IMEAdaptor.java b/src/main/java/appeng/util/inv/IMEAdaptor.java index 15b1b7ea9..0babb835c 100644 --- a/src/main/java/appeng/util/inv/IMEAdaptor.java +++ b/src/main/java/appeng/util/inv/IMEAdaptor.java @@ -19,12 +19,6 @@ package appeng.util.inv; -import java.util.Iterator; - -import com.google.common.collect.ImmutableList; - -import net.minecraft.item.ItemStack; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.FuzzyMode; @@ -35,173 +29,145 @@ import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import appeng.util.InventoryAdaptor; import appeng.util.item.AEItemStack; +import com.google.common.collect.ImmutableList; +import net.minecraft.item.ItemStack; + +import java.util.Iterator; -public class IMEAdaptor extends InventoryAdaptor -{ +public class IMEAdaptor extends InventoryAdaptor { - private final IMEInventory target; - private final IActionSource src; - private int maxSlots = 0; + private final IMEInventory target; + private final IActionSource src; + private int maxSlots = 0; - public IMEAdaptor( final IMEInventory input, final IActionSource src ) - { - this.target = input; - this.src = src; - } + public IMEAdaptor(final IMEInventory input, final IActionSource src) { + this.target = input; + this.src = src; + } - @Override - public boolean hasSlots() - { - return true; - } + @Override + public boolean hasSlots() { + return true; + } - @Override - public Iterator iterator() - { - return new IMEAdaptorIterator( this, this.getList() ); - } + @Override + public Iterator iterator() { + return new IMEAdaptorIterator(this, this.getList()); + } - private IItemList getList() - { - return this.target.getAvailableItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList() ); - } + private IItemList getList() { + return this.target.getAvailableItems(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList()); + } - @Override - public ItemStack removeItems( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - return this.doRemoveItems( amount, filter, destination, Actionable.MODULATE ); - } + @Override + public ItemStack removeItems(final int amount, final ItemStack filter, final IInventoryDestination destination) { + return this.doRemoveItems(amount, filter, destination, Actionable.MODULATE); + } - private ItemStack doRemoveItems( final int amount, final ItemStack filter, final IInventoryDestination destination, final Actionable type ) - { - IAEItemStack req = null; + private ItemStack doRemoveItems(final int amount, final ItemStack filter, final IInventoryDestination destination, final Actionable type) { + IAEItemStack req = null; - if( filter.isEmpty() ) - { - final IItemList list = this.getList(); - if( !list.isEmpty() ) - { - req = list.getFirstItem(); - } - } - else - { - req = AEItemStack.fromItemStack( filter ); - } + if (filter.isEmpty()) { + final IItemList list = this.getList(); + if (!list.isEmpty()) { + req = list.getFirstItem(); + } + } else { + req = AEItemStack.fromItemStack(filter); + } - IAEItemStack out = null; + IAEItemStack out = null; - if( req != null ) - { - req.setStackSize( amount ); - out = this.target.extractItems( req, type, this.src ); - } + if (req != null) { + req.setStackSize(amount); + out = this.target.extractItems(req, type, this.src); + } - if( out != null ) - { - return out.createItemStack(); - } + if (out != null) { + return out.createItemStack(); + } - return ItemStack.EMPTY; - } + return ItemStack.EMPTY; + } - @Override - public ItemStack simulateRemove( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - return this.doRemoveItems( amount, filter, destination, Actionable.SIMULATE ); - } + @Override + public ItemStack simulateRemove(final int amount, final ItemStack filter, final IInventoryDestination destination) { + return this.doRemoveItems(amount, filter, destination, Actionable.SIMULATE); + } - @Override - public ItemStack removeSimilarItems( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - if( filter.isEmpty() ) - { - return this.doRemoveItems( amount, null, destination, Actionable.MODULATE ); - } - return this.doRemoveItemsFuzzy( amount, filter, destination, Actionable.MODULATE, fuzzyMode ); - } + @Override + public ItemStack removeSimilarItems(final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination) { + if (filter.isEmpty()) { + return this.doRemoveItems(amount, null, destination, Actionable.MODULATE); + } + return this.doRemoveItemsFuzzy(amount, filter, destination, Actionable.MODULATE, fuzzyMode); + } - private ItemStack doRemoveItemsFuzzy( final int amount, final ItemStack filter, final IInventoryDestination destination, final Actionable type, final FuzzyMode fuzzyMode ) - { - final IAEItemStack reqFilter = AEItemStack.fromItemStack( filter ); - if( reqFilter == null ) - { - return ItemStack.EMPTY; - } + private ItemStack doRemoveItemsFuzzy(final int amount, final ItemStack filter, final IInventoryDestination destination, final Actionable type, final FuzzyMode fuzzyMode) { + final IAEItemStack reqFilter = AEItemStack.fromItemStack(filter); + if (reqFilter == null) { + return ItemStack.EMPTY; + } - IAEItemStack out = null; + IAEItemStack out = null; - for( final IAEItemStack req : ImmutableList.copyOf( this.getList().findFuzzy( reqFilter, fuzzyMode ) ) ) - { - if( req != null ) - { - req.setStackSize( amount ); - out = this.target.extractItems( req, type, this.src ); - if( out != null ) - { - return out.createItemStack(); - } - } - } + for (final IAEItemStack req : ImmutableList.copyOf(this.getList().findFuzzy(reqFilter, fuzzyMode))) { + if (req != null) { + req.setStackSize(amount); + out = this.target.extractItems(req, type, this.src); + if (out != null) { + return out.createItemStack(); + } + } + } - return ItemStack.EMPTY; - } + return ItemStack.EMPTY; + } - @Override - public ItemStack simulateSimilarRemove( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - if( filter.isEmpty() ) - { - return this.doRemoveItems( amount, ItemStack.EMPTY, destination, Actionable.SIMULATE ); - } - return this.doRemoveItemsFuzzy( amount, filter, destination, Actionable.SIMULATE, fuzzyMode ); - } + @Override + public ItemStack simulateSimilarRemove(final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination) { + if (filter.isEmpty()) { + return this.doRemoveItems(amount, ItemStack.EMPTY, destination, Actionable.SIMULATE); + } + return this.doRemoveItemsFuzzy(amount, filter, destination, Actionable.SIMULATE, fuzzyMode); + } - @Override - public ItemStack addItems( final ItemStack toBeAdded ) - { - final IAEItemStack in = AEItemStack.fromItemStack( toBeAdded ); - if( in != null ) - { - final IAEItemStack out = this.target.injectItems( in, Actionable.MODULATE, this.src ); - if( out != null ) - { - return out.createItemStack(); - } - } - return ItemStack.EMPTY; - } + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + final IAEItemStack in = AEItemStack.fromItemStack(toBeAdded); + if (in != null) { + final IAEItemStack out = this.target.injectItems(in, Actionable.MODULATE, this.src); + if (out != null) { + return out.createItemStack(); + } + } + return ItemStack.EMPTY; + } - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - final IAEItemStack in = AEItemStack.fromItemStack( toBeSimulated ); - if( in != null ) - { - final IAEItemStack out = this.target.injectItems( in, Actionable.SIMULATE, this.src ); - if( out != null ) - { - return out.createItemStack(); - } - } - return ItemStack.EMPTY; - } + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + final IAEItemStack in = AEItemStack.fromItemStack(toBeSimulated); + if (in != null) { + final IAEItemStack out = this.target.injectItems(in, Actionable.SIMULATE, this.src); + if (out != null) { + return out.createItemStack(); + } + } + return ItemStack.EMPTY; + } - @Override - public boolean containsItems() - { - return !this.getList().isEmpty(); - } + @Override + public boolean containsItems() { + return !this.getList().isEmpty(); + } - int getMaxSlots() - { - return this.maxSlots; - } + int getMaxSlots() { + return this.maxSlots; + } - void setMaxSlots( final int maxSlots ) - { - this.maxSlots = maxSlots; - } + void setMaxSlots(final int maxSlots) { + this.maxSlots = maxSlots; + } } diff --git a/src/main/java/appeng/util/inv/IMEAdaptorIterator.java b/src/main/java/appeng/util/inv/IMEAdaptorIterator.java index 23664e814..91386bf4c 100644 --- a/src/main/java/appeng/util/inv/IMEAdaptorIterator.java +++ b/src/main/java/appeng/util/inv/IMEAdaptorIterator.java @@ -19,64 +19,56 @@ package appeng.util.inv; -import java.util.Iterator; - -import net.minecraft.item.ItemStack; - import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; +import net.minecraft.item.ItemStack; + +import java.util.Iterator; -public final class IMEAdaptorIterator implements Iterator -{ - private final Iterator stack; - private final ItemSlot slot = new ItemSlot(); - private final IMEAdaptor parent; - private final int containerSize; +public final class IMEAdaptorIterator implements Iterator { + private final Iterator stack; + private final ItemSlot slot = new ItemSlot(); + private final IMEAdaptor parent; + private final int containerSize; - private int offset = 0; - private boolean hasNext; + private int offset = 0; + private boolean hasNext; - public IMEAdaptorIterator( final IMEAdaptor parent, final IItemList availableItems ) - { - this.stack = availableItems.iterator(); - this.containerSize = parent.getMaxSlots(); - this.parent = parent; - } + public IMEAdaptorIterator(final IMEAdaptor parent, final IItemList availableItems) { + this.stack = availableItems.iterator(); + this.containerSize = parent.getMaxSlots(); + this.parent = parent; + } - @Override - public boolean hasNext() - { - this.hasNext = this.stack.hasNext(); - return this.offset < this.containerSize || this.hasNext; - } + @Override + public boolean hasNext() { + this.hasNext = this.stack.hasNext(); + return this.offset < this.containerSize || this.hasNext; + } - @Override - public ItemSlot next() - { - this.slot.setSlot( this.offset ); - this.offset++; - this.slot.setExtractable( true ); + @Override + public ItemSlot next() { + this.slot.setSlot(this.offset); + this.offset++; + this.slot.setExtractable(true); - if( this.parent.getMaxSlots() < this.offset ) - { - this.parent.setMaxSlots( this.offset ); - } + if (this.parent.getMaxSlots() < this.offset) { + this.parent.setMaxSlots(this.offset); + } - if( this.hasNext ) - { - final IAEItemStack item = this.stack.next(); - this.slot.setAEItemStack( item ); - return this.slot; - } + if (this.hasNext) { + final IAEItemStack item = this.stack.next(); + this.slot.setAEItemStack(item); + return this.slot; + } - this.slot.setItemStack( ItemStack.EMPTY ); - return this.slot; - } + this.slot.setItemStack(ItemStack.EMPTY); + return this.slot; + } - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/inv/IMEInventoryDestination.java b/src/main/java/appeng/util/inv/IMEInventoryDestination.java index 1c07b3f7a..651c7ae04 100644 --- a/src/main/java/appeng/util/inv/IMEInventoryDestination.java +++ b/src/main/java/appeng/util/inv/IMEInventoryDestination.java @@ -19,39 +19,33 @@ package appeng.util.inv; -import net.minecraft.item.ItemStack; - import appeng.api.config.Actionable; import appeng.api.storage.IMEInventory; import appeng.api.storage.data.IAEItemStack; import appeng.util.item.AEItemStack; +import net.minecraft.item.ItemStack; -public class IMEInventoryDestination implements IInventoryDestination -{ +public class IMEInventoryDestination implements IInventoryDestination { - private final IMEInventory me; + private final IMEInventory me; - public IMEInventoryDestination( final IMEInventory o ) - { - this.me = o; - } + public IMEInventoryDestination(final IMEInventory o) { + this.me = o; + } - @Override - public boolean canInsert( final ItemStack stack ) - { + @Override + public boolean canInsert(final ItemStack stack) { - if( stack.isEmpty() ) - { - return false; - } + if (stack.isEmpty()) { + return false; + } - final IAEItemStack failed = this.me.injectItems( AEItemStack.fromItemStack( stack ), Actionable.SIMULATE, null ); + final IAEItemStack failed = this.me.injectItems(AEItemStack.fromItemStack(stack), Actionable.SIMULATE, null); - if( failed == null ) - { - return true; - } - return failed.getStackSize() != stack.getCount(); - } + if (failed == null) { + return true; + } + return failed.getStackSize() != stack.getCount(); + } } diff --git a/src/main/java/appeng/util/inv/InvOperation.java b/src/main/java/appeng/util/inv/InvOperation.java index b11390ac5..629bf0ee3 100644 --- a/src/main/java/appeng/util/inv/InvOperation.java +++ b/src/main/java/appeng/util/inv/InvOperation.java @@ -19,7 +19,6 @@ package appeng.util.inv; -public enum InvOperation -{ - EXTRACT, INSERT, SET +public enum InvOperation { + EXTRACT, INSERT, SET } diff --git a/src/main/java/appeng/util/inv/ItemHandlerIterator.java b/src/main/java/appeng/util/inv/ItemHandlerIterator.java index bbd78b388..aeb98e0b2 100644 --- a/src/main/java/appeng/util/inv/ItemHandlerIterator.java +++ b/src/main/java/appeng/util/inv/ItemHandlerIterator.java @@ -19,44 +19,39 @@ package appeng.util.inv; +import net.minecraftforge.items.IItemHandler; + import java.util.Iterator; import java.util.NoSuchElementException; -import net.minecraftforge.items.IItemHandler; +public class ItemHandlerIterator implements Iterator { -public class ItemHandlerIterator implements Iterator -{ + private final IItemHandler itemHandler; - private final IItemHandler itemHandler; + private final ItemSlot itemSlot = new ItemSlot(); - private final ItemSlot itemSlot = new ItemSlot(); + private int slot = 0; - private int slot = 0; + public ItemHandlerIterator(IItemHandler itemHandler) { + this.itemHandler = itemHandler; + } - public ItemHandlerIterator( IItemHandler itemHandler ) - { - this.itemHandler = itemHandler; - } + @Override + public boolean hasNext() { + return this.slot < this.itemHandler.getSlots(); + } - @Override - public boolean hasNext() - { - return this.slot < this.itemHandler.getSlots(); - } - - @Override - public ItemSlot next() - { - if( this.slot >= this.itemHandler.getSlots() ) - { - throw new NoSuchElementException(); - } - this.itemSlot.setExtractable( !this.itemHandler.extractItem( this.slot, Integer.MAX_VALUE, true ).isEmpty() ); - this.itemSlot.setItemStack( this.itemHandler.getStackInSlot( this.slot ) ); - this.itemSlot.setSlot( this.slot ); - this.slot++; - return this.itemSlot; - } + @Override + public ItemSlot next() { + if (this.slot >= this.itemHandler.getSlots()) { + throw new NoSuchElementException(); + } + this.itemSlot.setExtractable(!this.itemHandler.extractItem(this.slot, Integer.MAX_VALUE, true).isEmpty()); + this.itemSlot.setItemStack(this.itemHandler.getStackInSlot(this.slot)); + this.itemSlot.setSlot(this.slot); + this.slot++; + return this.itemSlot; + } } diff --git a/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java b/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java index 6cf39faff..6b39463fe 100644 --- a/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java +++ b/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java @@ -19,93 +19,79 @@ package appeng.util.inv; -import java.util.Collection; -import java.util.Iterator; - import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; +import java.util.Collection; +import java.util.Iterator; -public class ItemListIgnoreCrafting> implements IItemList -{ - private final IItemList target; +public class ItemListIgnoreCrafting> implements IItemList { - public ItemListIgnoreCrafting( final IItemList cla ) - { - this.target = cla; - } + private final IItemList target; - @Override - public void add( T option ) - { - if( option != null && option.isCraftable() ) - { - option = option.copy(); - option.setCraftable( false ); - } + public ItemListIgnoreCrafting(final IItemList cla) { + this.target = cla; + } - this.target.add( option ); - } + @Override + public void add(T option) { + if (option != null && option.isCraftable()) { + option = option.copy(); + option.setCraftable(false); + } - @Override - public T findPrecise( final T i ) - { - return this.target.findPrecise( i ); - } + this.target.add(option); + } - @Override - public Collection findFuzzy( final T input, final FuzzyMode fuzzy ) - { - return this.target.findFuzzy( input, fuzzy ); - } + @Override + public T findPrecise(final T i) { + return this.target.findPrecise(i); + } - @Override - public boolean isEmpty() - { - return this.target.isEmpty(); - } + @Override + public Collection findFuzzy(final T input, final FuzzyMode fuzzy) { + return this.target.findFuzzy(input, fuzzy); + } - @Override - public void addStorage( final T option ) - { - this.target.addStorage( option ); - } + @Override + public boolean isEmpty() { + return this.target.isEmpty(); + } - @Override - public void addCrafting( final T option ) - { - // nothing. - } + @Override + public void addStorage(final T option) { + this.target.addStorage(option); + } - @Override - public void addRequestable( final T option ) - { - this.target.addRequestable( option ); - } + @Override + public void addCrafting(final T option) { + // nothing. + } - @Override - public T getFirstItem() - { - return this.target.getFirstItem(); - } + @Override + public void addRequestable(final T option) { + this.target.addRequestable(option); + } - @Override - public int size() - { - return this.target.size(); - } + @Override + public T getFirstItem() { + return this.target.getFirstItem(); + } - @Override - public Iterator iterator() - { - return this.target.iterator(); - } + @Override + public int size() { + return this.target.size(); + } - @Override - public void resetStatus() - { - this.target.resetStatus(); - } + @Override + public Iterator iterator() { + return this.target.iterator(); + } + + @Override + public void resetStatus() { + this.target.resetStatus(); + } } diff --git a/src/main/java/appeng/util/inv/ItemSlot.java b/src/main/java/appeng/util/inv/ItemSlot.java index 795a6336e..bfedb1b02 100644 --- a/src/main/java/appeng/util/inv/ItemSlot.java +++ b/src/main/java/appeng/util/inv/ItemSlot.java @@ -19,62 +19,52 @@ package appeng.util.inv; -import net.minecraft.item.ItemStack; - import appeng.api.storage.data.IAEItemStack; import appeng.util.item.AEItemStack; +import net.minecraft.item.ItemStack; -public class ItemSlot -{ +public class ItemSlot { - private int slot; - private boolean isExtractable; - // one or the other.. - private IAEItemStack aeItemStack; - private ItemStack itemStack; + private int slot; + private boolean isExtractable; + // one or the other.. + private IAEItemStack aeItemStack; + private ItemStack itemStack; - public ItemStack getItemStack() - { - return this.itemStack - .isEmpty() ? ( this.aeItemStack == null ? ItemStack.EMPTY : ( this.itemStack = this.aeItemStack.createItemStack() ) ) : this.itemStack; - } + public ItemStack getItemStack() { + return this.itemStack + .isEmpty() ? (this.aeItemStack == null ? ItemStack.EMPTY : (this.itemStack = this.aeItemStack.createItemStack())) : this.itemStack; + } - public void setItemStack( final ItemStack is ) - { - this.aeItemStack = null; - this.itemStack = is; - } + public void setItemStack(final ItemStack is) { + this.aeItemStack = null; + this.itemStack = is; + } - public IAEItemStack getAEItemStack() - { - return this.aeItemStack == null ? ( this.itemStack - .isEmpty() ? null : ( this.aeItemStack = AEItemStack.fromItemStack( this.itemStack ) ) ) : this.aeItemStack; - } + public IAEItemStack getAEItemStack() { + return this.aeItemStack == null ? (this.itemStack + .isEmpty() ? null : (this.aeItemStack = AEItemStack.fromItemStack(this.itemStack))) : this.aeItemStack; + } - void setAEItemStack( final IAEItemStack is ) - { - this.aeItemStack = is; - this.itemStack = ItemStack.EMPTY; - } + void setAEItemStack(final IAEItemStack is) { + this.aeItemStack = is; + this.itemStack = ItemStack.EMPTY; + } - public boolean isExtractable() - { - return this.isExtractable; - } + public boolean isExtractable() { + return this.isExtractable; + } - void setExtractable( final boolean isExtractable ) - { - this.isExtractable = isExtractable; - } + void setExtractable(final boolean isExtractable) { + this.isExtractable = isExtractable; + } - public int getSlot() - { - return this.slot; - } + public int getSlot() { + return this.slot; + } - public void setSlot( final int slot ) - { - this.slot = slot; - } + public void setSlot(final int slot) { + this.slot = slot; + } } diff --git a/src/main/java/appeng/util/inv/WrapperChainedItemHandler.java b/src/main/java/appeng/util/inv/WrapperChainedItemHandler.java index 84d32ad77..0c200a0e6 100644 --- a/src/main/java/appeng/util/inv/WrapperChainedItemHandler.java +++ b/src/main/java/appeng/util/inv/WrapperChainedItemHandler.java @@ -19,152 +19,128 @@ package appeng.util.inv; -import java.util.ArrayList; - -import javax.annotation.Nonnull; - +import appeng.util.helpers.ItemHandlerUtil; import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.wrapper.EmptyHandler; -import appeng.util.helpers.ItemHandlerUtil; +import javax.annotation.Nonnull; +import java.util.ArrayList; -public class WrapperChainedItemHandler implements IItemHandlerModifiable -{ - private IItemHandler[] itemHandler; // the handlers - private int[] baseIndex; // index-offsets of the different handlers - private int slotCount; // number of total slots +public class WrapperChainedItemHandler implements IItemHandlerModifiable { + private IItemHandler[] itemHandler; // the handlers + private int[] baseIndex; // index-offsets of the different handlers + private int slotCount; // number of total slots - public WrapperChainedItemHandler( IItemHandler... itemHandler ) - { - this.setItemHandlers( itemHandler ); - } + public WrapperChainedItemHandler(IItemHandler... itemHandler) { + this.setItemHandlers(itemHandler); + } - private void setItemHandlers( IItemHandler[] handlers ) - { - this.itemHandler = handlers; - this.baseIndex = new int[this.itemHandler.length]; - int index = 0; - for( int i = 0; i < this.itemHandler.length; i++ ) - { - index += this.itemHandler[i].getSlots(); - this.baseIndex[i] = index; - } - this.slotCount = index; - } + private void setItemHandlers(IItemHandler[] handlers) { + this.itemHandler = handlers; + this.baseIndex = new int[this.itemHandler.length]; + int index = 0; + for (int i = 0; i < this.itemHandler.length; i++) { + index += this.itemHandler[i].getSlots(); + this.baseIndex[i] = index; + } + this.slotCount = index; + } - // returns the handler index for the slot - private int getIndexForSlot( int slot ) - { - if( slot < 0 ) - { - return -1; - } + // returns the handler index for the slot + private int getIndexForSlot(int slot) { + if (slot < 0) { + return -1; + } - for( int i = 0; i < this.baseIndex.length; i++ ) - { - if( slot - this.baseIndex[i] < 0 ) - { - return i; - } - } - return -1; - } + for (int i = 0; i < this.baseIndex.length; i++) { + if (slot - this.baseIndex[i] < 0) { + return i; + } + } + return -1; + } - private IItemHandler getHandlerFromIndex( int index ) - { - if( index < 0 || index >= this.itemHandler.length ) - { - return EmptyHandler.INSTANCE; - } - return this.itemHandler[index]; - } + private IItemHandler getHandlerFromIndex(int index) { + if (index < 0 || index >= this.itemHandler.length) { + return EmptyHandler.INSTANCE; + } + return this.itemHandler[index]; + } - private int getSlotFromIndex( int slot, int index ) - { - if( index <= 0 || index >= this.baseIndex.length ) - { - return slot; - } - return slot - this.baseIndex[index - 1]; - } + private int getSlotFromIndex(int slot, int index) { + if (index <= 0 || index >= this.baseIndex.length) { + return slot; + } + return slot - this.baseIndex[index - 1]; + } - public void cycleOrder() - { - if( this.itemHandler.length > 1 ) - { - ArrayList newOrder = new ArrayList<>(); - newOrder.add( this.itemHandler[this.itemHandler.length - 1] ); - for( int i = 0; i < this.itemHandler.length - 1; ++i ) - { - newOrder.add( this.itemHandler[i] ); - } - this.setItemHandlers( newOrder.toArray( new IItemHandler[this.itemHandler.length] ) ); - } - } + public void cycleOrder() { + if (this.itemHandler.length > 1) { + ArrayList newOrder = new ArrayList<>(); + newOrder.add(this.itemHandler[this.itemHandler.length - 1]); + for (int i = 0; i < this.itemHandler.length - 1; ++i) { + newOrder.add(this.itemHandler[i]); + } + this.setItemHandlers(newOrder.toArray(new IItemHandler[this.itemHandler.length])); + } + } - @Override - public int getSlots() - { - return this.slotCount; - } + @Override + public int getSlots() { + return this.slotCount; + } - @Override - @Nonnull - public ItemStack getStackInSlot( final int slot ) - { - int index = this.getIndexForSlot( slot ); - IItemHandler handler = this.getHandlerFromIndex( index ); - int targetSlot = this.getSlotFromIndex( slot, index ); - return handler.getStackInSlot( targetSlot ); - } + @Override + @Nonnull + public ItemStack getStackInSlot(final int slot) { + int index = this.getIndexForSlot(slot); + IItemHandler handler = this.getHandlerFromIndex(index); + int targetSlot = this.getSlotFromIndex(slot, index); + return handler.getStackInSlot(targetSlot); + } - @Override - @Nonnull - public ItemStack insertItem( final int slot, @Nonnull ItemStack stack, boolean simulate ) - { - int index = this.getIndexForSlot( slot ); - IItemHandler handler = this.getHandlerFromIndex( index ); - int targetSlot = this.getSlotFromIndex( slot, index ); - return handler.insertItem( targetSlot, stack, simulate ); - } + @Override + @Nonnull + public ItemStack insertItem(final int slot, @Nonnull ItemStack stack, boolean simulate) { + int index = this.getIndexForSlot(slot); + IItemHandler handler = this.getHandlerFromIndex(index); + int targetSlot = this.getSlotFromIndex(slot, index); + return handler.insertItem(targetSlot, stack, simulate); + } - @Override - @Nonnull - public ItemStack extractItem( int slot, int amount, boolean simulate ) - { - int index = this.getIndexForSlot( slot ); - IItemHandler handler = this.getHandlerFromIndex( index ); - int targetSlot = this.getSlotFromIndex( slot, index ); - return handler.extractItem( targetSlot, amount, simulate ); - } + @Override + @Nonnull + public ItemStack extractItem(int slot, int amount, boolean simulate) { + int index = this.getIndexForSlot(slot); + IItemHandler handler = this.getHandlerFromIndex(index); + int targetSlot = this.getSlotFromIndex(slot, index); + return handler.extractItem(targetSlot, amount, simulate); + } - @Override - public int getSlotLimit( int slot ) - { - int index = this.getIndexForSlot( slot ); - IItemHandler handler = this.getHandlerFromIndex( index ); - int localSlot = this.getSlotFromIndex( slot, index ); - return handler.getSlotLimit( localSlot ); - } + @Override + public int getSlotLimit(int slot) { + int index = this.getIndexForSlot(slot); + IItemHandler handler = this.getHandlerFromIndex(index); + int localSlot = this.getSlotFromIndex(slot, index); + return handler.getSlotLimit(localSlot); + } - @Override - public void setStackInSlot( int slot, ItemStack stack ) - { - int index = this.getIndexForSlot( slot ); - IItemHandler handler = this.getHandlerFromIndex( index ); - int targetSlot = this.getSlotFromIndex( slot, index ); - ItemHandlerUtil.setStackInSlot( handler, targetSlot, stack ); - } + @Override + public void setStackInSlot(int slot, ItemStack stack) { + int index = this.getIndexForSlot(slot); + IItemHandler handler = this.getHandlerFromIndex(index); + int targetSlot = this.getSlotFromIndex(slot, index); + ItemHandlerUtil.setStackInSlot(handler, targetSlot, stack); + } - @Override - public boolean isItemValid( int slot, ItemStack stack ) - { - int index = this.getIndexForSlot( slot ); - IItemHandler handler = this.getHandlerFromIndex( index ); - int targetSlot = this.getSlotFromIndex( slot, index ); - return handler.isItemValid( targetSlot, stack ); - } + @Override + public boolean isItemValid(int slot, ItemStack stack) { + int index = this.getIndexForSlot(slot); + IItemHandler handler = this.getHandlerFromIndex(index); + int targetSlot = this.getSlotFromIndex(slot, index); + return handler.isItemValid(targetSlot, stack); + } } diff --git a/src/main/java/appeng/util/inv/WrapperCursorItemHandler.java b/src/main/java/appeng/util/inv/WrapperCursorItemHandler.java index 3196c0a10..360bf7b9c 100644 --- a/src/main/java/appeng/util/inv/WrapperCursorItemHandler.java +++ b/src/main/java/appeng/util/inv/WrapperCursorItemHandler.java @@ -23,21 +23,18 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraftforge.items.ItemStackHandler; -public class WrapperCursorItemHandler extends ItemStackHandler -{ - private final InventoryPlayer inv; +public class WrapperCursorItemHandler extends ItemStackHandler { + private final InventoryPlayer inv; - public WrapperCursorItemHandler( InventoryPlayer inventoryPlayer ) - { - super( 1 ); + public WrapperCursorItemHandler(InventoryPlayer inventoryPlayer) { + super(1); - this.inv = inventoryPlayer; - this.setStackInSlot( 0, inventoryPlayer.getItemStack() ); - } + this.inv = inventoryPlayer; + this.setStackInSlot(0, inventoryPlayer.getItemStack()); + } - @Override - protected void onContentsChanged( int slot ) - { - this.inv.setItemStack( this.getStackInSlot( slot ) ); - } + @Override + protected void onContentsChanged(int slot) { + this.inv.setItemStack(this.getStackInSlot(slot)); + } } diff --git a/src/main/java/appeng/util/inv/WrapperFilteredItemHandler.java b/src/main/java/appeng/util/inv/WrapperFilteredItemHandler.java index 125da1c26..0768749f1 100644 --- a/src/main/java/appeng/util/inv/WrapperFilteredItemHandler.java +++ b/src/main/java/appeng/util/inv/WrapperFilteredItemHandler.java @@ -19,80 +19,67 @@ package appeng.util.inv; -import javax.annotation.Nonnull; - +import appeng.util.helpers.ItemHandlerUtil; +import appeng.util.inv.filter.IAEItemFilter; import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; -import appeng.util.helpers.ItemHandlerUtil; -import appeng.util.inv.filter.IAEItemFilter; +import javax.annotation.Nonnull; -public class WrapperFilteredItemHandler implements IItemHandlerModifiable -{ - private final IItemHandler handler; - private final IAEItemFilter filter; +public class WrapperFilteredItemHandler implements IItemHandlerModifiable { + private final IItemHandler handler; + private final IAEItemFilter filter; - public WrapperFilteredItemHandler( @Nonnull IItemHandler handler, @Nonnull IAEItemFilter filter ) - { - this.handler = handler; - this.filter = filter; - } + public WrapperFilteredItemHandler(@Nonnull IItemHandler handler, @Nonnull IAEItemFilter filter) { + this.handler = handler; + this.filter = filter; + } - @Override - public void setStackInSlot( int slot, ItemStack stack ) - { - ItemHandlerUtil.setStackInSlot( this.handler, slot, stack ); - } + @Override + public void setStackInSlot(int slot, ItemStack stack) { + ItemHandlerUtil.setStackInSlot(this.handler, slot, stack); + } - @Override - public int getSlots() - { - return this.handler.getSlots(); - } + @Override + public int getSlots() { + return this.handler.getSlots(); + } - @Override - public ItemStack getStackInSlot( int slot ) - { - return this.handler.getStackInSlot( slot ); - } + @Override + public ItemStack getStackInSlot(int slot) { + return this.handler.getStackInSlot(slot); + } - @Override - public ItemStack insertItem( int slot, ItemStack stack, boolean simulate ) - { - if( !this.filter.allowInsert( this.handler, slot, stack ) ) - { - return stack; - } + @Override + public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { + if (!this.filter.allowInsert(this.handler, slot, stack)) { + return stack; + } - return this.handler.insertItem( slot, stack, simulate ); - } + return this.handler.insertItem(slot, stack, simulate); + } - @Override - public ItemStack extractItem( int slot, int amount, boolean simulate ) - { - if( !this.filter.allowExtract( this.handler, slot, amount ) ) - { - return ItemStack.EMPTY; - } + @Override + public ItemStack extractItem(int slot, int amount, boolean simulate) { + if (!this.filter.allowExtract(this.handler, slot, amount)) { + return ItemStack.EMPTY; + } - return this.handler.extractItem( slot, amount, simulate ); - } + return this.handler.extractItem(slot, amount, simulate); + } - @Override - public int getSlotLimit( int slot ) - { - return this.handler.getSlotLimit( slot ); - } + @Override + public int getSlotLimit(int slot) { + return this.handler.getSlotLimit(slot); + } - @Override - public boolean isItemValid( int slot, ItemStack stack ) - { - if( !this.filter.allowInsert( this.handler, slot, stack ) ) - { - return false; - } - return this.handler.isItemValid( slot, stack ); - } + @Override + public boolean isItemValid(int slot, ItemStack stack) { + if (!this.filter.allowInsert(this.handler, slot, stack)) { + return false; + } + return this.handler.isItemValid(slot, stack); + } } diff --git a/src/main/java/appeng/util/inv/WrapperInvItemHandler.java b/src/main/java/appeng/util/inv/WrapperInvItemHandler.java index df85079e7..09ac0d3db 100644 --- a/src/main/java/appeng/util/inv/WrapperInvItemHandler.java +++ b/src/main/java/appeng/util/inv/WrapperInvItemHandler.java @@ -19,141 +19,118 @@ package appeng.util.inv; +import appeng.util.helpers.ItemHandlerUtil; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.util.text.ITextComponent; import net.minecraftforge.items.IItemHandler; -import appeng.util.helpers.ItemHandlerUtil; +public class WrapperInvItemHandler implements IInventory { + private final IItemHandler inv; -public class WrapperInvItemHandler implements IInventory -{ - private final IItemHandler inv; + public WrapperInvItemHandler(final IItemHandler inv) { + this.inv = inv; + } - public WrapperInvItemHandler( final IItemHandler inv ) - { - this.inv = inv; - } + @Override + public String getName() { + return null; + } - @Override - public String getName() - { - return null; - } + @Override + public boolean hasCustomName() { + return false; + } - @Override - public boolean hasCustomName() - { - return false; - } + @Override + public ITextComponent getDisplayName() { + return null; + } - @Override - public ITextComponent getDisplayName() - { - return null; - } + @Override + public int getSizeInventory() { + return this.inv.getSlots(); + } - @Override - public int getSizeInventory() - { - return this.inv.getSlots(); - } + @Override + public boolean isEmpty() { + return ItemHandlerUtil.isEmpty(this.inv); + } - @Override - public boolean isEmpty() - { - return ItemHandlerUtil.isEmpty( this.inv ); - } + @Override + public ItemStack getStackInSlot(int index) { + return this.inv.getStackInSlot(index); + } - @Override - public ItemStack getStackInSlot( int index ) - { - return this.inv.getStackInSlot( index ); - } + @Override + public ItemStack decrStackSize(int index, int count) { + return this.inv.extractItem(index, count, false); + } - @Override - public ItemStack decrStackSize( int index, int count ) - { - return this.inv.extractItem( index, count, false ); - } + @Override + public ItemStack removeStackFromSlot(int index) { + return this.inv.extractItem(index, this.inv.getSlotLimit(index), false); + } - @Override - public ItemStack removeStackFromSlot( int index ) - { - return this.inv.extractItem( index, this.inv.getSlotLimit( index ), false ); - } + @Override + public void setInventorySlotContents(int index, ItemStack stack) { + ItemHandlerUtil.setStackInSlot(this.inv, index, stack); + } - @Override - public void setInventorySlotContents( int index, ItemStack stack ) - { - ItemHandlerUtil.setStackInSlot( this.inv, index, stack ); - } + @Override + public int getInventoryStackLimit() { + int max = 0; + for (int i = 0; i < this.inv.getSlots(); ++i) { + max = Math.max(max, this.inv.getSlotLimit(i)); + } + return max; + } - @Override - public int getInventoryStackLimit() - { - int max = 0; - for( int i = 0; i < this.inv.getSlots(); ++i ) - { - max = Math.max( max, this.inv.getSlotLimit( i ) ); - } - return max; - } + @Override + public void markDirty() { + // NOP + } - @Override - public void markDirty() - { - // NOP - } + @Override + public boolean isUsableByPlayer(EntityPlayer player) { + return false; + } - @Override - public boolean isUsableByPlayer( EntityPlayer player ) - { - return false; - } + @Override + public void openInventory(EntityPlayer player) { + // NOP + } - @Override - public void openInventory( EntityPlayer player ) - { - // NOP - } + @Override + public void closeInventory(EntityPlayer player) { + // NOP + } - @Override - public void closeInventory( EntityPlayer player ) - { - // NOP - } + @Override + public boolean isItemValidForSlot(int index, ItemStack stack) { + return this.inv.isItemValid(index, stack); + } - @Override - public boolean isItemValidForSlot( int index, ItemStack stack ) - { - return this.inv.isItemValid( index, stack ); - } + @Override + public int getField(int id) { + return 0; + } - @Override - public int getField( int id ) - { - return 0; - } + @Override + public void setField(int id, int value) { + // NOP + } - @Override - public void setField( int id, int value ) - { - // NOP - } + @Override + public int getFieldCount() { + return 0; + } - @Override - public int getFieldCount() - { - return 0; - } - - @Override - public void clear() - { - ItemHandlerUtil.clear( this.inv ); - } + @Override + public void clear() { + ItemHandlerUtil.clear(this.inv); + } } diff --git a/src/main/java/appeng/util/inv/WrapperRangeItemHandler.java b/src/main/java/appeng/util/inv/WrapperRangeItemHandler.java index 986192967..5f9a0fa48 100644 --- a/src/main/java/appeng/util/inv/WrapperRangeItemHandler.java +++ b/src/main/java/appeng/util/inv/WrapperRangeItemHandler.java @@ -19,102 +19,85 @@ package appeng.util.inv; -import javax.annotation.Nonnull; - +import appeng.util.helpers.ItemHandlerUtil; import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; -import appeng.util.helpers.ItemHandlerUtil; +import javax.annotation.Nonnull; -public class WrapperRangeItemHandler implements IItemHandlerModifiable -{ - private final IItemHandler compose; - private final int minSlot; - private final int maxSlot; +public class WrapperRangeItemHandler implements IItemHandlerModifiable { + private final IItemHandler compose; + private final int minSlot; + private final int maxSlot; - public WrapperRangeItemHandler( IItemHandler compose, int minSlot, int maxSlotExclusive ) - { - this.compose = compose; - this.minSlot = minSlot; - this.maxSlot = maxSlotExclusive; - } + public WrapperRangeItemHandler(IItemHandler compose, int minSlot, int maxSlotExclusive) { + this.compose = compose; + this.minSlot = minSlot; + this.maxSlot = maxSlotExclusive; + } - @Override - public int getSlots() - { - return this.maxSlot - this.minSlot; - } + @Override + public int getSlots() { + return this.maxSlot - this.minSlot; + } - @Override - @Nonnull - public ItemStack getStackInSlot( int slot ) - { - if( this.checkSlot( slot ) ) - { - return this.compose.getStackInSlot( slot + this.minSlot ); - } + @Override + @Nonnull + public ItemStack getStackInSlot(int slot) { + if (this.checkSlot(slot)) { + return this.compose.getStackInSlot(slot + this.minSlot); + } - return ItemStack.EMPTY; - } + return ItemStack.EMPTY; + } - @Override - @Nonnull - public ItemStack insertItem( int slot, @Nonnull ItemStack stack, boolean simulate ) - { - if( this.checkSlot( slot ) ) - { - return this.compose.insertItem( slot + this.minSlot, stack, simulate ); - } + @Override + @Nonnull + public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) { + if (this.checkSlot(slot)) { + return this.compose.insertItem(slot + this.minSlot, stack, simulate); + } - return stack; - } + return stack; + } - @Override - @Nonnull - public ItemStack extractItem( int slot, int amount, boolean simulate ) - { - if( this.checkSlot( slot ) ) - { - return this.compose.extractItem( slot + this.minSlot, amount, simulate ); - } + @Override + @Nonnull + public ItemStack extractItem(int slot, int amount, boolean simulate) { + if (this.checkSlot(slot)) { + return this.compose.extractItem(slot + this.minSlot, amount, simulate); + } - return ItemStack.EMPTY; - } + return ItemStack.EMPTY; + } - @Override - public void setStackInSlot( int slot, @Nonnull ItemStack stack ) - { - if( this.checkSlot( slot ) ) - { - ItemHandlerUtil.setStackInSlot( this.compose, slot + this.minSlot, stack ); - } - } + @Override + public void setStackInSlot(int slot, @Nonnull ItemStack stack) { + if (this.checkSlot(slot)) { + ItemHandlerUtil.setStackInSlot(this.compose, slot + this.minSlot, stack); + } + } - @Override - public int getSlotLimit( int slot ) - { - if( this.checkSlot( slot ) ) - { - return this.compose.getSlotLimit( slot + this.minSlot ); - } + @Override + public int getSlotLimit(int slot) { + if (this.checkSlot(slot)) { + return this.compose.getSlotLimit(slot + this.minSlot); + } - return 0; - } + return 0; + } - private boolean checkSlot( int localSlot ) - { - return localSlot + this.minSlot < this.maxSlot; - } + private boolean checkSlot(int localSlot) { + return localSlot + this.minSlot < this.maxSlot; + } - @Override - public boolean isItemValid( int slot, ItemStack stack ) - { - if( this.checkSlot( slot ) ) - { - return this.compose.isItemValid( slot + this.minSlot, stack ); - } - return false; - } + @Override + public boolean isItemValid(int slot, ItemStack stack) { + if (this.checkSlot(slot)) { + return this.compose.isItemValid(slot + this.minSlot, stack); + } + return false; + } } diff --git a/src/main/java/appeng/util/inv/WrapperSupplierItemHandler.java b/src/main/java/appeng/util/inv/WrapperSupplierItemHandler.java index 7e75b393d..ea6798a07 100644 --- a/src/main/java/appeng/util/inv/WrapperSupplierItemHandler.java +++ b/src/main/java/appeng/util/inv/WrapperSupplierItemHandler.java @@ -19,63 +19,53 @@ package appeng.util.inv; -import java.util.function.Supplier; - +import appeng.util.helpers.ItemHandlerUtil; import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; -import appeng.util.helpers.ItemHandlerUtil; +import java.util.function.Supplier; -public class WrapperSupplierItemHandler implements IItemHandlerModifiable -{ - private final Supplier sourceHandler; +public class WrapperSupplierItemHandler implements IItemHandlerModifiable { + private final Supplier sourceHandler; - public WrapperSupplierItemHandler( Supplier source ) - { - this.sourceHandler = source; - } + public WrapperSupplierItemHandler(Supplier source) { + this.sourceHandler = source; + } - @Override - public int getSlots() - { - return this.sourceHandler.get().getSlots(); - } + @Override + public int getSlots() { + return this.sourceHandler.get().getSlots(); + } - @Override - public ItemStack getStackInSlot( int slot ) - { - return this.sourceHandler.get().getStackInSlot( slot ); - } + @Override + public ItemStack getStackInSlot(int slot) { + return this.sourceHandler.get().getStackInSlot(slot); + } - @Override - public ItemStack insertItem( int slot, ItemStack stack, boolean simulate ) - { - return this.sourceHandler.get().insertItem( slot, stack, simulate ); - } + @Override + public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { + return this.sourceHandler.get().insertItem(slot, stack, simulate); + } - @Override - public ItemStack extractItem( int slot, int amount, boolean simulate ) - { - return this.sourceHandler.get().extractItem( slot, amount, simulate ); - } + @Override + public ItemStack extractItem(int slot, int amount, boolean simulate) { + return this.sourceHandler.get().extractItem(slot, amount, simulate); + } - @Override - public int getSlotLimit( int slot ) - { - return this.sourceHandler.get().getSlotLimit( slot ); - } + @Override + public int getSlotLimit(int slot) { + return this.sourceHandler.get().getSlotLimit(slot); + } - @Override - public void setStackInSlot( int slot, ItemStack stack ) - { - ItemHandlerUtil.setStackInSlot( this.sourceHandler.get(), slot, stack ); - } + @Override + public void setStackInSlot(int slot, ItemStack stack) { + ItemHandlerUtil.setStackInSlot(this.sourceHandler.get(), slot, stack); + } - @Override - public boolean isItemValid( int slot, ItemStack stack ) - { - return this.sourceHandler.get().isItemValid( slot, stack ); - } + @Override + public boolean isItemValid(int slot, ItemStack stack) { + return this.sourceHandler.get().isItemValid(slot, stack); + } } diff --git a/src/main/java/appeng/util/inv/filter/AEItemDefinitionFilter.java b/src/main/java/appeng/util/inv/filter/AEItemDefinitionFilter.java index 0606d7253..37a498e7c 100644 --- a/src/main/java/appeng/util/inv/filter/AEItemDefinitionFilter.java +++ b/src/main/java/appeng/util/inv/filter/AEItemDefinitionFilter.java @@ -19,31 +19,26 @@ package appeng.util.inv.filter; +import appeng.api.definitions.IItemDefinition; import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; -import appeng.api.definitions.IItemDefinition; +public class AEItemDefinitionFilter implements IAEItemFilter { + private final IItemDefinition definition; -public class AEItemDefinitionFilter implements IAEItemFilter -{ - private final IItemDefinition definition; + public AEItemDefinitionFilter(IItemDefinition definition) { + this.definition = definition; + } - public AEItemDefinitionFilter( IItemDefinition definition ) - { - this.definition = definition; - } + @Override + public boolean allowExtract(IItemHandler inv, int slot, int amount) { + return true; + } - @Override - public boolean allowExtract( IItemHandler inv, int slot, int amount ) - { - return true; - } - - @Override - public boolean allowInsert( IItemHandler inv, int slot, ItemStack stack ) - { - return this.definition.isSameAs( stack ); - } + @Override + public boolean allowInsert(IItemHandler inv, int slot, ItemStack stack) { + return this.definition.isSameAs(stack); + } } diff --git a/src/main/java/appeng/util/inv/filter/AEItemFilters.java b/src/main/java/appeng/util/inv/filter/AEItemFilters.java index 9a713d140..faf075657 100644 --- a/src/main/java/appeng/util/inv/filter/AEItemFilters.java +++ b/src/main/java/appeng/util/inv/filter/AEItemFilters.java @@ -23,42 +23,34 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; -public class AEItemFilters -{ - public static final IAEItemFilter INSERT_ONLY = new InsertOnlyFilter(); - public static final IAEItemFilter EXTRACT_ONLY = new ExtractOnlyFilter(); +public class AEItemFilters { + public static final IAEItemFilter INSERT_ONLY = new InsertOnlyFilter(); + public static final IAEItemFilter EXTRACT_ONLY = new ExtractOnlyFilter(); - private AEItemFilters() - { - } + private AEItemFilters() { + } - private static class InsertOnlyFilter implements IAEItemFilter - { - @Override - public boolean allowExtract( IItemHandler inv, int slot, int amount ) - { - return false; - } + private static class InsertOnlyFilter implements IAEItemFilter { + @Override + public boolean allowExtract(IItemHandler inv, int slot, int amount) { + return false; + } - @Override - public boolean allowInsert( IItemHandler inv, int slot, ItemStack stack ) - { - return true; - } - } + @Override + public boolean allowInsert(IItemHandler inv, int slot, ItemStack stack) { + return true; + } + } - private static class ExtractOnlyFilter implements IAEItemFilter - { - @Override - public boolean allowExtract( IItemHandler inv, int slot, int amount ) - { - return true; - } + private static class ExtractOnlyFilter implements IAEItemFilter { + @Override + public boolean allowExtract(IItemHandler inv, int slot, int amount) { + return true; + } - @Override - public boolean allowInsert( IItemHandler inv, int slot, ItemStack stack ) - { - return false; - } - } + @Override + public boolean allowInsert(IItemHandler inv, int slot, ItemStack stack) { + return false; + } + } } diff --git a/src/main/java/appeng/util/inv/filter/IAEItemFilter.java b/src/main/java/appeng/util/inv/filter/IAEItemFilter.java index 6e9b671c2..1dcd38f8b 100644 --- a/src/main/java/appeng/util/inv/filter/IAEItemFilter.java +++ b/src/main/java/appeng/util/inv/filter/IAEItemFilter.java @@ -23,9 +23,8 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; -public interface IAEItemFilter -{ - boolean allowExtract( IItemHandler inv, int slot, int amount ); +public interface IAEItemFilter { + boolean allowExtract(IItemHandler inv, int slot, int amount); - boolean allowInsert( IItemHandler inv, int slot, ItemStack stack ); + boolean allowInsert(IItemHandler inv, int slot, ItemStack stack); } diff --git a/src/main/java/appeng/util/item/AEItemStack.java b/src/main/java/appeng/util/item/AEItemStack.java index 87417bf5f..d5b9eddd8 100644 --- a/src/main/java/appeng/util/item/AEItemStack.java +++ b/src/main/java/appeng/util/item/AEItemStack.java @@ -18,13 +18,12 @@ package appeng.util.item; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - +import appeng.api.config.FuzzyMode; +import appeng.api.storage.IStorageChannel; +import appeng.api.storage.channels.IItemStorageChannel; +import appeng.api.storage.data.IAEItemStack; +import appeng.core.Api; +import appeng.util.Platform; import com.google.common.primitives.Ints; import gregtech.api.items.IToolItem; import ic2.api.item.ICustomDamageItem; @@ -37,385 +36,317 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.ItemHandlerHelper; -import appeng.api.config.FuzzyMode; -import appeng.api.storage.IStorageChannel; -import appeng.api.storage.channels.IItemStorageChannel; -import appeng.api.storage.data.IAEItemStack; -import appeng.core.Api; -import appeng.util.Platform; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.List; +import java.util.Objects; +import java.util.Optional; -public class AEItemStack extends AEStack implements IAEItemStack -{ - private static final String NBT_STACKSIZE = "Cnt"; - private static final String NBT_REQUESTABLE = "Req"; - private static final String NBT_CRAFTABLE = "Craft"; +public class AEItemStack extends AEStack implements IAEItemStack { + private static final String NBT_STACKSIZE = "Cnt"; + private static final String NBT_REQUESTABLE = "Req"; + private static final String NBT_CRAFTABLE = "Craft"; - private final AESharedItemStack sharedStack; - private Optional oreReference; + private final AESharedItemStack sharedStack; + private final Optional oreReference; - @SideOnly( Side.CLIENT ) - private String displayName; - @SideOnly( Side.CLIENT ) - private List tooltip; - private ItemStack cachedItemStack; + @SideOnly(Side.CLIENT) + private String displayName; + @SideOnly(Side.CLIENT) + private List tooltip; + private ItemStack cachedItemStack; - private AEItemStack( final AEItemStack is ) - { - this.setStackSize( is.getStackSize() ); - this.setCraftable( is.isCraftable() ); - this.setCountRequestable( is.getCountRequestable() ); - this.sharedStack = is.sharedStack; - this.oreReference = is.oreReference; - this.cachedItemStack = is.cachedItemStack; - } + private AEItemStack(final AEItemStack is) { + this.setStackSize(is.getStackSize()); + this.setCraftable(is.isCraftable()); + this.setCountRequestable(is.getCountRequestable()); + this.sharedStack = is.sharedStack; + this.oreReference = is.oreReference; + this.cachedItemStack = is.cachedItemStack; + } - private AEItemStack( final AESharedItemStack is, long size ) - { - this.sharedStack = is; - this.setStackSize( size ); - this.setCraftable( false ); - this.setCountRequestable( 0 ); - this.oreReference = OreHelper.INSTANCE.getOre( is.getDefinition() ); - } + private AEItemStack(final AESharedItemStack is, long size) { + this.sharedStack = is; + this.setStackSize(size); + this.setCraftable(false); + this.setCountRequestable(0); + this.oreReference = OreHelper.INSTANCE.getOre(is.getDefinition()); + } - @Nullable - public static AEItemStack fromItemStack( @Nonnull final ItemStack stack ) - { - if( stack.isEmpty() ) - { - return null; - } + @Nullable + public static AEItemStack fromItemStack(@Nonnull final ItemStack stack) { + if (stack.isEmpty()) { + return null; + } - return new AEItemStack( AEItemStackRegistry.getRegisteredStack( stack ), stack.getCount() ); - } + return new AEItemStack(AEItemStackRegistry.getRegisteredStack(stack), stack.getCount()); + } - public static IAEItemStack fromNBT( final NBTTagCompound i ) - { - if( i == null ) - { - return null; - } + public static IAEItemStack fromNBT(final NBTTagCompound i) { + if (i == null) { + return null; + } - final ItemStack itemstack = new ItemStack( i ); - if( itemstack.isEmpty() ) - { - return null; - } + final ItemStack itemstack = new ItemStack(i); + if (itemstack.isEmpty()) { + return null; + } - final AEItemStack item = AEItemStack.fromItemStack( itemstack ); + final AEItemStack item = AEItemStack.fromItemStack(itemstack); - item.setStackSize( i.getLong( NBT_STACKSIZE ) ); - item.setCountRequestable( i.getLong( NBT_REQUESTABLE ) ); - item.setCraftable( i.getBoolean( NBT_CRAFTABLE ) ); - return item; - } + item.setStackSize(i.getLong(NBT_STACKSIZE)); + item.setCountRequestable(i.getLong(NBT_REQUESTABLE)); + item.setCraftable(i.getBoolean(NBT_CRAFTABLE)); + return item; + } - @Override - public void writeToNBT( final NBTTagCompound i ) - { - this.getDefinition().writeToNBT( i ); + @Override + public void writeToNBT(final NBTTagCompound i) { + this.getDefinition().writeToNBT(i); - i.setLong( NBT_STACKSIZE, this.getStackSize() ); - i.setLong( NBT_REQUESTABLE, this.getCountRequestable() ); - i.setBoolean( NBT_CRAFTABLE, this.isCraftable() ); - } + i.setLong(NBT_STACKSIZE, this.getStackSize()); + i.setLong(NBT_REQUESTABLE, this.getCountRequestable()); + i.setBoolean(NBT_CRAFTABLE, this.isCraftable()); + } - public static AEItemStack fromPacket( final ByteBuf data ) - { - final byte mask = data.readByte(); - final byte stackType = (byte) ( ( mask & 0x0C ) >> 2 ); - final byte countReqType = (byte) ( ( mask & 0x30 ) >> 4 ); - final boolean isCraftable = ( mask & 0x40 ) > 0; + public static AEItemStack fromPacket(final ByteBuf data) { + final byte mask = data.readByte(); + final byte stackType = (byte) ((mask & 0x0C) >> 2); + final byte countReqType = (byte) ((mask & 0x30) >> 4); + final boolean isCraftable = (mask & 0x40) > 0; - final ItemStack itemstack = new ItemStack( ByteBufUtils.readTag( data ) ); - final long stackSize = getPacketValue( stackType, data ); - final long countRequestable = getPacketValue( countReqType, data ); + final ItemStack itemstack = new ItemStack(ByteBufUtils.readTag(data)); + final long stackSize = getPacketValue(stackType, data); + final long countRequestable = getPacketValue(countReqType, data); - if( itemstack.isEmpty() ) - { - return null; - } + if (itemstack.isEmpty()) { + return null; + } - final AEItemStack item = new AEItemStack( AEItemStackRegistry.getRegisteredStack( itemstack ), stackSize ); - item.setCountRequestable( countRequestable ); - item.setCraftable( isCraftable ); - return item; - } + final AEItemStack item = new AEItemStack(AEItemStackRegistry.getRegisteredStack(itemstack), stackSize); + item.setCountRequestable(countRequestable); + item.setCraftable(isCraftable); + return item; + } - @Override - public void writeToPacket( final ByteBuf i ) - { - final byte mask = (byte) ( ( this.getType( this.getStackSize() ) << 2 ) | ( this.getType( this.getCountRequestable() ) << 4 ) | ( (byte) ( this.isCraftable() ? 1 : 0 ) << 6 ) | ( this.hasTagCompound() ? 1 : 0 ) << 7 ); + @Override + public void writeToPacket(final ByteBuf i) { + final byte mask = (byte) ((this.getType(this.getStackSize()) << 2) | (this.getType(this.getCountRequestable()) << 4) | ((byte) (this.isCraftable() ? 1 : 0) << 6) | (this.hasTagCompound() ? 1 : 0) << 7); - i.writeByte( mask ); - ByteBufUtils.writeTag( i, this.getDefinition().serializeNBT() ); - this.putPacketValue( i, this.getStackSize() ); - this.putPacketValue( i, this.getCountRequestable() ); - } + i.writeByte(mask); + ByteBufUtils.writeTag(i, this.getDefinition().serializeNBT()); + this.putPacketValue(i, this.getStackSize()); + this.putPacketValue(i, this.getCountRequestable()); + } - @Override - public void add( final IAEItemStack option ) - { - if( option == null ) - { - return; - } + @Override + public void add(final IAEItemStack option) { + if (option == null) { + return; + } - this.incStackSize( option.getStackSize() ); - this.setCountRequestable( this.getCountRequestable() + option.getCountRequestable() ); - this.setCraftable( this.isCraftable() || option.isCraftable() ); - } + this.incStackSize(option.getStackSize()); + this.setCountRequestable(this.getCountRequestable() + option.getCountRequestable()); + this.setCraftable(this.isCraftable() || option.isCraftable()); + } - @Override - public boolean fuzzyComparison( final IAEItemStack other, final FuzzyMode mode ) - { - final ItemStack itemStack = this.getDefinition(); - final ItemStack otherStack = other.getDefinition(); + @Override + public boolean fuzzyComparison(final IAEItemStack other, final FuzzyMode mode) { + final ItemStack itemStack = this.getDefinition(); + final ItemStack otherStack = other.getDefinition(); - return this.fuzzyItemStackComparison( itemStack, otherStack, mode ); - } + return this.fuzzyItemStackComparison(itemStack, otherStack, mode); + } - @Override - public IAEItemStack copy() - { - return new AEItemStack( this ); - } + @Override + public IAEItemStack copy() { + return new AEItemStack(this); + } - @Override - public boolean isItem() - { - return true; - } + @Override + public boolean isItem() { + return true; + } - @Override - public boolean isFluid() - { - return false; - } + @Override + public boolean isFluid() { + return false; + } - @Override - public IStorageChannel getChannel() - { - return Api.INSTANCE.storage().getStorageChannel( IItemStorageChannel.class ); - } + @Override + public IStorageChannel getChannel() { + return Api.INSTANCE.storage().getStorageChannel(IItemStorageChannel.class); + } - @Override - public ItemStack createItemStack() - { - return ItemHandlerHelper.copyStackWithSize( this.getDefinition(), (int) Math.min( Integer.MAX_VALUE, this.getStackSize() ) ); - } + @Override + public ItemStack createItemStack() { + return ItemHandlerHelper.copyStackWithSize(this.getDefinition(), (int) Math.min(Integer.MAX_VALUE, this.getStackSize())); + } - @Override - public Item getItem() - { - return this.getDefinition().getItem(); - } + @Override + public Item getItem() { + return this.getDefinition().getItem(); + } - @Override - public int getItemDamage() - { - return this.sharedStack.getItemDamage(); - } + @Override + public int getItemDamage() { + return this.sharedStack.getItemDamage(); + } - @Override - public boolean sameOre( final IAEItemStack is ) - { - return OreHelper.INSTANCE.sameOre( this, is ); - } + @Override + public boolean sameOre(final IAEItemStack is) { + return OreHelper.INSTANCE.sameOre(this, is); + } - @Override - public boolean isSameType( final IAEItemStack otherStack ) - { - if( otherStack == null ) - { - return false; - } + @Override + public boolean isSameType(final IAEItemStack otherStack) { + if (otherStack == null) { + return false; + } - return Objects.equals( this.sharedStack, ( (AEItemStack) otherStack ).sharedStack ); - } + return Objects.equals(this.sharedStack, ((AEItemStack) otherStack).sharedStack); + } - @Override - public boolean isSameType( final ItemStack otherStack ) - { - if( otherStack.isEmpty() ) - { - return false; - } - int oldSize = otherStack.getCount(); + @Override + public boolean isSameType(final ItemStack otherStack) { + if (otherStack.isEmpty()) { + return false; + } + int oldSize = otherStack.getCount(); - otherStack.setCount( 1 ); - boolean ret = ItemStack.areItemStacksEqual( this.getDefinition(), otherStack ); - otherStack.setCount( oldSize ); + otherStack.setCount(1); + boolean ret = ItemStack.areItemStacksEqual(this.getDefinition(), otherStack); + otherStack.setCount(oldSize); - return ret; - } + return ret; + } - @Override - public int hashCode() - { - return this.sharedStack.hashCode(); - } + @Override + public int hashCode() { + return this.sharedStack.hashCode(); + } - @Override - public boolean equals( final Object ia ) - { - if( ia instanceof AEItemStack ) - { - return this.isSameType( (AEItemStack) ia ); - } - else if( ia instanceof ItemStack ) - { - // this actually breaks the equals contract (being equals to unrelated classes) - return equals( (ItemStack) ia ); - } - return false; - } + @Override + public boolean equals(final Object ia) { + if (ia instanceof AEItemStack) { + return this.isSameType((AEItemStack) ia); + } else if (ia instanceof ItemStack) { + // this actually breaks the equals contract (being equals to unrelated classes) + return equals((ItemStack) ia); + } + return false; + } - @Override - public boolean equals( final ItemStack is ) - { - return this.isSameType( is ); - } + @Override + public boolean equals(final ItemStack is) { + return this.isSameType(is); + } - @Override - public ItemStack getCachedItemStack( long stackSize ) - { - if( this.cachedItemStack != null ) - { - ItemStack currentCached = this.cachedItemStack; - this.cachedItemStack = null; - currentCached.setCount( Ints.saturatedCast( stackSize ) ); - return currentCached; - } + @Override + public ItemStack getCachedItemStack(long stackSize) { + if (this.cachedItemStack != null) { + ItemStack currentCached = this.cachedItemStack; + this.cachedItemStack = null; + currentCached.setCount(Ints.saturatedCast(stackSize)); + return currentCached; + } - ItemStack itemStack = this.createItemStack(); - itemStack.setCount( Ints.saturatedCast( stackSize ) ); + ItemStack itemStack = this.createItemStack(); + itemStack.setCount(Ints.saturatedCast(stackSize)); - return itemStack; - } + return itemStack; + } - @Override - public void setCachedItemStack( ItemStack itemStack ) - { - this.cachedItemStack = itemStack; - } + @Override + public void setCachedItemStack(ItemStack itemStack) { + this.cachedItemStack = itemStack; + } - @Override - public String toString() - { - return this.getStackSize() + "x" + this.getDefinition().getItem().getRegistryName(); - } + @Override + public String toString() { + return this.getStackSize() + "x" + this.getDefinition().getItem().getRegistryName(); + } - @SideOnly( Side.CLIENT ) - public List getToolTip() - { - if( this.tooltip == null ) - { - this.tooltip = Platform.getTooltip( this.asItemStackRepresentation() ); - } - return this.tooltip; - } + @SideOnly(Side.CLIENT) + public List getToolTip() { + if (this.tooltip == null) { + this.tooltip = Platform.getTooltip(this.asItemStackRepresentation()); + } + return this.tooltip; + } - @SideOnly( Side.CLIENT ) - public String getDisplayName() - { - if( this.displayName == null ) - { - this.displayName = Platform.getItemDisplayName( this.asItemStackRepresentation() ); - } - return this.displayName; - } + @SideOnly(Side.CLIENT) + public String getDisplayName() { + if (this.displayName == null) { + this.displayName = Platform.getItemDisplayName(this.asItemStackRepresentation()); + } + return this.displayName; + } - @SideOnly( Side.CLIENT ) - public String getModID() - { - return this.getDefinition().getItem().getRegistryName().getResourceDomain(); - } + @SideOnly(Side.CLIENT) + public String getModID() { + return this.getDefinition().getItem().getRegistryName().getResourceDomain(); + } - public Optional getOre() - { - return this.oreReference; - } + public Optional getOre() { + return this.oreReference; + } - @Override - public boolean hasTagCompound() - { - return this.getDefinition().hasTagCompound(); - } + @Override + public boolean hasTagCompound() { + return this.getDefinition().hasTagCompound(); + } - @Override - public ItemStack asItemStackRepresentation() - { - return this.getDefinition().copy(); - } + @Override + public ItemStack asItemStackRepresentation() { + return this.getDefinition().copy(); + } - @Override - public ItemStack getDefinition() - { - return this.sharedStack.getDefinition(); - } + @Override + public ItemStack getDefinition() { + return this.sharedStack.getDefinition(); + } - AESharedItemStack getSharedStack() - { - return this.sharedStack; - } + AESharedItemStack getSharedStack() { + return this.sharedStack; + } - private boolean fuzzyItemStackComparison( ItemStack a, ItemStack b, FuzzyMode mode ) - { - if( a.getItem() == b.getItem() && ( a.getItem().isDamageable() || Platform.isGTDamageableItem( a.getItem() ) ) ) - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - if( a.getItem().isDamageable() ) - { - return true; - } - else if( Platform.isGTDamageableItem( a.getItem() ) ) - { - return a.getItemDamage() == b.getItemDamage(); - } - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - if( Platform.isIC2DamageableItem( a.getItem() ) ) - { - return ( (ICustomDamageItem) a.getItem() ).getCustomDamage( a ) > 1 == ( (ICustomDamageItem) b.getItem() ).getCustomDamage( b ) > 1; - } - else if( a.getItem().isDamageable() ) - { - return a.getItemDamage() > 1 == b.getItemDamage() > 1; - } - else if( Platform.isGTDamageableItem( a.getItem() ) ) - { - return ( (IToolItem) a.getItem() ).getItemDamage( a ) > 1 == ( (IToolItem) b.getItem() ).getItemDamage( b ) > 1; - } - } - else - { - float percentDamageOfA = 0; - float percentDamageOfB = 0; - if( Platform.isIC2DamageableItem( a.getItem() ) ) - { - percentDamageOfA = (float) ( (ICustomDamageItem) a.getItem() ).getCustomDamage( a ) / ( (ICustomDamageItem) a.getItem() ).getMaxCustomDamage( a ); - percentDamageOfB = (float) ( (ICustomDamageItem) b.getItem() ).getCustomDamage( b ) / ( (ICustomDamageItem) b.getItem() ).getMaxCustomDamage( b ); - } - else if( a.getItem().isDamageable() ) - { - percentDamageOfA = (float) a.getItemDamage() / a.getMaxDamage(); - percentDamageOfB = (float) b.getItemDamage() / b.getMaxDamage(); - } - else if( Platform.isGTDamageableItem( a.getItem() ) ) - { - percentDamageOfA = (float) ( (IToolItem) a.getItem() ).getItemDamage( a ) / ( (IToolItem) a.getItem() ).getMaxItemDamage( a ); - percentDamageOfB = (float) ( (IToolItem) b.getItem() ).getItemDamage( b ) / ( (IToolItem) b.getItem() ).getMaxItemDamage( b ); - } + private boolean fuzzyItemStackComparison(ItemStack a, ItemStack b, FuzzyMode mode) { + if (a.getItem() == b.getItem() && (a.getItem().isDamageable() || Platform.isGTDamageableItem(a.getItem()))) { + if (mode == FuzzyMode.IGNORE_ALL) { + if (a.getItem().isDamageable()) { + return true; + } else if (Platform.isGTDamageableItem(a.getItem())) { + return a.getItemDamage() == b.getItemDamage(); + } + } else if (mode == FuzzyMode.PERCENT_99) { + if (Platform.isIC2DamageableItem(a.getItem())) { + return ((ICustomDamageItem) a.getItem()).getCustomDamage(a) > 1 == ((ICustomDamageItem) b.getItem()).getCustomDamage(b) > 1; + } else if (a.getItem().isDamageable()) { + return a.getItemDamage() > 1 == b.getItemDamage() > 1; + } else if (Platform.isGTDamageableItem(a.getItem())) { + return ((IToolItem) a.getItem()).getItemDamage(a) > 1 == ((IToolItem) b.getItem()).getItemDamage(b) > 1; + } + } else { + float percentDamageOfA = 0; + float percentDamageOfB = 0; + if (Platform.isIC2DamageableItem(a.getItem())) { + percentDamageOfA = (float) ((ICustomDamageItem) a.getItem()).getCustomDamage(a) / ((ICustomDamageItem) a.getItem()).getMaxCustomDamage(a); + percentDamageOfB = (float) ((ICustomDamageItem) b.getItem()).getCustomDamage(b) / ((ICustomDamageItem) b.getItem()).getMaxCustomDamage(b); + } else if (a.getItem().isDamageable()) { + percentDamageOfA = (float) a.getItemDamage() / a.getMaxDamage(); + percentDamageOfB = (float) b.getItemDamage() / b.getMaxDamage(); + } else if (Platform.isGTDamageableItem(a.getItem())) { + percentDamageOfA = (float) ((IToolItem) a.getItem()).getItemDamage(a) / ((IToolItem) a.getItem()).getMaxItemDamage(a); + percentDamageOfB = (float) ((IToolItem) b.getItem()).getItemDamage(b) / ((IToolItem) b.getItem()).getMaxItemDamage(b); + } - return percentDamageOfA > mode.breakPoint == percentDamageOfB > mode.breakPoint; - } - } + return percentDamageOfA > mode.breakPoint == percentDamageOfB > mode.breakPoint; + } + } - return false; - } + return false; + } } diff --git a/src/main/java/appeng/util/item/AEItemStackRegistry.java b/src/main/java/appeng/util/item/AEItemStackRegistry.java index 0fce27e36..98ec97aa5 100644 --- a/src/main/java/appeng/util/item/AEItemStackRegistry.java +++ b/src/main/java/appeng/util/item/AEItemStackRegistry.java @@ -23,12 +23,11 @@ package appeng.util.item; -import java.lang.ref.WeakReference; -import java.util.WeakHashMap; +import net.minecraft.item.ItemStack; import javax.annotation.Nonnull; - -import net.minecraft.item.ItemStack; +import java.lang.ref.WeakReference; +import java.util.WeakHashMap; public final class AEItemStackRegistry { private static final WeakHashMap> REGISTRY = new WeakHashMap<>(); diff --git a/src/main/java/appeng/util/item/AESharedItemStack.java b/src/main/java/appeng/util/item/AESharedItemStack.java index 053c1db73..9586e8656 100644 --- a/src/main/java/appeng/util/item/AESharedItemStack.java +++ b/src/main/java/appeng/util/item/AESharedItemStack.java @@ -18,82 +18,70 @@ package appeng.util.item; -import java.util.Objects; - import com.google.common.base.Preconditions; - import net.minecraft.item.ItemStack; +import java.util.Objects; -final class AESharedItemStack -{ - private final ItemStack itemStack; - private final int itemDamage; - private final int hashCode; +final class AESharedItemStack { - public AESharedItemStack( final ItemStack itemStack ) - { - this( itemStack, itemStack.getItemDamage() ); - } + private final ItemStack itemStack; + private final int itemDamage; + private final int hashCode; - /** - * A constructor to explicitly set the damage value and not fetch it from the {@link ItemStack} - * - * @param itemStack The {@link ItemStack} to filter - * @param damage The damage of the item - */ - private AESharedItemStack( ItemStack itemStack, int damage ) - { - this.itemStack = itemStack; - this.itemDamage = damage; + public AESharedItemStack(final ItemStack itemStack) { + this(itemStack, itemStack.getItemDamage()); + } - // Ensure this is always called last. - this.hashCode = this.makeHashCode(); - } + /** + * A constructor to explicitly set the damage value and not fetch it from the {@link ItemStack} + * + * @param itemStack The {@link ItemStack} to filter + * @param damage The damage of the item + */ + private AESharedItemStack(ItemStack itemStack, int damage) { + this.itemStack = itemStack; + this.itemDamage = damage; - ItemStack getDefinition() - { - return this.itemStack; - } + // Ensure this is always called last. + this.hashCode = this.makeHashCode(); + } - int getItemDamage() - { - return this.itemDamage; - } + ItemStack getDefinition() { + return this.itemStack; + } - @Override - public int hashCode() - { - return this.hashCode; - } + int getItemDamage() { + return this.itemDamage; + } - @Override - public boolean equals( final Object obj ) - { - if( this == obj ) - { - return true; - } - if( !( obj instanceof AESharedItemStack ) ) - { - return false; - } + @Override + public int hashCode() { + return this.hashCode; + } - final AESharedItemStack other = (AESharedItemStack) obj; - Preconditions.checkState( this.itemStack.getCount() == 1, "ItemStack#getCount() has to be 1" ); - Preconditions.checkArgument( other.getDefinition().getCount() == 1, "ItemStack#getCount() has to be 1" ); + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof AESharedItemStack)) { + return false; + } - if( this.itemStack == other.itemStack ) - { - return true; - } - return ItemStack.areItemStacksEqual( this.itemStack, other.itemStack ); - } + final AESharedItemStack other = (AESharedItemStack) obj; + Preconditions.checkState(this.itemStack.getCount() == 1, "ItemStack#getCount() has to be 1"); + Preconditions.checkArgument(other.getDefinition().getCount() == 1, "ItemStack#getCount() has to be 1"); - private int makeHashCode() - { - return Objects.hash( this.itemStack.getItem(), this.itemDamage, this.itemStack.hasTagCompound() ? this.itemStack.getTagCompound() : 0 ); - } + if (this.itemStack == other.itemStack) { + return true; + } + return ItemStack.areItemStacksEqual(this.itemStack, other.itemStack); + } + + private int makeHashCode() { + return Objects.hash(this.itemStack.getItem(), this.itemDamage, this.itemStack.hasTagCompound() ? this.itemStack.getTagCompound() : 0); + } } diff --git a/src/main/java/appeng/util/item/AEStack.java b/src/main/java/appeng/util/item/AEStack.java index 0003b9e0e..6dc5e10d6 100644 --- a/src/main/java/appeng/util/item/AEStack.java +++ b/src/main/java/appeng/util/item/AEStack.java @@ -28,22 +28,16 @@ public abstract class AEStack> implements IAEStack { private long stackSize; private long countRequestable; - protected static long getPacketValue( final byte type, final ByteBuf tag ) - { - if( type == 0 ) - { + protected static long getPacketValue(final byte type, final ByteBuf tag) { + if (type == 0) { long l = tag.readByte(); l -= Byte.MIN_VALUE; return l; - } - else if( type == 1 ) - { + } else if (type == 1) { long l = tag.readShort(); l -= Short.MIN_VALUE; return l; - } - else if( type == 2 ) - { + } else if (type == 2) { long l = tag.readInt(); l -= Integer.MIN_VALUE; return l; @@ -125,45 +119,29 @@ public abstract class AEStack> implements IAEStack { this.countRequestable -= i; } - protected byte getType( final long num ) - { - if( num <= 255 ) - { + protected byte getType(final long num) { + if (num <= 255) { return 0; - } - else if( num <= 65535 ) - { + } else if (num <= 65535) { return 1; - } - else if( num <= 4294967295L ) - { + } else if (num <= 4294967295L) { return 2; - } - else - { + } else { return 3; } } protected abstract boolean hasTagCompound(); - protected void putPacketValue( final ByteBuf tag, final long num ) - { - if( num <= 255 ) - { - tag.writeByte( (byte) ( num + Byte.MIN_VALUE ) ); - } - else if( num <= 65535 ) - { - tag.writeShort( (short) ( num + Short.MIN_VALUE ) ); - } - else if( num <= 4294967295L ) - { - tag.writeInt( (int) ( num + Integer.MIN_VALUE ) ); - } - else - { - tag.writeLong( num ); + protected void putPacketValue(final ByteBuf tag, final long num) { + if (num <= 255) { + tag.writeByte((byte) (num + Byte.MIN_VALUE)); + } else if (num <= 65535) { + tag.writeShort((short) (num + Short.MIN_VALUE)); + } else if (num <= 4294967295L) { + tag.writeInt((int) (num + Integer.MIN_VALUE)); + } else { + tag.writeLong(num); } } } diff --git a/src/main/java/appeng/util/item/FuzzyItemVariantList.java b/src/main/java/appeng/util/item/FuzzyItemVariantList.java index aa444982a..6ad8a1302 100644 --- a/src/main/java/appeng/util/item/FuzzyItemVariantList.java +++ b/src/main/java/appeng/util/item/FuzzyItemVariantList.java @@ -18,227 +18,189 @@ package appeng.util.item; +import appeng.api.config.FuzzyMode; +import appeng.api.storage.data.IAEItemStack; +import appeng.util.Platform; +import com.google.common.base.Preconditions; +import gregtech.api.items.IToolItem; +import ic2.api.item.ICustomDamageItem; +import it.unimi.dsi.fastutil.objects.Object2ObjectAVLTreeMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectSortedMap; +import net.minecraft.item.ItemStack; + import java.util.Collection; import java.util.Comparator; import java.util.Map; -import appeng.util.Platform; -import com.google.common.base.Preconditions; - -import gregtech.api.items.IToolItem; -import ic2.api.item.ICustomDamageItem; -import net.minecraft.item.ItemStack; - -import it.unimi.dsi.fastutil.objects.Object2ObjectAVLTreeMap; -import it.unimi.dsi.fastutil.objects.Object2ObjectSortedMap; - -import appeng.api.config.FuzzyMode; -import appeng.api.storage.data.IAEItemStack; - /** * This variant list is optimized for damageable items, and supports selecting durability ranges with * {@link #findFuzzy(IAEItemStack, FuzzyMode)}. */ -class FuzzyItemVariantList extends ItemVariantList -{ +class FuzzyItemVariantList extends ItemVariantList { - static final SharedStackComparator COMPARATOR = new SharedStackComparator(); + static final SharedStackComparator COMPARATOR = new SharedStackComparator(); - // NOTE: We only use Object as they key here so we can pass our special DamageBounds to the subMap method. - // We NEVER put any keys in this map that are not AESharedItemStacks. - private final Object2ObjectSortedMap records = new Object2ObjectAVLTreeMap<>( COMPARATOR ); + // NOTE: We only use Object as they key here so we can pass our special DamageBounds to the subMap method. + // We NEVER put any keys in this map that are not AESharedItemStacks. + private final Object2ObjectSortedMap records = new Object2ObjectAVLTreeMap<>(COMPARATOR); - @Override - public Collection findFuzzy( final IAEItemStack filter, final FuzzyMode fuzzy ) - { - ItemStack itemStack = filter.getDefinition(); + @Override + public Collection findFuzzy(final IAEItemStack filter, final FuzzyMode fuzzy) { + ItemStack itemStack = filter.getDefinition(); - ItemDamageBound lowerBound = makeLowerBound( itemStack, fuzzy ); - ItemDamageBound upperBound = makeUpperBound( itemStack, fuzzy ); - Preconditions.checkState( lowerBound.itemDamage > upperBound.itemDamage ); + ItemDamageBound lowerBound = makeLowerBound(itemStack, fuzzy); + ItemDamageBound upperBound = makeUpperBound(itemStack, fuzzy); + Preconditions.checkState(lowerBound.itemDamage > upperBound.itemDamage); - return this.records.subMap( lowerBound, upperBound ).values(); - } + return this.records.subMap(lowerBound, upperBound).values(); + } - @SuppressWarnings( "unchecked" ) - @Override - Map getRecords() - { - // We ensure on our end that we NEVER use anything but AESharedItemStack as the key in this map - return (Map) (Object) this.records; - } + @SuppressWarnings("unchecked") + @Override + Map getRecords() { + // We ensure on our end that we NEVER use anything but AESharedItemStack as the key in this map + return (Map) (Object) this.records; + } - static class ItemDamageBound - { - final int itemDamage; + static class ItemDamageBound { + final int itemDamage; - public ItemDamageBound( int itemDamage ) - { - this.itemDamage = itemDamage; - } - } + public ItemDamageBound(int itemDamage) { + this.itemDamage = itemDamage; + } + } - /** - * This comparator creates a strict and total ordering over all {@link AESharedItemStack} of the same item. To - * support selecting ranges of durability, it is defined for type {@link Object} and also accepts - * {@link ItemDamageBound} as an argument to compare against. - */ - static class SharedStackComparator implements Comparator - { - @Override - public int compare( Object a, Object b ) - { - // Either argument can either be a damage bound or a shared item stack - // Since we never put damage bounds into the map as keys, only one - // of the two arguments can possibly be a bound - ItemDamageBound boundA = null; - AESharedItemStack stackA = null; - int itemDamageA; - if( a instanceof ItemDamageBound ) - { - boundA = (ItemDamageBound) a; - itemDamageA = boundA.itemDamage; - } - else - { - stackA = (AESharedItemStack) a; - itemDamageA = stackA.getItemDamage(); - } - ItemDamageBound boundB = null; - AESharedItemStack stackB = null; - int itemDamageB; - if( b instanceof ItemDamageBound ) - { - boundB = (ItemDamageBound) b; - itemDamageB = boundB.itemDamage; - } - else - { - stackB = (AESharedItemStack) b; - itemDamageB = stackB.getItemDamage(); - } + /** + * This comparator creates a strict and total ordering over all {@link AESharedItemStack} of the same item. To + * support selecting ranges of durability, it is defined for type {@link Object} and also accepts + * {@link ItemDamageBound} as an argument to compare against. + */ + static class SharedStackComparator implements Comparator { + @Override + public int compare(Object a, Object b) { + // Either argument can either be a damage bound or a shared item stack + // Since we never put damage bounds into the map as keys, only one + // of the two arguments can possibly be a bound + ItemDamageBound boundA = null; + AESharedItemStack stackA = null; + int itemDamageA; + if (a instanceof ItemDamageBound) { + boundA = (ItemDamageBound) a; + itemDamageA = boundA.itemDamage; + } else { + stackA = (AESharedItemStack) a; + itemDamageA = stackA.getItemDamage(); + } + ItemDamageBound boundB = null; + AESharedItemStack stackB = null; + int itemDamageB; + if (b instanceof ItemDamageBound) { + boundB = (ItemDamageBound) b; + itemDamageB = boundB.itemDamage; + } else { + stackB = (AESharedItemStack) b; + itemDamageB = stackB.getItemDamage(); + } - // When either argument is a damage bound, we just compare the damage values because it is used - // only to get a certain damage range out of the map. - if( boundA != null || boundB != null ) - { - return Integer.compare( itemDamageB, itemDamageA ); - } + // When either argument is a damage bound, we just compare the damage values because it is used + // only to get a certain damage range out of the map. + if (boundA != null || boundB != null) { + return Integer.compare(itemDamageB, itemDamageA); + } - ItemStack itemStackA = stackA.getDefinition(); - ItemStack itemStackB = stackB.getDefinition(); - Preconditions.checkState( itemStackA.getCount() == 1, "ItemStack#getCount() has to be 1" ); - Preconditions.checkArgument( itemStackB.getCount() == 1, "ItemStack#getCount() has to be 1" ); + ItemStack itemStackA = stackA.getDefinition(); + ItemStack itemStackB = stackB.getDefinition(); + Preconditions.checkState(itemStackA.getCount() == 1, "ItemStack#getCount() has to be 1"); + Preconditions.checkArgument(itemStackB.getCount() == 1, "ItemStack#getCount() has to be 1"); - if( itemStackA == itemStackB ) - { - return 0; - } + if (itemStackA == itemStackB) { + return 0; + } - // Damaged items are sorted before undamaged items - final int damageValue = Integer.compare( itemDamageB, itemDamageA ); - if( damageValue != 0 ) - { - return damageValue; - } + // Damaged items are sorted before undamaged items + final int damageValue = Integer.compare(itemDamageB, itemDamageA); + if (damageValue != 0) { + return damageValue; + } - // As a final tie breaker, order by the object identity of the item stack - // While this will order seemingly at random, we only need the order of - // damage values to be predictable, while still having to satisfy the - // complete order requirements of the sorted map - return Long.compare( System.identityHashCode( itemStackA ), System.identityHashCode( itemStackB ) ); - } - } + // As a final tie breaker, order by the object identity of the item stack + // While this will order seemingly at random, we only need the order of + // damage values to be predictable, while still having to satisfy the + // complete order requirements of the sorted map + return Long.compare(System.identityHashCode(itemStackA), System.identityHashCode(itemStackB)); + } + } - /** - * Minecraft reverses the damage values. So anything with a damage of 0 is undamaged and increases the more damaged - * the item is. - *

- * Further the used subMap follows [MAX_DAMAGE, MIN_DAMAGE), so to include undamaged items, we have to start with a - * lower damage value than 0, while it is fine to use {@link ItemStack#getMaxDamage()} for the upper bound. - */ - private static final int MIN_DAMAGE_VALUE = -1; + /** + * Minecraft reverses the damage values. So anything with a damage of 0 is undamaged and increases the more damaged + * the item is. + *

+ * Further the used subMap follows [MAX_DAMAGE, MIN_DAMAGE), so to include undamaged items, we have to start with a + * lower damage value than 0, while it is fine to use {@link ItemStack#getMaxDamage()} for the upper bound. + */ + private static final int MIN_DAMAGE_VALUE = -1; - /* - * Keep in mind that the stack order is from most damaged to least damaged, so this lower bound will actually be a - * higher number than the upper bound. - */ - static ItemDamageBound makeLowerBound( final ItemStack stack, final FuzzyMode fuzzy ) - { - Preconditions.checkState( stack.getItem().isDamageable() || ( Platform.isGTDamageableItem( stack.getItem() ) ), "Item#isDamageable() has to be true" ); + /* + * Keep in mind that the stack order is from most damaged to least damaged, so this lower bound will actually be a + * higher number than the upper bound. + */ + static ItemDamageBound makeLowerBound(final ItemStack stack, final FuzzyMode fuzzy) { + Preconditions.checkState(stack.getItem().isDamageable() || (Platform.isGTDamageableItem(stack.getItem())), "Item#isDamageable() has to be true"); - int damage; - int maxDamage; - if( Platform.isIC2DamageableItem( stack.getItem() ) ) - { - maxDamage = ( (ICustomDamageItem) stack.getItem() ).getMaxCustomDamage( stack ); - damage = ( (ICustomDamageItem) stack.getItem() ).getCustomDamage( stack ); - } - else if( Platform.isGTDamageableItem( stack.getItem() ) ) - { - maxDamage = ( (IToolItem) stack.getItem() ).getMaxItemDamage( stack ); - damage = ( (IToolItem) stack.getItem() ).getItemDamage( stack ); - } - else - { - maxDamage = stack.getMaxDamage(); - damage = stack.getItemDamage(); - } + int damage; + int maxDamage; + if (Platform.isIC2DamageableItem(stack.getItem())) { + maxDamage = ((ICustomDamageItem) stack.getItem()).getMaxCustomDamage(stack); + damage = ((ICustomDamageItem) stack.getItem()).getCustomDamage(stack); + } else if (Platform.isGTDamageableItem(stack.getItem())) { + maxDamage = ((IToolItem) stack.getItem()).getMaxItemDamage(stack); + damage = ((IToolItem) stack.getItem()).getItemDamage(stack); + } else { + maxDamage = stack.getMaxDamage(); + damage = stack.getItemDamage(); + } - if( fuzzy == FuzzyMode.IGNORE_ALL ) - { - if( maxDamage != 0 ) - { - damage = maxDamage; - } - } - else - { - final int breakpoint = fuzzy.calculateBreakPoint( maxDamage ); - damage = damage <= breakpoint ? breakpoint : maxDamage; - } + if (fuzzy == FuzzyMode.IGNORE_ALL) { + if (maxDamage != 0) { + damage = maxDamage; + } + } else { + final int breakpoint = fuzzy.calculateBreakPoint(maxDamage); + damage = damage <= breakpoint ? breakpoint : maxDamage; + } - return new ItemDamageBound( damage ); - } + return new ItemDamageBound(damage); + } - /* - * Keep in mind that the stack order is from most damaged to least damaged, so this upper bound will actually be a - * lower number than the lower bound. It also is exclusive. - */ - static ItemDamageBound makeUpperBound( final ItemStack stack, final FuzzyMode fuzzy ) - { - Preconditions.checkState( stack.getItem().isDamageable() || ( Platform.isGTDamageableItem( stack.getItem() ) ), "Item#isDamageable() has to be true" ); + /* + * Keep in mind that the stack order is from most damaged to least damaged, so this upper bound will actually be a + * lower number than the lower bound. It also is exclusive. + */ + static ItemDamageBound makeUpperBound(final ItemStack stack, final FuzzyMode fuzzy) { + Preconditions.checkState(stack.getItem().isDamageable() || (Platform.isGTDamageableItem(stack.getItem())), "Item#isDamageable() has to be true"); - int damage; - if( fuzzy == FuzzyMode.IGNORE_ALL ) - { - damage = MIN_DAMAGE_VALUE; - } - else - { - int maxDamage; - if( Platform.isIC2DamageableItem( stack.getItem() ) ) - { - maxDamage = ( (ICustomDamageItem) stack.getItem() ).getMaxCustomDamage( stack ); - damage = ( (ICustomDamageItem) stack.getItem() ).getCustomDamage( stack ); - } - else if( Platform.isGTDamageableItem( stack.getItem() ) ) - { - maxDamage = ( (IToolItem) stack.getItem() ).getMaxItemDamage( stack ); - damage = ( (IToolItem) stack.getItem() ).getItemDamage( stack ); - } - else - { - maxDamage = stack.getMaxDamage(); - damage = stack.getItemDamage(); - } + int damage; + if (fuzzy == FuzzyMode.IGNORE_ALL) { + damage = MIN_DAMAGE_VALUE; + } else { + int maxDamage; + if (Platform.isIC2DamageableItem(stack.getItem())) { + maxDamage = ((ICustomDamageItem) stack.getItem()).getMaxCustomDamage(stack); + damage = ((ICustomDamageItem) stack.getItem()).getCustomDamage(stack); + } else if (Platform.isGTDamageableItem(stack.getItem())) { + maxDamage = ((IToolItem) stack.getItem()).getMaxItemDamage(stack); + damage = ((IToolItem) stack.getItem()).getItemDamage(stack); + } else { + maxDamage = stack.getMaxDamage(); + damage = stack.getItemDamage(); + } - final int breakpoint = fuzzy.calculateBreakPoint( maxDamage ); - damage = damage <= breakpoint ? MIN_DAMAGE_VALUE : breakpoint; - } + final int breakpoint = fuzzy.calculateBreakPoint(maxDamage); + damage = damage <= breakpoint ? MIN_DAMAGE_VALUE : breakpoint; + } - return new ItemDamageBound( damage ); - } + return new ItemDamageBound(damage); + } } diff --git a/src/main/java/appeng/util/item/ItemList.java b/src/main/java/appeng/util/item/ItemList.java index 4fd1242ba..0c0223e7d 100644 --- a/src/main/java/appeng/util/item/ItemList.java +++ b/src/main/java/appeng/util/item/ItemList.java @@ -18,234 +18,192 @@ package appeng.util.item; -import java.util.Collection; -import java.util.Collections; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.concurrent.atomic.AtomicInteger; - -import appeng.util.Platform; -import net.minecraft.item.Item; - -import it.unimi.dsi.fastutil.objects.Reference2ObjectMap; -import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; - import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; +import appeng.util.Platform; +import it.unimi.dsi.fastutil.objects.Reference2ObjectMap; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; +import net.minecraft.item.Item; + +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; -public final class ItemList implements IItemList -{ +public final class ItemList implements IItemList { - private final Reference2ObjectMap records = new Reference2ObjectOpenHashMap<>(); - /** - * We increment this version field everytime an attempt to mutate this item list (or potentially one of its - * sub-lists) is made. Iterators will copy the version when they are created and compare it against the current - * version whenever they advance to trigger a {@link ConcurrentModificationException}. - */ - private final AtomicInteger version = new AtomicInteger( 0 ); + private final Reference2ObjectMap records = new Reference2ObjectOpenHashMap<>(); + /** + * We increment this version field everytime an attempt to mutate this item list (or potentially one of its + * sub-lists) is made. Iterators will copy the version when they are created and compare it against the current + * version whenever they advance to trigger a {@link ConcurrentModificationException}. + */ + private final AtomicInteger version = new AtomicInteger(0); - @Override - public IAEItemStack findPrecise( final IAEItemStack itemStack ) - { - if( itemStack == null ) - { - return null; - } + @Override + public IAEItemStack findPrecise(final IAEItemStack itemStack) { + if (itemStack == null) { + return null; + } - ItemVariantList record = this.records.get( itemStack.getItem() ); - return record != null ? record.findPrecise( itemStack ) : null; - } + ItemVariantList record = this.records.get(itemStack.getItem()); + return record != null ? record.findPrecise(itemStack) : null; + } - @Override - public Collection findFuzzy( final IAEItemStack filter, final FuzzyMode fuzzy ) - { - if( filter == null ) - { - return Collections.emptyList(); - } + @Override + public Collection findFuzzy(final IAEItemStack filter, final FuzzyMode fuzzy) { + if (filter == null) { + return Collections.emptyList(); + } - ItemVariantList record = this.records.get( filter.getItem() ); - return record != null ? record.findFuzzy( filter, fuzzy ) : Collections.emptyList(); - } + ItemVariantList record = this.records.get(filter.getItem()); + return record != null ? record.findFuzzy(filter, fuzzy) : Collections.emptyList(); + } - @Override - public boolean isEmpty() - { - return !this.iterator().hasNext(); - } + @Override + public boolean isEmpty() { + return !this.iterator().hasNext(); + } - @Override - public void add( final IAEItemStack itemStack ) - { - version.incrementAndGet(); + @Override + public void add(final IAEItemStack itemStack) { + version.incrementAndGet(); - if( itemStack == null ) - { - return; - } + if (itemStack == null) { + return; + } - this.getOrCreateRecord( itemStack.getItem() ).add( itemStack ); - } + this.getOrCreateRecord(itemStack.getItem()).add(itemStack); + } - @Override - public void addStorage( final IAEItemStack itemStack ) - { - version.incrementAndGet(); + @Override + public void addStorage(final IAEItemStack itemStack) { + version.incrementAndGet(); - if( itemStack == null ) - { - return; - } + if (itemStack == null) { + return; + } - this.getOrCreateRecord( itemStack.getItem() ).addStorage( itemStack ); - } + this.getOrCreateRecord(itemStack.getItem()).addStorage(itemStack); + } - @Override - public void addCrafting( final IAEItemStack itemStack ) - { - version.incrementAndGet(); + @Override + public void addCrafting(final IAEItemStack itemStack) { + version.incrementAndGet(); - if( itemStack == null ) - { - return; - } + if (itemStack == null) { + return; + } - this.getOrCreateRecord( itemStack.getItem() ).addCrafting( itemStack ); - } + this.getOrCreateRecord(itemStack.getItem()).addCrafting(itemStack); + } - @Override - public void addRequestable( final IAEItemStack itemStack ) - { - version.incrementAndGet(); + @Override + public void addRequestable(final IAEItemStack itemStack) { + version.incrementAndGet(); - if( itemStack == null ) - { - return; - } + if (itemStack == null) { + return; + } - this.getOrCreateRecord( itemStack.getItem() ).addRequestable( itemStack ); - } + this.getOrCreateRecord(itemStack.getItem()).addRequestable(itemStack); + } - @Override - public IAEItemStack getFirstItem() - { - for( final IAEItemStack stackType : this ) - { - return stackType; - } + @Override + public IAEItemStack getFirstItem() { + for (final IAEItemStack stackType : this) { + return stackType; + } - return null; - } + return null; + } - @Override - public int size() - { - int size = 0; - for( ItemVariantList entry : records.values() ) - { - size += entry.size(); - } + @Override + public int size() { + int size = 0; + for (ItemVariantList entry : records.values()) { + size += entry.size(); + } - return size; - } + return size; + } - @Override - public Iterator iterator() - { - return new ChainedIterator( this.records.values().iterator(), version ); - } + @Override + public Iterator iterator() { + return new ChainedIterator(this.records.values().iterator(), version); + } - @Override - public void resetStatus() - { - for( final IAEItemStack i : this ) - { - i.reset(); - } - } + @Override + public void resetStatus() { + for (final IAEItemStack i : this) { + i.reset(); + } + } - private ItemVariantList getOrCreateRecord( Item item ) - { - return this.records.computeIfAbsent( item, this::makeRecordMap ); - } + private ItemVariantList getOrCreateRecord(Item item) { + return this.records.computeIfAbsent(item, this::makeRecordMap); + } - private ItemVariantList makeRecordMap( Item item ) - { - if( item.isDamageable() || Platform.isGTDamageableItem( item ) ) - { - return new FuzzyItemVariantList(); - } - else - { - return new NormalItemVariantList(); - } - } + private ItemVariantList makeRecordMap(Item item) { + if (item.isDamageable() || Platform.isGTDamageableItem(item)) { + return new FuzzyItemVariantList(); + } else { + return new NormalItemVariantList(); + } + } - /** - * Iterates over multiple item lists as if they were one list. - */ - private static class ChainedIterator implements Iterator - { + /** + * Iterates over multiple item lists as if they were one list. + */ + private static class ChainedIterator implements Iterator { - private final AtomicInteger parentVersion; - private final int version; - private final Iterator parent; - private Iterator next; + private final AtomicInteger parentVersion; + private final int version; + private final Iterator parent; + private Iterator next; - public ChainedIterator( Iterator iterator, AtomicInteger parentVersion ) - { - this.parent = iterator; - this.parentVersion = parentVersion; - this.version = parentVersion.get(); - this.ensureItems(); - } + public ChainedIterator(Iterator iterator, AtomicInteger parentVersion) { + this.parent = iterator; + this.parentVersion = parentVersion; + this.version = parentVersion.get(); + this.ensureItems(); + } - @Override - public boolean hasNext() - { - return next != null && next.hasNext(); - } + @Override + public boolean hasNext() { + return next != null && next.hasNext(); + } - @Override - public IAEItemStack next() - { - if( this.next == null ) - { - throw new NoSuchElementException(); - } - if( this.version != this.parentVersion.get() ) - { - throw new ConcurrentModificationException(); - } + @Override + public IAEItemStack next() { + if (this.next == null) { + throw new NoSuchElementException(); + } + if (this.version != this.parentVersion.get()) { + throw new ConcurrentModificationException(); + } - IAEItemStack result = this.next.next(); - this.ensureItems(); - return result; - } + IAEItemStack result = this.next.next(); + this.ensureItems(); + return result; + } - private void ensureItems() - { - if( hasNext() ) - { - return; // Still items left in the current one - } + private void ensureItems() { + if (hasNext()) { + return; // Still items left in the current one + } - // Find the next iterator willing to return some items... - while ( this.parent.hasNext() ) - { - this.next = this.parent.next().iterator(); + // Find the next iterator willing to return some items... + while (this.parent.hasNext()) { + this.next = this.parent.next().iterator(); - if( this.next.hasNext() ) - { - return; // Found one! - } - } + if (this.next.hasNext()) { + return; // Found one! + } + } - // No more items - this.next = null; - } - } + // No more items + this.next = null; + } + } } diff --git a/src/main/java/appeng/util/item/ItemModList.java b/src/main/java/appeng/util/item/ItemModList.java index 60268f679..05da2df82 100644 --- a/src/main/java/appeng/util/item/ItemModList.java +++ b/src/main/java/appeng/util/item/ItemModList.java @@ -19,69 +19,56 @@ package appeng.util.item; -import java.util.Collection; - import appeng.api.AEApi; import appeng.api.config.FuzzyMode; import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemContainer; +import java.util.Collection; -public class ItemModList implements IItemContainer -{ - private final IItemContainer backingStore; - private final IItemContainer overrides = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); +public class ItemModList implements IItemContainer { - public ItemModList( final IItemContainer backend ) - { - this.backingStore = backend; - } + private final IItemContainer backingStore; + private final IItemContainer overrides = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList(); - @Override - public void add( final IAEItemStack option ) - { - IAEItemStack over = this.overrides.findPrecise( option ); - if( over == null ) - { - over = this.backingStore.findPrecise( option ); - if( over == null ) - { - this.overrides.add( option ); - } - else - { - option.add( over ); - this.overrides.add( option ); - } - } - else - { - this.overrides.add( option ); - } - } + public ItemModList(final IItemContainer backend) { + this.backingStore = backend; + } - @Override - public IAEItemStack findPrecise( final IAEItemStack i ) - { - final IAEItemStack over = this.overrides.findPrecise( i ); - if( over == null ) - { - return this.backingStore.findPrecise( i ); - } - return over; - } + @Override + public void add(final IAEItemStack option) { + IAEItemStack over = this.overrides.findPrecise(option); + if (over == null) { + over = this.backingStore.findPrecise(option); + if (over == null) { + this.overrides.add(option); + } else { + option.add(over); + this.overrides.add(option); + } + } else { + this.overrides.add(option); + } + } - @Override - public Collection findFuzzy( final IAEItemStack input, final FuzzyMode fuzzy ) - { - return this.overrides.findFuzzy( input, fuzzy ); - } + @Override + public IAEItemStack findPrecise(final IAEItemStack i) { + final IAEItemStack over = this.overrides.findPrecise(i); + if (over == null) { + return this.backingStore.findPrecise(i); + } + return over; + } - @Override - public boolean isEmpty() - { - return this.overrides.isEmpty() && this.backingStore.isEmpty(); - } + @Override + public Collection findFuzzy(final IAEItemStack input, final FuzzyMode fuzzy) { + return this.overrides.findFuzzy(input, fuzzy); + } + + @Override + public boolean isEmpty() { + return this.overrides.isEmpty() && this.backingStore.isEmpty(); + } } diff --git a/src/main/java/appeng/util/item/ItemVariantList.java b/src/main/java/appeng/util/item/ItemVariantList.java index 01af28937..f241021fe 100644 --- a/src/main/java/appeng/util/item/ItemVariantList.java +++ b/src/main/java/appeng/util/item/ItemVariantList.java @@ -18,13 +18,13 @@ package appeng.util.item; +import appeng.api.config.FuzzyMode; +import appeng.api.storage.data.IAEItemStack; + import java.util.Collection; import java.util.Iterator; import java.util.Map; -import appeng.api.config.FuzzyMode; -import appeng.api.storage.data.IAEItemStack; - /** * Stores variants of a single type of {@link net.minecraft.item.Item}, i.e. versions with different durability, or * different NBT or capabilities. diff --git a/src/main/java/appeng/util/item/MeaningfulItemIterator.java b/src/main/java/appeng/util/item/MeaningfulItemIterator.java index 2d84f7933..a38700eaf 100644 --- a/src/main/java/appeng/util/item/MeaningfulItemIterator.java +++ b/src/main/java/appeng/util/item/MeaningfulItemIterator.java @@ -18,12 +18,12 @@ package appeng.util.item; +import appeng.api.storage.data.IAEItemStack; + import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; -import appeng.api.storage.data.IAEItemStack; - /** * This iterator will only return items from a collection that are meaningful (w.r.t. * {@link IAEItemStack#isMeaningful()}. Items that are not meaningful are automatically removed from the collection as diff --git a/src/main/java/appeng/util/item/NormalItemVariantList.java b/src/main/java/appeng/util/item/NormalItemVariantList.java index 89a92a155..5a2a191b5 100644 --- a/src/main/java/appeng/util/item/NormalItemVariantList.java +++ b/src/main/java/appeng/util/item/NormalItemVariantList.java @@ -18,14 +18,13 @@ package appeng.util.item; -import java.util.Collection; -import java.util.Map; - +import appeng.api.config.FuzzyMode; +import appeng.api.storage.data.IAEItemStack; import it.unimi.dsi.fastutil.objects.Reference2ObjectMap; import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; -import appeng.api.config.FuzzyMode; -import appeng.api.storage.data.IAEItemStack; +import java.util.Collection; +import java.util.Map; /** * This variant list is optimized for items that cannot be damaged and thus do not support querying durability ranges diff --git a/src/main/java/appeng/util/item/OreDictFilterMatcher.java b/src/main/java/appeng/util/item/OreDictFilterMatcher.java index 62b80a661..e36c9c6ab 100644 --- a/src/main/java/appeng/util/item/OreDictFilterMatcher.java +++ b/src/main/java/appeng/util/item/OreDictFilterMatcher.java @@ -8,8 +8,7 @@ import java.util.List; * @author brachy84 * @butcherer PrototypeTrousers */ -public class OreDictFilterMatcher -{ +public class OreDictFilterMatcher { /** * Parses the given expression and creates a List. @@ -17,10 +16,9 @@ public class OreDictFilterMatcher * @param expression expr to parse * @return match rule list */ - public static List parseExpression( String expression ) - { + public static List parseExpression(String expression) { List rules = new ArrayList<>(); - parseExpression( rules, expression ); + parseExpression(rules, expression); return rules; } @@ -31,55 +29,47 @@ public class OreDictFilterMatcher * @param expression expr to parse * @return the position of the expr. Is only relevant for sub rules */ - public static int parseExpression( List rules, String expression ) - { + public static int parseExpression(List rules, String expression) { rules.clear(); StringBuilder builder = new StringBuilder(); - for( int i = 0; i < expression.length(); i++ ) - { - char c = expression.charAt( i ); - if( c == ' ' ) - { + for (int i = 0; i < expression.length(); i++) { + char c = expression.charAt(i); + if (c == ' ') { continue; } - if( c == '(' ) - { + if (c == '(') { List subRules = new ArrayList<>(); - i = parseExpression( subRules, expression.substring( i + 1 ) ) + i + 1; - rules.add( MatchRule.group( subRules, builder.toString() ) ); + i = parseExpression(subRules, expression.substring(i + 1)) + i + 1; + rules.add(MatchRule.group(subRules, builder.toString())); builder = new StringBuilder(); - } - else - { - switch ( c ) - { + } else { + switch (c) { case '&': - rules.add( new MatchRule( builder.toString() ) ); - rules.add( new MatchRule( MatchLogic.AND ) ); + rules.add(new MatchRule(builder.toString())); + rules.add(new MatchRule(MatchLogic.AND)); builder = new StringBuilder(); break; case '|': - rules.add( new MatchRule( builder.toString() ) ); - rules.add( new MatchRule( MatchLogic.OR ) ); + rules.add(new MatchRule(builder.toString())); + rules.add(new MatchRule(MatchLogic.OR)); builder = new StringBuilder(); break; case '^': - rules.add( new MatchRule( builder.toString() ) ); - rules.add( new MatchRule( MatchLogic.XOR ) ); + rules.add(new MatchRule(builder.toString())); + rules.add(new MatchRule(MatchLogic.XOR)); builder = new StringBuilder(); break; case ')': - rules.add( new MatchRule( builder.toString() ) ); + rules.add(new MatchRule(builder.toString())); return i + 1; default: - builder.append( c ); + builder.append(c); } } } - if( builder.length() > 0 ) - { - rules.add( new MatchRule( builder.toString() ) ); + if (builder.length() > 0) { + rules.add(new MatchRule(builder.toString())); } return expression.length(); } @@ -92,39 +82,28 @@ public class OreDictFilterMatcher * @param oreDict string to check * @return if the string matches the rules */ - public static boolean matches( List rules, String oreDict ) - { + public static boolean matches(List rules, String oreDict) { boolean first = true; boolean lastResult = false; MatchLogic lastLogic = null; - for( MatchRule rule : rules ) - { - if( lastLogic == null ) - { - if( rule.logic == MatchLogic.AND || rule.logic == MatchLogic.OR || rule.logic == MatchLogic.XOR ) - { + for (MatchRule rule : rules) { + if (lastLogic == null) { + if (rule.logic == MatchLogic.AND || rule.logic == MatchLogic.OR || rule.logic == MatchLogic.XOR) { lastLogic = rule.logic; continue; } } - if( lastLogic != null || first ) - { - if( lastLogic != null ) - { - switch ( lastLogic ) - { - case AND: - { - if( !lastResult ) - { + if (lastLogic != null || first) { + if (lastLogic != null) { + switch (lastLogic) { + case AND: { + if (!lastResult) { return false; } break; } - case OR: - { - if( lastResult ) - { + case OR: { + if (lastResult) { return true; } break; @@ -133,19 +112,14 @@ public class OreDictFilterMatcher } boolean newResult; - if( rule.isGroup() ) - { - newResult = rule.logic == MatchLogic.NOT ^ matches( rule.subRules, oreDict ); - } - else - { - newResult = matches( rule, oreDict ); + if (rule.isGroup()) { + newResult = rule.logic == MatchLogic.NOT ^ matches(rule.subRules, oreDict); + } else { + newResult = matches(rule, oreDict); } - if( lastLogic == MatchLogic.XOR ) - { - if( lastResult == newResult ) - { + if (lastLogic == MatchLogic.XOR) { + if (lastResult == newResult) { return false; } } @@ -160,45 +134,37 @@ public class OreDictFilterMatcher return lastResult; } - private static boolean matches( MatchRule rule, String oreDict ) - { + private static boolean matches(MatchRule rule, String oreDict) { String filter = rule.expression; - if( filter.equals( "*" ) ) - { + if (filter.equals("*")) { return true; } - boolean startWild = filter.startsWith( "*" ), endWild = filter.endsWith( "*" ); - if( startWild ) - { - filter = filter.substring( 1 ); + boolean startWild = filter.startsWith("*"), endWild = filter.endsWith("*"); + if (startWild) { + filter = filter.substring(1); } - String[] parts = filter.split( "\\*+" ); + String[] parts = filter.split("\\*+"); - return ( rule.logic == MatchLogic.NOT ) ^ matches( parts, oreDict, startWild, endWild ); + return (rule.logic == MatchLogic.NOT) ^ matches(parts, oreDict, startWild, endWild); } - private static boolean matches( String[] filter, String oreDict, boolean startWild, boolean endWild ) - { + private static boolean matches(String[] filter, String oreDict, boolean startWild, boolean endWild) { String lastlastPart = filter[0]; String lastPart = filter[0]; - int index = oreDict.indexOf( lastPart ); - if( ( !startWild && index != 0 ) || index < 0 ) - { + int index = oreDict.indexOf(lastPart); + if ((!startWild && index != 0) || index < 0) { return false; } boolean didGoBack = false; - for( int i = 1; i < filter.length; i++ ) - { + for (int i = 1; i < filter.length; i++) { String part = filter[i]; - int newIndex = oreDict.indexOf( part, index + lastPart.length() ); - if( newIndex < 0 ) - { - if( i > 1 && !didGoBack ) - { + int newIndex = oreDict.indexOf(part, index + lastPart.length()); + if (newIndex < 0) { + if (i > 1 && !didGoBack) { i -= 2; lastPart = lastlastPart; didGoBack = true; @@ -209,25 +175,20 @@ public class OreDictFilterMatcher lastlastPart = lastPart; lastPart = part; index = newIndex; - if( didGoBack ) - { + if (didGoBack) { didGoBack = false; } } - if( endWild || lastPart.length() + index == oreDict.length() ) - { + if (endWild || lastPart.length() + index == oreDict.length()) { return true; } - for( int i = filter.length - 1; i < filter.length; i++ ) - { + for (int i = filter.length - 1; i < filter.length; i++) { String part = filter[i]; - int newIndex = oreDict.indexOf( part, index + lastPart.length() ); - if( newIndex < 0 ) - { - if( i > 1 && !didGoBack ) - { + int newIndex = oreDict.indexOf(part, index + lastPart.length()); + if (newIndex < 0) { + if (i > 1 && !didGoBack) { i -= 2; lastPart = lastlastPart; didGoBack = true; @@ -238,142 +199,115 @@ public class OreDictFilterMatcher lastlastPart = lastPart; lastPart = part; index = newIndex; - if( didGoBack ) - { + if (didGoBack) { didGoBack = false; } } return lastPart.length() + index == oreDict.length(); } - public static String validateExp( String input ) - { + public static String validateExp(String input) { // remove all operators that are double - input = input.replaceAll( "\\*{2,}", "*" ); - input = input.replaceAll( "&{2,}", "&" ); - input = input.replaceAll( "\\|{2,}", "|" ); - input = input.replaceAll( "!{2,}", "!" ); - input = input.replaceAll( "\\^{2,}", "^" ); - input = input.replaceAll( " {2,}", " " ); + input = input.replaceAll("\\*{2,}", "*"); + input = input.replaceAll("&{2,}", "&"); + input = input.replaceAll("\\|{2,}", "|"); + input = input.replaceAll("!{2,}", "!"); + input = input.replaceAll("\\^{2,}", "^"); + input = input.replaceAll(" {2,}", " "); // move ( and ) so it doesn't create invalid expressions f.e. xxx (& yyy) => xxx & (yyy) // append or prepend ( and ) if the amount is not equal StringBuilder builder = new StringBuilder(); int unclosed = 0; char last = ' '; - for( int i = 0; i < input.length(); i++ ) - { - char c = input.charAt( i ); - if( c == ' ' ) - { - if( last != '(' ) - { - builder.append( " " ); + for (int i = 0; i < input.length(); i++) { + char c = input.charAt(i); + if (c == ' ') { + if (last != '(') { + builder.append(" "); } continue; } - if( c == '(' ) - { + if (c == '(') { unclosed++; - } - else if( c == ')' ) - { + } else if (c == ')') { unclosed--; - if( last == '&' || last == '|' || last == '^' ) - { - int l = builder.lastIndexOf( " " + last ); - int l2 = builder.lastIndexOf( "" + last ); - builder.insert( l == l2 - 1 ? l : l2, ")" ); + if (last == '&' || last == '|' || last == '^') { + int l = builder.lastIndexOf(" " + last); + int l2 = builder.lastIndexOf("" + last); + builder.insert(l == l2 - 1 ? l : l2, ")"); continue; } - if( i > 0 && builder.charAt( builder.length() - 1 ) == ' ' ) - { - builder.deleteCharAt( builder.length() - 1 ); + if (i > 0 && builder.charAt(builder.length() - 1) == ' ') { + builder.deleteCharAt(builder.length() - 1); } - } - else if( ( c == '&' || c == '|' || c == '^' ) && last == '(' ) - { - builder.deleteCharAt( builder.lastIndexOf( "(" ) ); - builder.append( c ).append( " (" ); + } else if ((c == '&' || c == '|' || c == '^') && last == '(') { + builder.deleteCharAt(builder.lastIndexOf("(")); + builder.append(c).append(" ("); continue; } - builder.append( c ); + builder.append(c); last = c; } - if( unclosed > 0 ) - { - for( int i = 0; i < unclosed; i++ ) - { - builder.append( ")" ); + if (unclosed > 0) { + for (int i = 0; i < unclosed; i++) { + builder.append(")"); } - } - else if( unclosed < 0 ) - { + } else if (unclosed < 0) { unclosed = -unclosed; - for( int i = 0; i < unclosed; i++ ) - { - builder.insert( 0, "(" ); + for (int i = 0; i < unclosed; i++) { + builder.insert(0, "("); } } input = builder.toString(); - input = input.replaceAll( " {2,}", " " ); + input = input.replaceAll(" {2,}", " "); return input; } - public static class MatchRule - { + public static class MatchRule { public final MatchLogic logic; public final String expression; private final List subRules; - private MatchRule( MatchLogic logic, String expression, List subRules ) - { - if( expression.startsWith( "!" ) ) - { + private MatchRule(MatchLogic logic, String expression, List subRules) { + if (expression.startsWith("!")) { logic = MatchLogic.NOT; - expression = expression.substring( 1 ); + expression = expression.substring(1); } this.logic = logic; this.expression = expression; this.subRules = subRules; } - public MatchRule( MatchLogic logic, String expression ) - { - this( logic, expression, null ); + public MatchRule(MatchLogic logic, String expression) { + this(logic, expression, null); } - public MatchRule( MatchLogic logic ) - { - this( logic, "" ); + public MatchRule(MatchLogic logic) { + this(logic, ""); } - public MatchRule( String expression ) - { - this( MatchLogic.ANY, expression ); + public MatchRule(String expression) { + this(MatchLogic.ANY, expression); } - public static MatchRule not( String expression, boolean not ) - { - return new MatchRule( not ? MatchLogic.NOT : MatchLogic.ANY, expression ); + public static MatchRule not(String expression, boolean not) { + return new MatchRule(not ? MatchLogic.NOT : MatchLogic.ANY, expression); } - public static MatchRule group( List subRules, String expression ) - { - MatchLogic logic = expression.startsWith( "!" ) ? MatchLogic.NOT : MatchLogic.ANY; - return new MatchRule( logic, "", subRules ); + public static MatchRule group(List subRules, String expression) { + MatchLogic logic = expression.startsWith("!") ? MatchLogic.NOT : MatchLogic.ANY; + return new MatchRule(logic, "", subRules); } - public boolean isGroup() - { + public boolean isGroup() { return subRules != null; } } - public enum MatchLogic - { + public enum MatchLogic { OR, AND, XOR, diff --git a/src/main/java/appeng/util/item/OreHelper.java b/src/main/java/appeng/util/item/OreHelper.java index 8b926a691..7a6439e0c 100644 --- a/src/main/java/appeng/util/item/OreHelper.java +++ b/src/main/java/appeng/util/item/OreHelper.java @@ -30,22 +30,19 @@ import net.minecraftforge.oredict.OreDictionary; import java.util.*; -public class OreHelper -{ +public class OreHelper { public static final OreHelper INSTANCE = new OreHelper(); /** * A local cache to speed up OreDictionary lookups. */ - private final LoadingCache> oreDictCache = CacheBuilder.newBuilder().build( new CacheLoader>() - { + private final LoadingCache> oreDictCache = CacheBuilder.newBuilder().build(new CacheLoader>() { @Override - public List load( final String oreName ) - { - return OreDictionary.getOres( oreName ); + public List load(final String oreName) { + return OreDictionary.getOres(oreName); } - } ); + }); private final Map references = new HashMap<>(); @@ -55,80 +52,64 @@ public class OreHelper * @param itemStack the itemstack to test * @return true if an ore entry exists, false otherwise */ - public Optional getOre( final ItemStack itemStack ) - { - final ItemRef ir = new ItemRef( itemStack ); + public Optional getOre(final ItemStack itemStack) { + final ItemRef ir = new ItemRef(itemStack); - if( !this.references.containsKey( ir ) ) - { + if (!this.references.containsKey(ir)) { final OreReference ref = new OreReference(); final Collection ores = ref.getOres(); final Collection set = ref.getEquivalents(); final Set toAdd = new HashSet<>(); - for( final String ore : OreDictionary.getOreNames() ) - { + for (final String ore : OreDictionary.getOreNames()) { // skip ore if it is a match already or null. - if( ore == null || toAdd.contains( ore ) ) - { + if (ore == null || toAdd.contains(ore)) { continue; } - for( final ItemStack oreItem : this.oreDictCache.getUnchecked( ore ) ) - { - if( OreDictionary.itemMatches( oreItem, itemStack, false ) ) - { - toAdd.add( ore ); + for (final ItemStack oreItem : this.oreDictCache.getUnchecked(ore)) { + if (OreDictionary.itemMatches(oreItem, itemStack, false)) { + toAdd.add(ore); break; } } } - for( final String ore : toAdd ) - { - set.add( ore ); - ores.add( OreDictionary.getOreID( ore ) ); + for (final String ore : toAdd) { + set.add(ore); + ores.add(OreDictionary.getOreID(ore)); } - if( !set.isEmpty() ) - { - this.references.put( ir, ref ); - } - else - { - this.references.put( ir, null ); + if (!set.isEmpty()) { + this.references.put(ir, ref); + } else { + this.references.put(ir, null); } } - return Optional.ofNullable( this.references.get( ir ) ); + return Optional.ofNullable(this.references.get(ir)); } - boolean sameOre( final AEItemStack aeItemStack, final IAEItemStack is ) - { - final OreReference a = aeItemStack.getOre().orElse( null ); - final OreReference b = ( (AEItemStack) is ).getOre().orElse( null ); + boolean sameOre(final AEItemStack aeItemStack, final IAEItemStack is) { + final OreReference a = aeItemStack.getOre().orElse(null); + final OreReference b = ((AEItemStack) is).getOre().orElse(null); - return this.sameOre( a, b ); + return this.sameOre(a, b); } - public boolean sameOre( final OreReference a, final OreReference b ) - { - if( a == null || b == null ) - { + public boolean sameOre(final OreReference a, final OreReference b) { + if (a == null || b == null) { return false; } - if( a == b ) - { + if (a == b) { return true; } final Collection bOres = b.getOres(); - for( final Integer ore : a.getOres() ) - { - if( bOres.contains( ore ) ) - { + for (final Integer ore : a.getOres()) { + if (bOres.contains(ore)) { return true; } } @@ -136,60 +117,47 @@ public class OreHelper return false; } - boolean sameOre( final AEItemStack aeItemStack, final ItemStack o ) - { - return aeItemStack.getOre().map( a -> { - for( final String oreName : a.getEquivalents() ) - { - for( final ItemStack oreItem : this.oreDictCache.getUnchecked( oreName ) ) - { - if( OreDictionary.itemMatches( oreItem, o, false ) ) - { + boolean sameOre(final AEItemStack aeItemStack, final ItemStack o) { + return aeItemStack.getOre().map(a -> { + for (final String oreName : a.getEquivalents()) { + for (final ItemStack oreItem : this.oreDictCache.getUnchecked(oreName)) { + if (OreDictionary.itemMatches(oreItem, o, false)) { return true; } } } return false; - } ).orElse( false ); + }).orElse(false); } - public Set getMatchingOre( String oreExp ) - { + public Set getMatchingOre(String oreExp) { Set matchingIds = new HashSet<>(); - List rulesList = OreDictFilterMatcher.parseExpression( oreExp ); - for( String ore : OreDictionary.getOreNames() ) - { - if( OreDictFilterMatcher.matches( rulesList, ore ) ) - { - matchingIds.add( OreDictionary.getOreID( ore ) ); + List rulesList = OreDictFilterMatcher.parseExpression(oreExp); + for (String ore : OreDictionary.getOreNames()) { + if (OreDictFilterMatcher.matches(rulesList, ore)) { + matchingIds.add(OreDictionary.getOreID(ore)); } } return matchingIds; } - public List getCachedOres( final String oreName ) - { - return this.oreDictCache.getUnchecked( oreName ); + public List getCachedOres(final String oreName) { + return this.oreDictCache.getUnchecked(oreName); } - private static class ItemRef - { + private static class ItemRef { private final Item ref; private final int damage; private final int hash; - ItemRef( final ItemStack stack ) - { + ItemRef(final ItemStack stack) { this.ref = stack.getItem(); - if( stack.getItem().isDamageable() ) - { + if (stack.getItem().isDamageable()) { this.damage = 0; // IGNORED - } - else - { + } else { this.damage = stack.getItemDamage(); // might be important... } @@ -197,20 +165,16 @@ public class OreHelper } @Override - public int hashCode() - { + public int hashCode() { return this.hash; } @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { + public boolean equals(final Object obj) { + if (obj == null) { return false; } - if( this.getClass() != obj.getClass() ) - { + if (this.getClass() != obj.getClass()) { return false; } final ItemRef other = (ItemRef) obj; @@ -218,8 +182,7 @@ public class OreHelper } @Override - public String toString() - { + public String toString() { return "ItemRef [ref=" + this.ref.getUnlocalizedName() + ", damage=" + this.damage + ", hash=" + this.hash + ']'; } } diff --git a/src/main/java/appeng/util/item/OreReference.java b/src/main/java/appeng/util/item/OreReference.java index 515843c45..adf309f12 100644 --- a/src/main/java/appeng/util/item/OreReference.java +++ b/src/main/java/appeng/util/item/OreReference.java @@ -19,54 +19,41 @@ package appeng.util.item; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - +import appeng.api.storage.data.IAEItemStack; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -import appeng.api.storage.data.IAEItemStack; +import java.util.*; -public class OreReference -{ +public class OreReference { - private final List otherOptions = new ArrayList<>(); - private final Set ores = new HashSet<>(); - private List aeOtherOptions = null; + private final List otherOptions = new ArrayList<>(); + private final Set ores = new HashSet<>(); + private List aeOtherOptions = null; - Collection getEquivalents() - { - return this.otherOptions; - } + Collection getEquivalents() { + return this.otherOptions; + } - public List getAEEquivalents() - { - if( this.aeOtherOptions == null ) - { - this.aeOtherOptions = new ArrayList<>( this.otherOptions.size() ); + public List getAEEquivalents() { + if (this.aeOtherOptions == null) { + this.aeOtherOptions = new ArrayList<>(this.otherOptions.size()); - // SUMMON AE STACKS! - for( final String oreName : this.otherOptions ) - { - for( final ItemStack is : OreHelper.INSTANCE.getCachedOres( oreName ) ) - { - if( is.getItem() != Items.AIR ) - { - this.aeOtherOptions.add( AEItemStack.fromItemStack( is ) ); - } - } - } - } + // SUMMON AE STACKS! + for (final String oreName : this.otherOptions) { + for (final ItemStack is : OreHelper.INSTANCE.getCachedOres(oreName)) { + if (is.getItem() != Items.AIR) { + this.aeOtherOptions.add(AEItemStack.fromItemStack(is)); + } + } + } + } - return this.aeOtherOptions; - } + return this.aeOtherOptions; + } - public Collection getOres() - { + public Collection getOres() { return this.ores; } } diff --git a/src/main/java/appeng/util/iterators/AEInvIterator.java b/src/main/java/appeng/util/iterators/AEInvIterator.java index 988b27873..b0108c271 100644 --- a/src/main/java/appeng/util/iterators/AEInvIterator.java +++ b/src/main/java/appeng/util/iterators/AEInvIterator.java @@ -19,44 +19,39 @@ package appeng.util.iterators; -import java.util.Iterator; - import appeng.api.storage.data.IAEItemStack; import appeng.tile.inventory.AppEngInternalAEInventory; +import java.util.Iterator; -public final class AEInvIterator implements Iterator -{ - private final AppEngInternalAEInventory inventory; - private final int size; - private int counter = 0; +public final class AEInvIterator implements Iterator { + private final AppEngInternalAEInventory inventory; + private final int size; - public AEInvIterator( final AppEngInternalAEInventory inventory ) - { - this.inventory = inventory; - this.size = this.inventory.getSlots(); - } + private int counter = 0; - @Override - public boolean hasNext() - { - return this.counter < this.size; - } + public AEInvIterator(final AppEngInternalAEInventory inventory) { + this.inventory = inventory; + this.size = this.inventory.getSlots(); + } - @Override - public IAEItemStack next() - { - final IAEItemStack result = this.inventory.getAEStackInSlot( this.counter ); + @Override + public boolean hasNext() { + return this.counter < this.size; + } - this.counter++; + @Override + public IAEItemStack next() { + final IAEItemStack result = this.inventory.getAEStackInSlot(this.counter); - return result; - } + this.counter++; - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + return result; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/iterators/ChainedIterator.java b/src/main/java/appeng/util/iterators/ChainedIterator.java index 93f3769f7..47a8d7924 100644 --- a/src/main/java/appeng/util/iterators/ChainedIterator.java +++ b/src/main/java/appeng/util/iterators/ChainedIterator.java @@ -22,34 +22,29 @@ package appeng.util.iterators; import java.util.Iterator; -public final class ChainedIterator implements Iterator -{ - private final T[] list; +public final class ChainedIterator implements Iterator { + private final T[] list; - private int offset = 0; + private int offset = 0; - public ChainedIterator( final T... list ) - { - this.list = list; - } + public ChainedIterator(final T... list) { + this.list = list; + } - @Override - public boolean hasNext() - { - return this.offset < this.list.length; - } + @Override + public boolean hasNext() { + return this.offset < this.list.length; + } - @Override - public T next() - { - final T result = this.list[this.offset]; - this.offset++; - return result; - } + @Override + public T next() { + final T result = this.list[this.offset]; + this.offset++; + return result; + } - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/iterators/InvIterator.java b/src/main/java/appeng/util/iterators/InvIterator.java index 942c1c4d5..906430f81 100644 --- a/src/main/java/appeng/util/iterators/InvIterator.java +++ b/src/main/java/appeng/util/iterators/InvIterator.java @@ -19,43 +19,38 @@ package appeng.util.iterators; -import java.util.Iterator; - import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; +import java.util.Iterator; -public final class InvIterator implements Iterator -{ - private final IItemHandler inventory; - private final int size; - private int counter = 0; +public final class InvIterator implements Iterator { + private final IItemHandler inventory; + private final int size; - public InvIterator( final IItemHandler inventory ) - { - this.inventory = inventory; - this.size = this.inventory.getSlots(); - } + private int counter = 0; - @Override - public boolean hasNext() - { - return this.counter < this.size; - } + public InvIterator(final IItemHandler inventory) { + this.inventory = inventory; + this.size = this.inventory.getSlots(); + } - @Override - public ItemStack next() - { - final ItemStack result = this.inventory.getStackInSlot( this.counter ); - this.counter++; + @Override + public boolean hasNext() { + return this.counter < this.size; + } - return result; - } + @Override + public ItemStack next() { + final ItemStack result = this.inventory.getStackInSlot(this.counter); + this.counter++; - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + return result; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/iterators/NullIterator.java b/src/main/java/appeng/util/iterators/NullIterator.java index 3ce3edcc5..e737d5fda 100644 --- a/src/main/java/appeng/util/iterators/NullIterator.java +++ b/src/main/java/appeng/util/iterators/NullIterator.java @@ -22,24 +22,20 @@ package appeng.util.iterators; import java.util.Iterator; -public class NullIterator implements Iterator -{ +public class NullIterator implements Iterator { - @Override - public boolean hasNext() - { - return false; - } + @Override + public boolean hasNext() { + return false; + } - @Override - public T next() - { - return null; - } + @Override + public T next() { + return null; + } - @Override - public void remove() - { + @Override + public void remove() { - } + } } diff --git a/src/main/java/appeng/util/iterators/ProxyNodeIterator.java b/src/main/java/appeng/util/iterators/ProxyNodeIterator.java index 662c094ab..09d4f2b83 100644 --- a/src/main/java/appeng/util/iterators/ProxyNodeIterator.java +++ b/src/main/java/appeng/util/iterators/ProxyNodeIterator.java @@ -19,38 +19,33 @@ package appeng.util.iterators; -import java.util.Iterator; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.util.AEPartLocation; +import java.util.Iterator; -public final class ProxyNodeIterator implements Iterator -{ - private final Iterator hosts; - public ProxyNodeIterator( final Iterator hosts ) - { - this.hosts = hosts; - } +public final class ProxyNodeIterator implements Iterator { + private final Iterator hosts; - @Override - public boolean hasNext() - { - return this.hosts.hasNext(); - } + public ProxyNodeIterator(final Iterator hosts) { + this.hosts = hosts; + } - @Override - public IGridNode next() - { - final IGridHost host = this.hosts.next(); - return host.getGridNode( AEPartLocation.INTERNAL ); - } + @Override + public boolean hasNext() { + return this.hosts.hasNext(); + } - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public IGridNode next() { + final IGridHost host = this.hosts.next(); + return host.getGridNode(AEPartLocation.INTERNAL); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/iterators/StackToSlotIterator.java b/src/main/java/appeng/util/iterators/StackToSlotIterator.java index aae4c544c..6a61d65e4 100644 --- a/src/main/java/appeng/util/iterators/StackToSlotIterator.java +++ b/src/main/java/appeng/util/iterators/StackToSlotIterator.java @@ -19,43 +19,37 @@ package appeng.util.iterators; -import java.util.Iterator; - +import appeng.util.inv.ItemSlot; import net.minecraft.item.ItemStack; -import appeng.util.inv.ItemSlot; +import java.util.Iterator; -public class StackToSlotIterator implements Iterator -{ +public class StackToSlotIterator implements Iterator { - private final ItemSlot iss = new ItemSlot(); - private final Iterator is; - private int x = 0; + private final ItemSlot iss = new ItemSlot(); + private final Iterator is; + private int x = 0; - public StackToSlotIterator( final Iterator is ) - { - this.is = is; - } + public StackToSlotIterator(final Iterator is) { + this.is = is; + } - @Override - public boolean hasNext() - { - return this.is.hasNext(); - } + @Override + public boolean hasNext() { + return this.is.hasNext(); + } - @Override - public ItemSlot next() - { - this.iss.setSlot( this.x ); - this.x++; - this.iss.setItemStack( this.is.next() ); - return this.iss; - } + @Override + public ItemSlot next() { + this.iss.setSlot(this.x); + this.x++; + this.iss.setItemStack(this.is.next()); + return this.iss; + } - @Override - public void remove() - { - // uhh no. - } + @Override + public void remove() { + // uhh no. + } } diff --git a/src/main/java/appeng/util/prioritylist/DefaultPriorityList.java b/src/main/java/appeng/util/prioritylist/DefaultPriorityList.java index c8ca99837..91347f268 100644 --- a/src/main/java/appeng/util/prioritylist/DefaultPriorityList.java +++ b/src/main/java/appeng/util/prioritylist/DefaultPriorityList.java @@ -19,29 +19,25 @@ package appeng.util.prioritylist; -import java.util.Collections; - import appeng.api.storage.data.IAEStack; +import java.util.Collections; -public class DefaultPriorityList> implements IPartitionList -{ - @Override - public boolean isListed( final T input ) - { - return false; - } +public class DefaultPriorityList> implements IPartitionList { - @Override - public boolean isEmpty() - { - return true; - } + @Override + public boolean isListed(final T input) { + return false; + } - @Override - public Iterable getItems() - { - return Collections.emptyList(); - } + @Override + public boolean isEmpty() { + return true; + } + + @Override + public Iterable getItems() { + return Collections.emptyList(); + } } diff --git a/src/main/java/appeng/util/prioritylist/FuzzyPriorityList.java b/src/main/java/appeng/util/prioritylist/FuzzyPriorityList.java index 39d03e3b4..a24b3f495 100644 --- a/src/main/java/appeng/util/prioritylist/FuzzyPriorityList.java +++ b/src/main/java/appeng/util/prioritylist/FuzzyPriorityList.java @@ -19,41 +19,36 @@ package appeng.util.prioritylist; -import java.util.Collection; - import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; +import java.util.Collection; -public class FuzzyPriorityList> implements IPartitionList -{ - private final IItemList list; - private final FuzzyMode mode; +public class FuzzyPriorityList> implements IPartitionList { - public FuzzyPriorityList( final IItemList in, final FuzzyMode mode ) - { - this.list = in; - this.mode = mode; - } + private final IItemList list; + private final FuzzyMode mode; - @Override - public boolean isListed( final T input ) - { - final Collection out = this.list.findFuzzy( input, this.mode ); - return out != null && !out.isEmpty(); - } + public FuzzyPriorityList(final IItemList in, final FuzzyMode mode) { + this.list = in; + this.mode = mode; + } - @Override - public boolean isEmpty() - { - return this.list.isEmpty(); - } + @Override + public boolean isListed(final T input) { + final Collection out = this.list.findFuzzy(input, this.mode); + return out != null && !out.isEmpty(); + } - @Override - public Iterable getItems() - { - return this.list; - } + @Override + public boolean isEmpty() { + return this.list.isEmpty(); + } + + @Override + public Iterable getItems() { + return this.list; + } } diff --git a/src/main/java/appeng/util/prioritylist/IPartitionList.java b/src/main/java/appeng/util/prioritylist/IPartitionList.java index 7daf69df1..88263aea3 100644 --- a/src/main/java/appeng/util/prioritylist/IPartitionList.java +++ b/src/main/java/appeng/util/prioritylist/IPartitionList.java @@ -22,11 +22,10 @@ package appeng.util.prioritylist; import appeng.api.storage.data.IAEStack; -public interface IPartitionList> -{ - boolean isListed( T input ); +public interface IPartitionList> { + boolean isListed(T input); - boolean isEmpty(); + boolean isEmpty(); - Iterable getItems(); + Iterable getItems(); } diff --git a/src/main/java/appeng/util/prioritylist/MergedPriorityList.java b/src/main/java/appeng/util/prioritylist/MergedPriorityList.java index b893ba81e..ddb109086 100644 --- a/src/main/java/appeng/util/prioritylist/MergedPriorityList.java +++ b/src/main/java/appeng/util/prioritylist/MergedPriorityList.java @@ -19,66 +19,53 @@ package appeng.util.prioritylist; +import appeng.api.storage.data.IAEStack; + import java.util.ArrayList; import java.util.Collection; -import appeng.api.storage.data.IAEStack; +public final class MergedPriorityList> implements IPartitionList { -public final class MergedPriorityList> implements IPartitionList -{ + private final Collection> positive = new ArrayList<>(); + private final Collection> negative = new ArrayList<>(); - private final Collection> positive = new ArrayList<>(); - private final Collection> negative = new ArrayList<>(); + public void addNewList(final IPartitionList list, final boolean isWhitelist) { + if (isWhitelist) { + this.positive.add(list); + } else { + this.negative.add(list); + } + } - public void addNewList( final IPartitionList list, final boolean isWhitelist ) - { - if( isWhitelist ) - { - this.positive.add( list ); - } - else - { - this.negative.add( list ); - } - } + @Override + public boolean isListed(final T input) { + for (final IPartitionList l : this.negative) { + if (l.isListed(input)) { + return false; + } + } - @Override - public boolean isListed( final T input ) - { - for( final IPartitionList l : this.negative ) - { - if( l.isListed( input ) ) - { - return false; - } - } + if (!this.positive.isEmpty()) { + for (final IPartitionList l : this.positive) { + if (l.isListed(input)) { + return true; + } + } - if( !this.positive.isEmpty() ) - { - for( final IPartitionList l : this.positive ) - { - if( l.isListed( input ) ) - { - return true; - } - } + return false; + } - return false; - } + return true; + } - return true; - } + @Override + public boolean isEmpty() { + return this.positive.isEmpty() && this.negative.isEmpty(); + } - @Override - public boolean isEmpty() - { - return this.positive.isEmpty() && this.negative.isEmpty(); - } - - @Override - public Iterable getItems() - { - throw new UnsupportedOperationException(); - } + @Override + public Iterable getItems() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/prioritylist/OreDictPriorityList.java b/src/main/java/appeng/util/prioritylist/OreDictPriorityList.java index 52d217807..0d3fa4010 100644 --- a/src/main/java/appeng/util/prioritylist/OreDictPriorityList.java +++ b/src/main/java/appeng/util/prioritylist/OreDictPriorityList.java @@ -8,27 +8,21 @@ import java.util.ArrayList; import java.util.Set; -public class OreDictPriorityList> implements IPartitionList -{ +public class OreDictPriorityList> implements IPartitionList { private final Set oreIDs; private final String oreMatch; - public OreDictPriorityList( Set oreIDs, String oreMatch ) - { + public OreDictPriorityList(Set oreIDs, String oreMatch) { this.oreIDs = oreIDs; this.oreMatch = oreMatch; } @Override - public boolean isListed( final T input ) - { - OreReference or = ( (AEItemStack) input ).getOre().orElse( null ); - if( or != null ) - { - for( Integer oreID : or.getOres() ) - { - if( this.oreIDs.contains( oreID ) ) - { + public boolean isListed(final T input) { + OreReference or = ((AEItemStack) input).getOre().orElse(null); + if (or != null) { + for (Integer oreID : or.getOres()) { + if (this.oreIDs.contains(oreID)) { return true; } } @@ -37,14 +31,12 @@ public class OreDictPriorityList> implements IPartitionLis } @Override - public boolean isEmpty() - { - return oreMatch.equals( "" ); + public boolean isEmpty() { + return oreMatch.equals(""); } @Override - public Iterable getItems() - { + public Iterable getItems() { return new ArrayList<>(); } diff --git a/src/main/java/appeng/util/prioritylist/PrecisePriorityList.java b/src/main/java/appeng/util/prioritylist/PrecisePriorityList.java index 29100901c..4041527bb 100644 --- a/src/main/java/appeng/util/prioritylist/PrecisePriorityList.java +++ b/src/main/java/appeng/util/prioritylist/PrecisePriorityList.java @@ -23,31 +23,26 @@ import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; -public class PrecisePriorityList> implements IPartitionList -{ +public class PrecisePriorityList> implements IPartitionList { - private final IItemList list; + private final IItemList list; - public PrecisePriorityList( final IItemList in ) - { - this.list = in; - } + public PrecisePriorityList(final IItemList in) { + this.list = in; + } - @Override - public boolean isListed( final T input ) - { - return this.list.findPrecise( input ) != null; - } + @Override + public boolean isListed(final T input) { + return this.list.findPrecise(input) != null; + } - @Override - public boolean isEmpty() - { - return this.list.isEmpty(); - } + @Override + public boolean isEmpty() { + return this.list.isEmpty(); + } - @Override - public Iterable getItems() - { - return this.list; - } + @Override + public Iterable getItems() { + return this.list; + } } diff --git a/src/main/java/appeng/worldgen/MeteoritePlacer.java b/src/main/java/appeng/worldgen/MeteoritePlacer.java index d2a57d0a7..a7280dacb 100644 --- a/src/main/java/appeng/worldgen/MeteoritePlacer.java +++ b/src/main/java/appeng/worldgen/MeteoritePlacer.java @@ -19,11 +19,16 @@ package appeng.worldgen; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; - +import appeng.api.AEApi; +import appeng.api.definitions.IBlockDefinition; +import appeng.api.definitions.IBlocks; +import appeng.api.definitions.IMaterials; +import appeng.core.AEConfig; +import appeng.core.features.AEFeature; +import appeng.core.worlddata.WorldData; +import appeng.util.InventoryAdaptor; +import appeng.util.Platform; +import appeng.worldgen.meteorite.*; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; @@ -37,539 +42,442 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraftforge.oredict.OreDictionary; -import appeng.api.AEApi; -import appeng.api.definitions.IBlockDefinition; -import appeng.api.definitions.IBlocks; -import appeng.api.definitions.IMaterials; -import appeng.core.AEConfig; -import appeng.core.features.AEFeature; -import appeng.core.worlddata.WorldData; -import appeng.util.InventoryAdaptor; -import appeng.util.Platform; -import appeng.worldgen.meteorite.Fallout; -import appeng.worldgen.meteorite.FalloutCopy; -import appeng.worldgen.meteorite.FalloutSand; -import appeng.worldgen.meteorite.FalloutSnow; -import appeng.worldgen.meteorite.IMeteoriteWorld; -import appeng.worldgen.meteorite.MeteoriteBlockPutter; - - -public final class MeteoritePlacer -{ - private static final double PRESSES_SPAWN_CHANCE = 0.7; - private static final int SKYSTONE_SPAWN_LIMIT = 12; - private final Collection validSpawn = new HashSet<>(); - private final Collection invalidSpawn = new HashSet<>(); - private final IBlockDefinition skyChestDefinition; - private final IBlockDefinition skyStoneDefinition; - private final MeteoriteBlockPutter putter = new MeteoriteBlockPutter(); - private double meteoriteSize = ( Math.random() * 6.0 ) + 2; - private double realCrater = this.meteoriteSize * 2 + 5; - private double squaredMeteoriteSize = this.meteoriteSize * this.meteoriteSize; - private double crater = this.realCrater * this.realCrater; - private NBTTagCompound settings; - private Fallout type; - - public MeteoritePlacer() - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); - - this.skyChestDefinition = blocks.skyStoneChest(); - this.skyStoneDefinition = blocks.skyStoneBlock(); - - this.validSpawn.add( Blocks.STONE ); - this.validSpawn.add( Blocks.COBBLESTONE ); - this.validSpawn.add( Blocks.GRASS ); - this.validSpawn.add( Blocks.SAND ); - this.validSpawn.add( Blocks.DIRT ); - this.validSpawn.add( Blocks.GRAVEL ); - this.validSpawn.add( Blocks.NETHERRACK ); - this.validSpawn.add( Blocks.IRON_ORE ); - this.validSpawn.add( Blocks.GOLD_ORE ); - this.validSpawn.add( Blocks.DIAMOND_ORE ); - this.validSpawn.add( Blocks.REDSTONE_ORE ); - this.validSpawn.add( Blocks.HARDENED_CLAY ); - this.validSpawn.add( Blocks.ICE ); - this.validSpawn.add( Blocks.SNOW ); - this.validSpawn.add( Blocks.STAINED_HARDENED_CLAY ); - - this.skyStoneDefinition.maybeBlock().ifPresent( this.invalidSpawn::add ); - this.invalidSpawn.add( Blocks.PLANKS ); - this.invalidSpawn.add( Blocks.IRON_DOOR ); - this.invalidSpawn.add( Blocks.IRON_BARS ); - this.invalidSpawn.add( Blocks.OAK_DOOR ); - this.invalidSpawn.add( Blocks.ACACIA_DOOR ); - this.invalidSpawn.add( Blocks.BIRCH_DOOR ); - this.invalidSpawn.add( Blocks.DARK_OAK_DOOR ); - this.invalidSpawn.add( Blocks.IRON_DOOR ); - this.invalidSpawn.add( Blocks.JUNGLE_DOOR ); - this.invalidSpawn.add( Blocks.SPRUCE_DOOR ); - this.invalidSpawn.add( Blocks.BRICK_BLOCK ); - this.invalidSpawn.add( Blocks.CLAY ); - this.invalidSpawn.add( Blocks.WATER ); - this.invalidSpawn.add( Blocks.LOG ); - this.invalidSpawn.add( Blocks.LOG2 ); - - this.type = new Fallout( this.putter, this.skyStoneDefinition ); - } - - boolean spawnMeteorite( final IMeteoriteWorld w, final NBTTagCompound meteoriteBlob ) - { - this.settings = meteoriteBlob; - - final int x = this.settings.getInteger( "x" ); - final int y = this.settings.getInteger( "y" ); - final int z = this.settings.getInteger( "z" ); - - this.meteoriteSize = this.settings.getDouble( "real_sizeOfMeteorite" ); - this.realCrater = this.settings.getDouble( "realCrater" ); - this.squaredMeteoriteSize = this.settings.getDouble( "sizeOfMeteorite" ); - this.crater = this.settings.getDouble( "crater" ); - - final Block blk = Block.getBlockById( this.settings.getInteger( "blk" ) ); - - if( blk == Blocks.SAND ) - { - this.type = new FalloutSand( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - else if( blk == Blocks.HARDENED_CLAY ) - { - this.type = new FalloutCopy( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - else if( blk == Blocks.ICE || blk == Blocks.SNOW ) - { - this.type = new FalloutSnow( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - - final int skyMode = this.settings.getInteger( "skyMode" ); - - // creator - if( skyMode > 10 ) - { - this.placeCrater( w, x, y, z ); - } - - this.placeMeteorite( w, x, y, z ); - - // collapse blocks... - if( skyMode > 3 ) - { - this.decay( w, x, y, z ); - } - - w.done(); - return true; - } - - private void placeCrater( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final boolean lava = this.settings.getBoolean( "lava" ); - - final int maxY = 255; - final int minX = w.minX( x - 200 ); - final int maxX = w.maxX( x + 200 ); - final int minZ = w.minZ( z - 200 ); - final int maxZ = w.maxZ( z + 200 ); - - for( int j = y - 5; j < maxY; j++ ) - { - boolean changed = false; - - for( int i = minX; i < maxX; i++ ) - { - for( int k = minZ; k < maxZ; k++ ) - { - final double dx = i - x; - final double dz = k - z; - final double h = y - this.meteoriteSize + 1 + this.type.adjustCrater(); - - final double distanceFrom = dx * dx + dz * dz; - - if( j > h + distanceFrom * 0.02 ) - { - if( lava && j < y && w.getBlockState( i, j, k ).getMaterial().isSolid() ) - { - if( j > h + distanceFrom * 0.02 ) - { - this.putter.put( w, i, j, k, Blocks.LAVA ); - } - } - else - { - changed = this.putter.put( w, i, j, k, Platform.AIR_BLOCK ) || changed; - } - } - } - } - } - - for( final Object o : w.getWorld() - .getEntitiesWithinAABB( EntityItem.class, - new AxisAlignedBB( w.minX( x - 30 ), y - 5, w.minZ( z - 30 ), w.maxX( x + 30 ), y + 30, w.maxZ( z + 30 ) ) ) ) - { - final Entity e = (Entity) o; - e.setDead(); - } - } - - private void placeMeteorite( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - - // spawn meteor - this.skyStoneDefinition.maybeBlock().ifPresent( block -> this.placeMeteoriteSkyStone( w, x, y, z, block ) ); - - if( AEConfig.instance().isFeatureEnabled( AEFeature.SPAWN_PRESSES_IN_METEORITES ) ) - { - this.skyChestDefinition.maybeBlock().ifPresent( block -> this.putter.put( w, x, y, z, block ) ); - - final TileEntity te = w.getTileEntity( x, y, z ); - final InventoryAdaptor ap = InventoryAdaptor.getAdaptor( te, EnumFacing.UP ); - if( ap != null ) - { - int primary = Math.max( 1, (int) ( Math.random() * 4 ) ); - - if( primary > 3 ) // in case math breaks... - { - primary = 3; - } - - for( int zz = 0; zz < primary; zz++ ) - { - int r; - boolean duplicate; - - do - { - duplicate = false; - - if( Math.random() > PRESSES_SPAWN_CHANCE ) - { - r = WorldData.instance().storageData().getNextOrderedValue( "presses" ); - } - else - { - r = (int) ( Math.random() * 1000 ); - } - - ItemStack toAdd = ItemStack.EMPTY; - final IMaterials materials = AEApi.instance().definitions().materials(); - - switch( r % 4 ) - { - case 0: - toAdd = materials.calcProcessorPress().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - break; - case 1: - toAdd = materials.engProcessorPress().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - break; - case 2: - toAdd = materials.logicProcessorPress().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - break; - case 3: - toAdd = materials.siliconPress().maybeStack( 1 ).orElse( ItemStack.EMPTY ); - break; - default: - } - - if( !toAdd.isEmpty() ) - { - if( ap.simulateRemove( 1, toAdd, null ).isEmpty() ) - { - ap.addItems( toAdd ); - } - else - { - duplicate = true; - } - } - } - while( duplicate ); - } - - final int secondary = Math.max( 1, (int) ( Math.random() * 3 ) ); - for( int zz = 0; zz < secondary; zz++ ) - { - switch( (int) ( Math.random() * 1000 ) % 3 ) - { - case 0: - final int amount = (int) ( ( Math.random() * SKYSTONE_SPAWN_LIMIT ) + 1 ); - this.skyStoneDefinition.maybeStack( amount ).ifPresent( ap::addItems ); - break; - case 1: - final List possibles = new ArrayList<>(); - possibles.addAll( OreDictionary.getOres( "nuggetIron" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetCopper" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetTin" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetSilver" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetLead" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetPlatinum" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetNickel" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetAluminium" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetElectrum" ) ); - possibles.add( new ItemStack( net.minecraft.init.Items.GOLD_NUGGET ) ); - - ItemStack nugget = Platform.pickRandom( possibles ); - if( !nugget.isEmpty() ) - { - nugget = nugget.copy(); - nugget.setCount( (int) ( Math.random() * 12 ) + 1 ); - ap.addItems( nugget ); - } - break; - } - } - } - } - } - - private void placeMeteoriteSkyStone( IMeteoriteWorld w, int x, int y, int z, Block block ) - { - final int meteorXLength = w.minX( x - 8 ); - final int meteorXHeight = w.maxX( x + 8 ); - final int meteorZLength = w.minZ( z - 8 ); - final int meteorZHeight = w.maxZ( z + 8 ); - - for( int i = meteorXLength; i < meteorXHeight; i++ ) - { - for( int j = y - 8; j < y + 8; j++ ) - { - for( int k = meteorZLength; k < meteorZHeight; k++ ) - { - final double dx = i - x; - final double dy = j - y; - final double dz = k - z; - - if( dx * dx * 0.7 + dy * dy * ( j > y ? 1.4 : 0.8 ) + dz * dz * 0.7 < this.squaredMeteoriteSize ) - { - this.putter.put( w, i, j, k, block ); - } - } - } - } - } - - private void decay( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - double randomShit = 0; - - final int meteorXLength = w.minX( x - 30 ); - final int meteorXHeight = w.maxX( x + 30 ); - final int meteorZLength = w.minZ( z - 30 ); - final int meteorZHeight = w.maxZ( z + 30 ); - - for( int i = meteorXLength; i < meteorXHeight; i++ ) - { - for( int k = meteorZLength; k < meteorZHeight; k++ ) - { - for( int j = y - 9; j < y + 30; j++ ) - { - Block blk = w.getBlock( i, j, k ); - if( blk == Blocks.LAVA ) - { - continue; - } - - if( blk.isReplaceable( w.getWorld(), new BlockPos( i, j, k ) ) ) - { - blk = Platform.AIR_BLOCK; - final Block blk_b = w.getBlock( i, j + 1, k ); - - if( blk_b != blk ) - { - final IBlockState meta_b = w.getBlockState( i, j + 1, k ); - - w.setBlock( i, j, k, meta_b, 3 ); - } - else if( randomShit < 100 * this.crater ) - { - final double dx = i - x; - final double dy = j - y; - final double dz = k - z; - final double dist = dx * dx + dy * dy + dz * dz; - - final Block xf = w.getBlock( i, j - 1, k ); - if( !xf.isReplaceable( w.getWorld(), new BlockPos( i, j - 1, k ) ) ) - { - final double extraRange = Math.random() * 0.6; - final double height = this.crater * ( extraRange + 0.2 ) - Math.abs( dist - this.crater * 1.7 ); - - if( xf != blk && height > 0 && Math.random() > 0.6 ) - { - randomShit++; - this.type.getRandomFall( w, i, j, k ); - } - } - } - } - else - { - // decay. - final Block blk_b = w.getBlock( i, j + 1, k ); - if( blk_b == Platform.AIR_BLOCK ) - { - if( Math.random() > 0.4 ) - { - final double dx = i - x; - final double dy = j - y; - final double dz = k - z; - - if( dx * dx + dy * dy + dz * dz < this.crater * 1.6 ) - { - this.type.getRandomInset( w, i, j, k ); - } - } - } - } - } - } - } - } - - double getSqDistance( final int x, final int z ) - { - final int chunkX = this.settings.getInteger( "x" ) - x; - final int chunkZ = this.settings.getInteger( "z" ) - z; - - return chunkX * chunkX + chunkZ * chunkZ; - } - - public boolean spawnMeteorite( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - - if( !w.isNether() ) - { - return false; - } - - Block blk = w.getBlock( x, y, z ); - if( !this.validSpawn.contains( blk ) ) - { - return false; // must spawn on a valid block.. - } - - this.settings = new NBTTagCompound(); - this.settings.setInteger( "x", x ); - this.settings.setInteger( "y", y ); - this.settings.setInteger( "z", z ); - this.settings.setInteger( "blk", Block.getIdFromBlock( blk ) ); - - this.settings.setDouble( "real_sizeOfMeteorite", this.meteoriteSize ); - this.settings.setDouble( "realCrater", this.realCrater ); - this.settings.setDouble( "sizeOfMeteorite", this.squaredMeteoriteSize ); - this.settings.setDouble( "crater", this.crater ); - - this.settings.setBoolean( "lava", Math.random() > 0.9 ); - - if( blk == Blocks.SAND ) - { - this.type = new FalloutSand( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - else if( blk == Blocks.HARDENED_CLAY ) - { - this.type = new FalloutCopy( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - else if( blk == Blocks.ICE || blk == Blocks.SNOW ) - { - this.type = new FalloutSnow( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - - int realValidBlocks = 0; - - for( int i = x - 6; i < x + 6; i++ ) - { - for( int j = y - 6; j < y + 6; j++ ) - { - for( int k = z - 6; k < z + 6; k++ ) - { - blk = w.getBlock( i, j, k ); - if( this.validSpawn.contains( blk ) ) - { - realValidBlocks++; - } - } - } - } - - int validBlocks = 0; - for( int i = x - 15; i < x + 15; i++ ) - { - for( int j = y - 15; j < y + 15; j++ ) - { - for( int k = z - 15; k < z + 15; k++ ) - { - blk = w.getBlock( i, j, k ); - if( this.invalidSpawn.contains( blk ) ) - { - return false; - } - if( this.validSpawn.contains( blk ) ) - { - validBlocks++; - } - } - } - } - - final int minBlocks = 200; - if( validBlocks > minBlocks && realValidBlocks > 80 ) - { - // we can spawn here! - - int skyMode = 0; - - for( int i = x - 15; i < x + 15; i++ ) - { - for( int j = y - 15; j < y + 11; j++ ) - { - for( int k = z - 15; k < z + 15; k++ ) - { - if( w.canBlockSeeTheSky( i, j, k ) ) - { - skyMode++; - } - } - } - } - - boolean solid = true; - for( int j = y - 15; j < y - 1; j++ ) - { - if( w.getBlock( x, j, z ) == Platform.AIR_BLOCK ) - { - solid = false; - } - } - - if( !solid ) - { - skyMode = 0; - } - - // creator - if( skyMode > 10 ) - { - this.placeCrater( w, x, y, z ); - } - - this.placeMeteorite( w, x, y, z ); - - // collapse blocks... - if( skyMode > 3 ) - { - this.decay( w, x, y, z ); - } - - this.settings.setInteger( "skyMode", skyMode ); - w.done(); - - WorldData.instance().spawnData().addNearByMeteorites( w.getWorld().provider.getDimension(), x >> 4, z >> 4, this.settings ); - return true; - } - return false; - } - - NBTTagCompound getSettings() - { - return this.settings; - } +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; + + +public final class MeteoritePlacer { + private static final double PRESSES_SPAWN_CHANCE = 0.7; + private static final int SKYSTONE_SPAWN_LIMIT = 12; + private final Collection validSpawn = new HashSet<>(); + private final Collection invalidSpawn = new HashSet<>(); + private final IBlockDefinition skyChestDefinition; + private final IBlockDefinition skyStoneDefinition; + private final MeteoriteBlockPutter putter = new MeteoriteBlockPutter(); + private double meteoriteSize = (Math.random() * 6.0) + 2; + private double realCrater = this.meteoriteSize * 2 + 5; + private double squaredMeteoriteSize = this.meteoriteSize * this.meteoriteSize; + private double crater = this.realCrater * this.realCrater; + private NBTTagCompound settings; + private Fallout type; + + public MeteoritePlacer() { + final IBlocks blocks = AEApi.instance().definitions().blocks(); + + this.skyChestDefinition = blocks.skyStoneChest(); + this.skyStoneDefinition = blocks.skyStoneBlock(); + + this.validSpawn.add(Blocks.STONE); + this.validSpawn.add(Blocks.COBBLESTONE); + this.validSpawn.add(Blocks.GRASS); + this.validSpawn.add(Blocks.SAND); + this.validSpawn.add(Blocks.DIRT); + this.validSpawn.add(Blocks.GRAVEL); + this.validSpawn.add(Blocks.NETHERRACK); + this.validSpawn.add(Blocks.IRON_ORE); + this.validSpawn.add(Blocks.GOLD_ORE); + this.validSpawn.add(Blocks.DIAMOND_ORE); + this.validSpawn.add(Blocks.REDSTONE_ORE); + this.validSpawn.add(Blocks.HARDENED_CLAY); + this.validSpawn.add(Blocks.ICE); + this.validSpawn.add(Blocks.SNOW); + this.validSpawn.add(Blocks.STAINED_HARDENED_CLAY); + + this.skyStoneDefinition.maybeBlock().ifPresent(this.invalidSpawn::add); + this.invalidSpawn.add(Blocks.PLANKS); + this.invalidSpawn.add(Blocks.IRON_DOOR); + this.invalidSpawn.add(Blocks.IRON_BARS); + this.invalidSpawn.add(Blocks.OAK_DOOR); + this.invalidSpawn.add(Blocks.ACACIA_DOOR); + this.invalidSpawn.add(Blocks.BIRCH_DOOR); + this.invalidSpawn.add(Blocks.DARK_OAK_DOOR); + this.invalidSpawn.add(Blocks.IRON_DOOR); + this.invalidSpawn.add(Blocks.JUNGLE_DOOR); + this.invalidSpawn.add(Blocks.SPRUCE_DOOR); + this.invalidSpawn.add(Blocks.BRICK_BLOCK); + this.invalidSpawn.add(Blocks.CLAY); + this.invalidSpawn.add(Blocks.WATER); + this.invalidSpawn.add(Blocks.LOG); + this.invalidSpawn.add(Blocks.LOG2); + + this.type = new Fallout(this.putter, this.skyStoneDefinition); + } + + boolean spawnMeteorite(final IMeteoriteWorld w, final NBTTagCompound meteoriteBlob) { + this.settings = meteoriteBlob; + + final int x = this.settings.getInteger("x"); + final int y = this.settings.getInteger("y"); + final int z = this.settings.getInteger("z"); + + this.meteoriteSize = this.settings.getDouble("real_sizeOfMeteorite"); + this.realCrater = this.settings.getDouble("realCrater"); + this.squaredMeteoriteSize = this.settings.getDouble("sizeOfMeteorite"); + this.crater = this.settings.getDouble("crater"); + + final Block blk = Block.getBlockById(this.settings.getInteger("blk")); + + if (blk == Blocks.SAND) { + this.type = new FalloutSand(w, x, y, z, this.putter, this.skyStoneDefinition); + } else if (blk == Blocks.HARDENED_CLAY) { + this.type = new FalloutCopy(w, x, y, z, this.putter, this.skyStoneDefinition); + } else if (blk == Blocks.ICE || blk == Blocks.SNOW) { + this.type = new FalloutSnow(w, x, y, z, this.putter, this.skyStoneDefinition); + } + + final int skyMode = this.settings.getInteger("skyMode"); + + // creator + if (skyMode > 10) { + this.placeCrater(w, x, y, z); + } + + this.placeMeteorite(w, x, y, z); + + // collapse blocks... + if (skyMode > 3) { + this.decay(w, x, y, z); + } + + w.done(); + return true; + } + + private void placeCrater(final IMeteoriteWorld w, final int x, final int y, final int z) { + final boolean lava = this.settings.getBoolean("lava"); + + final int maxY = 255; + final int minX = w.minX(x - 200); + final int maxX = w.maxX(x + 200); + final int minZ = w.minZ(z - 200); + final int maxZ = w.maxZ(z + 200); + + for (int j = y - 5; j < maxY; j++) { + boolean changed = false; + + for (int i = minX; i < maxX; i++) { + for (int k = minZ; k < maxZ; k++) { + final double dx = i - x; + final double dz = k - z; + final double h = y - this.meteoriteSize + 1 + this.type.adjustCrater(); + + final double distanceFrom = dx * dx + dz * dz; + + if (j > h + distanceFrom * 0.02) { + if (lava && j < y && w.getBlockState(i, j, k).getMaterial().isSolid()) { + if (j > h + distanceFrom * 0.02) { + this.putter.put(w, i, j, k, Blocks.LAVA); + } + } else { + changed = this.putter.put(w, i, j, k, Platform.AIR_BLOCK) || changed; + } + } + } + } + } + + for (final Object o : w.getWorld() + .getEntitiesWithinAABB(EntityItem.class, + new AxisAlignedBB(w.minX(x - 30), y - 5, w.minZ(z - 30), w.maxX(x + 30), y + 30, w.maxZ(z + 30)))) { + final Entity e = (Entity) o; + e.setDead(); + } + } + + private void placeMeteorite(final IMeteoriteWorld w, final int x, final int y, final int z) { + + // spawn meteor + this.skyStoneDefinition.maybeBlock().ifPresent(block -> this.placeMeteoriteSkyStone(w, x, y, z, block)); + + if (AEConfig.instance().isFeatureEnabled(AEFeature.SPAWN_PRESSES_IN_METEORITES)) { + this.skyChestDefinition.maybeBlock().ifPresent(block -> this.putter.put(w, x, y, z, block)); + + final TileEntity te = w.getTileEntity(x, y, z); + final InventoryAdaptor ap = InventoryAdaptor.getAdaptor(te, EnumFacing.UP); + if (ap != null) { + int primary = Math.max(1, (int) (Math.random() * 4)); + + if (primary > 3) // in case math breaks... + { + primary = 3; + } + + for (int zz = 0; zz < primary; zz++) { + int r; + boolean duplicate; + + do { + duplicate = false; + + if (Math.random() > PRESSES_SPAWN_CHANCE) { + r = WorldData.instance().storageData().getNextOrderedValue("presses"); + } else { + r = (int) (Math.random() * 1000); + } + + ItemStack toAdd = ItemStack.EMPTY; + final IMaterials materials = AEApi.instance().definitions().materials(); + + switch (r % 4) { + case 0: + toAdd = materials.calcProcessorPress().maybeStack(1).orElse(ItemStack.EMPTY); + break; + case 1: + toAdd = materials.engProcessorPress().maybeStack(1).orElse(ItemStack.EMPTY); + break; + case 2: + toAdd = materials.logicProcessorPress().maybeStack(1).orElse(ItemStack.EMPTY); + break; + case 3: + toAdd = materials.siliconPress().maybeStack(1).orElse(ItemStack.EMPTY); + break; + default: + } + + if (!toAdd.isEmpty()) { + if (ap.simulateRemove(1, toAdd, null).isEmpty()) { + ap.addItems(toAdd); + } else { + duplicate = true; + } + } + } + while (duplicate); + } + + final int secondary = Math.max(1, (int) (Math.random() * 3)); + for (int zz = 0; zz < secondary; zz++) { + switch ((int) (Math.random() * 1000) % 3) { + case 0: + final int amount = (int) ((Math.random() * SKYSTONE_SPAWN_LIMIT) + 1); + this.skyStoneDefinition.maybeStack(amount).ifPresent(ap::addItems); + break; + case 1: + final List possibles = new ArrayList<>(); + possibles.addAll(OreDictionary.getOres("nuggetIron")); + possibles.addAll(OreDictionary.getOres("nuggetCopper")); + possibles.addAll(OreDictionary.getOres("nuggetTin")); + possibles.addAll(OreDictionary.getOres("nuggetSilver")); + possibles.addAll(OreDictionary.getOres("nuggetLead")); + possibles.addAll(OreDictionary.getOres("nuggetPlatinum")); + possibles.addAll(OreDictionary.getOres("nuggetNickel")); + possibles.addAll(OreDictionary.getOres("nuggetAluminium")); + possibles.addAll(OreDictionary.getOres("nuggetElectrum")); + possibles.add(new ItemStack(net.minecraft.init.Items.GOLD_NUGGET)); + + ItemStack nugget = Platform.pickRandom(possibles); + if (!nugget.isEmpty()) { + nugget = nugget.copy(); + nugget.setCount((int) (Math.random() * 12) + 1); + ap.addItems(nugget); + } + break; + } + } + } + } + } + + private void placeMeteoriteSkyStone(IMeteoriteWorld w, int x, int y, int z, Block block) { + final int meteorXLength = w.minX(x - 8); + final int meteorXHeight = w.maxX(x + 8); + final int meteorZLength = w.minZ(z - 8); + final int meteorZHeight = w.maxZ(z + 8); + + for (int i = meteorXLength; i < meteorXHeight; i++) { + for (int j = y - 8; j < y + 8; j++) { + for (int k = meteorZLength; k < meteorZHeight; k++) { + final double dx = i - x; + final double dy = j - y; + final double dz = k - z; + + if (dx * dx * 0.7 + dy * dy * (j > y ? 1.4 : 0.8) + dz * dz * 0.7 < this.squaredMeteoriteSize) { + this.putter.put(w, i, j, k, block); + } + } + } + } + } + + private void decay(final IMeteoriteWorld w, final int x, final int y, final int z) { + double randomShit = 0; + + final int meteorXLength = w.minX(x - 30); + final int meteorXHeight = w.maxX(x + 30); + final int meteorZLength = w.minZ(z - 30); + final int meteorZHeight = w.maxZ(z + 30); + + for (int i = meteorXLength; i < meteorXHeight; i++) { + for (int k = meteorZLength; k < meteorZHeight; k++) { + for (int j = y - 9; j < y + 30; j++) { + Block blk = w.getBlock(i, j, k); + if (blk == Blocks.LAVA) { + continue; + } + + if (blk.isReplaceable(w.getWorld(), new BlockPos(i, j, k))) { + blk = Platform.AIR_BLOCK; + final Block blk_b = w.getBlock(i, j + 1, k); + + if (blk_b != blk) { + final IBlockState meta_b = w.getBlockState(i, j + 1, k); + + w.setBlock(i, j, k, meta_b, 3); + } else if (randomShit < 100 * this.crater) { + final double dx = i - x; + final double dy = j - y; + final double dz = k - z; + final double dist = dx * dx + dy * dy + dz * dz; + + final Block xf = w.getBlock(i, j - 1, k); + if (!xf.isReplaceable(w.getWorld(), new BlockPos(i, j - 1, k))) { + final double extraRange = Math.random() * 0.6; + final double height = this.crater * (extraRange + 0.2) - Math.abs(dist - this.crater * 1.7); + + if (xf != blk && height > 0 && Math.random() > 0.6) { + randomShit++; + this.type.getRandomFall(w, i, j, k); + } + } + } + } else { + // decay. + final Block blk_b = w.getBlock(i, j + 1, k); + if (blk_b == Platform.AIR_BLOCK) { + if (Math.random() > 0.4) { + final double dx = i - x; + final double dy = j - y; + final double dz = k - z; + + if (dx * dx + dy * dy + dz * dz < this.crater * 1.6) { + this.type.getRandomInset(w, i, j, k); + } + } + } + } + } + } + } + } + + double getSqDistance(final int x, final int z) { + final int chunkX = this.settings.getInteger("x") - x; + final int chunkZ = this.settings.getInteger("z") - z; + + return chunkX * chunkX + chunkZ * chunkZ; + } + + public boolean spawnMeteorite(final IMeteoriteWorld w, final int x, final int y, final int z) { + + if (!w.isNether()) { + return false; + } + + Block blk = w.getBlock(x, y, z); + if (!this.validSpawn.contains(blk)) { + return false; // must spawn on a valid block.. + } + + this.settings = new NBTTagCompound(); + this.settings.setInteger("x", x); + this.settings.setInteger("y", y); + this.settings.setInteger("z", z); + this.settings.setInteger("blk", Block.getIdFromBlock(blk)); + + this.settings.setDouble("real_sizeOfMeteorite", this.meteoriteSize); + this.settings.setDouble("realCrater", this.realCrater); + this.settings.setDouble("sizeOfMeteorite", this.squaredMeteoriteSize); + this.settings.setDouble("crater", this.crater); + + this.settings.setBoolean("lava", Math.random() > 0.9); + + if (blk == Blocks.SAND) { + this.type = new FalloutSand(w, x, y, z, this.putter, this.skyStoneDefinition); + } else if (blk == Blocks.HARDENED_CLAY) { + this.type = new FalloutCopy(w, x, y, z, this.putter, this.skyStoneDefinition); + } else if (blk == Blocks.ICE || blk == Blocks.SNOW) { + this.type = new FalloutSnow(w, x, y, z, this.putter, this.skyStoneDefinition); + } + + int realValidBlocks = 0; + + for (int i = x - 6; i < x + 6; i++) { + for (int j = y - 6; j < y + 6; j++) { + for (int k = z - 6; k < z + 6; k++) { + blk = w.getBlock(i, j, k); + if (this.validSpawn.contains(blk)) { + realValidBlocks++; + } + } + } + } + + int validBlocks = 0; + for (int i = x - 15; i < x + 15; i++) { + for (int j = y - 15; j < y + 15; j++) { + for (int k = z - 15; k < z + 15; k++) { + blk = w.getBlock(i, j, k); + if (this.invalidSpawn.contains(blk)) { + return false; + } + if (this.validSpawn.contains(blk)) { + validBlocks++; + } + } + } + } + + final int minBlocks = 200; + if (validBlocks > minBlocks && realValidBlocks > 80) { + // we can spawn here! + + int skyMode = 0; + + for (int i = x - 15; i < x + 15; i++) { + for (int j = y - 15; j < y + 11; j++) { + for (int k = z - 15; k < z + 15; k++) { + if (w.canBlockSeeTheSky(i, j, k)) { + skyMode++; + } + } + } + } + + boolean solid = true; + for (int j = y - 15; j < y - 1; j++) { + if (w.getBlock(x, j, z) == Platform.AIR_BLOCK) { + solid = false; + } + } + + if (!solid) { + skyMode = 0; + } + + // creator + if (skyMode > 10) { + this.placeCrater(w, x, y, z); + } + + this.placeMeteorite(w, x, y, z); + + // collapse blocks... + if (skyMode > 3) { + this.decay(w, x, y, z); + } + + this.settings.setInteger("skyMode", skyMode); + w.done(); + + WorldData.instance().spawnData().addNearByMeteorites(w.getWorld().provider.getDimension(), x >> 4, z >> 4, this.settings); + return true; + } + return false; + } + + NBTTagCompound getSettings() { + return this.settings; + } } diff --git a/src/main/java/appeng/worldgen/MeteoriteWorldGen.java b/src/main/java/appeng/worldgen/MeteoriteWorldGen.java index 74e552695..e8baeef8c 100644 --- a/src/main/java/appeng/worldgen/MeteoriteWorldGen.java +++ b/src/main/java/appeng/worldgen/MeteoriteWorldGen.java @@ -19,14 +19,6 @@ package appeng.worldgen; -import java.util.Random; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.gen.IChunkGenerator; -import net.minecraftforge.fml.common.IWorldGenerator; - import appeng.api.features.IWorldGen.WorldGenType; import appeng.core.AEConfig; import appeng.core.features.registries.WorldGenRegistry; @@ -35,118 +27,105 @@ import appeng.hooks.TickHandler; import appeng.util.IWorldCallable; import appeng.util.Platform; import appeng.worldgen.meteorite.ChunkOnly; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import net.minecraft.world.chunk.IChunkProvider; +import net.minecraft.world.gen.IChunkGenerator; +import net.minecraftforge.fml.common.IWorldGenerator; + +import java.util.Random; -public final class MeteoriteWorldGen implements IWorldGenerator -{ - @Override - public void generate( final Random r, final int chunkX, final int chunkZ, final World w, final IChunkGenerator chunkGenerator, final IChunkProvider chunkProvider ) - { - if( WorldGenRegistry.INSTANCE.isWorldGenEnabled( WorldGenType.METEORITES, w ) ) - { - final int x = r.nextInt( 16 ) + ( chunkX << 4 ); - final int z = r.nextInt( 16 ) + ( chunkZ << 4 ); - final int depth = AEConfig.instance().getMeteoriteMaximumSpawnHeight() + r.nextInt( 20 ); +public final class MeteoriteWorldGen implements IWorldGenerator { + @Override + public void generate(final Random r, final int chunkX, final int chunkZ, final World w, final IChunkGenerator chunkGenerator, final IChunkProvider chunkProvider) { + if (WorldGenRegistry.INSTANCE.isWorldGenEnabled(WorldGenType.METEORITES, w)) { + final int x = r.nextInt(16) + (chunkX << 4); + final int z = r.nextInt(16) + (chunkZ << 4); + final int depth = AEConfig.instance().getMeteoriteMaximumSpawnHeight() + r.nextInt(20); - TickHandler.INSTANCE.addCallable( w, new MeteoriteSpawn( x, depth, z ) ); - } - else - { - WorldData.instance().compassData().service().updateArea( w, chunkX, chunkZ ); - } - } + TickHandler.INSTANCE.addCallable(w, new MeteoriteSpawn(x, depth, z)); + } else { + WorldData.instance().compassData().service().updateArea(w, chunkX, chunkZ); + } + } - private boolean tryMeteorite( final World w, int depth, final int x, final int z ) - { - for( int tries = 0; tries < 20; tries++ ) - { - final MeteoritePlacer mp = new MeteoritePlacer(); + private boolean tryMeteorite(final World w, int depth, final int x, final int z) { + for (int tries = 0; tries < 20; tries++) { + final MeteoritePlacer mp = new MeteoritePlacer(); - if( mp.spawnMeteorite( new ChunkOnly( w, x >> 4, z >> 4 ), x, depth, z ) ) - { - final int px = x >> 4; - final int pz = z >> 4; + if (mp.spawnMeteorite(new ChunkOnly(w, x >> 4, z >> 4), x, depth, z)) { + final int px = x >> 4; + final int pz = z >> 4; - for( int cx = px - 6; cx < px + 6; cx++ ) - { - for( int cz = pz - 6; cz < pz + 6; cz++ ) - { - if( w.getChunkProvider().getLoadedChunk( cx, cz ) != null ) - { - if( px == cx && pz == cz ) - { - continue; - } + for (int cx = px - 6; cx < px + 6; cx++) { + for (int cz = pz - 6; cz < pz + 6; cz++) { + if (w.getChunkProvider().getLoadedChunk(cx, cz) != null) { + if (px == cx && pz == cz) { + continue; + } - if( WorldData.instance().spawnData().hasGenerated( w.provider.getDimension(), cx, cz ) ) - { - final MeteoritePlacer mp2 = new MeteoritePlacer(); - mp2.spawnMeteorite( new ChunkOnly( w, cx, cz ), mp.getSettings() ); - } - } - } - } + if (WorldData.instance().spawnData().hasGenerated(w.provider.getDimension(), cx, cz)) { + final MeteoritePlacer mp2 = new MeteoritePlacer(); + mp2.spawnMeteorite(new ChunkOnly(w, cx, cz), mp.getSettings()); + } + } + } + } - return true; - } + return true; + } - depth -= 15; - if( depth < 40 ) - { - return false; - } - } + depth -= 15; + if (depth < 40) { + return false; + } + } - return false; - } + return false; + } - private Iterable getNearByMeteorites( final World w, final int chunkX, final int chunkZ ) - { - return WorldData.instance().spawnData().getNearByMeteorites( w.provider.getDimension(), chunkX, chunkZ ); - } + private Iterable getNearByMeteorites(final World w, final int chunkX, final int chunkZ) { + return WorldData.instance().spawnData().getNearByMeteorites(w.provider.getDimension(), chunkX, chunkZ); + } - private class MeteoriteSpawn implements IWorldCallable - { + private class MeteoriteSpawn implements IWorldCallable { - private final int x; - private final int z; - private final int depth; + private final int x; + private final int z; + private final int depth; - public MeteoriteSpawn( final int x, final int depth, final int z ) - { - this.x = x; - this.z = z; - this.depth = depth; - } + public MeteoriteSpawn(final int x, final int depth, final int z) { + this.x = x; + this.z = z; + this.depth = depth; + } - @Override - public Object call( final World world ) throws Exception - { - final int chunkX = this.x >> 4; - final int chunkZ = this.z >> 4; + @Override + public Object call(final World world) throws Exception { + final int chunkX = this.x >> 4; + final int chunkZ = this.z >> 4; - double minSqDist = Double.MAX_VALUE; + double minSqDist = Double.MAX_VALUE; - // near by meteorites! - for( final NBTTagCompound data : MeteoriteWorldGen.this.getNearByMeteorites( world, chunkX, chunkZ ) ) - { - final MeteoritePlacer mp = new MeteoritePlacer(); - mp.spawnMeteorite( new ChunkOnly( world, chunkX, chunkZ ), data ); + // near by meteorites! + for (final NBTTagCompound data : MeteoriteWorldGen.this.getNearByMeteorites(world, chunkX, chunkZ)) { + final MeteoritePlacer mp = new MeteoritePlacer(); + mp.spawnMeteorite(new ChunkOnly(world, chunkX, chunkZ), data); - minSqDist = Math.min( minSqDist, mp.getSqDistance( this.x, this.z ) ); - } + minSqDist = Math.min(minSqDist, mp.getSqDistance(this.x, this.z)); + } - final boolean isCluster = ( minSqDist < 30 * 30 ) && Platform.getRandomFloat() < AEConfig.instance().getMeteoriteClusterChance(); + final boolean isCluster = (minSqDist < 30 * 30) && Platform.getRandomFloat() < AEConfig.instance().getMeteoriteClusterChance(); - if( minSqDist > AEConfig.instance().getMinMeteoriteDistanceSq() || isCluster ) - { - MeteoriteWorldGen.this.tryMeteorite( world, this.depth, this.x, this.z ); - } + if (minSqDist > AEConfig.instance().getMinMeteoriteDistanceSq() || isCluster) { + MeteoriteWorldGen.this.tryMeteorite(world, this.depth, this.x, this.z); + } - WorldData.instance().spawnData().setGenerated( world.provider.getDimension(), chunkX, chunkZ ); - WorldData.instance().compassData().service().updateArea( world, chunkX, chunkZ ); + WorldData.instance().spawnData().setGenerated(world.provider.getDimension(), chunkX, chunkZ); + WorldData.instance().compassData().service().updateArea(world, chunkX, chunkZ); - return null; - } - } + return null; + } + } } diff --git a/src/main/java/appeng/worldgen/QuartzWorldGen.java b/src/main/java/appeng/worldgen/QuartzWorldGen.java index f9323840f..85ec2c9ee 100644 --- a/src/main/java/appeng/worldgen/QuartzWorldGen.java +++ b/src/main/java/appeng/worldgen/QuartzWorldGen.java @@ -19,8 +19,12 @@ package appeng.worldgen; -import java.util.Random; - +import appeng.api.AEApi; +import appeng.api.definitions.IBlockDefinition; +import appeng.api.definitions.IBlocks; +import appeng.api.features.IWorldGen.WorldGenType; +import appeng.core.AEConfig; +import appeng.core.features.registries.WorldGenRegistry; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; @@ -28,75 +32,61 @@ import net.minecraft.world.gen.IChunkGenerator; import net.minecraft.world.gen.feature.WorldGenMinable; import net.minecraftforge.fml.common.IWorldGenerator; -import appeng.api.AEApi; -import appeng.api.definitions.IBlockDefinition; -import appeng.api.definitions.IBlocks; -import appeng.api.features.IWorldGen.WorldGenType; -import appeng.core.AEConfig; -import appeng.core.features.registries.WorldGenRegistry; +import java.util.Random; -public final class QuartzWorldGen implements IWorldGenerator -{ - private final WorldGenMinable oreNormal; - private final WorldGenMinable oreCharged; +public final class QuartzWorldGen implements IWorldGenerator { + private final WorldGenMinable oreNormal; + private final WorldGenMinable oreCharged; - public QuartzWorldGen() - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); - final IBlockDefinition oreDefinition = blocks.quartzOre(); - final IBlockDefinition chargedDefinition = blocks.quartzOreCharged(); + public QuartzWorldGen() { + final IBlocks blocks = AEApi.instance().definitions().blocks(); + final IBlockDefinition oreDefinition = blocks.quartzOre(); + final IBlockDefinition chargedDefinition = blocks.quartzOreCharged(); - this.oreNormal = oreDefinition.maybeBlock() - .map( b -> new WorldGenMinable( b.getDefaultState(), AEConfig.instance().getQuartzOresPerCluster() ) ) - .orElse( null ); - this.oreCharged = chargedDefinition.maybeBlock() - .map( b -> new WorldGenMinable( b.getDefaultState(), AEConfig.instance().getQuartzOresPerCluster() ) ) - .orElse( null ); - } + this.oreNormal = oreDefinition.maybeBlock() + .map(b -> new WorldGenMinable(b.getDefaultState(), AEConfig.instance().getQuartzOresPerCluster())) + .orElse(null); + this.oreCharged = chargedDefinition.maybeBlock() + .map(b -> new WorldGenMinable(b.getDefaultState(), AEConfig.instance().getQuartzOresPerCluster())) + .orElse(null); + } - @Override - public void generate( final Random r, final int chunkX, final int chunkZ, final World w, final IChunkGenerator chunkGenerator, final IChunkProvider chunkProvider ) - { - if( this.oreNormal == null && this.oreCharged == null ) - { - return; - } + @Override + public void generate(final Random r, final int chunkX, final int chunkZ, final World w, final IChunkGenerator chunkGenerator, final IChunkProvider chunkProvider) { + if (this.oreNormal == null && this.oreCharged == null) { + return; + } - int seaLevel = w.provider.getAverageGroundLevel() + 1; + int seaLevel = w.provider.getAverageGroundLevel() + 1; - if( seaLevel < 20 ) - { - final int x = ( chunkX << 4 ) + 8; - final int z = ( chunkZ << 4 ) + 8; - seaLevel = w.getHeight( x, z ); - } + if (seaLevel < 20) { + final int x = (chunkX << 4) + 8; + final int z = (chunkZ << 4) + 8; + seaLevel = w.getHeight(x, z); + } - final double oreDepthMultiplier = AEConfig.instance().getQuartzOresClusterAmount() * seaLevel / 64; - final int scale = (int) Math.round( r.nextGaussian() * Math.sqrt( oreDepthMultiplier ) + oreDepthMultiplier ); + final double oreDepthMultiplier = AEConfig.instance().getQuartzOresClusterAmount() * seaLevel / 64; + final int scale = (int) Math.round(r.nextGaussian() * Math.sqrt(oreDepthMultiplier) + oreDepthMultiplier); - for( int cnt = 0; cnt < ( r.nextBoolean() ? scale * 2 : scale ) / 2; ++cnt ) - { - boolean isCharged = false; + for (int cnt = 0; cnt < (r.nextBoolean() ? scale * 2 : scale) / 2; ++cnt) { + boolean isCharged = false; - if( this.oreCharged != null ) - { - isCharged = r.nextFloat() > AEConfig.instance().getSpawnChargedChance(); - } + if (this.oreCharged != null) { + isCharged = r.nextFloat() > AEConfig.instance().getSpawnChargedChance(); + } - final WorldGenMinable whichOre = isCharged ? this.oreCharged : this.oreNormal; - if( whichOre != null && shouldGenerate( isCharged, w ) ) - { - final int cx = chunkX * 16 + r.nextInt( 16 ); - final int cy = r.nextInt( 40 * seaLevel / 64 ) + r.nextInt( 22 * seaLevel / 64 ) + 12 * seaLevel / 64; - final int cz = chunkZ * 16 + r.nextInt( 16 ); - whichOre.generate( w, r, new BlockPos( cx, cy, cz ) ); - } - } - } + final WorldGenMinable whichOre = isCharged ? this.oreCharged : this.oreNormal; + if (whichOre != null && shouldGenerate(isCharged, w)) { + final int cx = chunkX * 16 + r.nextInt(16); + final int cy = r.nextInt(40 * seaLevel / 64) + r.nextInt(22 * seaLevel / 64) + 12 * seaLevel / 64; + final int cz = chunkZ * 16 + r.nextInt(16); + whichOre.generate(w, r, new BlockPos(cx, cy, cz)); + } + } + } - private static boolean shouldGenerate( final boolean isCharged, final World w ) - { - return WorldGenRegistry.INSTANCE.isWorldGenEnabled( isCharged ? WorldGenType.CHARGED_CERTUS_QUARTZ : WorldGenType.CERTUS_QUARTZ, w ); - } + private static boolean shouldGenerate(final boolean isCharged, final World w) { + return WorldGenRegistry.INSTANCE.isWorldGenEnabled(isCharged ? WorldGenType.CHARGED_CERTUS_QUARTZ : WorldGenType.CERTUS_QUARTZ, w); + } } diff --git a/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java b/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java index 4060933f7..f3777a444 100644 --- a/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java +++ b/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java @@ -19,97 +19,81 @@ package appeng.worldgen.meteorite; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; -import appeng.util.Platform; +public class ChunkOnly extends StandardWorld { -public class ChunkOnly extends StandardWorld -{ + private final Chunk target; + private final int cx; + private final int cz; + private int verticalBits = 0; - private final Chunk target; - private final int cx; - private final int cz; - private int verticalBits = 0; + public ChunkOnly(final World w, final int cx, final int cz) { + super(w); + this.target = w.getChunkFromChunkCoords(cx, cz); + this.cx = cx; + this.cz = cz; + } - public ChunkOnly( final World w, final int cx, final int cz ) - { - super( w ); - this.target = w.getChunkFromChunkCoords( cx, cz ); - this.cx = cx; - this.cz = cz; - } + @Override + public int minX(final int in) { + return Math.max(in, this.cx << 4); + } - @Override - public int minX( final int in ) - { - return Math.max( in, this.cx << 4 ); - } + @Override + public int minZ(final int in) { + return Math.max(in, this.cz << 4); + } - @Override - public int minZ( final int in ) - { - return Math.max( in, this.cz << 4 ); - } + @Override + public int maxX(final int in) { + return Math.min(in, (this.cx + 1) << 4); + } - @Override - public int maxX( final int in ) - { - return Math.min( in, ( this.cx + 1 ) << 4 ); - } + @Override + public int maxZ(final int in) { + return Math.min(in, (this.cz + 1) << 4); + } - @Override - public int maxZ( final int in ) - { - return Math.min( in, ( this.cz + 1 ) << 4 ); - } + @Override + public Block getBlock(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.target.getBlockState(x, y, z).getBlock(); + } + return Platform.AIR_BLOCK; + } - @Override - public Block getBlock( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.target.getBlockState( x, y, z ).getBlock(); - } - return Platform.AIR_BLOCK; - } + @Override + public void setBlock(final int x, final int y, final int z, final Block blk) { + if (this.range(x, y, z)) { + this.verticalBits |= 1 << (y >> 4); + this.getWorld().setBlockState(new BlockPos(x, y, z), blk.getDefaultState()); + } + } - @Override - public void setBlock( final int x, final int y, final int z, final Block blk ) - { - if( this.range( x, y, z ) ) - { - this.verticalBits |= 1 << ( y >> 4 ); - this.getWorld().setBlockState( new BlockPos( x, y, z ), blk.getDefaultState() ); - } - } + @Override + public void setBlock(final int x, final int y, final int z, final IBlockState state, final int flags) { + if (this.range(x, y, z)) { + this.verticalBits |= 1 << (y >> 4); + this.getWorld().setBlockState(new BlockPos(x, y, z), state, flags & (~2)); + } + } - @Override - public void setBlock( final int x, final int y, final int z, final IBlockState state, final int flags ) - { - if( this.range( x, y, z ) ) - { - this.verticalBits |= 1 << ( y >> 4 ); - this.getWorld().setBlockState( new BlockPos( x, y, z ), state, flags & ( ~2 ) ); - } - } + @Override + public void done() { + if (this.verticalBits != 0) { + Platform.sendChunk(this.target, this.verticalBits); + } + } - @Override - public void done() - { - if( this.verticalBits != 0 ) - { - Platform.sendChunk( this.target, this.verticalBits ); - } - } - - @Override - public boolean range( final int x, final int y, final int z ) - { - return this.cx == ( x >> 4 ) && this.cz == ( z >> 4 ); - } + @Override + public boolean range(final int x, final int y, final int z) { + return this.cx == (x >> 4) && this.cz == (z >> 4); + } } diff --git a/src/main/java/appeng/worldgen/meteorite/Fallout.java b/src/main/java/appeng/worldgen/meteorite/Fallout.java index 955d0e37e..4fe5a0a20 100644 --- a/src/main/java/appeng/worldgen/meteorite/Fallout.java +++ b/src/main/java/appeng/worldgen/meteorite/Fallout.java @@ -19,75 +19,51 @@ package appeng.worldgen.meteorite; -import net.minecraft.init.Blocks; - import appeng.api.definitions.IBlockDefinition; import appeng.util.Platform; +import net.minecraft.init.Blocks; -public class Fallout -{ - private final MeteoriteBlockPutter putter; - private final IBlockDefinition skyStoneDefinition; +public class Fallout { + private final MeteoriteBlockPutter putter; + private final IBlockDefinition skyStoneDefinition; - public Fallout( final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition ) - { - this.putter = putter; - this.skyStoneDefinition = skyStoneDefinition; - } + public Fallout(final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition) { + this.putter = putter; + this.skyStoneDefinition = skyStoneDefinition; + } - public int adjustCrater() - { - return 0; - } + public int adjustCrater() { + return 0; + } - public void getRandomFall( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final double a = Math.random(); - if( a > 0.9 ) - { - this.putter.put( w, x, y, z, Blocks.STONE ); - } - else if( a > 0.8 ) - { - this.putter.put( w, x, y, z, Blocks.COBBLESTONE ); - } - else if( a > 0.7 ) - { - this.putter.put( w, x, y, z, Blocks.DIRT ); - } - else - { - this.putter.put( w, x, y, z, Blocks.GRAVEL ); - } - } + public void getRandomFall(final IMeteoriteWorld w, final int x, final int y, final int z) { + final double a = Math.random(); + if (a > 0.9) { + this.putter.put(w, x, y, z, Blocks.STONE); + } else if (a > 0.8) { + this.putter.put(w, x, y, z, Blocks.COBBLESTONE); + } else if (a > 0.7) { + this.putter.put(w, x, y, z, Blocks.DIRT); + } else { + this.putter.put(w, x, y, z, Blocks.GRAVEL); + } + } - public void getRandomInset( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final double a = Math.random(); - if( a > 0.9 ) - { - this.putter.put( w, x, y, z, Blocks.COBBLESTONE ); - } - else if( a > 0.8 ) - { - this.putter.put( w, x, y, z, Blocks.STONE ); - } - else if( a > 0.7 ) - { - this.putter.put( w, x, y, z, Blocks.GRASS ); - } - else if( a > 0.6 ) - { - this.skyStoneDefinition.maybeBlock().ifPresent( block -> this.putter.put( w, x, y, z, block ) ); - } - else if( a > 0.5 ) - { - this.putter.put( w, x, y, z, Blocks.GRAVEL ); - } - else - { - this.putter.put( w, x, y, z, Platform.AIR_BLOCK ); - } - } + public void getRandomInset(final IMeteoriteWorld w, final int x, final int y, final int z) { + final double a = Math.random(); + if (a > 0.9) { + this.putter.put(w, x, y, z, Blocks.COBBLESTONE); + } else if (a > 0.8) { + this.putter.put(w, x, y, z, Blocks.STONE); + } else if (a > 0.7) { + this.putter.put(w, x, y, z, Blocks.GRASS); + } else if (a > 0.6) { + this.skyStoneDefinition.maybeBlock().ifPresent(block -> this.putter.put(w, x, y, z, block)); + } else if (a > 0.5) { + this.putter.put(w, x, y, z, Blocks.GRAVEL); + } else { + this.putter.put(w, x, y, z, Platform.AIR_BLOCK); + } + } } diff --git a/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java b/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java index a203de694..49af3c9a9 100644 --- a/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java +++ b/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java @@ -19,62 +19,48 @@ package appeng.worldgen.meteorite; -import net.minecraft.block.state.IBlockState; - import appeng.api.definitions.IBlockDefinition; import appeng.util.Platform; +import net.minecraft.block.state.IBlockState; -public class FalloutCopy extends Fallout -{ - private static final double SPECIFIED_BLOCK_THRESHOLD = 0.9; - private static final double AIR_BLOCK_THRESHOLD = 0.8; - private static final double BLOCK_THRESHOLD_STEP = 0.1; +public class FalloutCopy extends Fallout { + private static final double SPECIFIED_BLOCK_THRESHOLD = 0.9; + private static final double AIR_BLOCK_THRESHOLD = 0.8; + private static final double BLOCK_THRESHOLD_STEP = 0.1; - private final IBlockState block; - private final MeteoriteBlockPutter putter; + private final IBlockState block; + private final MeteoriteBlockPutter putter; - public FalloutCopy( final IMeteoriteWorld w, final int x, final int y, final int z, final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition ) - { - super( putter, skyStoneDefinition ); - this.putter = putter; - this.block = w.getBlockState( x, y, z ); - } + public FalloutCopy(final IMeteoriteWorld w, final int x, final int y, final int z, final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition) { + super(putter, skyStoneDefinition); + this.putter = putter; + this.block = w.getBlockState(x, y, z); + } - @Override - public void getRandomFall( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final double a = Math.random(); - if( a > SPECIFIED_BLOCK_THRESHOLD ) - { - this.putter.put( w, x, y, z, this.block, 3 ); - } - else - { - this.getOther( w, x, y, z, a ); - } - } + @Override + public void getRandomFall(final IMeteoriteWorld w, final int x, final int y, final int z) { + final double a = Math.random(); + if (a > SPECIFIED_BLOCK_THRESHOLD) { + this.putter.put(w, x, y, z, this.block, 3); + } else { + this.getOther(w, x, y, z, a); + } + } - public void getOther( final IMeteoriteWorld w, final int x, final int y, final int z, final double a ) - { + public void getOther(final IMeteoriteWorld w, final int x, final int y, final int z, final double a) { - } + } - @Override - public void getRandomInset( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final double a = Math.random(); - if( a > SPECIFIED_BLOCK_THRESHOLD ) - { - this.putter.put( w, x, y, z, this.block, 3 ); - } - else if( a > AIR_BLOCK_THRESHOLD ) - { - this.putter.put( w, x, y, z, Platform.AIR_BLOCK ); - } - else - { - this.getOther( w, x, y, z, a - BLOCK_THRESHOLD_STEP ); - } - } + @Override + public void getRandomInset(final IMeteoriteWorld w, final int x, final int y, final int z) { + final double a = Math.random(); + if (a > SPECIFIED_BLOCK_THRESHOLD) { + this.putter.put(w, x, y, z, this.block, 3); + } else if (a > AIR_BLOCK_THRESHOLD) { + this.putter.put(w, x, y, z, Platform.AIR_BLOCK); + } else { + this.getOther(w, x, y, z, a - BLOCK_THRESHOLD_STEP); + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/worldgen/meteorite/FalloutSand.java b/src/main/java/appeng/worldgen/meteorite/FalloutSand.java index c81df9f38..7ecbae684 100644 --- a/src/main/java/appeng/worldgen/meteorite/FalloutSand.java +++ b/src/main/java/appeng/worldgen/meteorite/FalloutSand.java @@ -19,34 +19,28 @@ package appeng.worldgen.meteorite; +import appeng.api.definitions.IBlockDefinition; import net.minecraft.init.Blocks; -import appeng.api.definitions.IBlockDefinition; +public class FalloutSand extends FalloutCopy { + private static final double GLASS_THRESHOLD = 0.66; + private final MeteoriteBlockPutter putter; -public class FalloutSand extends FalloutCopy -{ - private static final double GLASS_THRESHOLD = 0.66; - private final MeteoriteBlockPutter putter; + public FalloutSand(final IMeteoriteWorld w, final int x, final int y, final int z, final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition) { + super(w, x, y, z, putter, skyStoneDefinition); + this.putter = putter; + } - public FalloutSand( final IMeteoriteWorld w, final int x, final int y, final int z, final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition ) - { - super( w, x, y, z, putter, skyStoneDefinition ); - this.putter = putter; - } + @Override + public int adjustCrater() { + return 2; + } - @Override - public int adjustCrater() - { - return 2; - } - - @Override - public void getOther( final IMeteoriteWorld w, final int x, final int y, final int z, final double a ) - { - if( a > GLASS_THRESHOLD ) - { - this.putter.put( w, x, y, z, Blocks.GLASS ); - } - } + @Override + public void getOther(final IMeteoriteWorld w, final int x, final int y, final int z, final double a) { + if (a > GLASS_THRESHOLD) { + this.putter.put(w, x, y, z, Blocks.GLASS); + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java b/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java index f3053ac3d..4721f1934 100644 --- a/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java +++ b/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java @@ -19,39 +19,31 @@ package appeng.worldgen.meteorite; +import appeng.api.definitions.IBlockDefinition; import net.minecraft.init.Blocks; -import appeng.api.definitions.IBlockDefinition; +public class FalloutSnow extends FalloutCopy { + private static final double SNOW_THRESHOLD = 0.7; + private static final double ICE_THRESHOLD = 0.5; + private final MeteoriteBlockPutter putter; -public class FalloutSnow extends FalloutCopy -{ - private static final double SNOW_THRESHOLD = 0.7; - private static final double ICE_THRESHOLD = 0.5; - private final MeteoriteBlockPutter putter; + public FalloutSnow(final IMeteoriteWorld w, final int x, final int y, final int z, final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition) { + super(w, x, y, z, putter, skyStoneDefinition); + this.putter = putter; + } - public FalloutSnow( final IMeteoriteWorld w, final int x, final int y, final int z, final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition ) - { - super( w, x, y, z, putter, skyStoneDefinition ); - this.putter = putter; - } + @Override + public int adjustCrater() { + return 2; + } - @Override - public int adjustCrater() - { - return 2; - } - - @Override - public void getOther( final IMeteoriteWorld w, final int x, final int y, final int z, final double a ) - { - if( a > SNOW_THRESHOLD ) - { - this.putter.put( w, x, y, z, Blocks.SNOW ); - } - else if( a > ICE_THRESHOLD ) - { - this.putter.put( w, x, y, z, Blocks.ICE ); - } - } + @Override + public void getOther(final IMeteoriteWorld w, final int x, final int y, final int z, final double a) { + if (a > SNOW_THRESHOLD) { + this.putter.put(w, x, y, z, Blocks.SNOW); + } else if (a > ICE_THRESHOLD) { + this.putter.put(w, x, y, z, Blocks.ICE); + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/worldgen/meteorite/IMeteoriteWorld.java b/src/main/java/appeng/worldgen/meteorite/IMeteoriteWorld.java index 3663a405c..babdfb627 100644 --- a/src/main/java/appeng/worldgen/meteorite/IMeteoriteWorld.java +++ b/src/main/java/appeng/worldgen/meteorite/IMeteoriteWorld.java @@ -25,31 +25,30 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -public interface IMeteoriteWorld -{ - int minX( int in ); +public interface IMeteoriteWorld { + int minX(int in); - int minZ( int in ); + int minZ(int in); - int maxX( int in ); + int maxX(int in); - int maxZ( int in ); + int maxZ(int in); - boolean isNether(); + boolean isNether(); - Block getBlock( int x, int y, int z ); + Block getBlock(int x, int y, int z); - boolean canBlockSeeTheSky( int i, int j, int k ); + boolean canBlockSeeTheSky(int i, int j, int k); - TileEntity getTileEntity( int x, int y, int z ); + TileEntity getTileEntity(int x, int y, int z); - World getWorld(); + World getWorld(); - void setBlock( int i, int j, int k, Block blk ); + void setBlock(int i, int j, int k, Block blk); - void setBlock( int i, int j, int k, IBlockState state, int l ); + void setBlock(int i, int j, int k, IBlockState state, int l); - void done(); + void done(); - IBlockState getBlockState( int x, int y, int z ); + IBlockState getBlockState(int x, int y, int z); } \ No newline at end of file diff --git a/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java b/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java index 823ca78f3..edf910a1d 100644 --- a/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java +++ b/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java @@ -24,28 +24,23 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; -public class MeteoriteBlockPutter -{ - public boolean put( final IMeteoriteWorld w, final int i, final int j, final int k, final Block blk ) - { - final Block original = w.getBlock( i, j, k ); +public class MeteoriteBlockPutter { + public boolean put(final IMeteoriteWorld w, final int i, final int j, final int k, final Block blk) { + final Block original = w.getBlock(i, j, k); - if( original == Blocks.BEDROCK || original == blk ) - { - return false; - } + if (original == Blocks.BEDROCK || original == blk) { + return false; + } - w.setBlock( i, j, k, blk ); - return true; - } + w.setBlock(i, j, k, blk); + return true; + } - void put( final IMeteoriteWorld w, final int i, final int j, final int k, final IBlockState state, final int meta ) - { - if( w.getBlock( i, j, k ) == Blocks.BEDROCK ) - { - return; - } + void put(final IMeteoriteWorld w, final int i, final int j, final int k, final IBlockState state, final int meta) { + if (w.getBlock(i, j, k) == Blocks.BEDROCK) { + return; + } - w.setBlock( i, j, k, state, 3 ); - } + w.setBlock(i, j, k, state, 3); + } } diff --git a/src/main/java/appeng/worldgen/meteorite/StandardWorld.java b/src/main/java/appeng/worldgen/meteorite/StandardWorld.java index 350a1c687..560ee20d7 100644 --- a/src/main/java/appeng/worldgen/meteorite/StandardWorld.java +++ b/src/main/java/appeng/worldgen/meteorite/StandardWorld.java @@ -19,6 +19,7 @@ package appeng.worldgen.meteorite; +import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -26,121 +27,97 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import appeng.util.Platform; +public class StandardWorld implements IMeteoriteWorld { -public class StandardWorld implements IMeteoriteWorld -{ + private final World w; - private final World w; + public StandardWorld(final World w) { + this.w = w; + } - public StandardWorld( final World w ) - { - this.w = w; - } + @Override + public int minX(final int in) { + return in; + } - @Override - public int minX( final int in ) - { - return in; - } + @Override + public int minZ(final int in) { + return in; + } - @Override - public int minZ( final int in ) - { - return in; - } + @Override + public int maxX(final int in) { + return in; + } - @Override - public int maxX( final int in ) - { - return in; - } + @Override + public int maxZ(final int in) { + return in; + } - @Override - public int maxZ( final int in ) - { - return in; - } + @Override + public boolean isNether() { + return !this.getWorld().provider.isNether(); + } - @Override - public boolean isNether() - { - return !this.getWorld().provider.isNether(); - } + @Override + public Block getBlock(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.getWorld().getBlockState(new BlockPos(x, y, z)).getBlock(); + } + return Platform.AIR_BLOCK; + } - @Override - public Block getBlock( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.getWorld().getBlockState( new BlockPos( x, y, z ) ).getBlock(); - } - return Platform.AIR_BLOCK; - } + @Override + public boolean canBlockSeeTheSky(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.getWorld().canBlockSeeSky(new BlockPos(x, y, z)); + } + return false; + } - @Override - public boolean canBlockSeeTheSky( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.getWorld().canBlockSeeSky( new BlockPos( x, y, z ) ); - } - return false; - } + @Override + public TileEntity getTileEntity(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.getWorld().getTileEntity(new BlockPos(x, y, z)); + } + return null; + } - @Override - public TileEntity getTileEntity( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.getWorld().getTileEntity( new BlockPos( x, y, z ) ); - } - return null; - } + @Override + public World getWorld() { + return this.w; + } - @Override - public World getWorld() - { - return this.w; - } + @Override + public void setBlock(final int x, final int y, final int z, final Block blk) { + if (this.range(x, y, z)) { + this.getWorld().setBlockState(new BlockPos(x, y, z), blk.getDefaultState()); + } + } - @Override - public void setBlock( final int x, final int y, final int z, final Block blk ) - { - if( this.range( x, y, z ) ) - { - this.getWorld().setBlockState( new BlockPos( x, y, z ), blk.getDefaultState() ); - } - } + @Override + public void done() { - @Override - public void done() - { + } - } + public boolean range(final int x, final int y, final int z) { + return true; + } - public boolean range( final int x, final int y, final int z ) - { - return true; - } + @Override + public void setBlock(final int x, final int y, final int z, final IBlockState state, final int l) { + if (this.range(x, y, z)) { + this.w.setBlockState(new BlockPos(x, y, z), state, l); + } + } - @Override - public void setBlock( final int x, final int y, final int z, final IBlockState state, final int l ) - { - if( this.range( x, y, z ) ) - { - this.w.setBlockState( new BlockPos( x, y, z ), state, l ); - } - } - - @Override - public IBlockState getBlockState( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.w.getBlockState( new BlockPos( x, y, z ) ); - } - return Blocks.AIR.getDefaultState(); - } + @Override + public IBlockState getBlockState(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.w.getBlockState(new BlockPos(x, y, z)); + } + return Blocks.AIR.getDefaultState(); + } }